security: redact Sentry request credentials (#411)
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Successful in 19m42s
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 15m43s
Heimdall Gitea / Publish versioned installer release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 2s

This commit is contained in:
arnaud.dartois committed 2026-11-13 13:12:54 +01:00
1 parent 04b3279d1f
commit 05dbcbdc69
5 files changed
+289 -8

No files matched your search

+22
View File
@@ -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.
+81
View File
@@ -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:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&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" <<EOF
REPO_ROOT=$repo_root
EOF
cat > "$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
+3 -8
View File
@@ -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<string, object?>)?.Remove("password");
if (sentryEvent.Extra?.ContainsKey("token") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("token");
if (sentryEvent.Extra?.ContainsKey("secret") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.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)
@@ -0,0 +1,111 @@
using Sentry;
namespace Heimdall.Web.Security;
/// <summary>Removes authentication material from request data before error telemetry is sent.</summary>
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<string, object?> extra)
RedactObjectValues(extra);
return sentryEvent;
}
internal static Breadcrumb SanitizeBreadcrumb(Breadcrumb breadcrumb)
{
ArgumentNullException.ThrowIfNull(breadcrumb);
if (breadcrumb.Data is IDictionary<string, string> 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<string, string>? values)
{
if (values is null)
return;
foreach (var key in values.Keys.ToArray())
{
if (IsSensitiveName(key))
values[key] = Redacted;
}
}
private static void RedactObjectValues(IDictionary<string, object?> values)
{
foreach (var key in values.Keys.ToArray())
{
if (IsSensitiveName(key))
{
values[key] = Redacted;
continue;
}
if (values[key] is IDictionary<string, object?> 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;
}
}
@@ -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<string, object?>)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<string, string>
{
["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);
}
}