Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions src/Sentry/Breadcrumb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ public sealed class Breadcrumb : ISentryJsonSerializable
private readonly IReadOnlyDictionary<string, string>? _data;
private readonly string? _message;

private bool _sendDefaultPii = true;
internal void Redact() => _sendDefaultPii = false;
private bool _redacted;
internal void Redact() => _redacted = true;

/// <summary>
/// A timestamp representing when the breadcrumb occurred.
Expand All @@ -30,7 +30,7 @@ public sealed class Breadcrumb : ISentryJsonSerializable
/// </summary>
public string? Message
{
get => _sendDefaultPii ? _message : _message?.RedactUrl();
get => _redacted ? _message?.RedactUrl() : _message;
private init => _message = value;
}

Expand All @@ -52,12 +52,12 @@ public string? Message
/// </remarks>
public IReadOnlyDictionary<string, string>? Data
{
get => _sendDefaultPii
? _data
: _data?.ToDictionary(
get => _redacted
? _data?.ToDictionary(
x => x.Key,
x => x.Value.RedactUrl()
)
: _data
;
private init => _data = value;
}
Expand Down
14 changes: 11 additions & 3 deletions src/Sentry/HttpHeadersExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@ namespace Sentry;

internal static class HttpHeadersExtensions
{
internal static string GetCookies(this HttpHeaders headers) =>
internal static string? GetCookies(this HttpHeaders headers, KeyValueCollectionBehavior? behavior = null) =>
headers.TryGetValues("Cookie", out var values)
? CookieFilter.ToEventCookies(CookieFilter.FilterCookieHeaders(values))
: string.Empty;
? ToEventCookies(CookieFilter.FilterCookieHeaders(values, behavior))
: null;

internal static string? GetSetCookies(this HttpHeaders headers, KeyValueCollectionBehavior? behavior = null) =>
headers.TryGetValues("Set-Cookie", out var values)
? ToEventCookies(CookieFilter.FilterSetCookieHeaders(values, behavior))
: null;

private static string? ToEventCookies(string[] cookies) =>
cookies.Length > 0 ? CookieFilter.ToEventCookies(cookies) : null;

internal static RedactedHeaders? ToRedactedHeaders(this Dictionary<string, string?>? headers)
{
Expand Down
19 changes: 19 additions & 0 deletions src/Sentry/Internal/DataCollection/CookieFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,25 @@
internal static string[] FilterCookieHeaders(IEnumerable<string?> headers, KeyValueCollectionBehavior? behavior = null) =>
headers.SelectMany(header => FilterCookieHeader(header, behavior)).ToArray();

internal static string[] FilterSetCookieHeader(string? header, KeyValueCollectionBehavior? behavior = null)
{
behavior ??= KeyValueCollectionBehavior.DenyList();
if (behavior.Mode == KeyValueCollectionMode.Off || string.IsNullOrWhiteSpace(header))
{
return [];
}

var attributesStart = header.IndexOf(';');
var cookie = (attributesStart < 0 ? header : header[..attributesStart]).Trim();

Check warning on line 47 in src/Sentry/Internal/DataCollection/CookieFilter.cs

View workflow job for this annotation

GitHub Actions / Mutation Testing

Mutant not caught

Equality mutation (Survived): attributesStart <= 0
var separator = cookie.IndexOf('=');
var name = separator < 0 ? null : cookie[..separator].TrimEnd();

Check warning on line 49 in src/Sentry/Internal/DataCollection/CookieFilter.cs

View workflow job for this annotation

GitHub Actions / Mutation Testing

Mutant not caught

Equality mutation (Survived): separator <= 0
var value = separator < 0 ? cookie : cookie[(separator + 1)..].TrimStart();

Check warning on line 50 in src/Sentry/Internal/DataCollection/CookieFilter.cs

View workflow job for this annotation

GitHub Actions / Mutation Testing

Mutant not caught

Equality mutation (Survived): separator <= 0

Check warning on line 50 in src/Sentry/Internal/DataCollection/CookieFilter.cs

View workflow job for this annotation

GitHub Actions / Mutation Testing

Mutant not caught

Conditional (false) mutation (Survived): (false?cookie :cookie[(separator + 1)..].TrimStart())
return [FilterPair(name, value, behavior)];
}

internal static string[] FilterSetCookieHeaders(IEnumerable<string?> headers, KeyValueCollectionBehavior? behavior = null) =>
headers.SelectMany(header => FilterSetCookieHeader(header, behavior)).ToArray();

internal static string[] FilterCookiePairs(IEnumerable<KeyValuePair<string?, string?>> cookies, KeyValueCollectionBehavior? behavior = null)
{
behavior ??= KeyValueCollectionBehavior.DenyList();
Expand Down
20 changes: 17 additions & 3 deletions src/Sentry/Internal/DataCollection/QueryStringFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,22 @@
internal static class QueryStringFilter
{
private static readonly char[] QueryOrFragmentStart = ['?', '#'];
private static readonly KeyValueCollectionBehavior DefaultBehavior = KeyValueCollectionBehavior.DenyList();

// Works on the raw string because the spec requires encoded parameters to be stored exactly as they appear in the URL.
internal static string? Filter(string? queryString)
internal static string? Filter(string? queryString, KeyValueCollectionBehavior? behavior = null)
{
if (string.IsNullOrEmpty(queryString))
{
return queryString;
}

behavior ??= DefaultBehavior;
if (behavior.Mode == KeyValueCollectionMode.Off)
{
return null;
}

var prefix = queryString[0] == '?' ? "?" : string.Empty;
var parameters = queryString[prefix.Length..].Split('&');
var filtered = false;
Expand All @@ -25,9 +32,16 @@
return prefix + SensitiveDataFilter.FilteredValue;
}

if (separator >= 0 && SensitiveDataFilter.IsSensitiveKey(SensitiveDataFilter.DecodeKeyForMatching(name)))
if (separator < 0)

Check warning on line 35 in src/Sentry/Internal/DataCollection/QueryStringFilter.cs

View workflow job for this annotation

GitHub Actions / Mutation Testing

Mutant not caught

Equality mutation (Survived): separator <= 0
{
continue;
}

var value = parameter[(separator + 1)..];
var filteredValue = SensitiveDataFilter.FilterValue(SensitiveDataFilter.DecodeKeyForMatching(name), value, behavior);
if (!ReferenceEquals(filteredValue, value))
{
parameters[i] = $"{name}={SensitiveDataFilter.FilteredValue}";
parameters[i] = $"{name}={filteredValue}";
filtered = true;
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/Sentry/Internal/DataCollection/SensitiveDataFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ internal static class SensitiveDataFilter
internal static string FilterHeaderValue(string name, string value) =>
IsSensitiveKey(name) || IsCookieHeader(name) ? FilteredValue : value;

internal static string FilterHeaderValue(string name, string value, KeyValueCollectionBehavior behavior) =>
IsCookieHeader(name) ? FilteredValue : FilterValue(name, value, behavior);

// Exact match, because a "cookie" denylist term would also filter names such as X-Cookie-Debug
private static bool IsCookieHeader(string name) =>
name.Equals("Cookie", StringComparison.OrdinalIgnoreCase) ||
Expand Down
21 changes: 21 additions & 0 deletions src/Sentry/Internal/DataCollectionResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,29 @@ internal sealed class DataCollectionResolver(SentryOptions options)

public KeyValueCollectionBehavior ResponseHeaders => Configured?.HttpHeaders.Response ?? DenyList;

/// <summary>
/// Temporary bridge for call sites that only sent headers with <c>SendDefaultPii</c>; remove with it, see
/// https://github.com/getsentry/sentry-dotnet/issues/5439
/// </summary>
public KeyValueCollectionBehavior RequestHeadersWithLegacyPiiGate =>
Configured?.HttpHeaders.Request ?? (SendDefaultPii ? DenyList : Off);

/// <summary>
/// Temporary bridge for call sites that only sent headers with <c>SendDefaultPii</c>; remove with it, see
/// https://github.com/getsentry/sentry-dotnet/issues/5439
/// </summary>
public KeyValueCollectionBehavior ResponseHeadersWithLegacyPiiGate =>
Configured?.HttpHeaders.Response ?? (SendDefaultPii ? DenyList : Off);

public KeyValueCollectionBehavior UrlQueryParams => Configured?.UrlQueryParams ?? DenyList;

/// <summary>
/// Temporary bridge for call sites that only sent the URL fragment with <c>SendDefaultPii</c>; remove with it, see
/// https://github.com/getsentry/sentry-dotnet/issues/5439
/// </summary>
public KeyValueCollectionBehavior UrlFragmentWithLegacyPiiGate =>
Configured?.UrlQueryParams ?? (SendDefaultPii ? DenyList : Off);
Comment thread
jamescrosswell marked this conversation as resolved.
Resolved

public bool IncomingRequestBody => CollectsBody(HttpBodyTypes.IncomingRequest, legacyFallback: true);

public bool OutgoingRequestBody => CollectsBody(HttpBodyTypes.OutgoingRequest, SendDefaultPii);
Expand Down
12 changes: 9 additions & 3 deletions src/Sentry/Internal/Extensions/UriExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@ namespace Sentry.Internal.Extensions;

internal static class UriExtensions
{
public static string FilteredHttpRequestUrl(this Uri uri)
public static string FilteredHttpRequestUrl(this Uri uri, KeyValueCollectionBehavior? behavior = null)
{
// This is a safe way to get the HttpRequestUrl, even when DisablePathAndQueryCanonicalization is true
// See https://github.com/getsentry/sentry-dotnet/issues/3387
var safeUri = new UriBuilder(uri).Uri;
return safeUri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped)
+ QueryStringFilter.Filter(safeUri.Query);
return safeUri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.SafeUnescaped)
+ QueryStringFilter.Filter(safeUri.Query, behavior);
}

public static string? HttpRequestFragment(this Uri uri)
{
var fragment = new UriBuilder(uri).Fragment;
return fragment.Length > 1 ? fragment[1..] : null;
}
}
40 changes: 7 additions & 33 deletions src/Sentry/Internal/PiiExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,21 @@
internal static class PiiExtensions
{
internal const string RedactedText = "[Filtered]";
private static readonly Regex AuthRegex = new(@"(?i)\b(https?://.*@.*)\b", RegexOptions.Compiled);
private static readonly Regex UserInfoMatcher = new(@"^(?i)(https?://)(.*@)(.*)$", RegexOptions.Compiled);

// Userinfo ends at the last '@' before the path, query or fragment, as sentry-python parses it
private static readonly Regex UserInfoRegex = new(@"(?i)\b(https?://)([^\s/?#]*)@", RegexOptions.Compiled);

/// <summary>
/// Searches for URLs in text data and redacts any PII data from these, as required.
/// Replaces the userinfo (credentials) of any http or https URLs in <paramref name="data"/> with a placeholder.
/// </summary>
/// <param name="data">The data to be searched</param>
/// <returns>
/// The data, if no PII data is present or a copy of the data with PII data redacted otherwise
/// </returns>
public static string RedactUrl(this string data)
{
// If the data is empty then we don't need to redact anything
if (string.IsNullOrWhiteSpace(data))
if (string.IsNullOrWhiteSpace(data) || data.IndexOf('@') < 0)

Check warning on line 19 in src/Sentry/Internal/PiiExtensions.cs

View workflow job for this annotation

GitHub Actions / Mutation Testing

Mutant not caught

Equality mutation (Survived): data.IndexOf('@') <= 0
{
return data;
}

// The pattern @"(?i)\b(https?://.*@.*)\b" uses the \b word boundary anchors to ensure that the match occurs at
// a word boundary. This allows the URL to be matched even if it is part of a larger text. The (?i) flag ensures
// case-insensitive matching for "https" or "http".
var result = AuthRegex.Replace(data, match =>
{
var matchedUrl = match.Groups[1].Value;
return RedactAuth(matchedUrl);
});

return result;
}

private static string RedactAuth(string data)
{
// ^ matches the start of the string. (?i)(https?://) gives a case-insensitive matching of the protocol.
// (.*@) matches the username and password (authentication information). (.*)$ matches the rest of the URL.
var match = UserInfoMatcher.Match(data);
if (match is not { Success: true, Groups.Count: 4 })
{
return data;
}
var userInfoString = match.Groups[2].Value;
var replacementString = userInfoString.Contains(":") ? "[Filtered]:[Filtered]@" : "[Filtered]@";
return match.Groups[1].Value + replacementString + match.Groups[3].Value;
return UserInfoRegex.Replace(data, match =>
match.Groups[1].Value + (match.Groups[2].Value.Contains(":") ? "[Filtered]:[Filtered]@" : "[Filtered]@"));
}
}
13 changes: 11 additions & 2 deletions src/Sentry/Protocol/Response.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,20 @@ public sealed class Response : ISentryJsonSerializable, ICloneable<Response>, IU
/// <value>The HTTP method.</value>
public short? StatusCode { get; set; }

internal void AddHeaders(IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers)
internal void AddHeaders(IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers,
KeyValueCollectionBehavior? behavior = null)
{
if (behavior?.Mode == KeyValueCollectionMode.Off)
{
return;
}

foreach (var header in headers)
{
Headers.Add(header.Key, SensitiveDataFilter.FilterHeaderValue(header.Key, string.Join("; ", header.Value)));
var value = string.Join("; ", header.Value);
Headers.Add(header.Key, behavior is null
? SensitiveDataFilter.FilterHeaderValue(header.Key, value)
: SensitiveDataFilter.FilterHeaderValue(header.Key, value, behavior));
}
}

Expand Down
25 changes: 10 additions & 15 deletions src/Sentry/SentryHttpFailedRequestHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,23 @@ protected internal override void DoEnsureSuccessfulResponse([NotNull] HttpReques
var @event = new SentryEvent(exception);
var hint = new SentryHint(HintTypes.HttpResponseMessage, response);

var dataCollection = Options.DataCollectionResolver;
var queryParams = dataCollection.UrlQueryParams;
var uri = response.RequestMessage?.RequestUri;
var sentryRequest = new SentryRequest
{
QueryString = QueryStringFilter.Filter(uri?.Query),
Method = response.RequestMessage?.Method.Method.ToUpperInvariant()
Url = uri?.FilteredHttpRequestUrl(queryParams),
QueryString = QueryStringFilter.Filter(uri?.Query, queryParams),
Fragment = QueryStringFilter.Filter(uri?.HttpRequestFragment(), dataCollection.UrlFragmentWithLegacyPiiGate),
Method = response.RequestMessage?.Method.Method.ToUpperInvariant(),
Cookies = request.Headers.GetCookies(dataCollection.Cookies)
};
sentryRequest.AddHeaders(request.Headers, dataCollection.RequestHeadersWithLegacyPiiGate);

var responseContext = new Response
{
StatusCode = (short)response.StatusCode,
Cookies = response.Headers.GetSetCookies(dataCollection.Cookies),
#if NET5_0_OR_GREATER
// Starting with .NET 5, the content and headers are guaranteed to not be null.
BodySize = response.Content.Headers.ContentLength
Expand All @@ -78,19 +85,7 @@ protected internal override void DoEnsureSuccessfulResponse([NotNull] HttpReques
BodySize = response.Content?.Headers?.ContentLength
#endif
};

if (!Options.SendDefaultPii)
{
sentryRequest.Url = uri?.FilteredHttpRequestUrl();
}
else
{
sentryRequest.Url = QueryStringFilter.FilterUrl(uri?.AbsoluteUri);
sentryRequest.Cookies = request.Headers.GetCookies();
sentryRequest.AddHeaders(request.Headers);
responseContext.Cookies = response.Headers.GetCookies();
responseContext.AddHeaders(response.Headers);
}
responseContext.AddHeaders(response.Headers, dataCollection.ResponseHeadersWithLegacyPiiGate);

@event.Request = sentryRequest;
@event.Contexts[Response.Type] = responseContext;
Expand Down
15 changes: 9 additions & 6 deletions src/Sentry/SentryMessageHandler.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Sentry.Extensibility;
using Sentry.Internal;
using Sentry.Internal.Extensions;

namespace Sentry;
Expand Down Expand Up @@ -62,7 +63,7 @@ internal SentryMessageHandler(IHub? hub, SentryOptions? options, HttpMessageHand
/// </summary>
/// <param name="request">The <see cref="HttpRequestMessage"/></param>
/// <param name="method">The request method (e.g. "GET")</param>
/// <param name="url">The request URL</param>
/// <param name="url">The request URL, with any credentials redacted</param>
/// <returns>An <see cref="ISpan"/></returns>
protected internal abstract ISpan? ProcessRequest(HttpRequestMessage request, string method, string url);

Expand All @@ -72,7 +73,7 @@ internal SentryMessageHandler(IHub? hub, SentryOptions? options, HttpMessageHand
/// <param name="response">The <see cref="HttpResponseMessage"/></param>
/// <param name="span">The <see cref="ISpan"/> created in <see cref="ProcessRequest"/></param>
/// <param name="method">The request method (e.g. "GET")</param>
/// <param name="url">The request URL</param>
/// <param name="url">The request URL, with any credentials redacted</param>
protected internal abstract void HandleResponse(HttpResponseMessage response, ISpan? span, string method, string url);

/// <inheritdoc />
Expand All @@ -82,13 +83,14 @@ protected override async Task<HttpResponseMessage> SendAsync(
{
var method = request.Method.Method.ToUpperInvariant();
var url = request.RequestUri?.ToString() ?? string.Empty;
var redactedUrl = url.RedactUrl();

var span = ProcessRequest(request, method, url);
var span = ProcessRequest(request, method, redactedUrl);
try
{
PropagateTraceHeaders(request, url, span);
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
HandleResponse(response, span, method, url);
HandleResponse(response, span, method, redactedUrl);
return response;
}
catch (Exception ex)
Expand All @@ -104,13 +106,14 @@ protected override HttpResponseMessage Send(HttpRequestMessage request, Cancella
{
var method = request.Method.Method.ToUpperInvariant();
var url = request.RequestUri?.ToString() ?? string.Empty;
var redactedUrl = url.RedactUrl();

var span = ProcessRequest(request, method, url);
var span = ProcessRequest(request, method, redactedUrl);
try
{
PropagateTraceHeaders(request, url, span);
var response = base.Send(request, cancellationToken);
HandleResponse(response, span, method, url);
HandleResponse(response, span, method, redactedUrl);
return response;
}
catch (Exception ex)
Expand Down
Loading
Loading