Path: redb-route/redb.Route/Abstractions/EndpointUri.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Abstractions/EndpointUri.cs ---- using System.Text; using System.Text.RegularExpressions; namespace redb.Route.Abstractions; /// /// Parsed endpoint URI. Immutable record with normalized cache key. /// Created by EndpointUriParser — the single URI parser for the entire framework. /// /// URI scheme (e.g., "kafka", "rabbitmq", "redis", "direct"). /// Path part (e.g., "orders", "GET:user:123", "my-topic"). /// Cache key: "{scheme}://{path}" without query parameters. /// Query string parameters as raw strings before type conversion. public sealed record EndpointUri( string Scheme, string Path, string NormalizedKey, IReadOnlyDictionary RawParameters) { /// Constant emitted in place of a redacted secret value. public const string Redacted = "****"; /// /// Cache key without query parameters: scheme://path. /// Used by in-process transports (Direct, SEDA) where consumer and producer /// must share the same endpoint regardless of per-side options. /// public string BaseKey => $"{Scheme}://{Path}"; /// public override string ToString() => ToMaskedUriString(); /// /// Reconstructs the full URI string including scheme, path, and all query parameters. /// Example: seda:order-queue?concurrentConsumers=4&size=1000 /// public string ToUriString() { if (RawParameters.Count == 0) return $"{Scheme}:{Path}"; var sb = new StringBuilder(); sb.Append(Scheme); sb.Append(':'); sb.Append(Path); var sep = '?'; foreach (var (key, value) in RawParameters) { sb.Append(sep); sb.Append(Uri.EscapeDataString(key)); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); sep = '&'; } return sb.ToString(); } // --- Secret detection ------------------------------------------------ // Substring keywords (case-insensitive). A parameter name is treated as a // secret if it CONTAINS any of these. Deliberately avoids bare "key"/"pass" // so benign params (routingKey, partitionKey, ...) are never over-masked; // "password" already covers bindPassword/sslKeyPassword/proxyPassword/etc. private static readonly string[] SensitiveKeywords = { "password", "passphrase", "pwd", "secret", "token", "apikey", "accesskey", "credential", "connectionstring", "privatekey", "authorization", "bearer", "sasljaasconfig" }; // Connector-registered extra names (copy-on-write; read via a stable snapshot). private static volatile HashSet _extraSensitiveKeys = new(StringComparer.OrdinalIgnoreCase); /// /// Registers additional query-parameter names that must be masked in logs and /// telemetry (analogous to Camel's addSanitizeKeywords). Case-insensitive. /// Intended to be called once at startup by connector registration. /// public static void AddSensitiveKeys(params string[] keys) { if (keys is null || keys.Length == 0) return; var copy = new HashSet(_extraSensitiveKeys, StringComparer.OrdinalIgnoreCase); foreach (var k in keys) if (!string.IsNullOrWhiteSpace(k)) copy.Add(k.Trim()); _extraSensitiveKeys = copy; } /// Returns true if a query-parameter name should be masked. public static bool IsSensitiveKey(string key) { if (string.IsNullOrEmpty(key)) return false; if (_extraSensitiveKeys.Contains(key)) return true; foreach (var kw in SensitiveKeywords) if (key.Contains(kw, StringComparison.OrdinalIgnoreCase)) return true; return false; } // Masks the password segment of a "user:password@host..." authority/path. // Anchored at start so only the leading userinfo (authority position) matches; // a bare "host:port/seg@x" (no ':' before '@' within the authority) is left as-is. private static readonly Regex PathUserInfoPassword = new(@"^([^/@:]*:)([^/@]*)@", RegexOptions.Compiled); /// /// Masks the password in userinfo of a scheme-less path/authority /// (user:password@host → user:****@host). Returns the input /// unchanged when there is no userinfo password. /// public static string MaskUserInfoPassword(string pathOrAuthority) { if (string.IsNullOrEmpty(pathOrAuthority) || pathOrAuthority.IndexOf('@') < 0) return pathOrAuthority; return PathUserInfoPassword.Replace(pathOrAuthority, m => m.Groups[1].Value + Redacted + "@"); } /// /// Format-preserving redaction of a raw endpoint URI string. Keeps scheme, /// separator (:// vs :), path, parameter names, order, and every /// non-secret value byte-for-byte; replaces sensitive query-parameter values and /// the userinfo password with . Never throws. /// Use this at every logging / telemetry / DTO boundary that would otherwise emit /// a raw URI (Camel URISupport.sanitizeUri equivalent). /// public static string Sanitize(string? rawUri) { if (string.IsNullOrEmpty(rawUri)) return rawUri ?? string.Empty; var queryIndex = rawUri.IndexOf('?'); var basePart = queryIndex >= 0 ? rawUri[..queryIndex] : rawUri; var queryPart = queryIndex >= 0 ? rawUri[(queryIndex + 1)..] : null; // Mask userinfo password in the authority (only for scheme://authority form). var doubleSlash = basePart.IndexOf("://", StringComparison.Ordinal); if (doubleSlash > 0) { var head = basePart[..(doubleSlash + 3)]; var rest = basePart[(doubleSlash + 3)..]; basePart = head + MaskUserInfoPassword(rest); } if (queryPart is null) return basePart; var pairs = queryPart.Split('&'); for (var i = 0; i < pairs.Length; i++) { var pair = pairs[i]; var eq = pair.IndexOf('='); if (eq <= 0) continue; var rawKey = pair[..eq]; // Key may be URL-encoded; decode only for the sensitivity test. var key = Uri.UnescapeDataString(rawKey); if (IsSensitiveKey(key)) pairs[i] = rawKey + "=" + Redacted; } return basePart + "?" + string.Join("&", pairs); } /// The length up to which keeps a URI whole. public const int LogLength = 120; /// /// The short log form of a raw endpoint URI: d, and when longer than , /// cut at the last parameter boundary (? or &) that keeps at least half of it, or else at the length, /// never inside a value, followed by ... [+N chars #hash]. The hash is the first eight /// hex digits of the SHA-256 of the whole sanitized URI, so two endpoints that share a long prefix still read apart. /// public static string ForLog(string? rawUri) { var full = Sanitize(rawUri); if (full.Length <= LogLength) return full; var cut = full.LastIndexOfAny(['?', '&'], LogLength); if (cut < LogLength / 2) cut = LogLength; // A cut inside a masked value would show part of the mask, as if the secret were cut: keep the mask whole. for (var start = full.IndexOf(Redacted, StringComparison.Ordinal); start >= 0 && start < cut; start = full.IndexOf(Redacted, start + 1, StringComparison.Ordinal)) { if (start + Redacted.Length > cut) { cut = start + Redacted.Length; break; } } var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(full)))[..8].ToLowerInvariant(); return $"{full[..cut]}... [+{full.Length - cut} chars #{hash}]"; } /// /// An endpoint URI or name for an Information line of : the short form of /// , or the whole d URI on the same line when the logger has Debug /// on. Start and stop lines of the engine and the connectors use it. /// public static string ForLog(string? rawUri, Microsoft.Extensions.Logging.ILogger? logger) => logger?.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug) == true ? Sanitize(rawUri) : ForLog(rawUri); /// /// Redacts key=value secret assignments inside arbitrary text — connection strings /// (...;Password=p;...), query fragments, and driver exception messages that may embed /// either. Only the value of a key considered sensitive by is /// replaced, and the password of a URI quoted in the text (amqp://user:password@host); /// everything else is preserved verbatim. Never throws. /// /// Use this as the backstop for text that is not a parseable endpoint URI. Note that logging an /// object itself cannot be scrubbed in-process (the formatter renders /// ToString()); wire this into a logging-sink filter for that case. /// /// public static string RedactSecrets(string? text) { if (string.IsNullOrEmpty(text)) return string.Empty; // A URI quoted in the text may carry a password in its userinfo (amqp://user:password@host). text = RedactUserInfoPasswords(text); if (text.IndexOf('=') < 0) return text; var sb = new StringBuilder(text.Length); var i = 0; while (i < text.Length) { var eq = text.IndexOf('=', i); if (eq < 0) { sb.Append(text, i, text.Length - i); break; } // The key is the run of identifier-ish characters immediately before '='. var keyStart = eq; while (keyStart > i && IsKeyChar(text[keyStart - 1])) keyStart--; var key = text[keyStart..eq]; // The value runs to the next separator (connection-string ';', query '&', quote, space). var valueStart = eq + 1; var valueEnd = valueStart; while (valueEnd < text.Length && !IsValueDelimiter(text[valueEnd])) valueEnd++; sb.Append(text, i, eq - i + 1); // everything up to and including '=' if (valueEnd > valueStart && key.Length > 0 && IsSensitiveKey(key)) sb.Append(Redacted); else sb.Append(text, valueStart, valueEnd - valueStart); i = valueEnd; } return sb.ToString(); } /// /// Masks the password of every scheme://user:password@host in : the authority after /// :// runs to the next /, ?, #, quote or white space, and its userinfo (before the last /// @) keeps the user and loses what follows the first :. /// private static string RedactUserInfoPasswords(string text) { var marker = text.IndexOf("://", StringComparison.Ordinal); if (marker < 0) return text; var sb = new StringBuilder(text.Length); var i = 0; while (marker >= 0) { var authorityStart = marker + 3; var authorityEnd = authorityStart; while (authorityEnd < text.Length && !IsAuthorityEnd(text[authorityEnd])) authorityEnd++; sb.Append(text, i, authorityStart - i); var at = text.LastIndexOf('@', authorityEnd - 1, authorityEnd - authorityStart); var colon = at > authorityStart ? text.IndexOf(':', authorityStart, at - authorityStart) : -1; if (colon >= 0) { sb.Append(text, authorityStart, colon - authorityStart + 1); sb.Append(Redacted); sb.Append(text, at, authorityEnd - at); } else { sb.Append(text, authorityStart, authorityEnd - authorityStart); } i = authorityEnd; marker = authorityEnd < text.Length ? text.IndexOf("://", authorityEnd, StringComparison.Ordinal) : -1; } sb.Append(text, i, text.Length - i); return sb.ToString(); } private static bool IsAuthorityEnd(char c) => c is '/' or '?' or '#' or ';' or '"' or '\'' || char.IsWhiteSpace(c); private static bool IsKeyChar(char c) => char.IsLetterOrDigit(c) || c is '_' or '.' or '-'; private static bool IsValueDelimiter(char c) => c is ';' or '&' or '"' or '\'' || char.IsWhiteSpace(c); /// /// Reconstructs the URI with sensitive parameters and userinfo passwords masked. /// Secret values are fully redacted to (no partial disclosure). /// Example: rabbitmq:my-queue?host=localhost&username=admin&password=**** /// public string ToMaskedUriString() { var maskedPath = MaskUserInfoPassword(Path); if (RawParameters.Count == 0) return $"{Scheme}:{maskedPath}"; var sb = new StringBuilder(); sb.Append(Scheme); sb.Append(':'); sb.Append(maskedPath); var sep = '?'; foreach (var (key, value) in RawParameters) { sb.Append(sep); sb.Append(Uri.EscapeDataString(key)); sb.Append('='); sb.Append(IsSensitiveKey(key) ? Redacted : Uri.EscapeDataString(value)); sep = '&'; } return sb.ToString(); } }