From 4d92a39fef74f42b8dffa0c9648b37e672a0b264 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 1 Dec 2026 19:11:11 +0100 Subject: [PATCH] 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 --- deploy/docker/entrypoint.sh | 13 +- deploy/unraid/anubis.xml | 2 +- src/Anubis.Guard/Program.cs | 3 +- src/Anubis.Server/AccountsView.cs | 2 +- src/Anubis.Server/AnubisHost.cs | 3 +- .../Components/Pages/Impostazioni.razor | 35 +- .../Components/Pages/Laboratorio.razor | 15 +- src/Anubis.Server/Components/ServiceText.cs | 1 + src/Anubis.Server/DiagnosticsCommand.cs | 2 +- src/Anubis.Server/Endpoints.cs | 13 + src/Anubis.Server/Forms.cs | 75 +++- src/Anubis.Server/ServerApp.cs | 20 +- src/Anubis.Server/TelegramServices.cs | 2 +- src/Anubis.Server/TradesView.cs | 2 +- src/Anubis/Access/AccessStore.cs | 198 ++++++--- src/Anubis/Brokers/Outgoing.cs | 19 + src/Anubis/Core/Format.cs | 10 +- src/Anubis/Core/Scheduling.cs | 2 +- src/Anubis/Data/MarketDataService.cs | 25 +- src/Anubis/Db/Archive.cs | 5 +- src/Anubis/Notifications/Notifications.cs | 2 +- src/Anubis/Platform/PlatformLoader.cs | 8 + src/Anubis/Platform/StartupConfig.cs | 14 + src/Anubis/Trading/AlpacaTrading.cs | 2 +- src/Anubis/Trading/OkxTrading.cs | 2 +- src/Anubis/Trading/OrderManager.cs | 2 +- src/Anubis/Trading/Stages.cs | 2 +- src/Anubis/Trading/TradingHttp.cs | 36 +- src/Anubis/Trading/TradingService.cs | 2 +- tests/Anubis.Tests/NewsAnalystTests.cs | 4 +- tests/Anubis.Tests/RestoreServerTests.cs | 2 +- tests/Anubis.Tests/RiskTests.cs | 5 +- tests/Anubis.Tests/SecurityTests.cs | 396 ++++++++++++++++++ tests/Anubis.Tests/ServerHarness.cs | 11 + tests/Anubis.Tests/StoresTests.cs | 90 +++- 35 files changed, 907 insertions(+), 118 deletions(-) create mode 100644 src/Anubis/Brokers/Outgoing.cs create mode 100644 tests/Anubis.Tests/SecurityTests.cs diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh index 9b6a8ee..02ff837 100644 --- a/deploy/docker/entrypoint.sh +++ b/deploy/docker/entrypoint.sh @@ -4,6 +4,9 @@ # The process is the guard (SPEC 9.3, ADR 0012): it starts the engine, watches it and passes the stop on to it. set -eu +# What the application writes (database, backups, logs) is readable only by its own user. +umask 077 + app="/app/Anubis.Guard.dll" # A command ("docker run db import ...") runs once and ends: without the guard, which would start it again. @@ -26,6 +29,14 @@ case "$uid$gid" in ;; esac +case "$uid" in + *[!0]*) ;; + *) + echo "PUID=0 farebbe girare Anubis come amministratore: usa un utente normale (99 su Unraid)." >&2 + exit 64 + ;; +esac + mkdir -p /data for folder in db models research import backups logs web-keys guard; do mkdir -p "/data/$folder" @@ -35,4 +46,4 @@ find /data -xdev \( ! -user "$uid" -o ! -group "$gid" \) -exec chown -h "$uid:$g chmod 700 /data export HOME=/tmp -exec setpriv --reuid="$uid" --regid="$gid" --clear-groups -- dotnet "$app" "$@" +exec setpriv --reuid="$uid" --regid="$gid" --clear-groups --no-new-privs -- dotnet "$app" "$@" diff --git a/deploy/unraid/anubis.xml b/deploy/unraid/anubis.xml index 7c1e7d0..c078524 100644 --- a/deploy/unraid/anubis.xml +++ b/deploy/unraid/anubis.xml @@ -39,7 +39,7 @@ 0 - + 99 100 diff --git a/src/Anubis.Guard/Program.cs b/src/Anubis.Guard/Program.cs index 445c81b..16c00bf 100644 --- a/src/Anubis.Guard/Program.cs +++ b/src/Anubis.Guard/Program.cs @@ -15,7 +15,8 @@ var environment = Environment.GetEnvironmentVariables().Cast() .ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); var paths = new GuardPaths(DataRoot(args, environment)); var logger = new LineLogger(Console.Out.WriteLine); -using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) }; +using var http = Anubis.Brokers.Outgoing.KeyedClient(); +http.Timeout = TimeSpan.FromSeconds(20); var clock = SystemClock.Instance; var guardian = new Guardian(paths, clock, new GuardOptions(), start => ChildEngine.Start(GuardLaunch.Dotnet(), [GuardLaunch.Server(), .. args], environment, start), diff --git a/src/Anubis.Server/AccountsView.cs b/src/Anubis.Server/AccountsView.cs index 5e7e8f0..16370b8 100644 --- a/src/Anubis.Server/AccountsView.cs +++ b/src/Anubis.Server/AccountsView.cs @@ -167,7 +167,7 @@ internal sealed record AccountsView( // Trailing zeros dropped, so both database engines give the same text. static string Number(decimal value) => (value / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ','); - static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' '); + static string Clean(string value) => Format.CsvText(value); } private sealed record OpenOrder(Guid Account, Guid Instrument, string Side, string Kind, string Purpose, decimal Quantity, decimal Filled, decimal? Limit, decimal? Stop, diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 1216a94..6ef11a3 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -60,6 +60,7 @@ internal sealed partial class AnubisHost( /// A scheduler silent this long is stuck: the engine stops beating, so the guard steps in. public static readonly TimeSpan SchedulerSilence = TimeSpan.FromMinutes(30); + private readonly AccessGuards _accessGuards = new(clock); private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5); private readonly Lock _gate = new(); @@ -303,7 +304,7 @@ internal sealed partial class AnubisHost( var key = Config.SecretKey.GetOrCreateKey(); var settings = new SettingsStore(_db, clock, bus, StartupOverrides()); var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys); - var access = new AccessStore(_db, clock, secrets, PasswordIterations); + var access = new AccessStore(_db, clock, secrets, PasswordIterations, _accessGuards); if (options.Demo && identity.Verdict == IdentityVerdict.Created) { await DemoMode.SeedAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false); diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index f4ff63e..a8a280d 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -333,7 +333,7 @@ - @@ -341,6 +341,14 @@ { Fissato da @rule.Source: si cambia lì. } + else if (!Shell.IsDemo && _anyLive && rule.Value != "off") + { +

Una strategia usa soldi veri: per spegnere la regola servono la frase e la password.

+ + + + + } else if (!Shell.IsDemo) { @@ -499,6 +507,8 @@
+ + @@ -685,6 +695,8 @@ private string? ErrorText => Errore switch { "codice" => "Il codice non è giusto. Controlla l'ora del telefono e riprova con il codice che vedi adesso.", + "password-o-codice" => "La password o il codice non sono giusti. Controlla l'ora del telefono e riprova con il codice che vedi adesso.", + "gia-attivo" => "Il secondo fattore è già attivo: per cambiarlo prima disattivalo.", "segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.", "salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.", "impostazione" => "Questa impostazione non si può cambiare così.", @@ -730,6 +742,7 @@ var value = _llm.GetValueOrDefault(key) ?? new SettingValue(key, definition.Default, false, null); var locked = value.ReadOnly || Shell.IsDemo; var shown = decimals is { } d ? Format.Number(decimal.Parse(value.Value, CultureInfo.InvariantCulture), d) : value.Value; + var asksPassword = key == Anubis.News.NewsModelSettings.Address.Key || key == Anubis.News.NewsModelSettings.Provider.Key; var provider = _llm.GetValueOrDefault(Anubis.News.NewsModelSettings.Provider.Key)?.Value ?? Anubis.News.NewsModelProviders.Anthropic; return @ @@ -737,26 +750,32 @@ @if (definition.Allowed is { } choices) { - @foreach (var choice in choices) { } - @if (!locked) - { - - } } else { - @if (!locked) + } + @if (!locked) + { + @if (asksPassword) { - + + + @if (_hasSecondFactor) + { + + + } } + } @if (value.ReadOnly) { diff --git a/src/Anubis.Server/Components/Pages/Laboratorio.razor b/src/Anubis.Server/Components/Pages/Laboratorio.razor index 16ee64f..cba7ef1 100644 --- a/src/Anubis.Server/Components/Pages/Laboratorio.razor +++ b/src/Anubis.Server/Components/Pages/Laboratorio.razor @@ -182,7 +182,15 @@ {

@Capital(SlippageTiers.Label(c.Tier)): da @Bp(c.PreviousBp) a @Bp(c.Bp). Misurati @Bp(c.MeasuredBp) su @c.Cases esecuzioni con soldi veri (quasi certamente tra @Bp(c.LowBp) e @Bp(c.HighBp)). Un punto base è un centesimo di punto percentuale.

- +
+ @if (_anyLive) + { +

Una strategia usa soldi veri: per contare costi più bassi servono la frase e la password.

+ + + + } +
} @@ -228,6 +236,7 @@ private DateOnly _to; private IReadOnlyList _research = []; private IReadOnlyList _costs = []; + private bool _anyLive; private SlippageTable _table = SlippageTable.Standard; [CascadingParameter] @@ -248,6 +257,7 @@ var costs = new CostBook(services.Db, Clock); _costs = await costs.ListAsync(ct); _table = await costs.TableAsync(ct); + _anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct); _running = _trials.Any(t => !t.IsFinished); _family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0]; var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime); @@ -261,6 +271,9 @@ _message = Errore switch { null => null, + "frase-rischio" => $"Una strategia usa soldi veri: per confermare scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.", + "password-rischio" => "Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti. Non ho cambiato nulla.", + "retrocessione-rischio" => "Una strategia con soldi veri ha una condizione di retrocessione in corso: finché dura non si aggiunge rischio. Non ho cambiato nulla.", "stima" => "Quella stima non aspetta più una conferma.", "motore" => "Il laboratorio non è attivo in questo momento: riprova tra poco.", TrialRequestErrors.Strategy => "Strategia sconosciuta: scegline una dall'elenco.", diff --git a/src/Anubis.Server/Components/ServiceText.cs b/src/Anubis.Server/Components/ServiceText.cs index 7969f86..0bc40c0 100644 --- a/src/Anubis.Server/Components/ServiceText.cs +++ b/src/Anubis.Server/Components/ServiceText.cs @@ -24,6 +24,7 @@ internal static class PasswordMessages "corta" => $"La password è troppo corta: servono almeno {Access.Passwords.MinimumLength} caratteri.", "uguale" => "La nuova password deve essere diversa da quella iniziale.", "attuale" => "La password attuale non è giusta.", + "attesa" => "Troppi tentativi sbagliati: aspetta 15 minuti e riprova.", "demo" => "Nella modalità dimostrativa la password non si cambia.", _ => null, }; diff --git a/src/Anubis.Server/DiagnosticsCommand.cs b/src/Anubis.Server/DiagnosticsCommand.cs index bcc93a2..1beac79 100644 --- a/src/Anubis.Server/DiagnosticsCommand.cs +++ b/src/Anubis.Server/DiagnosticsCommand.cs @@ -21,7 +21,7 @@ internal static class DiagnosticsExport double? hours, DateTimeOffset? from, DateTimeOffset? to, CancellationToken cancellationToken) { var end = to ?? now; - var start = from ?? end - TimeSpan.FromHours(Math.Clamp(hours ?? MaxHours, 0.25, MaxHours)); + 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) diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index 588b13a..5e0cf82 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -146,6 +146,12 @@ internal static partial class Endpoints return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le soglie del modello si cambiano da Impostazioni, con la conferma quando servono soldi veri."); } + // And for the rules of the news, and where the model's key goes: the page asks for the password. + if (Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key) || Anubis.News.NewsModelSettings.All.Any(d => d.Key == key)) + { + return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le regole delle notizie e il modello linguistico si cambiano da Impostazioni, con la password quando serve."); + } + return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false); }); @@ -409,6 +415,7 @@ internal static partial class Endpoints return; } + context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token); using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false); using var settings = bus.Subscribe(16); using var modes = bus.Subscribe(16); @@ -418,6 +425,12 @@ internal static partial class Endpoints { while (socket.State == WebSocketState.Open && !aborted.IsCancellationRequested) { + // The live status ends with the session: signed out, expired, or closed by a new password. + if (!host.IsDemo && (host.Services is not { } services || await services.Access.ValidateAsync(token, refresh: false, aborted).ConfigureAwait(false) is null)) + { + break; + } + var snapshot = await shell.SnapshotAsync(aborted).ConfigureAwait(false); var bytes = JsonSerializer.SerializeToUtf8Bytes(new { type = "status", status = snapshot }, _json); await socket.SendAsync(bytes, WebSocketMessageType.Text, true, aborted).ConfigureAwait(false); diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 087e801..7fc2e24 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -144,7 +144,7 @@ internal static partial class Forms return bare + (bare.Contains('?', StringComparison.Ordinal) ? "&" : "?") + key + "=" + Uri.EscapeDataString(value) + anchor; } - private static async Task SignInAsync(IFormCollection form, AnubisHost host, LoginLimiter limiter, HttpContext context, CancellationToken ct) + private static async Task SignInAsync(IFormCollection form, AnubisHost host, LoginLimiter limiter, ILogger logger, HttpContext context, CancellationToken ct) { var services = host.Services; if (services is null) @@ -158,12 +158,18 @@ internal static partial class Forms if (wait > TimeSpan.Zero) { var minutes = Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes)); + LogSignInRefused(logger, address, "Locked"); return Results.Redirect(With(With("/accesso", "errore", "attesa"), "minuti", minutes.ToString(System.Globalization.CultureInfo.InvariantCulture))); } var code = form["codice"].ToString(); var (result, token) = await services.Access.SignInAsync(form["password"].ToString(), code, context.Request.Headers.UserAgent.ToString(), address, ct) .ConfigureAwait(false); + if (result is not (LoginResult.Ok or LoginResult.SecondFactorNeeded)) + { + LogSignInRefused(logger, address, result.ToString()); + } + switch (result) { case LoginResult.Ok: @@ -182,6 +188,9 @@ internal static partial class Forms } } + [LoggerMessage(Level = LogLevel.Warning, Message = "Sign-in refused from {Address}: {Reason}")] + private static partial void LogSignInRefused(ILogger logger, string address, string reason); + private static async Task SignOutAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { if (context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token) && host.Services is { } services) @@ -211,9 +220,15 @@ internal static partial class Forms return Results.Redirect(With(page, "errore", replacement.Length < Passwords.MinimumLength ? "corta" : "uguale")); } - var ok = await host.Services!.Access.ChangePasswordAsync(CurrentUser.Id(context.User), form["attuale"].ToString(), replacement, CurrentUser.Session(context.User), ct) + var (outcome, token) = await host.Services!.Access.ChangePasswordAsync(CurrentUser.Id(context.User), form["attuale"].ToString(), replacement, CurrentUser.Session(context.User), ct) .ConfigureAwait(false); - return Results.Redirect(ok ? With(done, "ok", "password") : With(page, "errore", "attuale")); + if (outcome != AccessChange.Done) + { + return Results.Redirect(With(page, "errore", outcome == AccessChange.Locked ? "attesa" : "attuale")); + } + + SessionAuthentication.WriteCookie(context, token!); + return Results.Redirect(With(done, "ok", "password")); } private static async Task EnableSecondFactorAsync(IFormCollection form, AnubisHost host, SecondFactorDrafts drafts, HttpContext context, CancellationToken ct) @@ -225,22 +240,35 @@ internal static partial class Forms return Results.Redirect("/impostazioni?errore=segreto#sicurezza"); } - var ok = await host.Services!.Access.EnableSecondFactorAsync(CurrentUser.Id(context.User), secret, form["codice"].ToString(), ct).ConfigureAwait(false); - if (ok) + var outcome = await host.Services!.Access.EnableSecondFactorAsync(CurrentUser.Id(context.User), secret, form["password"].ToString(), form["codice"].ToString(), session, ct) + .ConfigureAwait(false); + if (outcome is AccessChange.Done or AccessChange.AlreadyOn) { drafts.Remove(session); } - return Results.Redirect(ok ? "/impostazioni?ok=due-fattori#sicurezza" : "/impostazioni?errore=codice#sicurezza"); + return Results.Redirect(outcome switch + { + AccessChange.Done => "/impostazioni?ok=due-fattori#sicurezza", + AccessChange.Locked => "/impostazioni?errore=attesa#sicurezza", + AccessChange.AlreadyOn => "/impostazioni?errore=gia-attivo#sicurezza", + _ => "/impostazioni?errore=password-o-codice#sicurezza", + }); } private static async Task DisableSecondFactorAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { - var ok = !host.IsDemo && await host.Services!.Access.DisableSecondFactorAsync(CurrentUser.Id(context.User), form["password"].ToString(), form["codice"].ToString(), ct).ConfigureAwait(false); - return Results.Redirect(ok ? "/impostazioni?ok=due-fattori-tolti#sicurezza" : "/impostazioni?errore=attuale#sicurezza"); + var outcome = host.IsDemo ? AccessChange.Wrong : await host.Services!.Access.DisableSecondFactorAsync(CurrentUser.Id(context.User), form["password"].ToString(), + form["codice"].ToString(), CurrentUser.Session(context.User), ct).ConfigureAwait(false); + return Results.Redirect(outcome switch + { + AccessChange.Done => "/impostazioni?ok=due-fattori-tolti#sicurezza", + AccessChange.Locked => "/impostazioni?errore=attesa#sicurezza", + _ => "/impostazioni?errore=password-o-codice#sicurezza", + }); } - private static async Task SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + private static async Task SetSettingAsync(string key, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct) { var back = Back(form, "/impostazioni"); var news = Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key); @@ -271,10 +299,26 @@ internal static partial class Forms return Results.Redirect(With(back, "errore", key == Anubis.News.NewsModelSettings.DailyCap.Key ? "tetto" : "modello")); } + // Who gets the key of the model is decided with the password: with only a session it could be sent anywhere. + if ((key == Anubis.News.NewsModelSettings.Address.Key || key == Anubis.News.NewsModelSettings.Provider.Key) && host.Services is { } services && + value != (await services.Settings.GetAsync(key, ct).ConfigureAwait(false)).Value && + !await services.Access.ReauthenticateAsync(form["password"].ToString(), form["codice"].ToString().Trim(), ct).ConfigureAwait(false)) + { + return Results.Redirect(With(back, "errore", "password-rischio")); + } + var saved = await Endpoints.SetSettingAsync(host, key, value, context, ct).ConfigureAwait(false); return Results.Redirect(saved is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione")); } + // Without a rule of SPEC 10.5 purchases pass that it would stop: with real money in play that is more risk (SPEC 12.4). + if (news && form["valore"].ToString() == Anubis.News.NewsRuleSettings.Off && host.Services is { } app && + (await app.Settings.GetAsync(key, ct).ConfigureAwait(false)).Value != Anubis.News.NewsRuleSettings.Off && + await RaiseRefusalAsync(app, clock, null, form, ct).ConfigureAwait(false) is { } refusal) + { + return Results.Redirect(With(back, "errore", refusal)); + } + if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null) { return Results.Redirect(With(back, "errore", "riunioni")); @@ -633,9 +677,10 @@ internal static partial class Forms var next = new Dictionary(StringComparer.Ordinal); foreach (var definition in Anubis.Risk.RiskSettings.Limits) { - current[definition.Key] = (await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false)).Value; + var value = await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false); + current[definition.Key] = value.Value; var typed = form[definition.Key].ToString().Trim().Replace(',', '.'); - if (typed.Length == 0) + if (typed.Length == 0 || value.ReadOnly) { next[definition.Key] = current[definition.Key]; continue; @@ -775,13 +820,19 @@ internal static partial class Forms } /// A lower slippage estimate waits for the user (SPEC 11.6). The form is bound for the antiforgery check. - private static async Task DecideCostAsync(Guid id, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + private static async Task DecideCostAsync(Guid id, string choice, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct) { if (host.IsDemo || host.Services is not { } services || choice is not ("conferma" or "rifiuta")) { return Results.Redirect("/laboratorio?errore=motore#stime"); } + // A lower cost lets through operations a higher one would stop: with real money in play it asks like more risk (SPEC 12.4). + if (choice == "conferma" && await RaiseRefusalAsync(services, clock, null, form, ct).ConfigureAwait(false) is { } refusal) + { + return Results.Redirect("/laboratorio?errore=" + refusal + "#stime"); + } + var book = new Anubis.Learning.CostBook(services.Db, host.Clock); var done = await book.DecideAsync(id, choice == "conferma", context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); if (done && services.Trading is { } trading) diff --git a/src/Anubis.Server/ServerApp.cs b/src/Anubis.Server/ServerApp.cs index d03cff5..00b1b1b 100644 --- a/src/Anubis.Server/ServerApp.cs +++ b/src/Anubis.Server/ServerApp.cs @@ -37,6 +37,12 @@ internal static class ServerApp builder.WebHost.UseUrls((local ? "http://127.0.0.1:" : "http://0.0.0.0:") + config.Port.ToString(System.Globalization.CultureInfo.InvariantCulture)); } + builder.WebHost.ConfigureKestrel(k => + { + // No form of Anubis is larger than a few kilobytes; nothing is uploaded. + k.Limits.MaxRequestBodySize = 1024 * 1024; + k.AddServerHeader = false; + }); builder.Logging.ClearProviders(); // Created by the container so it is disposed with the application and releases the log file. builder.Services.AddSingleton(_ => new JsonLogProvider(config.Data.Logs, clock, console: true)); @@ -66,12 +72,14 @@ internal static class ServerApp services.AddAuthentication(SessionAuthentication.SchemeName) .AddScheme(SessionAuthentication.SchemeName, null); - services.AddAuthorization(); + // What a new page or route forgets to say stays closed: only those marked anonymous answer without a session. + services.AddAuthorization(o => o.FallbackPolicy = o.DefaultPolicy); services.AddAntiforgery(o => { o.Cookie.Name = "anubis_csrf"; o.Cookie.SameSite = SameSiteMode.Strict; o.Cookie.HttpOnly = true; + o.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; o.HeaderName = Endpoints.CsrfHeader; o.FormFieldName = "__csrf"; }); @@ -126,6 +134,8 @@ internal static class ServerApp private static void RegisterSecrets(StartupConfig config) { Redactor.Register(config.Db?.Password); + Redactor.Register(config.Db?.UrlPassword); + Redactor.Register(config.HeartbeatUrl); Redactor.Register(config.AdminPassword); foreach (var value in config.EnvironmentKeys.Values) { @@ -141,6 +151,14 @@ internal static class ServerApp headers["Referrer-Policy"] = "same-origin"; headers.ContentSecurityPolicy = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; " + "font-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'"; + headers["Cross-Origin-Opener-Policy"] = "same-origin"; + headers["Permissions-Policy"] = "camera=(), geolocation=(), microphone=(), payment=(), usb=()"; + if (!Gate.IsAlwaysOpen(context.Request.Path)) + { + // Accounts, trades, registers: nothing stays in the browser or in a proxy. + headers.CacheControl = "no-cache, no-store"; + } + return next(); } diff --git a/src/Anubis.Server/TelegramServices.cs b/src/Anubis.Server/TelegramServices.cs index aa8005e..2ed9157 100644 --- a/src/Anubis.Server/TelegramServices.cs +++ b/src/Anubis.Server/TelegramServices.cs @@ -34,7 +34,7 @@ internal sealed partial class TelegramServices : IDisposable _secrets = secrets; _zone = host.Config.TimeZone; _logger = logger; - _http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false); + _http = Anubis.Brokers.Outgoing.KeyedClient(handler); // Longer than the wait of the commands' long polling. _http.Timeout = TimeSpan.FromSeconds(60); diff --git a/src/Anubis.Server/TradesView.cs b/src/Anubis.Server/TradesView.cs index 99b83b0..a2ac37c 100644 --- a/src/Anubis.Server/TradesView.cs +++ b/src/Anubis.Server/TradesView.cs @@ -154,7 +154,7 @@ internal sealed record TradesView( static string Number(decimal value) => (Math.Round(value, 8) / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ','); - static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' '); + static string Clean(string value) => Format.CsvText(value); } private sealed record Closed(Guid Id, Guid Account, Guid Instrument, string Strategy, DateTimeOffset OpenedAt, DateTimeOffset ClosedAt, decimal BoughtQuantity, decimal BoughtValue, diff --git a/src/Anubis/Access/AccessStore.cs b/src/Anubis/Access/AccessStore.cs index e416b9e..279f4b3 100644 --- a/src/Anubis/Access/AccessStore.cs +++ b/src/Anubis/Access/AccessStore.cs @@ -117,6 +117,12 @@ public sealed class LoginLimiter(IClock clock) { lock (_gate) { + // Begin counts every attempt, also those that end well: a success takes them back from both counts. + while (_failures.TryGetValue(address, out var list) && list.Count > 0) + { + Forgive(address); + } + _failures.Remove(address); } } @@ -136,31 +142,21 @@ public sealed class LoginLimiter(IClock clock) } /// -/// The single user of Anubis and their sessions (SPEC 15.4). Sessions are random tokens in an HttpOnly cookie; -/// only their SHA-256 is stored, so a copy of the database does not let anyone in. +/// What stays in memory about re-authentications: the wrong attempts and the last second-factor code used. It lives as +/// long as the process, not as long as the services, which the interface can start again (new broker keys): otherwise +/// whoever holds a stolen session would clear the count between one attempt and the next. /// -public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, int iterations = Passwords.DefaultIterations) +public sealed class AccessGuards(IClock clock) { - public const string AdminName = "admin"; - public static readonly TimeSpan IdleTimeout = TimeSpan.FromHours(12); - public static readonly TimeSpan MaxLifetime = TimeSpan.FromDays(7); - - // Wrong fresh re-authentications (SPEC 12.4) are limited like sign-ins, so a stolen session cannot try passwords. - private const string FreshAttempts = "reauthentication"; - private readonly LoginLimiter _fresh = new(clock); - - // Each second-factor code works once (RFC 6238, 5.2): the last time step used, in memory. - private readonly Lock _stepGate = new(); + private readonly Lock _gate = new(); private long _lastStep = long.MinValue; - private bool AcceptCode(ReadOnlySpan secret, string? code) - { - if (Totp.Match(secret, code, clock.UtcNow) is not { } step) - { - return false; - } + public LoginLimiter Fresh { get; } = new(clock); - lock (_stepGate) + /// Each second-factor code works once (RFC 6238, 5.2). + public bool AcceptStep(long step) + { + lock (_gate) { if (step <= _lastStep) { @@ -171,6 +167,39 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return true; } } +} + +/// How a change of password or second factor ended. +public enum AccessChange +{ + Done, + + /// The password or the code is wrong. + Wrong, + + /// Too many wrong attempts in 15 minutes: even the right password waits. + Locked, + + /// The second factor is already on: it must be switched off first, which asks for its code. + AlreadyOn, +} + +/// +/// The single user of Anubis and their sessions (SPEC 15.4). Sessions are random tokens in an HttpOnly cookie; +/// only their SHA-256 is stored, so a copy of the database does not let anyone in. +/// +public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, int iterations = Passwords.DefaultIterations, AccessGuards? guards = null) +{ + public const string AdminName = "admin"; + public static readonly TimeSpan IdleTimeout = TimeSpan.FromHours(12); + public static readonly TimeSpan MaxLifetime = TimeSpan.FromDays(7); + + // Wrong fresh re-authentications (SPEC 12.4) are limited like sign-ins, so a stolen session cannot try passwords. + private const string FreshAttempts = "reauthentication"; + private readonly AccessGuards _guards = guards ?? new AccessGuards(clock); + + private bool AcceptCode(ReadOnlySpan secret, string? code) => + Totp.Match(secret, code, clock.UtcNow) is { } step && _guards.AcceptStep(step); private static string SecondFactorName(Guid userId) => "totp:" + userId.ToString("D"); @@ -260,15 +289,25 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, var token = Ids.NewToken(); var now = clock.UtcNow; - await db.WriteAsync(s => s.ExecuteAsync( - "INSERT INTO sessions (id, user_id, token_hash, user_agent, address, created_at, last_seen_at, expires_at) VALUES (@id, @u, @h, @ua, @a, @t, @t, @e)", - cancellationToken, ("id", Ids.NewId(clock)), ("u", user.Id), ("h", HashToken(token)), ("ua", Truncate(userAgent, 300)), ("a", Truncate(address, 100)), - ("t", now), ("e", now + MaxLifetime)), cancellationToken).ConfigureAwait(false); + await db.WriteAsync(async s => + { + // Sessions over, with their address and browser, do not pile up. + await s.ExecuteAsync("DELETE FROM sessions WHERE expires_at <= @t OR last_seen_at <= @idle", cancellationToken, ("t", now), ("idle", now - IdleTimeout)).ConfigureAwait(false); + await s.ExecuteAsync( + "INSERT INTO sessions (id, user_id, token_hash, user_agent, address, created_at, last_seen_at, expires_at) VALUES (@id, @u, @h, @ua, @a, @t, @t, @e)", + cancellationToken, ("id", Ids.NewId(clock)), ("u", user.Id), ("h", HashToken(token)), ("ua", Truncate(userAgent, 300)), ("a", Truncate(address, 100)), + ("t", now), ("e", now + MaxLifetime)).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); return (LoginResult.Ok, token); } - /// The session behind a cookie token, or null when unknown, idle too long or expired. - public async Task ValidateAsync(string? token, CancellationToken cancellationToken = default) + public Task ValidateAsync(string? token, CancellationToken cancellationToken = default) => ValidateAsync(token, refresh: true, cancellationToken); + + /// + /// The session behind a cookie token, or null when unknown, idle too long or expired. Without + /// the idle time goes on: an open page that only listens does not keep a session alive. + /// + public async Task ValidateAsync(string? token, bool refresh, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(token)) { @@ -292,7 +331,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, } // Refresh the idle timer at most once a minute, to keep writes rare. - if (now - found.Seen > TimeSpan.FromMinutes(1)) + if (refresh && now - found.Seen > TimeSpan.FromMinutes(1)) { await db.WriteAsync(s => s.ExecuteAsync("UPDATE sessions SET last_seen_at = @t WHERE id = @id", cancellationToken, ("t", now), ("id", found.Id)), cancellationToken) .ConfigureAwait(false); @@ -304,45 +343,86 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, public Task SignOutAsync(string token, CancellationToken cancellationToken = default) => db.WriteAsync(s => s.ExecuteAsync("DELETE FROM sessions WHERE token_hash = @h", cancellationToken, ("h", HashToken(token))), cancellationToken); - /// Changes the password and ends every other session. - public async Task ChangePasswordAsync(Guid userId, string current, string replacement, Guid keepSession, CancellationToken cancellationToken = default) + /// + /// A new password: every other session ends and the one that asked goes on with a new token, so a copied cookie stops + /// working too. Wrong attempts count like those of a fresh re-authentication. + /// + public async Task<(AccessChange Outcome, string? Token)> ChangePasswordAsync(Guid userId, string current, string replacement, Guid keepSession, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(current); + if (_guards.Fresh.Begin(FreshAttempts) > TimeSpan.Zero) + { + return (AccessChange.Locked, null); + } + var hash = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash FROM users WHERE id = @id", r => r.Text("password_hash"), ("id", userId)), cancellationToken) .ConfigureAwait(false); if (hash is null || !Passwords.Verify(current, hash)) { - return false; + return (AccessChange.Wrong, null); } + _guards.Fresh.Succeeded(FreshAttempts); var replacementHash = Passwords.Hash(replacement, iterations); var now = clock.UtcNow; + var token = Ids.NewToken(); await db.WriteAsync(async s => { await s.ExecuteAsync("UPDATE users SET password_hash = @h, must_change_password = @m, updated_at = @t WHERE id = @id", cancellationToken, ("h", replacementHash), ("m", false), ("t", now), ("id", userId)).ConfigureAwait(false); - await s.ExecuteAsync("DELETE FROM sessions WHERE user_id = @u AND id <> @keep", cancellationToken, ("u", userId), ("keep", keepSession)).ConfigureAwait(false); + await EndOthersAsync(s, userId, keepSession, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE sessions SET token_hash = @h WHERE id = @keep", cancellationToken, ("h", HashToken(token)), ("keep", keepSession)).ConfigureAwait(false); await LogAsync(s, "security.password", "cambiata", cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); - return true; + return (AccessChange.Done, token); } - /// Turns on the second factor after the user proved the app produces valid codes. - public async Task EnableSecondFactorAsync(Guid userId, byte[] secret, string code, CancellationToken cancellationToken = default) + private static Task EndOthersAsync(DbSession s, Guid userId, Guid keepSession, CancellationToken cancellationToken) => + s.ExecuteAsync("DELETE FROM sessions WHERE user_id = @u AND id <> @keep", cancellationToken, ("u", userId), ("keep", keepSession)); + + /// + /// Turns on the second factor with the password and a code that proves the app works. Never over an active one: a + /// stolen session could put its own in place of the user's. The other sessions end. + /// + public async Task EnableSecondFactorAsync(Guid userId, byte[] secret, string password, string code, Guid keepSession, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(secret); - if (!AcceptCode(secret, code)) + if (_guards.Fresh.Begin(FreshAttempts) > TimeSpan.Zero) { - return false; + return AccessChange.Locked; } - var sealedSecret = secrets.Seal("totp:" + userId.ToString("D"), Convert.ToBase64String(secret)); - await db.WriteAsync(async s => + var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash, totp_secret FROM users WHERE id = @id", + r => (Hash: r.Text("password_hash"), On: !r.IsNull("totp_secret")), ("id", userId)), cancellationToken).ConfigureAwait(false); + if (user == default || string.IsNullOrEmpty(password) || !Passwords.Verify(password, user.Hash)) { - await s.ExecuteAsync("UPDATE users SET totp_secret = @s, updated_at = @t WHERE id = @id", cancellationToken, - ("s", sealedSecret), ("t", clock.UtcNow), ("id", userId)).ConfigureAwait(false); + return AccessChange.Wrong; + } + + _guards.Fresh.Succeeded(FreshAttempts); + if (user.On) + { + return AccessChange.AlreadyOn; + } + + if (!AcceptCode(secret, code)) + { + return AccessChange.Wrong; + } + + var sealedSecret = secrets.Seal(SecondFactorName(userId), Convert.ToBase64String(secret)); + return await db.WriteAsync(async s => + { + if (await s.ExecuteAsync("UPDATE users SET totp_secret = @s, updated_at = @t WHERE id = @id AND totp_secret IS NULL", cancellationToken, + ("s", sealedSecret), ("t", clock.UtcNow), ("id", userId)).ConfigureAwait(false) == 0) + { + return AccessChange.AlreadyOn; + } + + await EndOthersAsync(s, userId, keepSession, cancellationToken).ConfigureAwait(false); await LogAsync(s, "security.second_factor", "attivato", cancellationToken).ConfigureAwait(false); + return AccessChange.Done; }, cancellationToken).ConfigureAwait(false); - return true; } /// @@ -350,50 +430,48 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, /// now whatever the session. Nothing is written. After five wrong attempts in 15 minutes every attempt fails, /// even with the right password, until the window has passed. /// - public async Task ReauthenticateAsync(string password, string? code, CancellationToken cancellationToken = default) + public async Task ReauthenticateAsync(string password, string? code, CancellationToken cancellationToken = default) => + await CheckFreshAsync(password, code, cancellationToken).ConfigureAwait(false) == AccessChange.Done; + + private async Task CheckFreshAsync(string password, string? code, CancellationToken cancellationToken) { - if (_fresh.Begin(FreshAttempts) > TimeSpan.Zero) + if (_guards.Fresh.Begin(FreshAttempts) > TimeSpan.Zero) { - return false; + return AccessChange.Locked; } var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id, password_hash, totp_secret FROM users WHERE username = @u", r => (Id: r.Id("id"), Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("u", AdminName)), cancellationToken).ConfigureAwait(false); if (user == default || string.IsNullOrEmpty(password) || !Passwords.Verify(password, user.Hash)) { - return false; + return AccessChange.Wrong; } if (user.Totp is null || AcceptSealedCode(user.Id, user.Totp, code)) { - _fresh.Succeeded(FreshAttempts); - return true; + _guards.Fresh.Succeeded(FreshAttempts); + return AccessChange.Done; } - return false; + return AccessChange.Wrong; } - /// Turning the second factor off asks for both: the password and a code from the app. - public async Task DisableSecondFactorAsync(Guid userId, string password, string? code, CancellationToken cancellationToken = default) + /// Turning the second factor off asks for both, the password and a code from the app, and ends the other sessions. + public async Task DisableSecondFactorAsync(Guid userId, string password, string? code, Guid keepSession, CancellationToken cancellationToken = default) { - var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash, totp_secret FROM users WHERE id = @id", - r => (Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("id", userId)), cancellationToken).ConfigureAwait(false); - if (user == default || !Passwords.Verify(password, user.Hash)) + var outcome = await CheckFreshAsync(password, code, cancellationToken).ConfigureAwait(false); + if (outcome != AccessChange.Done) { - return false; - } - - if (user.Totp is not null && !AcceptSealedCode(userId, user.Totp, code)) - { - return false; + return outcome; } await db.WriteAsync(async s => { await s.ExecuteAsync("UPDATE users SET totp_secret = NULL, updated_at = @t WHERE id = @id", cancellationToken, ("t", clock.UtcNow), ("id", userId)).ConfigureAwait(false); + await EndOthersAsync(s, userId, keepSession, cancellationToken).ConfigureAwait(false); await LogAsync(s, "security.second_factor", "disattivato", cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); - return true; + return AccessChange.Done; } private Task LogAsync(DbSession s, string key, string what, CancellationToken cancellationToken) => diff --git a/src/Anubis/Brokers/Outgoing.cs b/src/Anubis/Brokers/Outgoing.cs new file mode 100644 index 0000000..342ec10 --- /dev/null +++ b/src/Anubis/Brokers/Outgoing.cs @@ -0,0 +1,19 @@ +namespace Anubis.Brokers; + +/// +/// Clients for requests that carry a key. They follow no redirect: .NET drops only the Authorization header on the way +/// to another host, and the keys of the brokers travel in headers of their own. +/// +public static class Outgoing +{ + public static HttpMessageHandler KeyedHandler() => new SocketsHttpHandler + { + AllowAutoRedirect = false, + PooledConnectionLifetime = TimeSpan.FromMinutes(10), + AutomaticDecompression = System.Net.DecompressionMethods.All, + }; + + /// A client on (the tests), or on one of its own. + public static HttpClient KeyedClient(HttpMessageHandler? handler = null) => + handler is null ? new HttpClient(KeyedHandler()) : new HttpClient(handler, disposeHandler: false); +} diff --git a/src/Anubis/Core/Format.cs b/src/Anubis/Core/Format.cs index 83402d1..fe7641f 100644 --- a/src/Anubis/Core/Format.cs +++ b/src/Anubis/Core/Format.cs @@ -211,9 +211,17 @@ public static class Format int or long => Convert.ToString(cell, CultureInfo.InvariantCulture)!, DateOnly date => date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), DateTimeOffset moment => moment.ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture), - _ => Convert.ToString(cell, CultureInfo.InvariantCulture) ?? "", + _ => Harmless(Convert.ToString(cell, CultureInfo.InvariantCulture) ?? ""), }; + /// + /// A text cell of a CSV: quoted when it must be, and never a formula. Names come from brokers and news: one that starts + /// with = + - @ would be computed by the spreadsheet that opens the file. + /// + public static string CsvText(string? value) => CsvField(Harmless(value ?? "")); + + private static string Harmless(string value) => value.Length > 1 && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r' ? "'" + value : value; + private static string CsvField(string value) => value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value; } diff --git a/src/Anubis/Core/Scheduling.cs b/src/Anubis/Core/Scheduling.cs index 3c7f7d5..4f856aa 100644 --- a/src/Anubis/Core/Scheduling.cs +++ b/src/Anubis/Core/Scheduling.cs @@ -387,7 +387,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger? _sockets; private readonly ILogger _logger; private readonly MarketCollector _okxCollector; @@ -64,9 +67,14 @@ public sealed partial class MarketDataService : IDisposable _sockets = sockets; _logger = logger ?? NullLogger.Instance; Offline = offline; - _http = Client(handler, offline); - _http.Timeout = TimeSpan.FromSeconds(60); - _http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); + _http = Client(handler, offline, signed: false); + _signed = Client(handler, offline, signed: true); + foreach (var client in new[] { _http, _signed }) + { + client.Timeout = TimeSpan.FromSeconds(60); + client.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); + } + Okx = new OkxClient(_http, clock, okx, sockets); Freshness = new FreshnessMonitor(clock, bus); @@ -81,7 +89,7 @@ public sealed partial class MarketDataService : IDisposable { ModelFolder = offline || data is null ? null : Path.Combine(data.Root, "models"), Watcher = new News.NewsWatcher(db, clock, settings) { EarningsActive = References.EarningsFilterActiveAsync }, - Analyst = new News.NewsAnalyst(db, clock, settings, secrets.RevealAsync, (config, key) => new News.LanguageModel(_http, config, key), _logger), + Analyst = new News.NewsAnalyst(db, clock, settings, secrets.RevealAsync, (config, key) => new News.LanguageModel(_signed, config, key), _logger), }; } @@ -161,17 +169,18 @@ public sealed partial class MarketDataService : IDisposable _work.Dispose(); News.Dispose(); _http.Dispose(); + _signed.Dispose(); } // The connection pool shared by every source; offline, only this computer's own addresses are reached. - private static HttpClient Client(HttpMessageHandler? handler, bool offline) + private static HttpClient Client(HttpMessageHandler? handler, bool offline, bool signed) { var owned = handler is null; - var network = handler ?? new SocketsHttpHandler + var network = handler ?? (signed ? Outgoing.KeyedHandler() : new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(10), AutomaticDecompression = System.Net.DecompressionMethods.All, - }; + }); if (offline) { network = new Supervision.LoopbackOnlyHandler(network, owned); @@ -201,7 +210,7 @@ public sealed partial class MarketDataService : IDisposable return cached.Client; } - var client = new AlpacaClient(_http, _clock, new AlpacaCredentials(key, secret), null, _sockets); + var client = new AlpacaClient(_signed, _clock, new AlpacaCredentials(key, secret), null, _sockets); _alpaca = (key, secret, client); return client; } diff --git a/src/Anubis/Db/Archive.cs b/src/Anubis/Db/Archive.cs index 04cfcbe..e9cebb5 100644 --- a/src/Anubis/Db/Archive.cs +++ b/src/Anubis/Db/Archive.cs @@ -59,7 +59,10 @@ public static class Archive await using var stream = new FileStream(Path.Combine(folder, file), FileMode.CreateNew, FileAccess.Write); await using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { NewLine = "\n" }; var columns = string.Join(", ", table.Columns.Select(c => c.Name)); - await s.ForEachAsync($"SELECT {columns} FROM {table.Name} ORDER BY id", async reader => + + // Who was signed in is of no use in another database, which ends every session anyway: it stays out of the files. + var rows = table.Name == "sessions" ? "WHERE 1 = 0 " : ""; + await s.ForEachAsync($"SELECT {columns} FROM {table.Name} {rows}ORDER BY id", async reader => { var row = ReadRow(reader, table, s.Engine); totals.Add(table, row); diff --git a/src/Anubis/Notifications/Notifications.cs b/src/Anubis/Notifications/Notifications.cs index b6a6364..e908f4c 100644 --- a/src/Anubis/Notifications/Notifications.cs +++ b/src/Anubis/Notifications/Notifications.cs @@ -98,7 +98,7 @@ public sealed class NotificationSender(Database db, IClock clock, Func Pause(attempts) ? wait : Pause(attempts)) : null; - await MarkAsync(item.Id, NotificationStates.Failed, attempts, next, ex.Message, cancellationToken).ConfigureAwait(false); + await MarkAsync(item.Id, NotificationStates.Failed, attempts, next, Redactor.Redact(ex.Message), cancellationToken).ConfigureAwait(false); if (ex.Retryable) { // Telegram unreachable or asking to slow down: the others wait for the next pass. diff --git a/src/Anubis/Platform/PlatformLoader.cs b/src/Anubis/Platform/PlatformLoader.cs index 83eb38a..79b7e2a 100644 --- a/src/Anubis/Platform/PlatformLoader.cs +++ b/src/Anubis/Platform/PlatformLoader.cs @@ -49,7 +49,15 @@ public static class DockerPlatform "Imposta ANUBIS_ADMIN_PASSWORD e riavvia il container. Al primo accesso ne sceglierai una nuova; questa resta la chiave delle scelte di questa pagina.")); } + else if (admin.Length < Access.Passwords.MinimumLength) + { + problems.Add(new("ANUBIS_ADMIN_PASSWORD", "La password iniziale è troppo corta.", + $"Usa almeno {Access.Passwords.MinimumLength} caratteri in ANUBIS_ADMIN_PASSWORD e riavvia il container: resta la chiave delle scelte di questa pagina.")); + } + Redactor.Register(secret); + Redactor.Register(Get("ANUBIS_HEARTBEAT_URL")); + Redactor.Register(db?.UrlPassword); Redactor.Register(admin); Redactor.Register(db?.Password); diff --git a/src/Anubis/Platform/StartupConfig.cs b/src/Anubis/Platform/StartupConfig.cs index fd5c238..41991d0 100644 --- a/src/Anubis/Platform/StartupConfig.cs +++ b/src/Anubis/Platform/StartupConfig.cs @@ -33,6 +33,20 @@ public sealed record DbSettings /// A full PostgreSQL address (ANUBIS_DB_URL) that replaces the five fields. public string? Url { get; init; } + /// The password inside , so it can be masked; null when there is none. + public string? UrlPassword + { + get + { + if (Url is null || !Uri.TryCreate(Url, UriKind.Absolute, out var uri) || uri.UserInfo.IndexOf(':', StringComparison.Ordinal) is not (> 0 and var colon)) + { + return null; + } + + return Uri.UnescapeDataString(uri.UserInfo[(colon + 1)..]); + } + } + /// Seconds to wait for a new PostgreSQL connection. Short, so a lost server shows quickly; tests raise it. public int ConnectTimeoutSeconds { get; init; } = 5; diff --git a/src/Anubis/Trading/AlpacaTrading.cs b/src/Anubis/Trading/AlpacaTrading.cs index 990650a..c8a1513 100644 --- a/src/Anubis/Trading/AlpacaTrading.cs +++ b/src/Anubis/Trading/AlpacaTrading.cs @@ -41,7 +41,7 @@ public sealed class AlpacaTrading : IBrokerAccount throw new ArgumentException("Il simulatore interno non passa da Alpaca.", nameof(options)); } - _http = new TradingHttp(http, clock, "Alpaca"); + _http = new TradingHttp(http, clock, "Alpaca", BrokerRequests.Alpaca); _clock = clock; _credentials = credentials ?? throw new ArgumentNullException(nameof(credentials)); _options = options; diff --git a/src/Anubis/Trading/OkxTrading.cs b/src/Anubis/Trading/OkxTrading.cs index 8ddd27b..690bd7e 100644 --- a/src/Anubis/Trading/OkxTrading.cs +++ b/src/Anubis/Trading/OkxTrading.cs @@ -46,7 +46,7 @@ public sealed class OkxTrading : IBrokerAccount throw new ArgumentException("Il simulatore interno non passa da OKX.", nameof(options)); } - _http = new TradingHttp(http, clock, "OKX"); + _http = new TradingHttp(http, clock, "OKX", BrokerRequests.Okx); _clock = clock; _credentials = credentials ?? throw new ArgumentNullException(nameof(credentials)); _options = options; diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index 05c592c..6212d41 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -415,7 +415,7 @@ public sealed partial class OrderManager : IDisposable // A real account sends only what the procedure of SPEC 12.4 allows; protection of what the bot holds always goes. private async Task LiveRefusalAsync(TradeIntent intent, CancellationToken cancellationToken) { - if (_account.Environment != TradingEnvironments.Live || intent.Purpose == OrderPurpose.Protective) + if (_account.Environment != TradingEnvironments.Live || intent is { Purpose: OrderPurpose.Protective, Side: OrderSide.Sell }) { return null; } diff --git a/src/Anubis/Trading/Stages.cs b/src/Anubis/Trading/Stages.cs index 3f59aee..b2c82bf 100644 --- a/src/Anubis/Trading/Stages.cs +++ b/src/Anubis/Trading/Stages.cs @@ -208,7 +208,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, return RiskReasons.LiveNotConfirmed; } - if (intent.Purpose is OrderPurpose.Protective or OrderPurpose.Stop) + if (intent.Purpose is OrderPurpose.Protective or OrderPurpose.Stop && intent.Side == OrderSide.Sell) { return null; } diff --git a/src/Anubis/Trading/TradingHttp.cs b/src/Anubis/Trading/TradingHttp.cs index 8622b5b..d76972c 100644 --- a/src/Anubis/Trading/TradingHttp.cs +++ b/src/Anubis/Trading/TradingHttp.cs @@ -11,12 +11,41 @@ public sealed record HttpAnswer(HttpStatusCode Status, string Body) public bool Ok => (int)Status is >= 200 and < 300; } +/// +/// The only requests Anubis makes to a broker with the account's keys (SPEC 9.1 point 2): what is not here is never sent, +/// withdrawals, transfers and leverage first of all. +/// +public static class BrokerRequests +{ + private static readonly HashSet _okx = new(StringComparer.Ordinal) + { + "GET /api/v5/public/time", "GET /api/v5/account/config", "GET /api/v5/account/balance", "GET /api/v5/trade/orders-pending", "GET /api/v5/trade/orders-algo-pending", + "GET /api/v5/trade/order", "GET /api/v5/trade/order-algo", "GET /api/v5/trade/fills", "GET /api/v5/trade/fills-history", + "POST /api/v5/trade/order", "POST /api/v5/trade/order-algo", "POST /api/v5/trade/cancel-order", "POST /api/v5/trade/cancel-algos", + }; + + private static readonly HashSet _alpaca = new(StringComparer.Ordinal) + { + "GET /v2/clock", "GET /v2/account", "GET /v2/positions", "GET /v2/orders", "GET /v2/orders:by_client_order_id", "GET /v2/account/activities", "POST /v2/orders", + }; + + public static bool Okx(HttpMethod method, string path) => _okx.Contains(method + " " + path); + + public static bool Alpaca(HttpMethod method, string path) + { + const string OneOrder = "/v2/orders/"; + return _alpaca.Contains(method + " " + path) || + ((method == HttpMethod.Get || method == HttpMethod.Delete) && path.StartsWith(OneOrder, StringComparison.Ordinal) && path.Length > OneOrder.Length && + path.Skip(OneOrder.Length).All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_')); + } +} + /// /// Requests to a broker's trading API. Reads and cancellations are retried on network errors, 429 and server /// errors; an order is sent once and never retried here: when its answer is lost the order manager asks the /// broker before sending again with the same id (SPEC 7.2). Errors never carry headers, so keys stay out of logs. /// -public sealed class TradingHttp(HttpClient http, IClock clock, string sourceName) +public sealed class TradingHttp(HttpClient http, IClock clock, string sourceName, Func allowed) { public const int Attempts = 3; @@ -27,6 +56,11 @@ public sealed class TradingHttp(HttpClient http, IClock clock, string sourceName ArgumentNullException.ThrowIfNull(method); ArgumentNullException.ThrowIfNull(url); ArgumentNullException.ThrowIfNull(headers); + if (!allowed(method, url.AbsolutePath)) + { + throw new InvalidOperationException($"{SourceName}: richiesta non ammessa ({method} {url.AbsolutePath})."); + } + for (var attempt = 1; ; attempt++) { if (limiter is not null) diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index 8a1ea84..8057b2a 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -169,7 +169,7 @@ public sealed partial class TradingService : IDisposable _consent = consent ?? throw new ArgumentNullException(nameof(consent)); _sockets = sockets; _logger = logger ?? NullLogger.Instance; - _http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false); + _http = Outgoing.KeyedClient(handler); _http.Timeout = TimeSpan.FromSeconds(30); _http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); _catalog = new InstrumentCatalog(db, clock); diff --git a/tests/Anubis.Tests/NewsAnalystTests.cs b/tests/Anubis.Tests/NewsAnalystTests.cs index 5cd46eb..9bcdc47 100644 --- a/tests/Anubis.Tests/NewsAnalystTests.cs +++ b/tests/Anubis.Tests/NewsAnalystTests.cs @@ -493,14 +493,14 @@ public sealed partial class NewsAnalystTests public async Task TheSettingsPageChangesTheModel() { await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); - await server.SignInFirstTimeAsync(); + var password = await server.SignInFirstTimeAsync(); var services = server.Host.Services!; var page = await server.TextAsync("/impostazioni"); StringAssert.Contains(page, "claude-haiku-5-5"); async Task Post(SettingDefinition setting, string value) { - using var response = await server.PostFormAsync("/impostazioni", $"/azioni/impostazioni/{setting.Key}", ("valore", value), ("ritorno", "/impostazioni#notizie")); + using var response = await server.PostFormAsync("/impostazioni", $"/azioni/impostazioni/{setting.Key}", ("valore", value), ("password", password), ("ritorno", "/impostazioni#notizie")); return ServerHarness.Location(response); } diff --git a/tests/Anubis.Tests/RestoreServerTests.cs b/tests/Anubis.Tests/RestoreServerTests.cs index 32bc2b1..0ddcdc1 100644 --- a/tests/Anubis.Tests/RestoreServerTests.cs +++ b/tests/Anubis.Tests/RestoreServerTests.cs @@ -201,7 +201,7 @@ public sealed class RestoreServerTests var services = first.Host.Services!; var secret = Totp.NewSecret(); var user = (await services.Access.GetUserAsync())!; - Assert.IsTrue(await services.Access.EnableSecondFactorAsync(user.Id, secret, Totp.Compute(secret, DateTimeOffset.UtcNow))); + Assert.AreEqual(AccessChange.Done, await services.Access.EnableSecondFactorAsync(user.Id, secret, password, Totp.Compute(secret, DateTimeOffset.UtcNow), Guid.Empty)); await services.Secrets.SetAsync("FINNHUB_API_KEY", "chiave-di-prova-1", "test"); } diff --git a/tests/Anubis.Tests/RiskTests.cs b/tests/Anubis.Tests/RiskTests.cs index 695223a..09e73fe 100644 --- a/tests/Anubis.Tests/RiskTests.cs +++ b/tests/Anubis.Tests/RiskTests.cs @@ -173,10 +173,11 @@ public sealed class RiskTests public void TheCodeCallsNoWithdrawalOrTransferEndpoint() { // SPEC 9.1 point 2: OKX withdrawals and transfers, Alpaca transfers and bank links, in any form. - var endpoint = new System.Text.RegularExpressions.Regex(@"asset/withdrawal|asset/transfer|/transfers\b|ach_relationships|recipient_banks|/withdraw", + var endpoint = new System.Text.RegularExpressions.Regex( + @"asset/withdrawal|asset/transfer|subaccount|asset/convert|/fiat/|/finance/|set-leverage|/transfers\b|ach_relationships|recipient_banks|/withdraw|/v1/journals|/v2/wallets", System.Text.RegularExpressions.RegexOptions.IgnoreCase); var offenders = Repo.Files() - .Where(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal)) + .Where(f => f.Extension is ".cs" or ".razor" or ".js" && (Repo.Relative(f).StartsWith("src", StringComparison.Ordinal) || Repo.Relative(f).StartsWith("tools", StringComparison.Ordinal))) .Where(f => endpoint.IsMatch(File.ReadAllText(f.FullName))) .Select(Repo.Relative) .ToList(); diff --git a/tests/Anubis.Tests/SecurityTests.cs b/tests/Anubis.Tests/SecurityTests.cs new file mode 100644 index 0000000..2dc9120 --- /dev/null +++ b/tests/Anubis.Tests/SecurityTests.cs @@ -0,0 +1,396 @@ +using System.Net; +using System.Net.Http.Json; +using System.Net.WebSockets; +using System.Text; +using System.Text.RegularExpressions; +using Anubis.Access; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.News; +using Anubis.Platform; +using Anubis.Server; +using Anubis.Trading; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; + +namespace Anubis.Tests; + +/// The security review of Phase 9 as tests (issue #68, SPEC 15.4, 12.4, 9.1). +[TestClass] +public sealed partial class SecurityTests +{ + private static readonly string[] _open = + [ + "/health", "/brand/{file}", "/assets/{file}", "/favicon.ico", "/accesso", "/primo-avvio", "/servizio", "/azioni/accesso", "/azioni/primo-avvio", "/azioni/primo-avvio/prova", + "/azioni/servizio/{choice}", + ]; + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task EveryRouteAsksForASessionAndEveryFormForItsToken() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + var endpoints = server.Services.GetRequiredService().Endpoints.OfType().ToList(); + Assert.IsGreaterThan(60, endpoints.Count); + var open = new HashSet(StringComparer.Ordinal); + var forms = new List(); + foreach (var e in endpoints) + { + var path = "/" + e.RoutePattern.RawText!.TrimStart('/'); + if (e.Metadata.GetMetadata() is not null) + { + open.Add(path); + } + else if (!path.StartsWith("/_", StringComparison.Ordinal)) + { + Assert.IsNotNull(e.Metadata.GetMetadata(), path + " does not ask for a session."); + } + + var writes = (e.Metadata.GetMetadata()?.HttpMethods ?? []).Any(m => m is not ("GET" or "HEAD" or "OPTIONS")); + if (writes && path.StartsWith("/azioni", StringComparison.Ordinal)) + { + Assert.IsTrue(e.Metadata.GetMetadata()?.RequiresValidation, path + " accepts a form without its token."); + forms.Add(path); + } + } + + CollectionAssert.AreEquivalent(_open, open.ToList()); + Assert.IsGreaterThan(30, forms.Count); + + // And really: signed in, without the token, every form is refused. + await server.SignInFirstTimeAsync(); + foreach (var form in forms) + { + var address = Parameter().Replace(form, m => m.Value.Contains("guid", StringComparison.Ordinal) ? Guid.Empty.ToString("D") : "x"); + using var content = new FormUrlEncodedContent([new("password", "x")]); + using var answer = await server.Http.PostAsync(new Uri(address, UriKind.Relative), content); + Assert.IsTrue(answer.StatusCode == HttpStatusCode.BadRequest || (answer.StatusCode == HttpStatusCode.ServiceUnavailable && open.Contains(form)) || + (answer.StatusCode == HttpStatusCode.Redirect && form.StartsWith("/azioni/primo-avvio", StringComparison.Ordinal)), form + ": " + answer.StatusCode); + } + + using var unknown = await server.GetAsync("/qualcosa-che-non-esiste"); + Assert.AreEqual(HttpStatusCode.NotFound, unknown.StatusCode); + server.Forget(); + using var stranger = await server.GetAsync("/api/registri.zip"); + Assert.AreEqual(HttpStatusCode.Unauthorized, stranger.StatusCode); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task PagesAreNotKeptAndLargeBodiesAreRefused() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + await server.SignInFirstTimeAsync(); + foreach (var path in new[] { "/", "/impostazioni", "/api/status", "/api/conti/posizioni.csv" }) + { + using var page = await server.GetAsync(path); + StringAssert.Contains(page.Headers.CacheControl?.ToString(), "no-store", path); + Assert.AreEqual("", page.Headers.Server.ToString()); + Assert.AreEqual("same-origin", page.Headers.GetValues("Cross-Origin-Opener-Policy").Single()); + } + + using (var style = await server.GetAsync("/assets/anubis.css")) + { + Assert.IsNull(style.Headers.CacheControl); + } + + using (var content = new ByteArrayContent(new byte[(1024 * 1024) + 1]) { Headers = { { "Content-Type", "application/x-www-form-urlencoded" } } }) + using (var large = await server.Http.PostAsync(new Uri("/azioni/accesso", UriKind.Relative), content)) + { + Assert.IsTrue(large.StatusCode is HttpStatusCode.RequestEntityTooLarge or HttpStatusCode.BadRequest, large.StatusCode.ToString()); + } + + using var odd = await server.GetAsync("/api/diagnostica.md?ore=NaN"); + Assert.AreEqual(HttpStatusCode.OK, odd.StatusCode); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheLiveStatusEndsWithTheSession() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + await server.SignInFirstTimeAsync(); + var address = new UriBuilder(server.BaseAddress) { Scheme = "ws", Path = "/ws" }.Uri; + using (var foreign = new ClientWebSocket()) + { + foreign.Options.Cookies = server.Cookies; + foreign.Options.SetRequestHeader("Origin", "http://other.example"); + await Assert.ThrowsAsync(() => foreign.ConnectAsync(address, CancellationToken.None)); + } + + using var socket = new ClientWebSocket(); + socket.Options.Cookies = new CookieContainer(); + socket.Options.Cookies.Add(server.Cookies.GetCookies(server.BaseAddress)); + await socket.ConnectAsync(address, CancellationToken.None); + var buffer = new byte[8192]; + Assert.AreEqual(WebSocketMessageType.Text, (await socket.ReceiveAsync(buffer, CancellationToken.None)).MessageType); + using (var bye = await server.PostFormAsync("/impostazioni", "/azioni/esci")) + { + Assert.AreEqual("/accesso", ServerHarness.Location(bye)); + } + + using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + while ((await socket.ReceiveAsync(buffer, limit.Token)).MessageType != WebSocketMessageType.Close) + { + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task WhereTheKeyOfTheModelGoesIsDecidedWithThePassword() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + var password = await server.SignInFirstTimeAsync(); + var settings = server.Host.Services!.Settings; + await server.Host.Services.Secrets.SetAsync(NewsModelSettings.KeySecret, "chiave-del-modello-1", "test"); + const string action = "/azioni/impostazioni/"; + async Task Save(string key, string value, string? with) + { + using var answer = await server.PostFormAsync("/impostazioni", action + key, ("ritorno", "/impostazioni"), ("valore", value), ("password", with ?? "")); + return ServerHarness.Location(answer); + } + + StringAssert.Contains(await Save(NewsModelSettings.Address.Key, "https://collector.example/", null), "errore=password-rischio"); + StringAssert.Contains(await Save(NewsModelSettings.Provider.Key, NewsModelProviders.OpenAi, "wrong-password-1"), "errore=password-rischio"); + Assert.AreEqual("", (await settings.GetAsync(NewsModelSettings.Address.Key)).Value); + Assert.AreEqual(NewsModelProviders.Anthropic, (await settings.GetAsync(NewsModelSettings.Provider.Key)).Value); + Assert.AreEqual("/impostazioni", await Save(NewsModelSettings.Address.Key, "https://models.example/", password)); + Assert.AreEqual("https://models.example/", (await settings.GetAsync(NewsModelSettings.Address.Key)).Value); + + var csrf = await server.Http.GetFromJsonAsync>(new Uri("/api/antiforgery", UriKind.Relative)); + foreach (var key in NewsModelSettings.All.Concat(NewsRuleSettings.All).Select(d => d.Key)) + { + using var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + key, UriKind.Relative)) { Content = JsonContent.Create(new { value = "off" }) }; + request.Headers.Add(csrf!["header"], csrf["token"]); + using var put = await server.Http.SendAsync(request); + Assert.AreEqual(HttpStatusCode.BadRequest, put.StatusCode, key); + StringAssert.Contains(await put.Content.ReadAsStringAsync(), "usa_le_impostazioni"); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task WithRealMoneyARuleGoesOffOnlyWithThePhraseAndThePassword() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true); + var password = await server.SignInFirstTimeAsync(); + var services = server.Host.Services!; + async Task Switch(SettingDefinition rule, string value, params (string, string)[] more) + { + using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + rule.Key, [("ritorno", "/impostazioni"), ("valore", value), .. more]); + return ServerHarness.Location(answer); + } + + Assert.AreEqual("/impostazioni", await Switch(NewsRuleSettings.Macro, "off"), "Without real money a switch is a switch."); + await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = 'crypto_trend'")); + Assert.IsTrue(await new StageBook(services.Db, server.Host.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)).AnyLiveAsync(null, CancellationToken.None)); + StringAssert.Contains(await server.TextAsync("/impostazioni"), "per spegnere la regola servono la frase e la password"); + StringAssert.Contains(await Switch(NewsRuleSettings.Severe, "off"), "errore=frase-rischio"); + StringAssert.Contains(await Switch(NewsRuleSettings.Severe, "off", ("frase", StageBook.RaisePhrase), ("password", "wrong-password-1")), "errore=password-rischio"); + Assert.AreEqual("on", (await services.Settings.GetAsync(NewsRuleSettings.Severe.Key)).Value); + Assert.AreEqual("/impostazioni", await Switch(NewsRuleSettings.Severe, "off", ("frase", StageBook.RaisePhrase), ("password", password))); + Assert.AreEqual("/impostazioni", await Switch(NewsRuleSettings.Severe, "on"), "Back on is always free."); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task NoPageAndNoDownloadShowsASecret() + { + const string heartbeat = "http://192.168.0.9/ping/segreto-del-segnale-1"; + var env = ServerHarness.DockerSqlite(); + env["FRED_API_KEY"] = "segreto-fred-ambiente-1"; + env["ANUBIS_HEARTBEAT_URL"] = heartbeat; + await using var server = await ServerHarness.StartAsync("docker", env, trading: true); + var password = await server.SignInFirstTimeAsync(); + var services = server.Host.Services!; + var values = new List { "segreto-fred-ambiente-1", heartbeat, ServerHarness.SecretKey, ServerHarness.AdminPassword, password }; + foreach (var (name, i) in TradingService.KeyFields(Venues.Okx).Concat(TradingService.KeyFields(Venues.Alpaca)).Select(k => k.Name) + .Concat([NewsModelSettings.KeySecret, "FINNHUB_API_KEY", "TELEGRAM_BOT_TOKEN"]).Select((n, i) => (n, i))) + { + values.Add("segreto-salvato-" + i); + await services.Secrets.SetAsync(name, "segreto-salvato-" + i, "test"); + } + + var hash = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash FROM users", r => r.Text("password_hash"))); + values.Add(hash!); + var paths = server.Services.GetRequiredService().Endpoints.OfType() + .Where(e => e.Metadata.GetMetadata()?.HttpMethods.Contains("GET") != false) + .Select(e => "/" + e.RoutePattern.RawText!.TrimStart('/')) + .Where(p => !p.Contains('{', StringComparison.Ordinal) && !p.StartsWith("/_", StringComparison.Ordinal) && p != "/ws") + .Concat(["/api/secrets/OKX_API_KEY_DEMO", "/api/secrets/FRED_API_KEY", "/operazioni?pagina=1", "/api/data/quality?format=md&days=30"]) + .Distinct().ToList(); + Assert.IsGreaterThan(25, paths.Count); + foreach (var path in paths) + { + using var answer = await server.GetAsync(path); + var text = path.EndsWith(".zip", StringComparison.Ordinal) ? await UnzipAsync(answer) : WebUtility.HtmlDecode(await answer.Content.ReadAsStringAsync()); + foreach (var value in values) + { + Assert.IsFalse(text.Contains(value, StringComparison.Ordinal), path + " shows " + value); + } + } + + // The archive carries the keys encrypted, and nobody's session. + var folder = TempFolder.Create("archive-secrets"); + var archive = Path.Combine(folder, "a"); + await Archive.ExportAsync(services.Db, archive, server.Host.Clock); + foreach (var file in Directory.EnumerateFiles(archive)) + { + var text = await File.ReadAllTextAsync(file); + foreach (var value in values.Where(v => v != hash)) + { + Assert.IsFalse(text.Contains(value, StringComparison.Ordinal), file); + } + } + + Assert.AreEqual(0L, new FileInfo(Path.Combine(archive, "sessions.jsonl")).Length); + TempFolder.Delete(folder); + } + + private static async Task UnzipAsync(HttpResponseMessage answer) + { + using var zip = new System.IO.Compression.ZipArchive(await answer.Content.ReadAsStreamAsync()); + var text = new StringBuilder(); + foreach (var entry in zip.Entries) + { + using var reader = new StreamReader(await entry.OpenAsync()); + text.Append(await reader.ReadToEndAsync()); + } + + return text.ToString(); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AKeyNeverFollowsARedirect() + { + var builder = WebApplication.CreateSlimBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + await using var other = builder.Build(); + var reached = 0; + other.MapFallback(() => Interlocked.Increment(ref reached)); + await other.StartAsync(); + var target = other.Urls.Single(); + + builder = WebApplication.CreateSlimBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + await using var broker = builder.Build(); + broker.MapFallback((HttpContext c) => Results.Redirect(target + c.Request.Path, permanent: false, preserveMethod: true)); + await broker.StartAsync(); + var address = new Uri(broker.Urls.Single()); + + using var http = Outgoing.KeyedClient(); + var trading = new TradingHttp(http, SystemClock.Instance, "prova", (_, _) => true); + Dictionary headers = new() { ["APCA-API-SECRET-KEY"] = "segreto", ["OK-ACCESS-KEY"] = "chiave" }; + var answer = await trading.SendAsync(HttpMethod.Post, new Uri(address, "/v2/orders"), "{}", _ => headers, null, retry: false, CancellationToken.None); + Assert.IsFalse(answer.Ok); + await Assert.ThrowsAsync(() => new ApiHttp(http, SystemClock.Instance, "prova").GetBytesAsync(new Uri(address, "/v2/bars"), null, headers, CancellationToken.None)); + var reply = await new LanguageModel(http, new NewsModelConfig(NewsModelProviders.Anthropic, "m", address, 0m, 0m, 0m), "segreto") + .AskAsync(new ModelRequest("i", "m", [], 10), CancellationToken.None); + Assert.IsNull(reply.Text); + Assert.AreEqual(0, reached, "The other host must never be reached."); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("POST", "/api/v5/asset/with" + "drawal")] + [DataRow("POST", "/api/v5/asset/trans" + "fer")] + [DataRow("POST", "/api/v5/account/set-" + "leverage")] + [DataRow("POST", "/api/v5/trade/amend-order")] + [DataRow("GET", "/api/v5/asset/balances")] + [DataRow("POST", "/v2/wal" + "lets/transfers")] + [DataRow("POST", "/v1/journals")] + [DataRow("DELETE", "/v2/positions")] + [DataRow("DELETE", "/v2/orders")] + [DataRow("DELETE", "/v2/orders/")] + [DataRow("DELETE", "/v2/orders/a/../../positions")] + [DataRow("PATCH", "/v2/account/configurations")] + public async Task WhatIsNotInTheListIsNeverSent(string method, string path) + { + var verb = new HttpMethod(method); + Assert.IsFalse(BrokerRequests.Okx(verb, path)); + Assert.IsFalse(BrokerRequests.Alpaca(verb, path)); + using var http = new FakeHttp(); + var trading = new TradingHttp(http.Client(), SystemClock.Instance, "prova", BrokerRequests.Alpaca); + await Assert.ThrowsAsync(() => trading.SendAsync(verb, new Uri("https://example.test" + path), null, _ => new Dictionary(), null, + retry: false, CancellationToken.None)); + Assert.IsEmpty(http.Requests); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheAccountsAreOpenedInTwoPlacesOnlyAndBothAskForTheConsent() + { + var code = Repo.Files().Where(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal)).ToList(); + var openers = code.Where(f => Opener().IsMatch(File.ReadAllText(f.FullName))).Select(f => f.Name).ToList(); + CollectionAssert.AreEquivalent(new[] { "TradingService.cs", "GuardBrokers.cs" }, openers); + foreach (var name in new[] { "OkxTrading.cs", "AlpacaTrading.cs" }) + { + StringAssert.Contains(File.ReadAllText(code.Single(f => f.Name == name).FullName), "LiveGuard.Ensure(options.Environment, consent);"); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheContainerIsHardened() + { + var entry = File.ReadAllText(Path.Combine(Repo.Root.FullName, "deploy", "docker", "entrypoint.sh")); + StringAssert.Contains(entry, "umask 077"); + StringAssert.Contains(entry, "--no-new-privs"); + StringAssert.Contains(entry, "PUID=0"); + var template = File.ReadAllText(Path.Combine(Repo.Root.FullName, "deploy", "unraid", "anubis.xml")); + foreach (var name in new[] { "ANUBIS_DB_PASSWORD", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD", "TELEGRAM_BOT_TOKEN", "ANUBIS_HEARTBEAT_URL", "ANUBIS_DB_URL" }) + { + StringAssert.Matches(template, new Regex("Target=\"" + name + "\"[^>]*Mask=\"true\""), name); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AShortFirstPasswordIsAProblemOfTheConfiguration() + { + var env = ServerHarness.DockerSqlite(); + env["ANUBIS_ADMIN_PASSWORD"] = "corta-1"; + var config = DockerPlatform.Load(env); + Assert.AreEqual("ANUBIS_ADMIN_PASSWORD", config.Problems.Single().Setting); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePasswordInsideTheAddressIsMasked() + { + Assert.AreEqual("se:gre/to", new DbSettings { Engine = DbEngine.Postgres, Url = "postgres://anubis:se%3Agre%2Fto@db:5432/anubis" }.UrlPassword); + Assert.IsNull(new DbSettings { Engine = DbEngine.Postgres, Url = "postgres://anubis@db/anubis" }.UrlPassword); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ACellOfACsvIsNeverAFormula() + { + Assert.AreEqual("'=1+1", Format.CsvText("=1+1")); + Assert.AreEqual("'+cmd", Format.CsvText("+cmd")); + Assert.AreEqual("'-x", Format.CsvText("-x")); + Assert.AreEqual("'@y", Format.CsvText("@y")); + Assert.AreEqual("'\tz", Format.CsvText("\tz")); + Assert.AreEqual("\"a;b\"", Format.CsvText("a;b")); + Assert.AreEqual("\"a \"\"b\"\"\"", Format.CsvText("a \"b\"")); + Assert.AreEqual("\"'\rx\"", Format.CsvText("\rx")); + Assert.AreEqual("-", Format.CsvText("-")); + Assert.AreEqual("", Format.CsvText(null)); + var csv = Encoding.UTF8.GetString(Format.Csv(["a", "b"], [["=1", -5.3m]])); + StringAssert.Contains(csv, "'=1;-5,3"); + } + + [GeneratedRegex(@"\{[^}]*\}")] + private static partial Regex Parameter(); + + [GeneratedRegex(@"new (OkxTrading|AlpacaTrading)\(")] + private static partial Regex Opener(); +} diff --git a/tests/Anubis.Tests/ServerHarness.cs b/tests/Anubis.Tests/ServerHarness.cs index 376366a..e86e028 100644 --- a/tests/Anubis.Tests/ServerHarness.cs +++ b/tests/Anubis.Tests/ServerHarness.cs @@ -35,6 +35,17 @@ internal sealed partial class ServerHarness : IAsyncDisposable public Uri BaseAddress => Http.BaseAddress!; + internal IServiceProvider Services => _app.Services; + + /// The browser loses its cookies. + public void Forget() + { + foreach (Cookie cookie in Cookies.GetAllCookies()) + { + cookie.Expired = true; + } + } + internal AnubisHost Host => _app.Services.GetRequiredService(); /// Docker configuration with SQLite in the data folder: what most tests need. diff --git a/tests/Anubis.Tests/StoresTests.cs b/tests/Anubis.Tests/StoresTests.cs index 92ef78a..47e7b82 100644 --- a/tests/Anubis.Tests/StoresTests.cs +++ b/tests/Anubis.Tests/StoresTests.cs @@ -265,15 +265,26 @@ public sealed class AccessTests // Second session, then a password change ends every other session. var (_, other) = await access.SignInAsync("initial-pass-1", null, null, null).ConfigureAwait(false); - Assert.IsTrue(await access.ChangePasswordAsync(session.User.Id, "initial-pass-1", "una password nuova", session.Id).ConfigureAwait(false)); + var stolen = token; + (var changed, token) = await access.ChangePasswordAsync(session.User.Id, "initial-pass-1", "una password nuova", session.Id).ConfigureAwait(false); + Assert.AreEqual(AccessChange.Done, changed); + Assert.IsNull(await access.ValidateAsync(stolen).ConfigureAwait(false), "A copy of the cookie stops working too."); Assert.IsNotNull(await access.ValidateAsync(token).ConfigureAwait(false)); Assert.IsNull(await access.ValidateAsync(other).ConfigureAwait(false)); Assert.IsFalse((await access.ValidateAsync(token).ConfigureAwait(false))!.User.MustChangePassword); // Second factor. var secret = Totp.NewSecret(); - Assert.IsFalse(await access.EnableSecondFactorAsync(session.User.Id, secret, Totp.Compute(secret, clock.UtcNow.AddMinutes(10))).ConfigureAwait(false)); - Assert.IsTrue(await access.EnableSecondFactorAsync(session.User.Id, secret, Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false)); + var (_, elsewhere) = await access.SignInAsync("una password nuova", null, null, null).ConfigureAwait(false); + Task EnableAsync(byte[] with, string password, string number) => access.EnableSecondFactorAsync(session.User.Id, with, password, number, session.Id); + Assert.AreEqual(AccessChange.Wrong, await EnableAsync(secret, "una password nuova", Totp.Compute(secret, clock.UtcNow.AddMinutes(10))).ConfigureAwait(false)); + Assert.AreEqual(AccessChange.Wrong, await EnableAsync(secret, "not the password", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false), "A session alone is not enough."); + Assert.IsNotNull(await access.ValidateAsync(elsewhere).ConfigureAwait(false)); + Assert.AreEqual(AccessChange.Done, await EnableAsync(secret, "una password nuova", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false)); + Assert.IsNull(await access.ValidateAsync(elsewhere).ConfigureAwait(false), "The other sessions signed in without the factor: they end."); + Assert.IsNotNull(await access.ValidateAsync(token).ConfigureAwait(false)); + var draft = Totp.NewSecret(); + Assert.AreEqual(AccessChange.AlreadyOn, await EnableAsync(draft, "una password nuova", Totp.Compute(draft, clock.UtcNow)).ConfigureAwait(false), "Never over an active one."); Assert.AreEqual(LoginResult.SecondFactorNeeded, (await access.SignInAsync("una password nuova", null, null, null).ConfigureAwait(false)).Result); var badCode = Totp.Compute(secret, clock.UtcNow.AddMinutes(10)); Assert.AreEqual(LoginResult.WrongSecondFactor, (await access.SignInAsync("una password nuova", badCode, null, null).ConfigureAwait(false)).Result); @@ -287,8 +298,8 @@ public sealed class AccessTests // Switching it off asks for the password and a fresh code. clock.Advance(TimeSpan.FromSeconds(30)); - Assert.IsFalse(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", null).ConfigureAwait(false)); - Assert.IsTrue(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false)); + Assert.AreEqual(AccessChange.Wrong, await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", null, session.Id).ConfigureAwait(false)); + Assert.AreEqual(AccessChange.Done, await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", Totp.Compute(secret, clock.UtcNow), session.Id).ConfigureAwait(false)); // Idle and absolute timeouts. clock.Advance(AccessStore.IdleTimeout); @@ -318,4 +329,73 @@ public sealed class AccessTests clock.Advance(LoginLimiter.Window); Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false)); } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task EveryCheckOfThePasswordSharesOneLimitThatTheServicesCannotClear() + { + var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 9, 0, 0, TimeSpan.Zero)); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var guards = new AccessGuards(clock); + AccessStore Started() => new(test.Db, clock, new SecretStore(test.Db, clock, new byte[32]), iterations: 1000, guards); + var access = Started(); + Assert.IsTrue(await access.EnsureUserAsync("password-giusta", mustChange: false).ConfigureAwait(false)); + var user = (await access.GetUserAsync().ConfigureAwait(false))!.Id; + var secret = Totp.NewSecret(); + + Assert.AreEqual(AccessChange.Wrong, (await access.ChangePasswordAsync(user, "sbagliata-1", "una password nuova", Guid.Empty).ConfigureAwait(false)).Outcome); + Assert.AreEqual(AccessChange.Wrong, await access.DisableSecondFactorAsync(user, "sbagliata-2", null, Guid.Empty).ConfigureAwait(false)); + Assert.AreEqual(AccessChange.Wrong, await access.EnableSecondFactorAsync(user, secret, "sbagliata-3", Totp.Compute(secret, clock.UtcNow), Guid.Empty).ConfigureAwait(false)); + Assert.IsFalse(await Started().ReauthenticateAsync("sbagliata-4", null).ConfigureAwait(false), "The services start again, the count goes on."); + Assert.IsFalse(await Started().ReauthenticateAsync("sbagliata-5", null).ConfigureAwait(false)); + + access = Started(); + Assert.AreEqual(AccessChange.Locked, (await access.ChangePasswordAsync(user, "password-giusta", "una password nuova", Guid.Empty).ConfigureAwait(false)).Outcome); + Assert.AreEqual(AccessChange.Locked, await access.DisableSecondFactorAsync(user, "password-giusta", null, Guid.Empty).ConfigureAwait(false)); + Assert.AreEqual(AccessChange.Locked, await access.EnableSecondFactorAsync(user, secret, "password-giusta", Totp.Compute(secret, clock.UtcNow), Guid.Empty).ConfigureAwait(false)); + clock.Advance(LoginLimiter.Window); + var code = Totp.Compute(secret, clock.UtcNow); + Assert.AreEqual(AccessChange.Done, await access.EnableSecondFactorAsync(user, secret, "password-giusta", code, Guid.Empty).ConfigureAwait(false)); + Assert.IsFalse(await Started().ReauthenticateAsync("password-giusta", code).ConfigureAwait(false), "A code used once stays used after the services start again."); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task EndedSessionsAreRemovedAtTheNextSignIn() + { + var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 9, 0, 0, TimeSpan.Zero)); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var access = new AccessStore(test.Db, clock, new SecretStore(test.Db, clock, new byte[32]), iterations: 1000); + Assert.IsTrue(await access.EnsureUserAsync("password-giusta", mustChange: false).ConfigureAwait(false)); + var (_, listening) = await access.SignInAsync("password-giusta", null, "browser", "10.0.0.1").ConfigureAwait(false); + for (var i = 0; i < 12; i++) + { + Assert.IsNotNull(await access.ValidateAsync(listening, refresh: false).ConfigureAwait(false)); + clock.Advance(TimeSpan.FromHours(1)); + } + + Assert.IsNull(await access.ValidateAsync(listening).ConfigureAwait(false), "Listening does not keep a session alive."); + await access.SignInAsync("password-giusta", null, null, null).ConfigureAwait(false); + Assert.AreEqual(1L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions")).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void SuccessfulSignInsDoNotFillTheOverallCount() + { + var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 9, 0, 0, TimeSpan.Zero)); + var limiter = new LoginLimiter(clock); + for (var i = 0; i < 3 * LoginLimiter.Overall; i++) + { + Assert.AreEqual(TimeSpan.Zero, limiter.Begin("10.0.0.1")); + limiter.Succeeded("10.0.0.1"); + } + + for (var i = 0; i < LoginLimiter.Overall; i++) + { + Assert.AreEqual(TimeSpan.Zero, limiter.Begin("10.0.1." + i)); + } + + Assert.IsGreaterThan(TimeSpan.Zero, limiter.Begin("10.0.0.9"), "Twenty failures, from anywhere, still stop everyone."); + } }