feat(diagnostics): scrubbed diagnostics bundles on the desktop and the server

SecretScrubber removes passwords, tokens, keys, cookies, authorisation
headers, URL credentials and private-key blocks from text and JSON;
DiagnosticsArchive zips reports, settings, failed jobs and log tails through
it. The desktop bundle (Settings > Advanced, About) now adds the codec and
encoder inventory, the settings and recent failed jobs; the server serves
the same as GET /api/v1/server/diagnostics (ManageArchive, audited), linked
from admin > Logs.

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-02 22:29:26 +00:00
1 parent 85d091d1fe
commit 2650aa31fb
16 files changed
+757 -40

No files matched your search

@@ -0,0 +1,127 @@
using System.Globalization;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using Titano.Core.Model;
namespace Titano.Core.Diagnostics;
/// <summary>
/// Writes a diagnostics bundle (Settings › Advanced, admin panel › Logs; BRIEF §22 Phase 8): a zip in which every entry
/// passes through <see cref="SecretScrubber"/>. Only what the caller hands over goes in — reports, settings, job
/// failures and the tail of each log — never photos or other user files.
/// </summary>
public sealed class DiagnosticsArchive : IDisposable
{
/// <summary>Bytes kept from the end of each log file.</summary>
public const long DefaultLogTailBytes = 4L << 20;
/// <summary>Newest log files included.</summary>
public const int DefaultLogFiles = 14;
private readonly ZipArchive _zip;
/// <summary>Writes into <paramref name="output"/> (left open).</summary>
public DiagnosticsArchive(Stream output) => _zip = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true);
/// <summary>Operating system, runtime, processor, memory and culture, one fact per line.</summary>
public static string SystemReport()
{
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"OS {RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Runtime {RuntimeInformation.FrameworkDescription} ({RuntimeInformation.ProcessArchitecture})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Processors {Environment.ProcessorCount}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Memory {GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024 * 1024)} MB");
sb.AppendLine(CultureInfo.InvariantCulture, $"Culture {CultureInfo.CurrentCulture.Name} / UI {CultureInfo.CurrentUICulture.Name}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Time zone {TimeZoneInfo.Local.Id} (UTC{TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow):hh\\:mm})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Created {DateTimeOffset.Now:O}");
return sb.ToString();
}
/// <summary>Adds a text entry, scrubbed.</summary>
public void AddText(string name, string text) => Write(name, SecretScrubber.ScrubText(text));
/// <summary>Adds a JSON entry with secret-named values removed and every other string scrubbed.</summary>
public void AddJson(string name, string json) => Write(name, SecretScrubber.ScrubJson(json));
/// <summary>Adds failed jobs (kind, times, attempts, node, error and log tail), scrubbed, as a JSON array.</summary>
public void AddJobs(string name, IEnumerable<Job> jobs)
{
using var buffer = new MemoryStream();
using (var w = new Utf8JsonWriter(buffer))
{
w.WriteStartArray();
foreach (var job in jobs)
{
w.WriteStartObject();
w.WriteString("id", job.Id);
w.WriteString("kind", job.Kind.ToString());
w.WriteString("state", job.State.ToString());
if (job.TargetLabel is { } target) w.WriteString("target", target);
w.WriteString("created", job.Created);
if (job.Started is { } started) w.WriteString("started", started);
if (job.Finished is { } finished) w.WriteString("finished", finished);
w.WriteNumber("attempts", job.Attempts);
if (job.NodeId is { } node) w.WriteString("node", node);
if (job.Error is { } error) w.WriteString("error", error);
if (job.LogTail is { } log) w.WriteString("log", log);
w.WriteEndObject();
}
w.WriteEndArray();
}
Write(name, SecretScrubber.ScrubJson(Encoding.UTF8.GetString(buffer.ToArray())));
}
/// <summary>
/// Adds the newest <paramref name="maxFiles"/> files matching <paramref name="pattern"/> under <c>logs/</c>, each cut
/// to its last <paramref name="tailBytes"/> and scrubbed line by line. Files being written are read through a shared
/// handle; a file that cannot be read becomes a note instead of failing the bundle.
/// </summary>
public void AddLogs(string directory, string pattern = "*.log", long tailBytes = DefaultLogTailBytes, int maxFiles = DefaultLogFiles,
CancellationToken cancellationToken = default)
{
if (!Directory.Exists(directory)) return;
var files = new DirectoryInfo(directory).EnumerateFiles(pattern)
.OrderByDescending(f => f.LastWriteTimeUtc).ThenByDescending(f => f.Name, StringComparer.Ordinal)
.Take(maxFiles);
foreach (var file in files)
{
cancellationToken.ThrowIfCancellationRequested();
var entry = _zip.CreateEntry("logs/" + file.Name, CompressionLevel.Optimal);
using var writer = new StreamWriter(entry.Open(), new UTF8Encoding(false));
try
{
using var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
var start = Math.Max(0, stream.Length - tailBytes);
stream.Position = start;
using var reader = new StreamReader(stream, Encoding.UTF8);
// A tail that starts mid-file begins with a partial line.
if (start > 0)
{
reader.ReadLine();
writer.WriteLine(string.Create(CultureInfo.InvariantCulture, $"[first {start:N0} bytes left out]"));
}
foreach (var line in SecretScrubber.ScrubLines(ReadLines(reader))) writer.WriteLine(line);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
writer.WriteLine("[unreadable: " + ex.Message + "]");
}
}
}
public void Dispose() => _zip.Dispose();
private void Write(string name, string text)
{
var entry = _zip.CreateEntry(name, CompressionLevel.Optimal);
using var writer = new StreamWriter(entry.Open(), new UTF8Encoding(false));
writer.Write(text);
}
private static IEnumerable<string> ReadLines(StreamReader reader)
{
while (reader.ReadLine() is { } line) yield return line;
}
}
@@ -0,0 +1,138 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
namespace Titano.Core.Diagnostics;
/// <summary>
/// Removes secrets from text and JSON before they leave the machine in a diagnostics bundle: passwords, tokens, keys,
/// cookies, authorisation headers, credentials in URLs and connection strings, private-key blocks. It errs towards
/// removing too much: a lost hint costs less than a leaked secret.
/// </summary>
public static partial class SecretScrubber
{
public const string Removed = "[removed]";
/// <summary>Fragments of property names whose string values are secret (compared without case, '_', '-' or '.').</summary>
private static readonly string[] SecretNames =
["password", "passwd", "pwd", "secret", "token", "apikey", "accesskey", "privatekey", "signingkey", "credential", "cookie", "authorization", "pfx"];
/// <summary>True when a setting or header with this name holds a secret.</summary>
public static bool IsSecretName(string name)
{
var normalized = string.Concat(name.Where(c => c is not ('_' or '-' or '.'))).ToLowerInvariant();
return SecretNames.Any(normalized.Contains);
}
/// <summary>
/// The JSON with every secret-named string value replaced and every other string scrubbed as text; numbers and
/// booleans stay (a "TokenLifetimeDays" is no secret). Text that is not JSON is scrubbed as text.
/// </summary>
public static string ScrubJson(string json)
{
JsonNode? root;
try
{
root = JsonNode.Parse(json);
}
catch (JsonException)
{
return ScrubText(json);
}
if (root is null) return json;
root = ScrubNode(root, secret: false);
return root.ToJsonString(new JsonSerializerOptions { WriteIndented = true });
}
/// <summary>Scrubs a block of text (several lines; private-key blocks are removed whole).</summary>
public static string ScrubText(string text) =>
string.Join('\n', ScrubLines(text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n')));
/// <summary>Scrubs lines one by one, dropping the body of any PEM private-key block.</summary>
public static IEnumerable<string> ScrubLines(IEnumerable<string> lines)
{
var inKey = false;
foreach (var line in lines)
{
if (!inKey && line.Contains("-----BEGIN", StringComparison.Ordinal) && line.Contains("PRIVATE KEY", StringComparison.Ordinal))
{
inKey = !line.Contains("-----END", StringComparison.Ordinal);
yield return "[removed private key]";
continue;
}
if (inKey)
{
if (line.Contains("-----END", StringComparison.Ordinal)) inKey = false;
continue;
}
yield return ScrubLine(line);
}
}
/// <summary>Scrubs one line of text.</summary>
public static string ScrubLine(string line)
{
if (line.Length == 0) return line;
var s = HeaderLine().Replace(line, m => m.Groups["name"].Value + ": " + Removed);
s = AuthScheme().Replace(s, m => m.Groups["scheme"].Value + " " + Removed);
s = UrlCredentials().Replace(s, m => m.Groups["prefix"].Value + Removed + "@");
s = QueryParameter().Replace(s, m => m.Groups["name"].Value + Removed);
s = NamedValue().Replace(s, m => m.Groups["name"].Value + Removed);
return KnownTokenFormat().Replace(s, Removed);
}
private static JsonNode ScrubNode(JsonNode node, bool secret)
{
switch (node)
{
case JsonObject obj:
foreach (var name in obj.Select(p => p.Key).ToList())
{
if (obj[name] is not { } child) continue;
var scrubbed = ScrubNode(child, secret || IsSecretName(name));
if (!ReferenceEquals(scrubbed, child)) obj[name] = scrubbed;
}
return obj;
case JsonArray array:
for (var i = 0; i < array.Count; i++)
{
if (array[i] is not { } item) continue;
var scrubbed = ScrubNode(item, secret);
if (!ReferenceEquals(scrubbed, item)) array[i] = scrubbed;
}
return array;
case JsonValue value when value.GetValueKind() == JsonValueKind.String:
return JsonValue.Create(secret ? Removed : ScrubText(value.GetValue<string>()));
default:
return node;
}
}
/// <summary>"Authorization: …", "Cookie: …", "Set-Cookie: …": the whole value goes.</summary>
[GeneratedRegex(@"(?<name>\b(?:proxy-)?authorization|\bset-cookie|\bcookie|\bx-csrf-token)\s*:\s*\S.*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex HeaderLine();
/// <summary>"Bearer abc…", "Basic dXNl…".</summary>
[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)]
private static partial Regex UrlCredentials();
/// <summary>"?token=…", "&amp;access_token=…", "&amp;sig=…".</summary>
[GeneratedRegex(@"(?<name>[?&](?:token|access_token|refresh_token|api_key|apikey|key|sig|signature|password|code)=)[^&\s#""']+", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
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).
/// </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;,&""']+)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex NamedValue();
/// <summary>Self-identifying credentials (GitHub tokens) wherever they appear.</summary>
[GeneratedRegex(@"\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b", RegexOptions.CultureInvariant)]
private static partial Regex KnownTokenFormat();
}