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:
16 files changed
+757
-40
No files matched your search
@@ -0,0 +1,65 @@
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Settings;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Windows;
|
||||
|
||||
/// <summary>The desktop diagnostics bundle: every entry present, the saved server token and passwords never inside.</summary>
|
||||
[WindowsOnly]
|
||||
public sealed class DiagnosticsBundleTests(TestContext context)
|
||||
{
|
||||
private const string Token = "AQAAANCMnd8BFdERjHoAwE-saved-token";
|
||||
|
||||
[Test]
|
||||
public async Task TheBundleCarriesReportsAndLogsButNoSecrets()
|
||||
{
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
try
|
||||
{
|
||||
var settings = new AppSettings { Language = "en", ServerUrl = "https://nas.local:8443", ServerUsername = "alice", ProtectedToken = Token };
|
||||
var services = new AppServices(environment, settings, () => { }, new NoDialogs()) { Encoders = new OneEncoder() };
|
||||
await File.WriteAllTextAsync(Path.Combine(environment.LogDirectory, "titano-20261002.log"), $"signed in with password={Token}\n");
|
||||
|
||||
var path = await DiagnosticsBundle.CreateAsync(services, context.CreateTempDirectory(), ["Self-test H.264 Test: passed"]);
|
||||
|
||||
using var zip = ZipFile.OpenRead(path);
|
||||
var texts = zip.Entries.ToDictionary(e => e.FullName, e =>
|
||||
{
|
||||
using var reader = new StreamReader(e.Open());
|
||||
return reader.ReadToEnd();
|
||||
});
|
||||
Assert.SequenceEqual(new[] { "codecs.txt", "environment.txt", "jobs-failed.json", "logs/titano-20261002.log", "settings.json" },
|
||||
texts.Keys.Order(StringComparer.Ordinal));
|
||||
foreach (var (name, text) in texts) Assert.False(text.Contains(Token, StringComparison.Ordinal), $"{name} leaks the token");
|
||||
Assert.Contains("Self-test H.264 Test: passed", texts["environment.txt"]);
|
||||
Assert.Contains("Test encoder", texts["codecs.txt"]);
|
||||
Assert.Contains("\"ServerUsername\": \"alice\"", texts["settings.json"]);
|
||||
Assert.Contains("\"ProtectedToken\": \"[removed]\"", texts["settings.json"]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
environment.DeleteCaptureData();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class OneEncoder : IEncoderInventory
|
||||
{
|
||||
public string? Adapter() => "Test adapter";
|
||||
|
||||
public IReadOnlyList<EncoderRow> Detect() =>
|
||||
[new EncoderRow("H.264", "Test encoder", null, EncoderSource.MediaFoundation, true, false, 4096, 2304, VideoCodec.H264)];
|
||||
|
||||
public Task<SelfTestResult> SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.FromResult(new SelfTestResult(true, 100, null));
|
||||
}
|
||||
|
||||
private sealed class NoDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Diagnostics;
|
||||
|
||||
public sealed class DiagnosticsArchiveTests(TestContext context)
|
||||
{
|
||||
private const string Secret = "correct-horse-battery";
|
||||
|
||||
[Test]
|
||||
public void EveryEntryIsScrubbedAndLogsKeepTheirTail()
|
||||
{
|
||||
var logs = context.CreateTempDirectory();
|
||||
File.WriteAllText(Path.Combine(logs, "titano-20261001.log"), "old line\nPassword=" + Secret + "\n");
|
||||
var big = new StringBuilder();
|
||||
for (var i = 0; i < 2_000; i++) big.Append("line ").Append(i).Append(" token: ").Append(Secret).Append('\n');
|
||||
File.WriteAllText(Path.Combine(logs, "titano-20261002.log"), big.ToString());
|
||||
File.WriteAllText(Path.Combine(logs, "photo.jpg"), "not a log");
|
||||
File.SetLastWriteTimeUtc(Path.Combine(logs, "titano-20261001.log"), DateTime.UtcNow.AddDays(-1));
|
||||
|
||||
using var zip = new MemoryStream();
|
||||
using (var bundle = new DiagnosticsArchive(zip))
|
||||
{
|
||||
bundle.AddText("environment.txt", DiagnosticsArchive.SystemReport() + "Server https://admin:" + Secret + "@nas:8443\n");
|
||||
bundle.AddJson("settings.json", $$"""{ "ProtectedToken": "{{Secret}}", "Theme": "Dark" }""");
|
||||
bundle.AddJobs("jobs-failed.json",
|
||||
[
|
||||
new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(), Kind = JobKind.Render, State = JobState.Failed, Attempts = 2, Created = DateTimeOffset.UtcNow,
|
||||
Error = "Upload refused: Authorization: Bearer " + Secret, LogTail = "retry with password=" + Secret,
|
||||
},
|
||||
]);
|
||||
bundle.AddLogs(logs, tailBytes: 4096);
|
||||
}
|
||||
|
||||
zip.Position = 0;
|
||||
using var archive = new ZipArchive(zip, ZipArchiveMode.Read);
|
||||
var names = archive.Entries.Select(e => e.FullName).Order(StringComparer.Ordinal).ToArray();
|
||||
Assert.SequenceEqual(new[] { "environment.txt", "jobs-failed.json", "logs/titano-20261001.log", "logs/titano-20261002.log", "settings.json" }, names);
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
var text = Read(entry);
|
||||
Assert.False(text.Contains(Secret, StringComparison.Ordinal), $"{entry.FullName} leaks the secret");
|
||||
}
|
||||
Assert.Contains("Runtime ", Read(archive.GetEntry("environment.txt")!));
|
||||
Assert.Contains("\"Theme\": \"Dark\"", Read(archive.GetEntry("settings.json")!));
|
||||
Assert.Contains("\"kind\": \"Render\"", Read(archive.GetEntry("jobs-failed.json")!));
|
||||
|
||||
var tail = Read(archive.GetEntry("logs/titano-20261002.log")!);
|
||||
Assert.True(tail.StartsWith("[first ", StringComparison.Ordinal), "a cut log says so");
|
||||
Assert.Contains("line 1999 token: [removed]", tail);
|
||||
Assert.Less(tail.Length, 5_000);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AMissingLogFolderAddsNothing()
|
||||
{
|
||||
using var zip = new MemoryStream();
|
||||
using (var bundle = new DiagnosticsArchive(zip)) bundle.AddLogs(Path.Combine(context.CreateTempDirectory(), "missing"));
|
||||
zip.Position = 0;
|
||||
using var archive = new ZipArchive(zip, ZipArchiveMode.Read);
|
||||
Assert.Empty(archive.Entries);
|
||||
}
|
||||
|
||||
private static string Read(ZipArchiveEntry entry)
|
||||
{
|
||||
using var reader = new StreamReader(entry.Open(), Encoding.UTF8);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Diagnostics;
|
||||
|
||||
public sealed class SecretScrubberTests
|
||||
{
|
||||
private const string Secret = "hunter2-S3cr3t!";
|
||||
|
||||
[Theory]
|
||||
[Case("Host=db;Port=5432;Username=titano;Password=" + Secret + ";SslMode=prefer", "Host=db;Port=5432;Username=titano;Password=[removed];SslMode=prefer")]
|
||||
[Case("TITANO_DB_PASSWORD=" + Secret, "TITANO_DB_PASSWORD=[removed]")]
|
||||
[Case("DbPassword: " + Secret, "DbPassword: [removed]")]
|
||||
[Case("login body {\"username\":\"alice\",\"password\":\"" + Secret + "\"}", "login body {\"username\":\"alice\",\"password\":[removed]}")]
|
||||
[Case("Authorization: Bearer " + Secret, "Authorization: [removed]")]
|
||||
[Case("calling with bearer abcdefghijklmnop", "calling with bearer [removed]")]
|
||||
[Case("Cookie: titano_session=" + Secret + "; titano_csrf=x", "Cookie: [removed]")]
|
||||
[Case("git clone https://x-access-token:" + Secret + "@github.com/o/r.git", "git clone https://x-access-token:[removed]@github.com/o/r.git")]
|
||||
[Case("GET /api/v1/events?token=" + Secret + "&x=1", "GET /api/v1/events?token=[removed]&x=1")]
|
||||
[Case("client_secret=" + Secret + " refresh_token='" + Secret + "'", "client_secret=[removed] refresh_token=[removed]")]
|
||||
[Case("pushed with ghp_0123456789abcdefghijABCDEFGHIJ012345", "pushed with [removed]")]
|
||||
public void SecretsInTextAreRemoved(string line, string expected) => Assert.Equal(expected, SecretScrubber.ScrubLine(line));
|
||||
|
||||
[Theory]
|
||||
[Case("2026-10-02T09:00:00Z Info archive: Scan of /archive found 1,204 frames in 12 sequences")]
|
||||
[Case("Index open (schema 3) at C:\\Users\\alice\\AppData\\Local\\Titano\\titano.db")]
|
||||
[Case("frame 0193 sha256 4f2a9c0e1b7d3a5f6e8c9b0a1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e verified")]
|
||||
[Case("Token revoked for user alice")]
|
||||
[Case("")]
|
||||
public void OrdinaryLinesAreKept(string line) => Assert.Equal(line, SecretScrubber.ScrubLine(line));
|
||||
|
||||
[Test]
|
||||
public void PrivateKeyBlocksAreDroppedWhole()
|
||||
{
|
||||
var text = "before\n-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\nBKcwggSjAgEAAoIBAQC7\n-----END PRIVATE KEY-----\nafter";
|
||||
Assert.Equal("before\n[removed private key]\nafter", SecretScrubber.ScrubText(text));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SecretNamedJsonValuesAreRemovedAndOtherStringsScrubbed()
|
||||
{
|
||||
var json = $$"""
|
||||
{
|
||||
"ServerName": "NAS",
|
||||
"AdminPassword": "{{Secret}}",
|
||||
"DbPassword": null,
|
||||
"DbConnectionString": "Host=db;Password={{Secret}}",
|
||||
"TokenLifetimeDays": 30,
|
||||
"ProtectedToken": "AQAAANCMnd8BFdERjHoAwE",
|
||||
"TrustedCertificates": [ { "Fingerprint": "AB:CD:EF", "Server": "nas" } ],
|
||||
"Nested": { "api_key": "{{Secret}}", "SigningKeys": [ "{{Secret}}" ], "Credentials": { "User": "alice", "Value": "{{Secret}}" } }
|
||||
}
|
||||
""";
|
||||
var scrubbed = SecretScrubber.ScrubJson(json);
|
||||
Assert.False(scrubbed.Contains(Secret, StringComparison.Ordinal), scrubbed);
|
||||
Assert.False(scrubbed.Contains("AQAAANCMnd8BFdERjHoAwE", StringComparison.Ordinal), scrubbed);
|
||||
|
||||
using var doc = JsonDocument.Parse(scrubbed);
|
||||
var root = doc.RootElement;
|
||||
Assert.Equal("NAS", root.GetProperty("ServerName").GetString());
|
||||
Assert.Equal(SecretScrubber.Removed, root.GetProperty("AdminPassword").GetString());
|
||||
Assert.Equal(JsonValueKind.Null, root.GetProperty("DbPassword").ValueKind);
|
||||
Assert.Equal("Host=db;Password=[removed]", root.GetProperty("DbConnectionString").GetString());
|
||||
Assert.Equal(30, root.GetProperty("TokenLifetimeDays").GetInt32());
|
||||
Assert.Equal("AB:CD:EF", root.GetProperty("TrustedCertificates")[0].GetProperty("Fingerprint").GetString());
|
||||
Assert.Equal(SecretScrubber.Removed, root.GetProperty("Nested").GetProperty("Credentials").GetProperty("User").GetString());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TextThatIsNotJsonIsScrubbedAsText() =>
|
||||
Assert.Equal("password=[removed] {", SecretScrubber.ScrubJson("password=" + Secret + " {"));
|
||||
|
||||
[Theory]
|
||||
[Case("DbPassword", true)]
|
||||
[Case("SIGN_PFX_BASE64", true)]
|
||||
[Case("X-Titano-Token", true)]
|
||||
[Case("set-cookie", true)]
|
||||
[Case("privateKey", true)]
|
||||
[Case("ServerName", false)]
|
||||
[Case("TlsCert", false)]
|
||||
[Case("SessionKey", false)]
|
||||
public void SecretNamesAreRecognised(string name, bool secret) => Assert.Equal(secret, SecretScrubber.IsSecretName(name));
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Api;
|
||||
|
||||
[Category("server")]
|
||||
public sealed class DiagnosticsTests(TestContext context)
|
||||
{
|
||||
private const string DbPassword = "db-secret-pw-42";
|
||||
|
||||
[Test]
|
||||
public async Task TheBundleHoldsReportsLogsAndFailuresWithoutSecrets()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.DbPassword = DbPassword);
|
||||
var admin = await server.AdminAsync();
|
||||
Directory.CreateDirectory(server.Options.LogPath);
|
||||
await File.WriteAllTextAsync(Path.Combine(server.Options.LogPath, "titano-server-test.log"),
|
||||
$"connecting with Password={DbPassword}\nAuthorization: Bearer {TestServer.Password}\n");
|
||||
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Render, State = JobState.Queued, Created = DateTimeOffset.UtcNow };
|
||||
await server.Database.Jobs.EnqueueAsync(job);
|
||||
await server.Database.Jobs.SetStateAsync(job.Id, JobState.Failed, "token=" + DbPassword + " rejected");
|
||||
|
||||
using var response = await admin.GetAsync("/api/v1/server/diagnostics");
|
||||
await response.ExpectAsync(HttpStatusCode.OK);
|
||||
Assert.Equal("application/zip", response.Content.Headers.ContentType?.MediaType);
|
||||
await using var body = await response.Content.ReadAsStreamAsync();
|
||||
using var zip = new ZipArchive(body, ZipArchiveMode.Read);
|
||||
var texts = zip.Entries.ToDictionary(e => e.FullName, Read);
|
||||
|
||||
Assert.Contains("environment.txt", texts.Keys);
|
||||
Assert.Contains("encoders.txt", texts.Keys);
|
||||
Assert.Contains("logs/titano-server-test.log", texts.Keys);
|
||||
foreach (var (name, text) in texts)
|
||||
{
|
||||
Assert.False(text.Contains(DbPassword, StringComparison.Ordinal), $"{name} leaks the database password");
|
||||
Assert.False(text.Contains(TestServer.AdminPassword, StringComparison.Ordinal), $"{name} leaks the admin password");
|
||||
Assert.False(text.Contains(TestServer.Password, StringComparison.Ordinal), $"{name} leaks a user password");
|
||||
}
|
||||
Assert.Contains("Titano Server ", texts["environment.txt"]);
|
||||
using (var settings = JsonDocument.Parse(texts["settings.json"]))
|
||||
{
|
||||
Assert.Equal("[removed]", settings.RootElement.GetProperty("DbPassword").GetString());
|
||||
Assert.Equal("[removed]", settings.RootElement.GetProperty("AdminPassword").GetString());
|
||||
}
|
||||
using (var failed = JsonDocument.Parse(texts["jobs-failed.json"]))
|
||||
{
|
||||
var entry = failed.RootElement.EnumerateArray().Single();
|
||||
Assert.Equal(("Render", "token=[removed] rejected"), (entry.GetProperty("kind").GetString(), entry.GetProperty("error").GetString()));
|
||||
}
|
||||
|
||||
var (viewer, _, _) = await server.UserAsync("vera", "viewer");
|
||||
using var refused = await viewer.GetAsync("/api/v1/server/diagnostics");
|
||||
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
Assert.NotEmpty((await server.Database.Audit.ListAsync(null, "server_diagnostics", 10, null)).Items);
|
||||
}
|
||||
|
||||
private static string Read(ZipArchiveEntry entry)
|
||||
{
|
||||
using var reader = new StreamReader(entry.Open());
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user