fix(diagnostics): scrub whole passwords; unique bundle names; no temporary files left behind

- A secret value runs to the next ';' or the end of the line unless quoted
  (backslash and doubled-quote escapes), so passwords with spaces, commas or
  quotes never leak in part; URL passwords run to the last '@' before the path.
- Desktop bundles get " (2)", " (3)"… instead of overwriting one made in the
  same minute, and a bundle that fails half-way deletes its .tmp file.
- The server builds its bundle in a temporary file that no crash leaves behind
  (DeleteOnClose on Windows, unlinked at once elsewhere).
- Tests: passwords with spaces, commas, quotes and '@'; a DbConnectionString in
  the server bundle; bundle name collisions and failure cleanup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:05:45 +00:00
1 parent ffa05d9f69
commit 03da77277c
6 files changed
+95 -27

No files matched your search

@@ -4,6 +4,7 @@ using System.Runtime.InteropServices;
using System.Text;
using Titano.App.Settings;
using Titano.Core.Diagnostics;
using Titano.Core.Export;
using Titano.Core.Model;
using Titano.Core.Windows.Codecs;
using Titano.Data;
@@ -22,7 +23,8 @@ public static class DiagnosticsBundle
public const int FailedJobs = 50;
/// <summary>
/// Writes "Titano diagnostics yyyy-MM-dd HHmm.zip" into <paramref name="folder"/> and returns its path. Call on the UI
/// Writes "Titano diagnostics yyyy-MM-dd HHmm.zip" (" (2)", " (3)"… when that name is taken) into
/// <paramref name="folder"/> and returns its path; a bundle that fails half-way leaves no file behind. Call on the UI
/// thread: the settings are captured there; detection and writing run in the background.
/// </summary>
public static Task<string> CreateAsync(AppServices services, string folder, IEnumerable<string>? extraLines = null, CancellationToken ct = default)
@@ -33,19 +35,27 @@ public static class DiagnosticsBundle
{
var failures = services.Database is { } db ? (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct).ConfigureAwait(false)).Items : [];
var codecs = Codecs(services.Encoders);
var path = Path.Combine(folder, $"Titano diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}.zip");
var path = ExportNaming.Unique(folder, $"Titano diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}", ".zip");
var temp = path + ".tmp";
await using (var file = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None))
using (var bundle = new DiagnosticsArchive(file))
try
{
bundle.AddText("environment.txt", report);
bundle.AddText("codecs.txt", codecs);
bundle.AddJson("settings.json", settings);
bundle.AddJobs("jobs-failed.json", failures);
bundle.AddLogs(services.Environment.LogDirectory, cancellationToken: ct);
await using (var file = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None))
using (var bundle = new DiagnosticsArchive(file))
{
bundle.AddText("environment.txt", report);
bundle.AddText("codecs.txt", codecs);
bundle.AddJson("settings.json", settings);
bundle.AddJobs("jobs-failed.json", failures);
bundle.AddLogs(services.Environment.LogDirectory, cancellationToken: ct);
}
File.Move(temp, path);
return path;
}
finally
{
// Gone after a successful move; after a failure a half-written zip helps nobody.
if (File.Exists(temp)) File.Delete(temp);
}
File.Move(temp, path, overwrite: true);
return path;
}, ct);
}
@@ -116,8 +116,8 @@ public static partial class SecretScrubber
[GeneratedRegex(@"(?<scheme>\b(?:bearer|basic))\s+[A-Za-z0-9._~+/=-]{6,}", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex AuthScheme();
/// <summary>"https://user:secret@host" keeps the user name.</summary>
[GeneratedRegex(@"(?<prefix>\b[a-z][a-z0-9+.-]*://[^/\s:@]+:)[^/\s@]+@", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
/// <summary>"https://user:secret@host" keeps the user name; the password runs to the last '@' before the path ("p@ss@db").</summary>
[GeneratedRegex(@"(?<prefix>\b[a-z][a-z0-9+.-]*://[^/\s:@]+:)[^/\s]+@", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex UrlCredentials();
/// <summary>"?token=…", "&amp;access_token=…", "&amp;sig=…".</summary>
@@ -125,10 +125,12 @@ public static partial class SecretScrubber
private static partial Regex QueryParameter();
/// <summary>
/// "Password=…", "DbPassword: …", "\"token\": \"…\"", "client_secret=…" (connection strings, settings dumps, JSON in
/// log messages): the value up to the next separator goes (a value an earlier rule already removed is left alone).
/// "Password=…", "DbPassword: …", "\"token\": \"…\"", "client_secret=…" (connection strings, environment and settings
/// dumps, JSON in log messages). A quoted value goes up to its closing quote (a backslash or a doubled quote escapes
/// one); any other value up to the next ';' (the connection-string separator) or the end of the line, because
/// passwords may hold spaces, commas or quotes. A value an earlier rule already removed is left alone.
/// </summary>
[GeneratedRegex(@"(?<name>[A-Za-z0-9_-]*(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_-]*[""']?\s*[=:]\s*)(?!\[removed\])(?:""[^""]*""|'[^']*'|[^\s;,&""']+)",
[GeneratedRegex(@"(?<name>[A-Za-z0-9_-]*(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_-]*[""']?\s*[=:]\s*)(?!\[removed\])(?:""(?:[^""\\]|\\.|"""")*""|'(?:[^']|'')*'|[^;\r\n]+)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex NamedValue();
@@ -33,8 +33,13 @@ public static class DiagnosticsEndpoints
var settings = JsonSerializer.Serialize(options, ServerOptionsJson.Default.ServerOptions);
var encoders = Encoders(services.GetService<ProcessingService>());
// The bundle is built in a self-deleting temporary file: zip writes are synchronous and logs can be large.
var file = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1 << 16, FileOptions.DeleteOnClose);
// The bundle is built in a temporary file (zip writes are synchronous and logs can be large) that no crash leaves
// behind: Windows deletes it when the handle closes; elsewhere it is unlinked at once and lives on through the
// open handle (DeleteOnClose there would unlink by name at close, possibly a newer file of the same name).
var temp = Path.GetTempFileName();
var file = new FileStream(temp, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1 << 16,
OperatingSystem.IsWindows() ? FileOptions.DeleteOnClose : FileOptions.None);
if (!OperatingSystem.IsWindows()) File.Delete(temp);
try
{
await Task.Run(() =>