Files
Chronos/src/Titano.Server/Api/DiagnosticsEndpoints.cs
T
Claude 03da77277c 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
2026-10-03 10:05:45 +00:00

114 lines
5.6 KiB
C#

using System.Globalization;
using System.Text;
using System.Text.Json;
using Titano.Core.Diagnostics;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Processing;
using Titano.Server.Configuration;
using Titano.Server.Jobs;
using Titano.Server.Security;
namespace Titano.Server.Api;
/// <summary>
/// <c>GET /api/v1/server/diagnostics</c> (BRIEF §22 Phase 8; ManageArchive): a zip with the environment report, the
/// effective configuration, the encoders, the latest failed jobs and the server logs. Everything passes through
/// <see cref="SecretScrubber"/> (admin and database passwords, tokens and keys are removed); no archive file is included.
/// </summary>
public static class DiagnosticsEndpoints
{
/// <summary>Failed jobs included, newest first.</summary>
public const int FailedJobs = 100;
public static void Map(RouteGroupBuilder api) =>
api.MapGet("/server/diagnostics", DownloadAsync).Requires(Permissions.ManageArchive);
private static async Task<IResult> DownloadAsync(HttpContext context, Caller caller, TitanoDatabase db, ServerOptions options, ServerState state,
JobEngineHost jobs, AuditLog audit, TimeProvider time, IServiceProvider services)
{
var ct = context.RequestAborted;
var failures = (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct)).Items;
var report = Report(options, state, jobs, time);
var settings = JsonSerializer.Serialize(options, ServerOptionsJson.Default.ServerOptions);
var encoders = Encoders(services.GetService<ProcessingService>());
// 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(() =>
{
using var bundle = new DiagnosticsArchive(file);
bundle.AddText("environment.txt", report);
bundle.AddJson("settings.json", settings);
bundle.AddText("encoders.txt", encoders);
bundle.AddJobs("jobs-failed.json", failures);
bundle.AddLogs(options.LogPath, cancellationToken: ct);
}, ct);
file.Position = 0;
}
catch
{
await file.DisposeAsync();
throw;
}
await audit.WriteAsync(caller, context, "server_diagnostics", "server");
context.Response.Headers.CacheControl = "no-store";
var name = string.Create(CultureInfo.InvariantCulture, $"titano-server-diagnostics-{time.GetUtcNow():yyyyMMdd-HHmm}.zip");
return Results.File(file, "application/zip", name);
}
private static string Report(ServerOptions options, ServerState state, JobEngineHost jobs, TimeProvider time)
{
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"Titano Server {SystemEndpoints.Version} ({options.ServerName})");
sb.Append(DiagnosticsArchive.SystemReport());
sb.AppendLine(CultureInfo.InvariantCulture, $"Uptime {time.GetUtcNow() - state.StartedAt:d\\.hh\\:mm\\:ss}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Database {state.Database} ({options.Database})");
sb.AppendLine(CultureInfo.InvariantCulture, $"TLS {options.TlsMode} {state.TlsFingerprint}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Workers {jobs.Workers}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Archive {options.ArchivePath} ({Space(options.ArchivePath)})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Data {options.DataPath} ({Space(options.DataPath)})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Container {File.Exists("/.dockerenv")}");
sb.AppendLine("Set by environment: " + string.Join(", ", options.Locked));
return sb.ToString();
}
private static string Encoders(ProcessingService? processing)
{
if (processing is null) return "No processing engine registered.\n";
var sb = new StringBuilder();
foreach (var provider in processing.Options.Encoders)
{
foreach (var c in provider.Capabilities)
{
sb.AppendLine(CultureInfo.InvariantCulture,
$"{provider.Name}: {c.Codec} {c.Name} ({(c.Hardware ? "hardware" : "software")}{(c.SupportsTenBit ? ", 10-bit" : string.Empty)}, max {c.MaxWidth}x{c.MaxHeight})");
}
}
return sb.ToString();
}
private static string Space(string path)
{
try
{
if (!Directory.Exists(path)) return "missing";
var full = Path.GetFullPath(path);
// Windows wants a drive root; Unix accepts any directory and reports the volume it is mounted on.
var drive = new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(full)! : full);
return string.Create(CultureInfo.InvariantCulture, $"{drive.AvailableFreeSpace / (1L << 30)} GB free of {drive.TotalSize / (1L << 30)} GB");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
{
return "free space unknown";
}
}
}