From 05dbcbdc69c569e9b7fd04a22896a46e86a17e4a Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 13 Nov 2026 13:12:54 +0100 Subject: [PATCH 1/5] security: redact Sentry request credentials (#411) --- skills/sentry-telemetry-privacy/SKILL.md | 22 ++++ skills/sentry-telemetry-privacy/acceptance.sh | 81 +++++++++++++ src/Heimdall.Web/Program.cs | 11 +- .../Security/SentryTelemetryPrivacy.cs | 111 ++++++++++++++++++ .../Security/SentryTelemetryPrivacyTests.cs | 72 ++++++++++++ 5 files changed, 289 insertions(+), 8 deletions(-) create mode 100644 skills/sentry-telemetry-privacy/SKILL.md create mode 100755 skills/sentry-telemetry-privacy/acceptance.sh create mode 100644 src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs create mode 100644 tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs diff --git a/skills/sentry-telemetry-privacy/SKILL.md b/skills/sentry-telemetry-privacy/SKILL.md new file mode 100644 index 0000000..3de7c31 --- /dev/null +++ b/skills/sentry-telemetry-privacy/SKILL.md @@ -0,0 +1,22 @@ +--- +name: sentry-telemetry-privacy +description: Keep Heimdall Sentry events free of authentication material while preserving safe diagnostic metadata. +--- + +# Sentry telemetry privacy + +Sentry event processing is configured in `src/Heimdall.Web/Program.cs`. Before an event is sent, `SentryTelemetryPrivacy` must remove or redact request authentication headers, cookies, query strings, request bodies, URL user information, and sensitive values in event extras and breadcrumbs. Keep the helper in the Web boundary; do not move request telemetry into Domain or Application. + +When changing this behavior: + +- Add focused tests under `tests/Heimdall.Web.Tests/Security/` using synthetic `SENTINEL_` values only. Serialize the final event and assert no sentinel survives. Also assert safe diagnostic metadata remains. +- Treat header names case-insensitively and normalize common separators before matching names that indicate authorization, API keys, tokens, secrets, passwords, credentials, or cookies. +- Clear entire fields such as cookie strings, query strings, and request bodies when selective redaction could miss nested or encoded credentials. Strip URL user information, query, and fragment while retaining the safe path. +- Apply the same sensitive-key filtering to event extras and breadcrumbs. Preserve the existing rate-limit breadcrumb filter. +- Never copy actual event headers, API keys, cookies, tokens, or request bodies into issue comments, test fixtures, logs, or acceptance evidence. Record only field names and synthetic test outcomes. + +## Acceptance + +Run `skills/sentry-telemetry-privacy/acceptance.sh`. The recipe runs the focused .NET test from the current checkout in a uniquely named disposable Compose project using the upstream .NET SDK image. It publishes no ports, creates no application image, uses no deployed configuration, and removes and verifies the project's containers, volumes, and network. Upstream SDK images remain cached. Record the project name, test result, `local images built: none`, and resource-cleanup verification in the linked Gitea issue/PR. + +This proves local sanitization logic and event-object handling only. It does not claim a live Sentry/GlitchTip event delivery or rotate any external credential. diff --git a/skills/sentry-telemetry-privacy/acceptance.sh b/skills/sentry-telemetry-privacy/acceptance.sh new file mode 100755 index 0000000..bb36752 --- /dev/null +++ b/skills/sentry-telemetry-privacy/acceptance.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')" +project="heimdall-sentry-privacy-${suffix}" +temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX") +env_file="$temp_dir/acceptance.env" +compose_file="$temp_dir/compose.yml" +local_image_tags=() + +cleanup() { + status=$? + trap - EXIT + cleanup_failed=0 + docker compose --project-directory "$repo_root" --env-file "$env_file" \ + -f "$compose_file" -p "$project" down --volumes --remove-orphans || cleanup_failed=1 + containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + if [[ -n "$containers" ]]; then + while IFS= read -r container; do + [[ -z "$container" ]] || docker rm -f "$container" >/dev/null || cleanup_failed=1 + done <<< "$containers" + fi + containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then + printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \ + "${containers:-}" "${volumes:-}" "${networks:-}" >&2 + cleanup_failed=1 + else + printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project" + fi + if ((${#local_image_tags[@]} == 0)); then + printf 'Local images built: none; upstream SDK image retained.\n' + fi + for tag in "${local_image_tags[@]}"; do + docker image rm "$tag" >/dev/null 2>&1 || true + if docker image inspect "$tag" >/dev/null 2>&1; then + printf 'Recipe image remains: %s\n' "$tag" >&2 + cleanup_failed=1 + else + printf 'Verified recipe image absent: %s\n' "$tag" + fi + done + rm -f -- "$env_file" "$compose_file" || cleanup_failed=1 + rmdir -- "$temp_dir" || cleanup_failed=1 + if ((cleanup_failed)); then + printf 'Disposable Sentry privacy acceptance cleanup failed for %s\n' "$project" >&2 + status=1 + fi + exit "$status" +} +trap cleanup EXIT + +cat > "$env_file" < "$compose_file" <<'EOF' +services: + focused-tests: + image: mcr.microsoft.com/dotnet/sdk:10.0 + entrypoint: ["dotnet"] + working_dir: /workspace + volumes: + - ${REPO_ROOT}:/workspace + command: + - test + - tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj + - --filter + - FullyQualifiedName~SentryTelemetryPrivacyTests + - --verbosity + - minimal + - -p:RestoreLockedMode=true +EOF + +printf 'Disposable project: %s\nLocal images built: none\n' "$project" +docker compose --project-directory "$repo_root" --env-file "$env_file" \ + -f "$compose_file" -p "$project" config --quiet +docker compose --project-directory "$repo_root" --env-file "$env_file" \ + -f "$compose_file" -p "$project" run --rm focused-tests diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index b32a35d..44a72ab 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -17,6 +17,7 @@ using Heimdall.Api.Hubs; using Heimdall.Api; using Heimdall.Web.Services; using Heimdall.Web; +using Heimdall.Web.Security; using Hangfire; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; @@ -822,18 +823,12 @@ public partial class Program options.SetBeforeSend(static (sentryEvent, _) => { sentryEvent.ServerName = null; - if (sentryEvent.Extra?.ContainsKey("password") == true) - (sentryEvent.Extra as IDictionary)?.Remove("password"); - if (sentryEvent.Extra?.ContainsKey("token") == true) - (sentryEvent.Extra as IDictionary)?.Remove("token"); - if (sentryEvent.Extra?.ContainsKey("secret") == true) - (sentryEvent.Extra as IDictionary)?.Remove("secret"); - return sentryEvent; + return SentryTelemetryPrivacy.Sanitize(sentryEvent); }); options.SetBeforeBreadcrumb(breadcrumb => breadcrumb.Category == "Microsoft.AspNetCore.RateLimiting" ? null - : breadcrumb); + : SentryTelemetryPrivacy.SanitizeBreadcrumb(breadcrumb)); } internal static void ConfigureMiddleware(WebApplication app) diff --git a/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs b/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs new file mode 100644 index 0000000..63e7dd8 --- /dev/null +++ b/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs @@ -0,0 +1,111 @@ +using Sentry; + +namespace Heimdall.Web.Security; + +/// Removes authentication material from request data before error telemetry is sent. +internal static class SentryTelemetryPrivacy +{ + private const string Redacted = "[Filtered]"; + + internal static SentryEvent Sanitize(SentryEvent sentryEvent) + { + ArgumentNullException.ThrowIfNull(sentryEvent); + + if (sentryEvent.Request is { } request) + { + RedactStringValues(request.Headers); + request.Cookies = null; + request.Url = StripQueryAndUserInfo(request.Url); + request.QueryString = null; + request.Data = null; + } + + if (sentryEvent.Extra is IDictionary extra) + RedactObjectValues(extra); + + return sentryEvent; + } + + internal static Breadcrumb SanitizeBreadcrumb(Breadcrumb breadcrumb) + { + ArgumentNullException.ThrowIfNull(breadcrumb); + if (breadcrumb.Data is IDictionary mutableData) + { + RedactStringValues(mutableData); + return breadcrumb; + } + + var data = breadcrumb.Data?.ToDictionary( + pair => pair.Key, + pair => IsSensitiveName(pair.Key) ? Redacted : pair.Value, + StringComparer.Ordinal); + return new Breadcrumb( + breadcrumb.Message ?? string.Empty, + breadcrumb.Type ?? string.Empty, + data, + breadcrumb.Category, + breadcrumb.Level); + } + + private static void RedactStringValues(IDictionary? values) + { + if (values is null) + return; + + foreach (var key in values.Keys.ToArray()) + { + if (IsSensitiveName(key)) + values[key] = Redacted; + } + } + + private static void RedactObjectValues(IDictionary values) + { + foreach (var key in values.Keys.ToArray()) + { + if (IsSensitiveName(key)) + { + values[key] = Redacted; + continue; + } + + if (values[key] is IDictionary nested) + RedactObjectValues(nested); + } + } + + private static bool IsSensitiveName(string name) + { + var normalized = name.Replace("-", string.Empty, StringComparison.Ordinal) + .Replace("_", string.Empty, StringComparison.Ordinal); + + return normalized.Contains("authorization", StringComparison.OrdinalIgnoreCase) || + normalized.Contains("apikey", StringComparison.OrdinalIgnoreCase) || + normalized.Contains("token", StringComparison.OrdinalIgnoreCase) || + normalized.Contains("secret", StringComparison.OrdinalIgnoreCase) || + normalized.Contains("password", StringComparison.OrdinalIgnoreCase) || + normalized.Contains("credential", StringComparison.OrdinalIgnoreCase) || + normalized.Contains("cookie", StringComparison.OrdinalIgnoreCase); + } + + private static string? StripQueryAndUserInfo(string? url) + { + if (string.IsNullOrWhiteSpace(url)) + return url; + + if (Uri.TryCreate(url, UriKind.Absolute, out var uri)) + { + var builder = new UriBuilder(uri) + { + UserName = string.Empty, + Password = string.Empty, + Query = string.Empty, + Fragment = string.Empty, + }; + return builder.Uri.GetLeftPart(UriPartial.Path); + } + + var queryStart = url.IndexOfAny(['?', '#']); + return queryStart >= 0 ? url[..queryStart] : url; + } +} diff --git a/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs b/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs new file mode 100644 index 0000000..7ed6ead --- /dev/null +++ b/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs @@ -0,0 +1,72 @@ +using Heimdall.Web.Security; +using Sentry; + +namespace Heimdall.Web.Tests.Security; + +public sealed class SentryTelemetryPrivacyTests +{ + [Fact] + public void Sanitize_RedactsAuthenticationHeadersAndCookies_AndKeepsSafeRequestMetadata() + { + const string apiKey = "SENTINEL_API_KEY_411"; + const string cookie = "SENTINEL_SESSION_COOKIE_411"; + using var document = System.Text.Json.JsonDocument.Parse($$""" + { + "request": { + "url": "https://user:SENTINEL_URL_PASSWORD_411@central.example/api/agents?access_token=SENTINEL_QUERY_TOKEN_411", + "query_string": "access_token=SENTINEL_QUERY_TOKEN_411", + "headers": { + "x-api-key": "{{apiKey}}", + "Content-Type": "application/json" + }, + "cookies": "session={{cookie}}", + "data": { "access_token": "SENTINEL_BODY_TOKEN_411" } + }, + "extra": { + "safeValue": "preserved", + "nested": { "clientSecret": "SENTINEL_EXTRA_SECRET_411" } + } + } + """); + var sentryEvent = SentryEvent.FromJson(document.RootElement); + + var sanitized = SentryTelemetryPrivacy.Sanitize(sentryEvent); + + Assert.Same(sentryEvent, sanitized); + Assert.Equal("[Filtered]", sanitized.Request!.Headers!["x-api-key"]); + Assert.Equal("application/json", sanitized.Request.Headers["Content-Type"]); + Assert.Null(sanitized.Request.Cookies); + Assert.Equal("https://central.example/api/agents", sanitized.Request.Url); + Assert.Null(sanitized.Request.QueryString); + Assert.Null(sanitized.Request.Data); + Assert.Equal("preserved", sanitized.Extra!["safeValue"]); + Assert.Equal("[Filtered]", ((IDictionary)sanitized.Extra["nested"]!)["clientSecret"]); + + var serialized = System.Text.Json.JsonSerializer.Serialize(sanitized); + Assert.DoesNotContain(apiKey, serialized, StringComparison.Ordinal); + Assert.DoesNotContain(cookie, serialized, StringComparison.Ordinal); + Assert.DoesNotContain("SENTINEL_", serialized, StringComparison.Ordinal); + } + + [Fact] + public void SanitizeBreadcrumb_RedactsSensitiveDataAndPreservesSafeData() + { + var breadcrumb = new Breadcrumb( + "request", + "http", + new Dictionary + { + ["Authorization"] = "SENTINEL_BREADCRUMB_AUTH_411", + ["method"] = "GET", + }, + "http.client", + BreadcrumbLevel.Info); + + var sanitized = SentryTelemetryPrivacy.SanitizeBreadcrumb(breadcrumb); + + Assert.Same(breadcrumb, sanitized); + Assert.Equal("[Filtered]", sanitized.Data!["Authorization"]); + Assert.Equal("GET", sanitized.Data["method"]); + Assert.DoesNotContain("SENTINEL_", System.Text.Json.JsonSerializer.Serialize(sanitized), StringComparison.Ordinal); + } +} -- 2.54.1 From fc36b38c6cd02304d8d2ce15f28250c179d6ca46 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 13 Nov 2026 13:41:08 +0100 Subject: [PATCH 2/5] security: sanitize Sentry transactions before send (#411) --- skills/sentry-telemetry-privacy/SKILL.md | 6 +- skills/sentry-telemetry-privacy/acceptance.sh | 22 ++++- src/Heimdall.Web/Program.cs | 2 + .../Security/SentryTelemetryPrivacy.cs | 88 +++++++++++++++++-- .../Security/SentryTelemetryPrivacyTests.cs | 86 +++++++++++++++++- 5 files changed, 191 insertions(+), 13 deletions(-) diff --git a/skills/sentry-telemetry-privacy/SKILL.md b/skills/sentry-telemetry-privacy/SKILL.md index 3de7c31..8e8de9d 100644 --- a/skills/sentry-telemetry-privacy/SKILL.md +++ b/skills/sentry-telemetry-privacy/SKILL.md @@ -5,11 +5,11 @@ description: Keep Heimdall Sentry events free of authentication material while p # Sentry telemetry privacy -Sentry event processing is configured in `src/Heimdall.Web/Program.cs`. Before an event is sent, `SentryTelemetryPrivacy` must remove or redact request authentication headers, cookies, query strings, request bodies, URL user information, and sensitive values in event extras and breadcrumbs. Keep the helper in the Web boundary; do not move request telemetry into Domain or Application. +Sentry event and transaction processing are configured in `src/Heimdall.Web/Program.cs`. `SetBeforeSend` and `SetBeforeSendTransaction` are separate SDK callbacks, so apply `SentryTelemetryPrivacy` to both. Before either payload is sent, remove or redact request/response authentication headers, cookies, query strings, bodies, URL user information, and sensitive values in event extras, transaction contexts, tags, spans, and breadcrumbs. Keep the helper in the Web boundary; do not move request telemetry into Domain or Application. When changing this behavior: -- Add focused tests under `tests/Heimdall.Web.Tests/Security/` using synthetic `SENTINEL_` values only. Serialize the final event and assert no sentinel survives. Also assert safe diagnostic metadata remains. +- Add focused tests under `tests/Heimdall.Web.Tests/Security/` using synthetic `SENTINEL_` values only. Serialize final events and transactions through the Sentry SDK serializers and assert no sentinel survives. Also assert safe diagnostic metadata remains. - Treat header names case-insensitively and normalize common separators before matching names that indicate authorization, API keys, tokens, secrets, passwords, credentials, or cookies. - Clear entire fields such as cookie strings, query strings, and request bodies when selective redaction could miss nested or encoded credentials. Strip URL user information, query, and fragment while retaining the safe path. - Apply the same sensitive-key filtering to event extras and breadcrumbs. Preserve the existing rate-limit breadcrumb filter. @@ -19,4 +19,4 @@ When changing this behavior: Run `skills/sentry-telemetry-privacy/acceptance.sh`. The recipe runs the focused .NET test from the current checkout in a uniquely named disposable Compose project using the upstream .NET SDK image. It publishes no ports, creates no application image, uses no deployed configuration, and removes and verifies the project's containers, volumes, and network. Upstream SDK images remain cached. Record the project name, test result, `local images built: none`, and resource-cleanup verification in the linked Gitea issue/PR. -This proves local sanitization logic and event-object handling only. It does not claim a live Sentry/GlitchTip event delivery or rotate any external credential. +This proves local sanitization logic and event/transaction payload handling only. It does not claim a live Sentry/GlitchTip delivery or rotate any external credential. diff --git a/skills/sentry-telemetry-privacy/acceptance.sh b/skills/sentry-telemetry-privacy/acceptance.sh index bb36752..0d841ab 100755 --- a/skills/sentry-telemetry-privacy/acceptance.sh +++ b/skills/sentry-telemetry-privacy/acceptance.sh @@ -7,6 +7,7 @@ project="heimdall-sentry-privacy-${suffix}" temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX") env_file="$temp_dir/acceptance.env" compose_file="$temp_dir/compose.yml" +props_file="$temp_dir/acceptance.props" local_image_tags=() cleanup() { @@ -43,7 +44,7 @@ cleanup() { printf 'Verified recipe image absent: %s\n' "$tag" fi done - rm -f -- "$env_file" "$compose_file" || cleanup_failed=1 + rm -f -- "$env_file" "$compose_file" "$props_file" || cleanup_failed=1 rmdir -- "$temp_dir" || cleanup_failed=1 if ((cleanup_failed)); then printf 'Disposable Sentry privacy acceptance cleanup failed for %s\n' "$project" >&2 @@ -55,15 +56,33 @@ trap cleanup EXIT cat > "$env_file" < "$props_file" <<'EOF' + + + /tmp/$(ACCEPTANCE_PROJECT)/obj/$(MSBuildProjectName)/ + /tmp/$(ACCEPTANCE_PROJECT)/obj/$(MSBuildProjectName)/ + /tmp/$(ACCEPTANCE_PROJECT)/bin/$(MSBuildProjectName)/ + $(DefaultItemExcludes);**/obj/**;**/bin/** + + EOF cat > "$compose_file" <<'EOF' services: focused-tests: image: mcr.microsoft.com/dotnet/sdk:10.0 entrypoint: ["dotnet"] + user: "${ACCEPTANCE_UID}:${ACCEPTANCE_GID}" working_dir: /workspace + environment: + ACCEPTANCE_PROJECT: ${ACCEPTANCE_PROJECT} volumes: - ${REPO_ROOT}:/workspace + - ${ACCEPTANCE_DIR}:/acceptance command: - test - tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj @@ -72,6 +91,7 @@ services: - --verbosity - minimal - -p:RestoreLockedMode=true + - -p:CustomBeforeDirectoryBuildProps=/acceptance/acceptance.props EOF printf 'Disposable project: %s\nLocal images built: none\n' "$project" diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 44a72ab..35832a0 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -825,6 +825,8 @@ public partial class Program sentryEvent.ServerName = null; return SentryTelemetryPrivacy.Sanitize(sentryEvent); }); + options.SetBeforeSendTransaction(static (transaction, _) => + SentryTelemetryPrivacy.Sanitize(transaction)); options.SetBeforeBreadcrumb(breadcrumb => breadcrumb.Category == "Microsoft.AspNetCore.RateLimiting" ? null diff --git a/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs b/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs index 63e7dd8..3467df6 100644 --- a/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs +++ b/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs @@ -11,14 +11,8 @@ internal static class SentryTelemetryPrivacy { ArgumentNullException.ThrowIfNull(sentryEvent); - if (sentryEvent.Request is { } request) - { - RedactStringValues(request.Headers); - request.Cookies = null; - request.Url = StripQueryAndUserInfo(request.Url); - request.QueryString = null; - request.Data = null; - } + SanitizeRequest(sentryEvent.Request); + SanitizeContexts(sentryEvent.Contexts); if (sentryEvent.Extra is IDictionary extra) RedactObjectValues(extra); @@ -26,6 +20,39 @@ internal static class SentryTelemetryPrivacy return sentryEvent; } + internal static SentryTransaction Sanitize(SentryTransaction transaction) + { + ArgumentNullException.ThrowIfNull(transaction); + + SanitizeRequest(transaction.Request); + SanitizeContexts(transaction.Contexts); + RedactObjectValues(transaction.Data, transaction.SetData); + + foreach (var key in transaction.Tags.Keys.ToArray()) + { + if (IsSensitiveName(key)) + transaction.SetTag(key, Redacted); + } + + if (transaction.Breadcrumbs is IList breadcrumbs) + { + for (var index = 0; index < breadcrumbs.Count; index++) + breadcrumbs[index] = SanitizeBreadcrumb(breadcrumbs[index]); + } + + foreach (var span in transaction.Spans) + { + RedactObjectValues(span.Data, span.SetData); + foreach (var key in span.Tags.Keys.ToArray()) + { + if (IsSensitiveName(key)) + span.SetTag(key, Redacted); + } + } + + return transaction; + } + internal static Breadcrumb SanitizeBreadcrumb(Breadcrumb breadcrumb) { ArgumentNullException.ThrowIfNull(breadcrumb); @@ -59,6 +86,34 @@ internal static class SentryTelemetryPrivacy } } + private static void SanitizeRequest(SentryRequest? request) + { + if (request is null) + return; + + RedactStringValues(request.Headers); + request.Cookies = null; + request.Url = StripQueryAndUserInfo(request.Url); + request.QueryString = null; + request.Data = null; + } + + private static void SanitizeContexts(SentryContexts contexts) + { + RedactObjectValues(contexts.Trace.Data, contexts.Trace.SetData); + RedactStringValues(contexts.Response.Headers); + contexts.Response.Cookies = null; + contexts.Response.Data = null; + + foreach (var key in contexts.Keys.ToArray()) + { + if (IsSensitiveName(key)) + contexts[key] = Redacted; + else if (contexts[key] is IDictionary nested) + RedactObjectValues(nested); + } + } + private static void RedactObjectValues(IDictionary values) { foreach (var key in values.Keys.ToArray()) @@ -74,6 +129,23 @@ internal static class SentryTelemetryPrivacy } } + private static void RedactObjectValues( + IReadOnlyDictionary values, + Action setValue) + { + foreach (var key in values.Keys.ToArray()) + { + if (IsSensitiveName(key)) + { + setValue(key, Redacted); + continue; + } + + if (values[key] is IDictionary nested) + RedactObjectValues(nested); + } + } + private static bool IsSensitiveName(string name) { var normalized = name.Replace("-", string.Empty, StringComparison.Ordinal) diff --git a/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs b/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs index 7ed6ead..cdd397f 100644 --- a/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs +++ b/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs @@ -42,7 +42,7 @@ public sealed class SentryTelemetryPrivacyTests Assert.Equal("preserved", sanitized.Extra!["safeValue"]); Assert.Equal("[Filtered]", ((IDictionary)sanitized.Extra["nested"]!)["clientSecret"]); - var serialized = System.Text.Json.JsonSerializer.Serialize(sanitized); + var serialized = SerializeEvent(sanitized); Assert.DoesNotContain(apiKey, serialized, StringComparison.Ordinal); Assert.DoesNotContain(cookie, serialized, StringComparison.Ordinal); Assert.DoesNotContain("SENTINEL_", serialized, StringComparison.Ordinal); @@ -69,4 +69,88 @@ public sealed class SentryTelemetryPrivacyTests Assert.Equal("GET", sanitized.Data["method"]); Assert.DoesNotContain("SENTINEL_", System.Text.Json.JsonSerializer.Serialize(sanitized), StringComparison.Ordinal); } + + [Fact] + public void SanitizeTransaction_RedactsRequestContextsBreadcrumbsTagsAndSpans() + { + using var document = System.Text.Json.JsonDocument.Parse(""" + { + "transaction": "GET /api/agents", + "start_timestamp": "2026-11-13T12:00:00Z", + "request": { + "url": "https://central.example/api/agents?api_key=SENTINEL_TRANSACTION_URL_411", + "query_string": "api_key=SENTINEL_TRANSACTION_QUERY_411", + "headers": { + "Authorization": "SENTINEL_TRANSACTION_AUTH_411", + "Content-Type": "application/json" + }, + "cookies": "session=SENTINEL_TRANSACTION_COOKIE_411", + "data": { "password": "SENTINEL_TRANSACTION_BODY_411" } + }, + "contexts": { + "trace": { "type": "trace", "data": { "api_key": "SENTINEL_TRANSACTION_TRACE_411", "safe": "preserved" } }, + "response": { "type": "response", "cookies": "session=SENTINEL_TRANSACTION_RESPONSE_COOKIE_411", "headers": { "Set-Cookie": "SENTINEL_TRANSACTION_SET_COOKIE_411", "Content-Type": "application/json" }, "data": { "token": "SENTINEL_TRANSACTION_RESPONSE_BODY_411" } }, + "custom": { "clientSecret": "SENTINEL_TRANSACTION_CONTEXT_411", "mode": "safe" } + }, + "breadcrumbs": [ + { "message": "request", "type": "http", "category": "http.client", "data": { "Authorization": "SENTINEL_TRANSACTION_BREADCRUMB_411", "method": "GET" } } + ], + "tags": { "api_key": "SENTINEL_TRANSACTION_TAG_411", "method": "GET" }, + "spans": [ + { "start_timestamp": "2026-11-13T12:00:00Z", "op": "http.client", "description": "GET /health", "data": { "credential": "SENTINEL_TRANSACTION_SPAN_411", "status_code": 200 }, "tags": { "secret": "SENTINEL_TRANSACTION_SPAN_TAG_411", "method": "GET" } } + ] + } + """); + var transaction = SentryTransaction.FromJson(document.RootElement); + + var sanitized = SentryTelemetryPrivacy.Sanitize(transaction); + + Assert.Same(transaction, sanitized); + Assert.Equal("[Filtered]", sanitized.Request.Headers!["Authorization"]); + Assert.Equal("application/json", sanitized.Request.Headers["Content-Type"]); + Assert.Null(sanitized.Request.Cookies); + Assert.Null(sanitized.Request.QueryString); + Assert.Null(sanitized.Request.Data); + Assert.Equal("[Filtered]", sanitized.Contexts.Trace.Data["api_key"]); + Assert.Equal("preserved", sanitized.Contexts.Trace.Data["safe"]); + Assert.Equal("[Filtered]", sanitized.Contexts.Response.Headers["Set-Cookie"]); + Assert.Equal("application/json", sanitized.Contexts.Response.Headers["Content-Type"]); + Assert.Null(sanitized.Contexts.Response.Cookies); + Assert.Null(sanitized.Contexts.Response.Data); + Assert.Equal("[Filtered]", ((IDictionary)sanitized.Contexts["custom"])["clientSecret"]); + Assert.Equal("safe", ((IDictionary)sanitized.Contexts["custom"])["mode"]); + Assert.Equal("[Filtered]", sanitized.Breadcrumbs.Single().Data!["Authorization"]); + Assert.Equal("GET", sanitized.Breadcrumbs.Single().Data!["method"]); + Assert.Equal("[Filtered]", sanitized.Tags["api_key"]); + Assert.Equal("GET", sanitized.Tags["method"]); + Assert.Equal("[Filtered]", sanitized.Spans.Single().Data["credential"]); + Assert.Equal("200", sanitized.Spans.Single().Data["status_code"]?.ToString()); + Assert.Equal("[Filtered]", sanitized.Spans.Single().Tags["secret"]); + Assert.Equal("GET", sanitized.Spans.Single().Tags["method"]); + + var serialized = SerializeTransaction(sanitized); + Assert.DoesNotContain("SENTINEL_", serialized, StringComparison.Ordinal); + } + + private static string SerializeTransaction(SentryTransaction transaction) + { + using var stream = new MemoryStream(); + using (var writer = new System.Text.Json.Utf8JsonWriter(stream)) + { + transaction.WriteTo(writer, null); + } + + return System.Text.Encoding.UTF8.GetString(stream.ToArray()); + } + + private static string SerializeEvent(SentryEvent sentryEvent) + { + using var stream = new MemoryStream(); + using (var writer = new System.Text.Json.Utf8JsonWriter(stream)) + { + sentryEvent.WriteTo(writer, null); + } + + return System.Text.Encoding.UTF8.GetString(stream.ToArray()); + } } -- 2.54.1 From 26c9ae5ebd851bfece086e8792a42d2bf573d30d Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 13 Nov 2026 13:59:27 +0100 Subject: [PATCH 3/5] security: sanitize nested Sentry metadata (#411) --- .../Security/SentryTelemetryPrivacy.cs | 57 +++++++++++++++++-- .../Security/SentryTelemetryPrivacyTests.cs | 22 ++++++- 2 files changed, 72 insertions(+), 7 deletions(-) diff --git a/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs b/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs index 3467df6..7870dd2 100644 --- a/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs +++ b/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs @@ -14,6 +14,12 @@ internal static class SentryTelemetryPrivacy SanitizeRequest(sentryEvent.Request); SanitizeContexts(sentryEvent.Contexts); + foreach (var key in sentryEvent.Tags.Keys.ToArray()) + { + if (IsSensitiveName(key)) + sentryEvent.SetTag(key, Redacted); + } + if (sentryEvent.Extra is IDictionary extra) RedactObjectValues(extra); @@ -107,10 +113,13 @@ internal static class SentryTelemetryPrivacy foreach (var key in contexts.Keys.ToArray()) { + if (key is "trace" or "response") + continue; + if (IsSensitiveName(key)) contexts[key] = Redacted; - else if (contexts[key] is IDictionary nested) - RedactObjectValues(nested); + else + contexts[key] = RedactValue(contexts[key])!; } } @@ -124,8 +133,7 @@ internal static class SentryTelemetryPrivacy continue; } - if (values[key] is IDictionary nested) - RedactObjectValues(nested); + values[key] = RedactValue(values[key]); } } @@ -141,11 +149,48 @@ internal static class SentryTelemetryPrivacy continue; } - if (values[key] is IDictionary nested) - RedactObjectValues(nested); + setValue(key, RedactValue(values[key])!); } } + private static object? RedactValue(object? value) + { + if (value is IDictionary mutableDictionary) + { + RedactObjectValues(mutableDictionary); + return value; + } + + if (value is IReadOnlyDictionary readOnlyDictionary) + { + var sanitized = new Dictionary(StringComparer.Ordinal); + foreach (var pair in readOnlyDictionary) + sanitized[pair.Key] = IsSensitiveName(pair.Key) ? Redacted : RedactValue(pair.Value); + return sanitized; + } + + if (value is System.Collections.IDictionary dictionary) + { + var sanitized = new Dictionary(StringComparer.Ordinal); + foreach (System.Collections.DictionaryEntry entry in dictionary) + { + if (entry.Key is not string key) + return Redacted; + sanitized[key] = IsSensitiveName(key) ? Redacted : RedactValue(entry.Value); + } + return sanitized; + } + + if (value is System.Collections.IEnumerable and not string) + return Redacted; + + // Arbitrary objects may serialize properties containing credentials under unknown names. + // Keep primitive values; discard unsupported object graphs rather than emit them unsanitized. + return value is null or string or bool or byte or sbyte or short or ushort or int or uint or long or ulong or float or double or decimal + ? value + : Redacted; + } + private static bool IsSensitiveName(string name) { var normalized = name.Replace("-", string.Empty, StringComparison.Ordinal) diff --git a/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs b/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs index cdd397f..b680f74 100644 --- a/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs +++ b/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs @@ -24,7 +24,9 @@ public sealed class SentryTelemetryPrivacyTests }, "extra": { "safeValue": "preserved", - "nested": { "clientSecret": "SENTINEL_EXTRA_SECRET_411" } + "nested": { "clientSecret": "SENTINEL_EXTRA_SECRET_411" }, + "array": [ { "accessToken": "SENTINEL_ARRAY_TOKEN_411", "safe": "preserved" } ], + "opaque": { "credential": "SENTINEL_OPAQUE_CREDENTIAL_411" } } } """); @@ -41,6 +43,8 @@ public sealed class SentryTelemetryPrivacyTests Assert.Null(sanitized.Request.Data); Assert.Equal("preserved", sanitized.Extra!["safeValue"]); Assert.Equal("[Filtered]", ((IDictionary)sanitized.Extra["nested"]!)["clientSecret"]); + Assert.Equal("[Filtered]", sanitized.Extra["array"]); + Assert.Equal("[Filtered]", ((IDictionary)sanitized.Extra["opaque"]!)["credential"]); var serialized = SerializeEvent(sanitized); Assert.DoesNotContain(apiKey, serialized, StringComparison.Ordinal); @@ -132,6 +136,22 @@ public sealed class SentryTelemetryPrivacyTests Assert.DoesNotContain("SENTINEL_", serialized, StringComparison.Ordinal); } + [Fact] + public void Sanitize_RedactsSensitiveEventTagsInSdkPayload() + { + using var document = System.Text.Json.JsonDocument.Parse(""" + { "message": "synthetic", "tags": { "api_key": "SENTINEL_EVENT_TAG_411", "method": "GET" } } + """); + var sentryEvent = SentryEvent.FromJson(document.RootElement); + + var sanitized = SentryTelemetryPrivacy.Sanitize(sentryEvent); + + Assert.Equal("[Filtered]", sanitized.Tags["api_key"]); + Assert.Equal("GET", sanitized.Tags["method"]); + var serialized = SerializeEvent(sanitized); + Assert.DoesNotContain("SENTINEL_EVENT_TAG_411", serialized, StringComparison.Ordinal); + } + private static string SerializeTransaction(SentryTransaction transaction) { using var stream = new MemoryStream(); -- 2.54.1 From bc2bff96fb30e15646f0ea012e658e291faee0aa Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 13 Nov 2026 14:09:24 +0100 Subject: [PATCH 4/5] security: sanitize Sentry request environment metadata (#411) --- skills/sentry-telemetry-privacy/SKILL.md | 5 ++++- src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs | 2 ++ .../Security/SentryTelemetryPrivacyTests.cs | 9 ++++++++- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/skills/sentry-telemetry-privacy/SKILL.md b/skills/sentry-telemetry-privacy/SKILL.md index 8e8de9d..61d6f0c 100644 --- a/skills/sentry-telemetry-privacy/SKILL.md +++ b/skills/sentry-telemetry-privacy/SKILL.md @@ -5,7 +5,7 @@ description: Keep Heimdall Sentry events free of authentication material while p # Sentry telemetry privacy -Sentry event and transaction processing are configured in `src/Heimdall.Web/Program.cs`. `SetBeforeSend` and `SetBeforeSendTransaction` are separate SDK callbacks, so apply `SentryTelemetryPrivacy` to both. Before either payload is sent, remove or redact request/response authentication headers, cookies, query strings, bodies, URL user information, and sensitive values in event extras, transaction contexts, tags, spans, and breadcrumbs. Keep the helper in the Web boundary; do not move request telemetry into Domain or Application. +Sentry event and transaction processing are configured in `src/Heimdall.Web/Program.cs`. `SetBeforeSend` and `SetBeforeSendTransaction` are separate SDK callbacks, so apply `SentryTelemetryPrivacy` to both. Before either payload is sent, filter request `Headers`, `Env`, and `Other` maps; remove request/response cookies, query strings, and bodies; strip URL user information; and filter sensitive values in event extras, transaction contexts, tags, spans, and breadcrumbs. Keep the helper in the Web boundary; do not move request telemetry into Domain or Application. When changing this behavior: @@ -13,6 +13,9 @@ When changing this behavior: - Treat header names case-insensitively and normalize common separators before matching names that indicate authorization, API keys, tokens, secrets, passwords, credentials, or cookies. - Clear entire fields such as cookie strings, query strings, and request bodies when selective redaction could miss nested or encoded credentials. Strip URL user information, query, and fragment while retaining the safe path. - Apply the same sensitive-key filtering to event extras and breadcrumbs. Preserve the existing rate-limit breadcrumb filter. +- Recursively inspect string-keyed maps in extras and custom contexts. Replace arrays, other collections, and opaque object graphs with `[Filtered]` instead of allowing uninspected JSON serialization; retain safe primitive values and safe map entries. +- Filter sensitive-name tags on both `SentryEvent` and `SentryTransaction`; sanitize trace custom data, response headers, and span data/tags. +- Include synthetic request `env`/`other`, sensitive event tags, nested maps, arrays, and opaque values in serializer-level tests. - Never copy actual event headers, API keys, cookies, tokens, or request bodies into issue comments, test fixtures, logs, or acceptance evidence. Record only field names and synthetic test outcomes. ## Acceptance diff --git a/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs b/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs index 7870dd2..a273f84 100644 --- a/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs +++ b/src/Heimdall.Web/Security/SentryTelemetryPrivacy.cs @@ -98,6 +98,8 @@ internal static class SentryTelemetryPrivacy return; RedactStringValues(request.Headers); + RedactStringValues(request.Env); + RedactStringValues(request.Other); request.Cookies = null; request.Url = StripQueryAndUserInfo(request.Url); request.QueryString = null; diff --git a/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs b/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs index b680f74..4e12ff5 100644 --- a/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs +++ b/tests/Heimdall.Web.Tests/Security/SentryTelemetryPrivacyTests.cs @@ -19,6 +19,8 @@ public sealed class SentryTelemetryPrivacyTests "x-api-key": "{{apiKey}}", "Content-Type": "application/json" }, + "env": { "AUTHORIZATION": "SENTINEL_ENV_AUTH_411", "REMOTE_ADDR": "192.0.2.1" }, + "other": { "access_token": "SENTINEL_OTHER_TOKEN_411", "safe": "preserved" }, "cookies": "session={{cookie}}", "data": { "access_token": "SENTINEL_BODY_TOKEN_411" } }, @@ -37,6 +39,10 @@ public sealed class SentryTelemetryPrivacyTests Assert.Same(sentryEvent, sanitized); Assert.Equal("[Filtered]", sanitized.Request!.Headers!["x-api-key"]); Assert.Equal("application/json", sanitized.Request.Headers["Content-Type"]); + Assert.Equal("[Filtered]", sanitized.Request.Env!["AUTHORIZATION"]); + Assert.Equal("192.0.2.1", sanitized.Request.Env["REMOTE_ADDR"]); + Assert.Equal("[Filtered]", sanitized.Request.Other!["access_token"]); + Assert.Equal("preserved", sanitized.Request.Other["safe"]); Assert.Null(sanitized.Request.Cookies); Assert.Equal("https://central.example/api/agents", sanitized.Request.Url); Assert.Null(sanitized.Request.QueryString); @@ -94,7 +100,7 @@ public sealed class SentryTelemetryPrivacyTests "contexts": { "trace": { "type": "trace", "data": { "api_key": "SENTINEL_TRANSACTION_TRACE_411", "safe": "preserved" } }, "response": { "type": "response", "cookies": "session=SENTINEL_TRANSACTION_RESPONSE_COOKIE_411", "headers": { "Set-Cookie": "SENTINEL_TRANSACTION_SET_COOKIE_411", "Content-Type": "application/json" }, "data": { "token": "SENTINEL_TRANSACTION_RESPONSE_BODY_411" } }, - "custom": { "clientSecret": "SENTINEL_TRANSACTION_CONTEXT_411", "mode": "safe" } + "custom": { "clientSecret": "SENTINEL_TRANSACTION_CONTEXT_411", "mode": "safe", "metadata": [ { "token": "SENTINEL_CONTEXT_ARRAY_411" } ] } }, "breadcrumbs": [ { "message": "request", "type": "http", "category": "http.client", "data": { "Authorization": "SENTINEL_TRANSACTION_BREADCRUMB_411", "method": "GET" } } @@ -123,6 +129,7 @@ public sealed class SentryTelemetryPrivacyTests Assert.Null(sanitized.Contexts.Response.Data); Assert.Equal("[Filtered]", ((IDictionary)sanitized.Contexts["custom"])["clientSecret"]); Assert.Equal("safe", ((IDictionary)sanitized.Contexts["custom"])["mode"]); + Assert.Equal("[Filtered]", ((IDictionary)sanitized.Contexts["custom"])["metadata"]); Assert.Equal("[Filtered]", sanitized.Breadcrumbs.Single().Data!["Authorization"]); Assert.Equal("GET", sanitized.Breadcrumbs.Single().Data!["method"]); Assert.Equal("[Filtered]", sanitized.Tags["api_key"]); -- 2.54.1 From 6da1fe4d675f46b1559c758579975f5479c01397 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 13 Nov 2026 14:22:14 +0100 Subject: [PATCH 5/5] test: make Sentry acceptance cleanup resilient (#411) --- skills/sentry-telemetry-privacy/SKILL.md | 2 +- skills/sentry-telemetry-privacy/acceptance.sh | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/skills/sentry-telemetry-privacy/SKILL.md b/skills/sentry-telemetry-privacy/SKILL.md index 61d6f0c..33a3782 100644 --- a/skills/sentry-telemetry-privacy/SKILL.md +++ b/skills/sentry-telemetry-privacy/SKILL.md @@ -20,6 +20,6 @@ When changing this behavior: ## Acceptance -Run `skills/sentry-telemetry-privacy/acceptance.sh`. The recipe runs the focused .NET test from the current checkout in a uniquely named disposable Compose project using the upstream .NET SDK image. It publishes no ports, creates no application image, uses no deployed configuration, and removes and verifies the project's containers, volumes, and network. Upstream SDK images remain cached. Record the project name, test result, `local images built: none`, and resource-cleanup verification in the linked Gitea issue/PR. +Run `skills/sentry-telemetry-privacy/acceptance.sh`. The recipe runs the focused .NET test from the current checkout in a uniquely named disposable Compose project using the upstream .NET SDK image. It publishes no ports, creates no application image, uses no deployed configuration, and removes and verifies the project's containers, volumes, and network. Its `EXIT` trap disables inherited `errexit`/`nounset` while attempting each independent cleanup step, preserves the original test status, and reports cleanup failures. Upstream SDK images remain cached. Record the project name, test result, `local images built: none`, and resource-cleanup verification in the linked Gitea issue/PR. This proves local sanitization logic and event/transaction payload handling only. It does not claim a live Sentry/GlitchTip delivery or rotate any external credential. diff --git a/skills/sentry-telemetry-privacy/acceptance.sh b/skills/sentry-telemetry-privacy/acceptance.sh index 0d841ab..9d98a7a 100755 --- a/skills/sentry-telemetry-privacy/acceptance.sh +++ b/skills/sentry-telemetry-privacy/acceptance.sh @@ -13,6 +13,10 @@ local_image_tags=() cleanup() { status=$? trap - EXIT + # Cleanup must continue through every independent resource even when the + # caller enabled errexit/nounset or an earlier Docker query failed. + set +e + set +u cleanup_failed=0 docker compose --project-directory "$repo_root" --env-file "$env_file" \ -f "$compose_file" -p "$project" down --volumes --remove-orphans || cleanup_failed=1 -- 2.54.1