Files
Anubis/src/Anubis.Server/DiagnosticsCommand.cs
T
Alby96andClaude Opus 5.5 4d92a39fef Close what the security review found
A session alone could change the password, switch the second factor on or
off, send the key of the language model to another address and remove the
rules that stop purchases. Each now needs the password and the code, with
one limit on wrong attempts that a restart of the services does not clear,
and the other sessions end when the password or the factor changes.

Requests to the brokers pass a list of allowed calls, never follow a
redirect with a key and are signed by one client only. Pages are closed by
default, nothing is cached, requests are limited to 1 MB, secrets are
masked in logs and notifications, exported tables cannot run as formulas,
archives carry no sessions and the container refuses to run as root.

refs #68

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 19:11:11 +01:00

140 lines
6.8 KiB
C#

using System.Collections;
using System.Globalization;
using Anubis.Core;
using Anubis.Db;
using Anubis.Diagnostics;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>The diagnostics report (issue #95, ADR 0013) as the command, the download and the Diario button make it.</summary>
internal static class DiagnosticsExport
{
/// <summary>Thirty days: as long as the samples are kept.</summary>
public const double MaxHours = 720;
/// <summary>
/// The report over the last <paramref name="hours"/> hours up to <paramref name="to"/>, or from
/// <paramref name="from"/>; without either, from the first sample kept, so a run of a release is covered whole.
/// </summary>
public static async Task<string> BuildAsync(Database db, StartupConfig config, IReadOnlyDictionary<string, string?> environment, DateTimeOffset now,
double? hours, DateTimeOffset? from, DateTimeOffset? to, CancellationToken cancellationToken)
{
var end = to ?? now;
var start = from ?? end - TimeSpan.FromHours(Math.Clamp(hours is { } h && double.IsFinite(h) ? h : MaxHours, 0.25, MaxHours));
if (from is null && hours is null)
{
var first = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(taken_at) AS t FROM diagnostic_samples", r => r.MomentOrNull("t")), cancellationToken)
.ConfigureAwait(false);
if (first is { } f && f > start && f < end)
{
start = f;
}
}
var request = new DiagnosticsRequest(start, end, config.TimeZone)
{
LogsFolder = config.Data.Logs,
Setup = Setup(config, environment),
GeneratedAt = now,
};
return await DiagnosticsReporter.BuildAsync(db, request, cancellationToken).ConfigureAwait(false);
}
/// <summary>The startup settings, and which ANUBIS_ variables are set: values only for those that cannot hold a secret.</summary>
internal static IReadOnlyList<KeyValuePair<string, string>> Setup(StartupConfig config, IReadOnlyDictionary<string, string?> environment)
{
var lines = new List<KeyValuePair<string, string>>
{
new("Piattaforma", config.Platform.ToString().ToLowerInvariant()),
new("Database", config.Db?.Describe() ?? "non configurato"),
new("Cartella dei dati", config.Data.Root),
new("Raggiungibile da altri computer", config.AllowNetwork ? "sì" : "no"),
new("Ordini reali consentiti", config.AllowLive ? "sì" : "no"),
};
var variables = environment
.Where(e => e.Key.StartsWith(AnubisInfo.EnvironmentPrefix, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(e.Value))
.OrderBy(e => e.Key, StringComparer.Ordinal)
.Select(e => e.Key + (Secretive(e.Key) ? "" : "=" + e.Value))
.ToList();
lines.Add(new("Variabili impostate", variables.Count == 0 ? "nessuna" : string.Join(", ", variables)));
return lines;
}
private static readonly string[] _secretWords = ["KEY", "SECRET", "PASS", "TOKEN", "URL"];
private static bool Secretive(string name) => _secretWords.Any(word => name.Contains(word, StringComparison.OrdinalIgnoreCase));
public static IReadOnlyDictionary<string, string?> ProcessEnvironment() =>
Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
}
/// <summary>
/// "anubis diagnostics": the report to paste back after a long run of a release (issue #95, ADR 0013). It only reads,
/// so it runs while the bot works: in Docker with <c>docker exec</c>, on desktop from a second terminal.
/// </summary>
internal static class DiagnosticsCommand
{
private const string Usage =
"Uso: anubis diagnostics [--hours 72] [--from AAAA-MM-GGTHH:MMZ] [--to AAAA-MM-GGTHH:MMZ] [--out file.md]\n" +
" senza --hours né --from copre tutto ciò che è stato raccolto (al massimo 30 giorni).\n" +
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
/// <summary>0 when the report was made, 1 when it could not be, 2 for the usage.</summary>
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null, IClock? clock = null)
{
output ??= Console.Out;
clock ??= new SystemClock();
var own = new Dictionary<string, string>(StringComparer.Ordinal);
var rest = new List<string>();
for (var i = 0; i < args.Length; i++)
{
if (args[i] is "--from" or "--to" or "--hours" or "--out" && i + 1 < args.Length)
{
own[args[i]] = args[++i];
}
else if (args[i] is "--help" or "-h")
{
await output.WriteLineAsync(Usage).ConfigureAwait(false);
return 2;
}
else
{
rest.Add(args[i]);
}
}
environment ??= DiagnosticsExport.ProcessEnvironment();
try
{
double? hours = own.TryGetValue("--hours", out var h) ? double.Parse(h, CultureInfo.InvariantCulture) : null;
DateTimeOffset? to = own.TryGetValue("--to", out var t) ? DateTimeOffset.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : null;
DateTimeOffset? from = own.TryGetValue("--from", out var f) ? DateTimeOffset.Parse(f, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : null;
var options = ServerOptions.Parse([.. rest], environment);
var config = options.LoadConfig(environment);
if (!config.IsComplete)
{
await output.WriteLineAsync("La configurazione d'avvio non è completa: avvia prima il server una volta.").ConfigureAwait(false);
return 1;
}
Redactor.Register(config.Db!.Password);
await using var db = Database.Open(config.Db!, allowCreate: false);
var text = await DiagnosticsExport.BuildAsync(db, config, environment, clock.UtcNow, hours, from, to, CancellationToken.None).ConfigureAwait(false);
if (own.TryGetValue("--out", out var file))
{
await File.WriteAllTextAsync(Path.GetFullPath(file), text).ConfigureAwait(false);
}
await output.WriteAsync(text).ConfigureAwait(false);
return 0;
}
catch (Exception ex) when (ex is IOException or FormatException or ArgumentException or InvalidOperationException or SchemaException
or System.Data.Common.DbException or UnauthorizedAccessException or TimeZoneNotFoundException)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return 1;
}
}
}