From 4897594b8706557ee62925a6a082c29019bf3b1f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 1 Dec 2026 18:52:08 +0100 Subject: [PATCH 01/15] Rebuild the state from the brokers after a restore and refuse an older copy A restore, an import or an adopted database restarts protected: the engine stays stopped, reads from the broker what the archive does not know (orders, stops, executions, also from the OKX history up to 89 days), cancels orders left working, protects what it finds and waits for the user. Strategies with real money stay exit only until confirmed again. The database of before the restore, put back by mistake, is refused by its fingerprint. A failed migration leaves the engine off with one backup and a way to try again; an archive is checked whole before the database is touched; a changed secret key no longer crashes anything, and "anubis access reset" gives the access back to whoever holds the computer. The image runs the db and access commands without the guard. refs #69 Co-Authored-By: Claude Opus 5.5 --- deploy/docker/entrypoint.sh | 7 + docs/API-NOTES.md | 1 + src/Anubis.Server/AccessCommand.cs | 56 ++++ src/Anubis.Server/AnubisHost.cs | 30 +- .../Components/IdentityChoices.razor | 3 + .../Components/Pages/Accesso.razor | 1 + .../Components/Pages/Impostazioni.razor | 1 + .../Components/Pages/Panoramica.razor | 4 + .../Components/Pages/Rischio.razor | 34 +- .../Components/Pages/Servizio.razor | 21 +- .../Components/Pages/Strategie.razor | 28 +- src/Anubis.Server/DatabaseCommand.cs | 15 +- src/Anubis.Server/Endpoints.cs | 15 + src/Anubis.Server/Forms.cs | 24 +- src/Anubis.Server/PanoramaView.cs | 8 +- src/Anubis.Server/Program.cs | 6 + src/Anubis.Server/RiskView.cs | 31 +- src/Anubis/Access/AccessStore.cs | 43 ++- src/Anubis/Core/SecretStore.cs | 39 ++- src/Anubis/Db/Archive.cs | 64 +++- src/Anubis/Db/Backups.cs | 20 +- src/Anubis/Db/Migrator.cs | 53 ++- src/Anubis/Platform/Installation.cs | 133 ++++++-- src/Anubis/Trading/LiveEngine.cs | 6 + src/Anubis/Trading/OkxTrading.cs | 59 +++- src/Anubis/Trading/OrderManager.Protection.cs | 8 +- src/Anubis/Trading/OrderManager.Rebuild.cs | 196 +++++++++++ src/Anubis/Trading/OrderManager.cs | 5 + src/Anubis/Trading/Orders.cs | 3 + src/Anubis/Trading/ReasonCatalog.cs | 1 + src/Anubis/Trading/Stages.cs | 40 ++- src/Anubis/Trading/TradingService.cs | 50 +++ tests/Anubis.Tests/ArchiveTests.cs | 175 +++++++++- tests/Anubis.Tests/LiveEngineTests.cs | 40 +++ tests/Anubis.Tests/OkxHistoryTests.cs | 74 +++++ tests/Anubis.Tests/RestoreServerTests.cs | 271 ++++++++++++++++ tests/Anubis.Tests/RestoreTests.cs | 303 ++++++++++++++++++ tests/Anubis.Tests/RiskEngineTests.cs | 55 ++++ tests/Anubis.Tests/StoresTests.cs | 18 +- tests/Anubis.Tests/TradingSupport.cs | 20 ++ 40 files changed, 1871 insertions(+), 90 deletions(-) create mode 100644 src/Anubis.Server/AccessCommand.cs create mode 100644 src/Anubis/Trading/OrderManager.Rebuild.cs create mode 100644 tests/Anubis.Tests/OkxHistoryTests.cs create mode 100644 tests/Anubis.Tests/RestoreServerTests.cs create mode 100644 tests/Anubis.Tests/RestoreTests.cs diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh index ec68e96..9b6a8ee 100644 --- a/deploy/docker/entrypoint.sh +++ b/deploy/docker/entrypoint.sh @@ -6,6 +6,13 @@ set -eu app="/app/Anubis.Guard.dll" +# A command ("docker run db import ...") runs once and ends: without the guard, which would start it again. +case "${1:-}" in + db|access|data|diagnostics|soak) + app="/app/Anubis.Server.dll" + ;; +esac + if [ "$(id -u)" != "0" ]; then exec dotnet "$app" "$@" fi diff --git a/docs/API-NOTES.md b/docs/API-NOTES.md index 05e9441..b71c508 100644 --- a/docs/API-NOTES.md +++ b/docs/API-NOTES.md @@ -208,6 +208,7 @@ Fatti controllati sulla documentazione ufficiale il 10/11/2026, scrivendo la par | Alpaca | Il flusso `trade_updates` ha due eventi in più (`order_replace_rejected`, `order_cancel_rejected`) e lo stato `held`. | Lo stato si prende dall'ordine dentro il messaggio; uno stato sconosciuto conta come "inviato" e le esecuzioni arrivano comunque dalla richiesta REST. | | OKX | `clOrdId` è unico solo tra gli ordini aperti; il doppione dà 51016 ("Client order ID already exists"), 51065 per gli algoritmici. | 51016 e 51065 vogliono dire "l'invio precedente è arrivato": si rilegge l'ordine invece di rimandarlo. | | OKX | Un ordine annullato senza esecuzioni sparisce dallo storico dopo 2 ore. | Un ordine OKX sconosciuto al broker da più di 2 ore si considera annullato (ADR 0009). | +| OKX | `/trade/fills` copre gli ultimi 3 giorni (60 richieste ogni 2 s), `/trade/fills-history` gli ultimi 3 mesi (10 ogni 2 s, `instType` obbligatorio); entrambe accettano `begin`/`end` su `ts` e si sfogliano con `after`/`before` su `billId`, 100 righe per pagina. Quanto a lungo si possa rileggere un ordine trigger scattato non è scritto. (Verificato il 30/11/2026, #69.) | Se si deve tornare indietro più di 60 ore si leggono entrambe, contando ogni esecuzione una volta, fino a 89 giorni; più indietro Anubis lo dice e il conto va controllato a mano. Un'esecuzione il cui ordine OKX non ricorda più resta senza nome e la mostra la riconciliazione. | | OKX | Le esecuzioni non hanno un `fillId`: la chiave è `tradeId`, unica per strumento. | Ogni esecuzione si registra una volta come `instId:tradeId`. | | OKX | Un ordine market spot che supera il saldo viene ridotto e eseguito, non rifiutato. | Il registro prende la quantità eseguita davvero, non quella chiesta. | | OKX | Gli ordini trigger (stop) non bloccano le monete: se allo scatto il saldo è minore, OKX vende quello che c'è. | Gli stop seguono la quantità della posizione dopo ogni esecuzione. | diff --git a/src/Anubis.Server/AccessCommand.cs b/src/Anubis.Server/AccessCommand.cs new file mode 100644 index 0000000..7cd3a6a --- /dev/null +++ b/src/Anubis.Server/AccessCommand.cs @@ -0,0 +1,56 @@ +using System.Collections; +using Anubis.Access; +using Anubis.Core; +using Anubis.Db; +using Anubis.Platform; + +namespace Anubis.Server; + +/// +/// "anubis access reset": a temporary password printed once, the second factor off, every session closed. Only whoever +/// can run a command on the computer or in the container gets here, and that person owns the data folder already. Used +/// after a lost password, a lost phone or a changed secret key (RUNBOOK). +/// +internal static class AccessCommand +{ + public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null, int? iterations = null) + { + output ??= Console.Out; + if (args.Length < 1 || args[0] != "reset") + { + await output.WriteLineAsync("Uso: anubis access reset [--platform docker|desktop] [--data-dir ]").ConfigureAwait(false); + return 2; + } + + environment ??= Environment.GetEnvironmentVariables().Cast().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); + var config = ServerOptions.Parse(args[1..], environment).LoadConfig(environment); + if (config.Db is not { } settings) + { + await output.WriteLineAsync("La configurazione d'avvio non indica il database.").ConfigureAwait(false); + return 1; + } + + Redactor.Register(settings.Password); + var clock = new SystemClock(); + try + { + await using var db = Database.Open(settings, allowCreate: false); + var access = new AccessStore(db, clock, new SecretStore(db, clock, new byte[32]), iterations ?? Passwords.DefaultIterations); + var temporary = Ids.NewToken()[..16]; + if (!await access.ResetAsync(temporary).ConfigureAwait(false)) + { + await output.WriteLineAsync("Non c'è ancora nessun utente: apri Anubis e fai il primo accesso.").ConfigureAwait(false); + return 1; + } + + await output.WriteLineAsync("Password provvisoria: " + temporary + Environment.NewLine + + "Accedi subito: ti chiederà di sceglierne una nuova. Il secondo fattore è tolto e tutte le sessioni sono chiuse.").ConfigureAwait(false); + return 0; + } + catch (Exception ex) when (Forms.IsArchiveProblem(ex)) + { + await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false); + return 1; + } + } +} diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 898c526..1216a94 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -96,6 +96,9 @@ internal sealed partial class AnubisHost( public int PasswordIterations => overrides?.PasswordIterations ?? Passwords.DefaultIterations; + /// Why the last migration failed; the error page's "Riprova" clears it. + internal string? MigrationFailed { get; set; } + /// Asks the loop to check again now (after the wizard or an error-page choice). public void Wake() { @@ -286,7 +289,7 @@ internal sealed partial class AnubisHost( } catch (SchemaException ex) { - SetStatus(HostMode.SchemaProblem, ex.Message); + SetStatus(HostMode.SchemaProblem, Redactor.Redact(ex.Message)); return; } @@ -396,9 +399,27 @@ internal sealed partial class AnubisHost( SetStatus(HostMode.Ready, null); } - private async Task MigrateAsync(Backups backups, CancellationToken cancellationToken) + internal async Task MigrateAsync(Backups backups, CancellationToken cancellationToken) { - var applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, "prima-della-migrazione", ct), cancellationToken).ConfigureAwait(false); + // SPEC 9.4: after a migration that failed the engine stays off. It is not tried again by itself, because every + // attempt would take one more backup; the user tries again from the error page or with a restart. + if (MigrationFailed is { } failed) + { + throw new SchemaException(failed); + } + + int applied; + try + { + applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, Backups.BeforeMigration, ct), cancellationToken).ConfigureAwait(false); + } + catch (SchemaException ex) when (ex.InnerException is not null) + { + LogMigrationFailed(logger, ex); + MigrationFailed = ex.Message; + throw; + } + if (applied > 0) { LogMigrated(logger, applied, Migrations.Latest); @@ -739,6 +760,9 @@ internal sealed partial class AnubisHost( [LoggerMessage(Level = LogLevel.Warning, Message = "Demo mode: separate database in {Folder}")] private static partial void LogDemo(ILogger logger, string folder); + [LoggerMessage(Level = LogLevel.Error, Message = "Migration failed: the engine stays off until the user tries again")] + private static partial void LogMigrationFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Information, Message = "Applied {Count} migrations, schema version {Version}")] private static partial void LogMigrated(ILogger logger, int count, int version); diff --git a/src/Anubis.Server/Components/IdentityChoices.razor b/src/Anubis.Server/Components/IdentityChoices.razor index 10f9076..69837fa 100644 --- a/src/Anubis.Server/Components/IdentityChoices.razor +++ b/src/Anubis.Server/Components/IdentityChoices.razor @@ -18,6 +18,9 @@ case IdentityVerdict.DifferentInstallation:

Il database appartiene a un'altra installazione di Anubis. Il motore resta spento: due registri sugli stessi conti produrrebbero ordini doppi.

break; + case IdentityVerdict.MissingFile: +

Il database appartiene a un'installazione, ma la cartella dei dati non ha il suo file d'identità: non posso sapere se questo database è quello giusto o una copia vecchia. Il motore resta spento finché non lo dici tu.

+ break; case IdentityVerdict.StaleDatabase:

È il database di questa installazione, ma una copia più vecchia: dopo l'ultimo ripristino o spostamento ne è nata una più recente. Il motore resta spento per non lavorare su dati superati.

break; diff --git a/src/Anubis.Server/Components/Pages/Accesso.razor b/src/Anubis.Server/Components/Pages/Accesso.razor index d628729..1d765b6 100644 --- a/src/Anubis.Server/Components/Pages/Accesso.razor +++ b/src/Anubis.Server/Components/Pages/Accesso.razor @@ -40,6 +40,7 @@ { "password" => "Password sbagliata. Riprova: dopo 5 tentativi sbagliati l'accesso si blocca per 15 minuti.", "codice" => "Il codice non è giusto o è scaduto. Usa quello che l'app mostra adesso.", + "chiave" => "La password è giusta, ma la chiave dei segreti (ANUBIS_SECRET_KEY) non è più quella di prima e il codice non si può controllare. Rimetti la vecchia chiave, oppure azzera l'accesso dal computer che ospita Anubis: il manuale dice come.", "attesa" => $"Troppi tentativi sbagliati. Riprova tra {Minuti ?? "15"} minuti.", _ => null, }; diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 48fd3a6..f4ff63e 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -812,6 +812,7 @@ private string KeyState(SecretStatus status) => status switch { { FromEnvironment: true } => "Dalle variabili d'ambiente", + { Unreadable: true } => "Non si legge più: la chiave dei segreti è cambiata, inseriscila di nuovo", { IsSet: true, UpdatedAt: { } at } => "Impostata " + Inline(Format.ShortDate(at, Shell.Now, Shell.Zone)), { IsSet: true } => "Impostata", _ => "Non impostata", diff --git a/src/Anubis.Server/Components/Pages/Panoramica.razor b/src/Anubis.Server/Components/Pages/Panoramica.razor index 6d4538b..f6d3985 100644 --- a/src/Anubis.Server/Components/Pages/Panoramica.razor +++ b/src/Anubis.Server/Components/Pages/Panoramica.razor @@ -17,6 +17,10 @@ var phoneMoves = moves.Select((m, i) => (m, i)).Where(x => !x.m.Calendar).Take(2).Select(x => x.i).ToHashSet(); var v = p.Accounts; } +@if (p.ProtectedRestart) +{ +
Ripartenza protetta. Dopo un ripristino o un'importazione sono fermo: non apro posizioni finché non hai controllato e non confermi dalla pagina Rischio.
+} @if (_absence is { } away) {
diff --git a/src/Anubis.Server/Components/Pages/Rischio.razor b/src/Anubis.Server/Components/Pages/Rischio.razor index d7ba40f..397890e 100644 --- a/src/Anubis.Server/Components/Pages/Rischio.razor +++ b/src/Anubis.Server/Components/Pages/Rischio.razor @@ -22,6 +22,34 @@

Interruttore d'emergenza

@BotText(v.BotState)
+ @if (v.ProtectedRestart is { } restart) + { +
+

Ripartenza protetta. Il database è cambiato il @Moment(restart.Since) (ripristino, importazione o copia più vecchia del conto): prima di ripartire guarda cosa ho ricostruito.

+
    + @foreach (var line in restart.Rebuilt) + { +
  • @line
  • + } + @if (restart.Working) + { +
  • Sto ancora leggendo i conti.
  • + } + else if (restart.Waiting.Count > 0) + { +
  • Non ho ancora letto: @string.Join(", ", restart.Waiting). Riprovo ogni minuto; se una chiave è scaduta, cambiala nelle Impostazioni.
  • + } + else if (restart.Rebuilt.Count == 0) + { +
  • Sui conti non c'era niente che il database non conoscesse già.
  • + } + @if (restart.ToReconfirm.Count > 0) + { +
  • Da riconfermare nella pagina Strategie, altrimenti restano in sola uscita: @string.Join(", ", restart.ToReconfirm).
  • + } +
+
+ } @if (v.WaitsForRestart) {

@@ -51,7 +79,7 @@

- + } } @@ -293,7 +321,9 @@ private static string Where(string world) => world == Worlds.Real ? "sui conti veri" : "nel mondo simulato"; - private static string RestartText(RiskView v) => v.Tripped.Count > 0 + private static string RestartText(RiskView v) => v.ProtectedRestart is not null + ? "Riparti dopo il ripristino: hai controllato posizioni e operazioni ricostruite? Il bot torna a operare; le strategie con soldi veri restano in sola uscita finché non le riconfermi. Confermi?" + : v.Tripped.Count > 0 ? "Riparti: il massimo di riferimento riparte dal patrimonio di adesso e il bot torna a operare. Confermi?" : "Riparti: il bot torna a operare. Confermi?"; diff --git a/src/Anubis.Server/Components/Pages/Servizio.razor b/src/Anubis.Server/Components/Pages/Servizio.razor index ce8803f..2d0f0d1 100644 --- a/src/Anubis.Server/Components/Pages/Servizio.razor +++ b/src/Anubis.Server/Components/Pages/Servizio.razor @@ -65,6 +65,25 @@ case HostMode.SchemaProblem:

@_status.Detail

+ @if (Host.MigrationFailed is not null) + { + var copies = new Backups(Host.Config.Data, Clock).List(); +

Il motore resta spento. + @if (copies.Count > 0) + { + L'ultimo salvataggio è @copies[0].Name, in @Host.Config.Data.Backups: per tornarci, indica nella configurazione un database nuovo e vuoto e sceglilo in questa pagina. + } + Se il problema è passeggero (spazio sul disco, permessi), risolvilo e riprova.

+ @if (Host.Config.Platform == PlatformKind.Docker || _local) + { +
+ + + + + } + break; + }

Per non rovinare i dati il motore resta spento. Aggiorna Anubis alla versione che ha creato questo database, oppure ripristina un salvataggio in un database vuoto.

break; @@ -82,7 +101,7 @@ diff --git a/src/Anubis.Server/Components/Pages/Strategie.razor b/src/Anubis.Server/Components/Pages/Strategie.razor index e5b782a..0c657ce 100644 --- a/src/Anubis.Server/Components/Pages/Strategie.razor +++ b/src/Anubis.Server/Components/Pages/Strategie.razor @@ -51,7 +51,7 @@ var up = s.ResultEur >= 0;
-

@s.Name @(s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))

+

@s.Name @(s.Stage.WaitsForReconfirmation ? "Da riconfermare" : s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))

@s.Description

    @foreach (var rule in s.Rules) @@ -92,7 +92,30 @@ }
- @if (s.Stage.ExitOnly) + @if (s.Stage.WaitsForReconfirmation) + { +

Dopo un ripristino non compra con soldi veri finché non la riconfermi: vende e tiene gli stop. I giorni e i conteggi restano quelli di prima.

+ @if (!Shell.IsDemo) + { +
+ Riconferma +
+ +

Ecco con che cosa riprende @s.Name:

+
    + @foreach (var line in s.Summary) + { +
  • @line
  • + } +
+ + + + +
+ } + } + else if (s.Stage.ExitOnly) {

Tornata indietro con posizioni vere ancora aperte: le gestisce fino a zero, con i loro stop, senza nuovi acquisti.

} @@ -220,6 +243,7 @@ ("simulazione", _) => ("Fatto: la strategia è in simulazione, con ordini finti su prezzi veri.", true), ("osservazione", _) => ("Fatto: la strategia è in osservazione.", true), ("reale", _) => ("Fatto: la strategia usa soldi veri da adesso. Se peggiora torna indietro da sola.", true), + ("riconferma", _) => ("Fatto: la strategia è riconfermata e torna a operare con soldi veri.", true), (_, "backtest") => ("Solo una strategia che ha superato il backtest può andare in simulazione.", false), (_, "osservazione-giorni") => ($"Prima della simulazione servono almeno {StageBook.ObservationDays} giorni di segnali raccolti dal vivo in osservazione.", false), (_, "frase") => ("La frase non corrisponde: scrivila esattamente come è mostrata.", false), diff --git a/src/Anubis.Server/DatabaseCommand.cs b/src/Anubis.Server/DatabaseCommand.cs index 9ec3798..a9f95d1 100644 --- a/src/Anubis.Server/DatabaseCommand.cs +++ b/src/Anubis.Server/DatabaseCommand.cs @@ -40,7 +40,15 @@ internal static class DatabaseCommand var folder = Path.GetFullPath(args[1]); try { - await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import" && !File.Exists(config.Data.InstallationFile)); + if (args[0] == "import") + { + // Read before the database is opened: a wrong folder must not leave a new empty SQLite file behind. + await Archive.ReadIndexAsync(folder).ConfigureAwait(false); + config.Data.Ensure(); + } + + // Moving to SQLite, the file does not exist yet: the user asked for it by name, unlike a start (trap 20). + await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import"); if (args[0] == "export") { var index = await Archive.ExportAsync(db, folder, clock).ConfigureAwait(false); @@ -48,14 +56,13 @@ internal static class DatabaseCommand return 0; } - config.Data.Ensure(); var imported = await Archive.ImportAsync(db, folder, clock).ConfigureAwait(false); - await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: !File.Exists(config.Data.InstallationFile)).ConfigureAwait(false); + await Installation.RenewAsync(db, config.Data, clock, "Archivio importato").ConfigureAwait(false); await output.WriteLineAsync($"Importate {imported.Tables.Sum(t => t.Count)} righe di {imported.Tables.Count} tabelle: conteggi e totali coincidono. " + "Al prossimo avvio il bot riparte protetto.").ConfigureAwait(false); return 0; } - catch (Exception ex) when (ex is IOException or InvalidOperationException or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException) + catch (Exception ex) when (Forms.IsArchiveProblem(ex)) { await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false); return 1; diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index 1aef93a..588b13a 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -330,6 +330,16 @@ internal static partial class Endpoints : "Comando non ammesso nello stato attuale del bot."); } + var restart = command is "restart" or "riattiva" + && await Platform.Installation.ReadRowAsync(host.Services.Db, ct).ConfigureAwait(false) is { ProtectedRestart: true }; + if (restart && (host.Services.Trading is not { Risk: not null, Started: true } engineOn || engineOn.AccountsToRebuild.Count > 0)) + { + // SPEC 15.1: first the executions after the archive, then the user's confirmation. + var waiting = host.Services.Trading?.AccountsToRebuild ?? []; + return (false, "Dopo il ripristino devo prima ricostruire dal broker le esecuzioni successive al salvataggio" + + (waiting.Count == 0 ? "." : $". Aspetto: {string.Join(", ", waiting)}.")); + } + if (host.Services.Trading is { Risk: { } risk } trading) { // The switch of SPEC 9.3 goes through the risk engine: it cancels the orders under way and keeps the stops. @@ -346,6 +356,11 @@ internal static partial class Endpoints try { await risk.RestartAsync(by, ct).ConfigureAwait(false); + if (restart) + { + await Platform.Installation.ClearProtectedRestartAsync(host.Services.Db, ct).ConfigureAwait(false); + } + await NotifyBotAsync(host, "bot_restarted", $"Il bot è ripartito dopo «Ferma tutto» (da {by}).", ct).ConfigureAwait(false); return (true, target); } diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 553b7c8..087e801 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -173,6 +173,8 @@ internal static partial class Forms case LoginResult.SecondFactorNeeded: limiter.Forgive(address); return Results.Redirect(With(With("/accesso", "fattore", "1"), "ritorno", back)); + case LoginResult.UnreadableSecondFactor: + return Results.Redirect(With("/accesso", "errore", "chiave")); case LoginResult.WrongSecondFactor: return Results.Redirect(With(With(With("/accesso", "fattore", "1"), "errore", "codice"), "ritorno", back)); default: @@ -590,6 +592,10 @@ internal static partial class Forms await stages.ConfirmLiveAsync(new Anubis.Trading.LiveConfirmation(strategy, account, form["frase"].ToString(), form["password"].ToString(), string.IsNullOrWhiteSpace(code) ? null : code.Trim(), by), ct).ConfigureAwait(false); return Results.Redirect("/strategie?ok=reale"); + case "riconferma": + var second = form["codice"].ToString(); + await stages.ReconfirmAsync(strategy, form["password"].ToString(), string.IsNullOrWhiteSpace(second) ? null : second.Trim(), by, ct).ConfigureAwait(false); + return Results.Redirect("/strategie?ok=riconferma"); default: return Results.Redirect("/strategie?errore=scelta"); } @@ -1041,6 +1047,14 @@ internal static partial class Forms using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false); var status = host.Status; var db = host.Database; + if (choice == "riprova" && status.Mode == HostMode.SchemaProblem) + { + host.MigrationFailed = null; + exclusive.Dispose(); + host.Wake(); + return Results.Redirect("/"); + } + if (status.Mode != HostMode.IdentityProblem || status.Identity is null || db is null) { return Results.Redirect("/"); @@ -1059,7 +1073,7 @@ internal static partial class Forms } await Archive.ImportAsync(db, Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false); - await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false); + await Installation.RenewAsync(db, config.Data, clock, "Salvataggio ripristinato", ct).ConfigureAwait(false); break; case "importa" when verdict == IdentityVerdict.EmptyDatabase: var folder = ServiceChoices.ImportFolders(config.Data).FirstOrDefault(f => Path.GetFileName(f) == form["archivio"].ToString()); @@ -1069,13 +1083,15 @@ internal static partial class Forms } await Archive.ImportAsync(db, folder, clock, ct).ConfigureAwait(false); - await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false); + await Installation.RenewAsync(db, config.Data, clock, "Archivio importato", ct).ConfigureAwait(false); break; case "da-capo" when verdict == IdentityVerdict.EmptyDatabase: Installation.StartOver(config.Data, clock); break; - case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase: - await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: true, ct).ConfigureAwait(false); + case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase or IdentityVerdict.MissingFile: + // An old copy may have an old schema: it is brought up to date, after its own backup, before it is protected. + await host.MigrateAsync(new Backups(config.Data, clock), ct).ConfigureAwait(false); + await Installation.RenewAsync(db, config.Data, clock, "Database scelto dalla pagina d'errore", ct).ConfigureAwait(false); break; default: return Results.Redirect("/?errore=scelta"); diff --git a/src/Anubis.Server/PanoramaView.cs b/src/Anubis.Server/PanoramaView.cs index 4693515..c28f569 100644 --- a/src/Anubis.Server/PanoramaView.cs +++ b/src/Anubis.Server/PanoramaView.cs @@ -40,6 +40,9 @@ internal sealed record PanoramaView( LearningSummary Learning, DateTimeOffset? FractionStops) { + /// After a restore the bot waits for the user (SPEC 15.1). + public bool ProtectedRestart { get; init; } + private static readonly CultureInfo _it = CultureInfo.InvariantCulture; /// "Notizie che contano" (SPEC 13.6): first those with an effect in force, then the latest on the positions or their markets. @@ -97,7 +100,10 @@ internal sealed record PanoramaView( { var board = await new Anubis.News.NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false); return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone), - services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), learning, fractions); + services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), learning, fractions) + { + ProtectedRestart = risk.ProtectedRestart is not null, + }; } var root = aggregates.RootElement; diff --git a/src/Anubis.Server/Program.cs b/src/Anubis.Server/Program.cs index f38827b..aebdd22 100644 --- a/src/Anubis.Server/Program.cs +++ b/src/Anubis.Server/Program.cs @@ -6,6 +6,12 @@ if (args.Length >= 1 && args[0] == "db") return await DatabaseCommand.RunAsync(args[1..]).ConfigureAwait(false); } +// "anubis access reset": a new password for whoever holds the computer, the second factor off (RUNBOOK). +if (args.Length >= 1 && args[0] == "access") +{ + return await AccessCommand.RunAsync(args[1..]).ConfigureAwait(false); +} + // "anubis data report|binance|csv": the data quality report and the research imports (Phase 2). if (args.Length >= 1 && args[0] == "data") { diff --git a/src/Anubis.Server/RiskView.cs b/src/Anubis.Server/RiskView.cs index f514ae8..99deff5 100644 --- a/src/Anubis.Server/RiskView.cs +++ b/src/Anubis.Server/RiskView.cs @@ -9,6 +9,29 @@ namespace Anubis.Server; /// A row of the limits table: what is used now against the threshold, and what happens beyond it. internal sealed record LimitRow(string Label, string Now, string? Detail, decimal? Usage, string Threshold, string Beyond, string Key); +/// +/// The protected restart of SPEC 15.1: since when, the accounts still to rebuild, what was rebuilt, the strategies +/// that stay in exit only until they are confirmed again. +/// +internal sealed record ProtectedRestartView(DateTimeOffset Since, bool Working, IReadOnlyList Waiting, IReadOnlyList Rebuilt, IReadOnlyList ToReconfirm) +{ + public bool CanRestart => !Working && Waiting.Count == 0; + + public static async Task LoadAsync(AppServices services, CancellationToken cancellationToken) + { + if (await Platform.Installation.ReadRowAsync(services.Db, cancellationToken).ConfigureAwait(false) is not { ProtectedRestart: true } row) + { + return null; + } + + var rebuilt = await services.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'ledger_rebuilt' AND occurred_at >= @f ORDER BY occurred_at, id", + r => r.Text("message"), ("f", row.RenewedAt)), cancellationToken).ConfigureAwait(false); + var stages = services.Trading is { } trading ? await trading.Stages.AllAsync(cancellationToken).ConfigureAwait(false) : []; + return new ProtectedRestartView(row.RenewedAt, services.Trading is { Started: false }, services.Trading?.AccountsToRebuild ?? [], rebuilt, + [.. stages.Where(s => s.WaitsForReconfirmation).Select(s => StrategyNames.Label(s.Strategy, withMarket: true))]); + } +} + /// A point of the fall from the high, as a fraction: 0 at the high, −0,03 three percent below. internal sealed record DrawdownPoint(DateTimeOffset At, decimal Drawdown); @@ -33,6 +56,9 @@ internal sealed record RiskView( bool HasPositions, IReadOnlyList Tripped) { + /// After a restore (SPEC 15.1): what the restart waits for, and what stays in exit only after it. + public ProtectedRestartView? ProtectedRestart { get; init; } + public bool AnyBlock => Tripped.Count > 0 || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active"; /// The switch tripped by itself in a world (SPEC 9.2): it waits for the user's restart, like "Ferma tutto". @@ -133,7 +159,10 @@ internal sealed record RiskView( return new RiskView(bot, engine.StopRequested, (await engine.BotAsync(cancellationToken).ConfigureAwait(false)).CloseAll, world, risk, limits, rows, drawdown, scenarios, await engine.EventsAsync(8, cancellationToken).ConfigureAwait(false), next, last, await RiskSettings.PdtGuardAsync(services.Settings, cancellationToken).ConfigureAwait(false), - positions.Count > 0, tripped); + positions.Count > 0, tripped) + { + ProtectedRestart = await ProtectedRestartView.LoadAsync(services, cancellationToken).ConfigureAwait(false), + }; } private static decimal? Worst(IReadOnlyList index, DateTimeOffset? from) diff --git a/src/Anubis/Access/AccessStore.cs b/src/Anubis/Access/AccessStore.cs index 19aaaa9..e416b9e 100644 --- a/src/Anubis/Access/AccessStore.cs +++ b/src/Anubis/Access/AccessStore.cs @@ -15,6 +15,9 @@ public enum LoginResult WrongPassword, SecondFactorNeeded, WrongSecondFactor, + + /// The second factor was sealed with another secret key: no code can be checked. + UnreadableSecondFactor, Locked, NoUser, } @@ -169,6 +172,34 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, } } + private static string SecondFactorName(Guid userId) => "totp:" + userId.ToString("D"); + + private bool CanReadSecondFactor(Guid userId, byte[] stored) => secrets.CanOpen(SecondFactorName(userId), stored); + + private bool AcceptSealedCode(Guid userId, byte[] stored, string? code) => + CanReadSecondFactor(userId, stored) && AcceptCode(Convert.FromBase64String(secrets.Open(SecondFactorName(userId), stored)), code); + + /// + /// For whoever holds the computer, from the command line (RUNBOOK): a new password to change at the next sign-in, the + /// second factor off, every session closed. The way back in after a lost password or a changed secret key. + /// + public async Task ResetAsync(string password, CancellationToken cancellationToken = default) + { + var hash = Passwords.Hash(password, iterations); + return await db.WriteAsync(async s => + { + if (await s.ExecuteAsync("UPDATE users SET password_hash = @h, must_change_password = @m, totp_secret = NULL, updated_at = @t WHERE username = @u", cancellationToken, + ("h", hash), ("m", true), ("t", clock.UtcNow), ("u", AdminName)).ConfigureAwait(false) == 0) + { + return false; + } + + await s.ExecuteAsync("DELETE FROM sessions", cancellationToken).ConfigureAwait(false); + await LogAsync(s, "security.access", "azzerato dalla riga di comando", cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken).ConfigureAwait(false); + } + public Task HasUserAsync(CancellationToken cancellationToken = default) => db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM users").ConfigureAwait(false) > 0, cancellationToken); @@ -216,8 +247,12 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return (LoginResult.SecondFactorNeeded, null); } - var secret = Convert.FromBase64String(secrets.Open("totp:" + user.Id.ToString("D"), user.Totp)); - if (!AcceptCode(secret, code)) + if (!CanReadSecondFactor(user.Id, user.Totp)) + { + return (LoginResult.UnreadableSecondFactor, null); + } + + if (!AcceptSealedCode(user.Id, user.Totp, code)) { return (LoginResult.WrongSecondFactor, null); } @@ -329,7 +364,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return false; } - if (user.Totp is null || AcceptCode(Convert.FromBase64String(secrets.Open("totp:" + user.Id.ToString("D"), user.Totp)), code)) + if (user.Totp is null || AcceptSealedCode(user.Id, user.Totp, code)) { _fresh.Succeeded(FreshAttempts); return true; @@ -348,7 +383,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return false; } - if (user.Totp is not null && !AcceptCode(Convert.FromBase64String(secrets.Open("totp:" + userId.ToString("D"), user.Totp)), code)) + if (user.Totp is not null && !AcceptSealedCode(userId, user.Totp, code)) { return false; } diff --git a/src/Anubis/Core/SecretStore.cs b/src/Anubis/Core/SecretStore.cs index 2d11b21..d4dca47 100644 --- a/src/Anubis/Core/SecretStore.cs +++ b/src/Anubis/Core/SecretStore.cs @@ -6,7 +6,7 @@ using Anubis.Db; namespace Anubis.Core; /// Whether a secret is set and where it comes from. Never the value (SPEC 13.5, 15.4). -public sealed record SecretStatus(string Name, bool IsSet, bool FromEnvironment, DateTimeOffset? UpdatedAt); +public sealed record SecretStatus(string Name, bool IsSet, bool FromEnvironment, DateTimeOffset? UpdatedAt, bool Unreadable = false); /// /// Secrets encrypted in the database with AES-GCM under the installation's secret key (SPEC 15.4). The name is @@ -65,7 +65,10 @@ public sealed class SecretStore(Database db, IClock clock, byte[] key, IReadOnly }, cancellationToken).ConfigureAwait(false); } - /// The plain value, for the code that needs it (adapters). Never pass it to the interface. + /// + /// The plain value, for the code that needs it (adapters). Never pass it to the interface. A value sealed with another + /// key (a restore on a new server) counts as missing: whoever asked goes on without it, and the Settings say so. + /// public async Task RevealAsync(string name, CancellationToken cancellationToken = default) { if (_environment.TryGetValue(name, out var fromEnvironment)) @@ -80,9 +83,16 @@ public sealed class SecretStore(Database db, IClock clock, byte[] key, IReadOnly return null; } - var value = Open(name, stored); - Redactor.Register(value); - return value; + try + { + var value = Open(name, stored); + Redactor.Register(value); + return value; + } + catch (CryptographicException) + { + return null; + } } public async Task StatusAsync(string name, CancellationToken cancellationToken = default) @@ -92,9 +102,22 @@ public sealed class SecretStore(Database db, IClock clock, byte[] key, IReadOnly return new SecretStatus(name, true, true, null); } - var updated = await db.ReadAsync(s => s.QueryAsync("SELECT updated_at FROM secrets WHERE name = @n", r => r.Moment("updated_at"), ("n", name)), cancellationToken) - .ConfigureAwait(false); - return new SecretStatus(name, updated.Count > 0, false, updated.Count > 0 ? updated[0] : null); + var stored = await db.ReadAsync(s => s.QueryAsync("SELECT ciphertext, updated_at FROM secrets WHERE name = @n", r => (Sealed: r.Bytes("ciphertext"), At: r.Moment("updated_at")), ("n", name)), + cancellationToken).ConfigureAwait(false); + return stored.Count == 0 ? new SecretStatus(name, false, false, null) : new SecretStatus(name, true, false, stored[0].At, !CanOpen(name, stored[0].Sealed)); + } + + internal bool CanOpen(string name, byte[] stored) + { + try + { + Open(name, stored); + return true; + } + catch (CryptographicException) + { + return false; + } } internal byte[] Seal(string name, string value) diff --git a/src/Anubis/Db/Archive.cs b/src/Anubis/Db/Archive.cs index 8798c2b..04cfcbe 100644 --- a/src/Anubis/Db/Archive.cs +++ b/src/Anubis/Db/Archive.cs @@ -91,6 +91,12 @@ public static class Archive throw new InvalidDataException("Formato d'archivio sconosciuto."); } + // The index of an archive that came from elsewhere is only data: it never points outside its own folder. + if (index.Tables.Any(t => t.File != Path.GetFileName(t.File) || t.File.Length == 0) || index.Tables.DistinctBy(t => t.Name).Count() != index.Tables.Count) + { + throw new InvalidDataException("L'indice dell'archivio non è valido."); + } + return index; } @@ -120,9 +126,12 @@ public static class Archive throw new InvalidOperationException("Il database di arrivo ha già uno schema più recente dell'archivio: usa un database vuoto."); } - await Migrations.MigrateAsync(db, clock, null, cancellationToken, upTo: index.SchemaVersion).ConfigureAwait(false); var tables = Schema.Parse(Migrations.All.Take(index.SchemaVersion)); + // The whole archive is read and checked before the database is touched: a damaged one leaves it as it was. + await VerifyAsync(index, folder, tables, cancellationToken).ConfigureAwait(false); + await Migrations.MigrateAsync(db, clock, null, cancellationToken, upTo: index.SchemaVersion).ConfigureAwait(false); + await db.WriteAsync(async s => { foreach (var entry in index.Tables) @@ -178,12 +187,62 @@ public static class Archive throw new InvalidDataException($"Il totale {key} non coincide: {value} nell'archivio, {actual ?? "nessuno"} nel database."); } } + + await Installation.SealAsync(s, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); await Migrations.MigrateAsync(db, clock, null, cancellationToken).ConfigureAwait(false); return index; } + private static async Task VerifyAsync(ArchiveIndex index, string folder, IReadOnlyList tables, CancellationToken cancellationToken) + { + var totals = new Totals(); + foreach (var entry in index.Tables) + { + var table = tables.FirstOrDefault(t => t.Name == entry.Name) ?? throw new InvalidDataException($"L'archivio contiene la tabella sconosciuta {entry.Name}."); + long count = 0; + using var reader = new StreamReader(Path.Combine(folder, entry.File), Encoding.UTF8); + while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) + { + if (line.Length == 0) + { + continue; + } + + var row = JsonNode.Parse(line) as JsonObject ?? throw new InvalidDataException($"La tabella {entry.Name} ha una riga che non si legge."); + foreach (var column in table.Columns) + { + _ = FromJson(row[column.Name], column); + } + + totals.Add(table, row); + count++; + } + + if (count != entry.Count) + { + throw new InvalidDataException($"La tabella {entry.Name} ha {count} righe nel file e {entry.Count} nell'indice: archivio incompleto."); + } + } + + // A table missing from the index would be silently empty: an export always writes every table of its version. + var missing = tables.FirstOrDefault(t => index.Tables.All(e => e.Name != t.Name)); + if (missing is not null) + { + throw new InvalidDataException($"Nell'archivio manca la tabella {missing.Name}."); + } + + var read = totals.ToDictionary(); + foreach (var (key, value) in index.AccountingTotals) + { + if (!read.TryGetValue(key, out var actual) || actual != value) + { + throw new InvalidDataException($"Il totale {key} non coincide: {value} nell'indice, {actual ?? "nessuno"} nei file."); + } + } + } + /// Row counts of every table, for comparisons in tests and on the System page. public static async Task> CountsAsync(Database db, CancellationToken cancellationToken = default) { @@ -191,7 +250,8 @@ public static class Archive return await db.ReadAsync(async s => { var counts = new Dictionary(StringComparer.Ordinal); - foreach (var table in Schema.Tables) + // The tables the database has: an import that stopped half way may have left an older schema. + foreach (var table in Schema.Parse(Migrations.All.Take(await CurrentVersionAsync(s).ConfigureAwait(false)))) { counts[table.Name] = await s.CountAsync($"SELECT COUNT(*) FROM {table.Name}").ConfigureAwait(false); } diff --git a/src/Anubis/Db/Backups.cs b/src/Anubis/Db/Backups.cs index fecd744..f957951 100644 --- a/src/Anubis/Db/Backups.cs +++ b/src/Anubis/Db/Backups.cs @@ -9,11 +9,13 @@ public sealed record BackupInfo(string Folder, string Name, DateTimeOffset Taken /// /// Backups (SPEC 5.4): the engine-independent archive, plus a consistent copy of the SQLite file made with the -/// backup API. Nightly at 03:30 Italian time, before every migration, and on request. The last 14 are kept. +/// backup API. Nightly at 03:30 Italian time, before every migration, and on request. The last 14 nightly ones are +/// kept, and separately the last 14 of each other kind, so a series of one kind never pushes out the others. /// public sealed class Backups(DataDirectory data, IClock clock) { public const int Keep = 14; + public const string BeforeMigration = "prima-della-migrazione"; public const string ArchiveFolder = "archivio"; public const string SqliteCopy = "anubis.sqlite3"; @@ -37,6 +39,7 @@ public sealed class Backups(DataDirectory data, IClock clock) if (db.Engine == DbEngine.Sqlite) { await db.BackupSqliteFileAsync(Path.Combine(temp, SqliteCopy), cancellationToken).ConfigureAwait(false); + await Installation.SealCopyAsync(Path.Combine(temp, SqliteCopy), cancellationToken).ConfigureAwait(false); } Directory.Move(temp, folder); @@ -69,10 +72,23 @@ public sealed class Backups(DataDirectory data, IClock clock) private void Prune() { - foreach (var old in List().Skip(Keep)) + foreach (var old in List().GroupBy(b => Kind(b.Reason)).SelectMany(g => g.Skip(Keep))) { Directory.Delete(old.Folder, recursive: true); } + + // What a backup cut off by a power failure left behind; one under way right now is younger than a day. + foreach (var partial in Directory.EnumerateDirectories(data.Backups, "*.partial").Where(d => clock.UtcNow - new DateTimeOffset(Directory.GetLastWriteTimeUtc(d)) > TimeSpan.FromDays(1))) + { + Directory.Delete(partial, recursive: true); + } + } + + // "notturno-2" is the second of the same second: the number is not part of the kind. + private static string Kind(string reason) + { + var dash = reason.LastIndexOf('-'); + return dash > 0 && int.TryParse(reason[(dash + 1)..], NumberStyles.None, CultureInfo.InvariantCulture, out _) ? reason[..dash] : reason; } private static BackupInfo? Describe(string folder) diff --git a/src/Anubis/Db/Migrator.cs b/src/Anubis/Db/Migrator.cs index 188f3db..c3076f0 100644 --- a/src/Anubis/Db/Migrator.cs +++ b/src/Anubis/Db/Migrator.cs @@ -121,12 +121,53 @@ public static partial class Migrations if (!status.IsEmpty && backupBeforeMigrating is not null) { - await backupBeforeMigrating(cancellationToken).ConfigureAwait(false); + try + { + await backupBeforeMigrating(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new SchemaException($"Non sono riuscito a salvare il database prima di aggiornarlo, quindi non l'ho toccato: {ex.Message}", ex); + } } foreach (var migration in pending) { - await db.WriteAsync(async s => + try + { + await ApplyAsync(db, clock, migration, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + if (!await AnswersAsync(db, cancellationToken).ConfigureAwait(false)) + { + throw; + } + + // The database is there and refuses the change: trying again in five seconds would fail the same way. + throw new SchemaException($"L'aggiornamento {migration.Version:D4} del database non è riuscito: {ex.Message} " + + $"Il database è rimasto alla versione {migration.Version - 1}, senza modifiche a metà.", ex); + } + } + + return pending.Count; + } + + private static async Task AnswersAsync(Database db, CancellationToken cancellationToken) + { + try + { + await db.PingAsync(cancellationToken).ConfigureAwait(false); + return true; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return false; + } + } + + private static Task ApplyAsync(Database db, IClock clock, Migration migration, CancellationToken cancellationToken) => + db.WriteAsync(async s => { if (migration.Version == 1) { @@ -138,11 +179,7 @@ public static partial class Migrations await s.ExecuteAsync(migration.SqlFor(db.Engine), cancellationToken).ConfigureAwait(false); await s.ExecuteAsync($"INSERT INTO {VersionTable} (version, name, checksum, applied_at) VALUES (@v, @n, @c, @t)", cancellationToken, ("v", migration.Version), ("n", migration.Name), ("c", migration.Checksum), ("t", clock.UtcNow)).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); - } - - return pending.Count; - } + }, cancellationToken); public static async Task TableExistsAsync(DbSession session, string table) { @@ -155,4 +192,4 @@ public static partial class Migrations } /// The database schema cannot be used by this version: shown on the error page. -public sealed class SchemaException(string message) : Exception(message); +public sealed class SchemaException(string message, Exception? inner = null) : Exception(message, inner); diff --git a/src/Anubis/Platform/Installation.cs b/src/Anubis/Platform/Installation.cs index 21b8346..88ae990 100644 --- a/src/Anubis/Platform/Installation.cs +++ b/src/Anubis/Platform/Installation.cs @@ -18,8 +18,8 @@ public enum IdentityVerdict /// Empty database and a data folder that belongs to nobody: a new installation was created. Created, - /// The database knows the installation but the data folder lost its file: it was rewritten from the database. - FileRestored, + /// The database belongs to an installation but the data folder has no file saying which: the fingerprints cannot coincide. + MissingFile, /// The database is empty while the data folder belongs to an existing installation. EmptyDatabase, @@ -33,7 +33,7 @@ public enum IdentityVerdict public sealed record IdentityCheck(IdentityVerdict Verdict, InstallationFile? File, InstallationRow? Row) { - public bool CanStart => Verdict is IdentityVerdict.Match or IdentityVerdict.Created or IdentityVerdict.FileRestored; + public bool CanStart => Verdict is IdentityVerdict.Match or IdentityVerdict.Created; } /// @@ -83,15 +83,17 @@ public static class Installation var row = await ReadRowAsync(db, cancellationToken).ConfigureAwait(false); switch (row, file) { + case (null, _) when await HasDataAsync(db, cancellationToken).ConfigureAwait(false): + // Rows without an installation (a dump, an import cut short): never adopted in silence, never "empty". + return new IdentityCheck(IdentityVerdict.DifferentInstallation, file, null); case (null, null): var created = await CreateAsync(db, data, clock, cancellationToken).ConfigureAwait(false); return new IdentityCheck(IdentityVerdict.Created, created.File, created.Row); case (null, not null): return new IdentityCheck(IdentityVerdict.EmptyDatabase, file, null); case (not null, null): - var restored = new InstallationFile(row.Id, row.Fingerprint, row.Engine, row.CreatedAt, row.RenewedAt); - WriteFile(data, restored); - return new IdentityCheck(IdentityVerdict.FileRestored, restored, row); + // An old database put back in front of a new data folder looks exactly like this: nobody can tell, so the user does. + return new IdentityCheck(IdentityVerdict.MissingFile, null, row); default: if (row.Id != file.InstallationId) { @@ -104,6 +106,21 @@ public static class Installation } } + private static readonly string[] _dataTables = ["users", "accounts", "orders", "fills", "cash_ledger"]; + + private static Task HasDataAsync(Database db, CancellationToken cancellationToken) => db.ReadAsync(async s => + { + foreach (var table in _dataTables) + { + if (await s.CountAsync($"SELECT COUNT(*) FROM {table}").ConfigureAwait(false) > 0) + { + return true; + } + } + + return false; + }, cancellationToken); + private static async Task<(InstallationFile File, InstallationRow Row)> CreateAsync(Database db, DataDirectory data, IClock clock, CancellationToken cancellationToken) { var now = clock.UtcNow; @@ -117,11 +134,32 @@ public static class Installation } /// - /// After an import, a restore, a move, or when the user adopts this database: a new fingerprint in the database - /// and in installation.json, the installation id of the data folder kept (or taken from the database when - /// ), and the protected restart switched on (SPEC 15.1). + /// Written inside the import itself (SPEC 15.1): the rows come with the fingerprint they had, often the very one of + /// installation.json. Until gives a new one to both sides the database must not be accepted, + /// so an import cut in half stops at the error page instead of starting on old data. /// - public static async Task RenewAsync(Database db, DataDirectory data, IClock clock, bool adoptDatabaseIdentity, CancellationToken cancellationToken = default) + internal static Task SealAsync(DbSession s, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(s); + return s.ExecuteAsync("UPDATE installation SET fingerprint = @f, protected_restart = @p", cancellationToken, ("f", Ids.NewToken()), ("p", true)); + } + + /// + /// The SQLite file inside a backup gets a fingerprint of its own and the protected restart, so copied by hand over the + /// live file it is recognised as an old copy (SPEC 15.1). The archive next to it keeps the rows as they were. + /// + internal static async Task SealCopyAsync(string sqliteFile, CancellationToken cancellationToken) + { + await using var copy = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = sqliteFile }, allowCreate: false); + await copy.WriteAsync(s => SealAsync(s, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + /// + /// After an import, a restore, a move, or when the user adopts this database: a new fingerprint in the database and + /// in installation.json and the protected restart switched on (SPEC 15.1). The database keeps its installation id: + /// the orders in its ledger carry that code, and by that code they are found again on the accounts. + /// + public static async Task RenewAsync(Database db, DataDirectory data, IClock clock, string reason, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(db); ArgumentNullException.ThrowIfNull(clock); @@ -129,7 +167,7 @@ public static class Installation var fingerprint = Ids.NewToken(); var file = ReadFile(data); var row = await ReadRowAsync(db, cancellationToken).ConfigureAwait(false); - var id = adoptDatabaseIdentity || file is null ? row?.Id ?? Ids.NewId(clock) : file.InstallationId; + var id = row?.Id ?? file?.InstallationId ?? Ids.NewId(clock); var createdAt = row?.CreatedAt ?? file?.CreatedAt ?? now; var engine = db.Engine.ToString().ToLowerInvariant(); await db.WriteAsync(async s => @@ -141,27 +179,68 @@ public static class Installation // Sessions of the old database do not survive: everyone signs in again. await s.ExecuteAsync("DELETE FROM sessions", cancellationToken).ConfigureAwait(false); - - // SPEC 15.1: after an import, a restore or a move the bot restarts with "Ferma tutto" on, whatever the archive said. - var key = Core.SettingsStore.BotState.Key; - var stopped = new DbJson(JsonSerializer.Serialize("stopped")); - var old = await s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false); - if (old != stopped.Text) - { - await s.ExecuteAsync(old is null - ? "INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)" - : "UPDATE config SET value = @v, updated_at = @t WHERE key = @k", - cancellationToken, ("id", Ids.NewId(clock)), ("k", key), ("v", stopped), ("t", now)).ConfigureAwait(false); - await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken, - ("id", Ids.NewId(clock)), ("k", key), ("o", new DbJson(old ?? JsonSerializer.Serialize(Core.SettingsStore.BotState.Default))), ("n", stopped), - ("by", "ripartenza protetta"), ("t", now)).ConfigureAwait(false); - } + await DisarmAsync(s, clock, cancellationToken).ConfigureAwait(false); + await Trading.Diary.NotifyAsync(s, clock, "protected_restart", + $"{reason}: il database ha una nuova impronta e il bot riparte protetto, con \"Ferma tutto\" acceso. Guarda cosa ho ricostruito e riparti dalla pagina Rischio.", + cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); var renewed = new InstallationFile(id, fingerprint, engine, createdAt, now); WriteFile(data, renewed); return renewed; } + /// + /// Switches the protected restart on without changing the fingerprint: the accounts hold orders this database never + /// saw, so it is an old copy put back by hand (a file, a dump), whatever its fingerprint says. + /// + public static Task ProtectAsync(Database db, IClock clock, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentNullException.ThrowIfNull(clock); + return db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE installation SET protected_restart = @p, renewed_at = @r", cancellationToken, ("p", true), ("r", clock.UtcNow)).ConfigureAwait(false); + await DisarmAsync(s, clock, cancellationToken).ConfigureAwait(false); + }, cancellationToken); + } + + /// + /// SPEC 15.1: "Ferma tutto" on, every strategy with real money in exit only until it is confirmed again, and no + /// order planned before the restore still waiting to leave (it may already have left, after the archive). + /// + private static async Task DisarmAsync(DbSession s, IClock clock, CancellationToken cancellationToken) + { + var now = clock.UtcNow; + var key = Core.SettingsStore.BotState.Key; + var stopped = new DbJson(JsonSerializer.Serialize("stopped")); + var old = await s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false); + if (old != stopped.Text) + { + await s.ExecuteAsync(old is null + ? "INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)" + : "UPDATE config SET value = @v, updated_at = @t WHERE key = @k", + cancellationToken, ("id", Ids.NewId(clock)), ("k", key), ("v", stopped), ("t", now)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("k", key), ("o", new DbJson(old ?? JsonSerializer.Serialize(Core.SettingsStore.BotState.Default))), ("n", stopped), + ("by", "ripartenza protetta"), ("t", now)).ConfigureAwait(false); + } + + foreach (var (strategy, stage) in await s.QueryAsync("SELECT strategy, stage FROM strategy_state WHERE exit_only = @no AND stage IN (@a, @b)", + r => (r.Text("strategy"), r.Text("stage")), ("no", false), ("a", Trading.StrategyStages.Reduced), ("b", Trading.StrategyStages.Real)).ConfigureAwait(false)) + { + await s.ExecuteAsync("INSERT INTO strategy_stage_history (id, strategy, from_stage, to_stage, reason, created_at) VALUES (@id, @s, @f, @f, @r, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("s", strategy), ("f", stage), ("r", "exit_only_after_restore"), ("t", now)).ConfigureAwait(false); + } + + await s.ExecuteAsync("UPDATE strategy_state SET exit_only = @x, updated_at = @t WHERE stage IN (@a, @b)", cancellationToken, + ("x", true), ("t", now), ("a", Trading.StrategyStages.Reduced), ("b", Trading.StrategyStages.Real)).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE planned_orders SET status = @d, outcome = @o, updated_at = @t WHERE status = @p", cancellationToken, + ("d", Trading.PlannedStates.Dropped), ("o", ProtectedRestartReason), ("t", now), ("p", Trading.PlannedStates.Pending)).ConfigureAwait(false); + } + + /// Why an order planned before a restore did not leave. + public const string ProtectedRestartReason = "protected_restart"; + /// "Comincia da capo": the data folder forgets its installation so an empty database can start a new one. public static void StartOver(DataDirectory data, IClock clock) { @@ -174,7 +253,7 @@ public static class Installation } } - /// The user confirmed the protected restart (phase 9 adds the full procedure of SPEC 15.1). + /// The user confirmed the restart, after the executions were rebuilt from the brokers (SPEC 15.1). public static Task ClearProtectedRestartAsync(Database db, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(db); diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index 45594a9..83b62a2 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -1145,6 +1145,12 @@ public sealed partial class LiveEngine : IDisposable ArgumentNullException.ThrowIfNull(manager); var canceled = await manager.CancelWorkingAsync(LiveReasons.Restart, cancellationToken: cancellationToken).ConfigureAwait(false); var again = 0; + if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is { ProtectedRestart: true }) + { + // After a restore what was interrupted in the archive may have been finished since: the strategies decide again. + return 0; + } + foreach (var execution in canceled) { var row = await InterruptedAsync(execution, cancellationToken).ConfigureAwait(false); diff --git a/src/Anubis/Trading/OkxTrading.cs b/src/Anubis/Trading/OkxTrading.cs index d434674..8ddd27b 100644 --- a/src/Anubis/Trading/OkxTrading.cs +++ b/src/Anubis/Trading/OkxTrading.cs @@ -175,15 +175,45 @@ public sealed class OkxTrading : IBrokerAccount return stop ? ReadAlgo(data[0]) : ReadOrder(data[0]); } + /// What fills-history covers, with a day of margin (API-NOTES). + public static readonly TimeSpan HistoryReach = TimeSpan.FromDays(89); + + // /trade/fills covers the last three days: half a day less, so a request near the limit misses nothing. + private static readonly TimeSpan _recentReach = TimeSpan.FromHours(60); + + public TimeSpan? FillHistory => HistoryReach; + + /// + /// The recent executions, and before them those of the history: after a long absence or a restore the recent ones + /// alone would leave a hole nobody notices. An execution told by both counts once. + /// public async Task> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken) { var fills = new List(); - string? after = null; - for (var page = 0; page < 30; page++) + if (_clock.UtcNow - since > _recentReach) { - var path = "/api/v5/trade/fills?instType=SPOT&limit=100&begin=" + since.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture) + var oldest = _clock.UtcNow - HistoryReach; + await AddFillsAsync(fills, "/api/v5/trade/fills-history", since > oldest ? since : oldest, _read, cancellationToken).ConfigureAwait(false); + } + + await AddFillsAsync(fills, "/api/v5/trade/fills", since, _trade, cancellationToken).ConfigureAwait(false); + return [.. fills.DistinctBy(f => (f.Symbol, f.ExecutionId))]; + } + + private async Task AddFillsAsync(List fills, string endpoint, DateTimeOffset since, RateLimiter limiter, CancellationToken cancellationToken) + { + string? after = null; + for (var page = 0; ; page++) + { + if (page == 300) + { + // Thirty thousand executions: better an error, and the account not ready, than a list cut short in silence. + throw new BrokerException("Troppe esecuzioni da leggere in una volta sola.", retryable: false); + } + + var path = endpoint + "?instType=SPOT&limit=100&begin=" + since.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture) + (after is null ? "" : "&after=" + after); - var data = await CallAsync(HttpMethod.Get, path, null, _trade, cancellationToken).ConfigureAwait(false); + var data = await CallAsync(HttpMethod.Get, path, null, limiter, cancellationToken).ConfigureAwait(false); foreach (var item in data) { var clientId = Text(item, "clOrdId"); @@ -198,13 +228,11 @@ public sealed class OkxTrading : IBrokerAccount if (data.Count < 100) { - break; + return; } after = Text(data[^1], "billId"); } - - return fills; } /// Spot crypto has no dividends; deposits and withdrawals do not change the bot's capital (SPEC 7.1). @@ -403,8 +431,21 @@ public sealed class OkxTrading : IBrokerAccount private async Task AlgoClientIdAsync(string instrument, string orderId, CancellationToken cancellationToken) { - var data = await CallAsync(HttpMethod.Get, $"/api/v5/trade/order?instId={Uri.EscapeDataString(instrument)}&ordId={Uri.EscapeDataString(orderId)}", null, _trade, cancellationToken) - .ConfigureAwait(false); + var path = $"/api/v5/trade/order?instId={Uri.EscapeDataString(instrument)}&ordId={Uri.EscapeDataString(orderId)}"; + var url = new Uri(_options.RestUrl, path); + var answer = await _http.SendAsync(HttpMethod.Get, url, null, b => Sign("GET", path, b), _trade, retry: true, cancellationToken).ConfigureAwait(false); + var (code, _, data) = Envelope(answer); + if (code == "51603") + { + // An order too old for OKX to remember: an execution without a name, which the reconciliation shows. + return null; + } + + if (code != "0") + { + throw _http.Failure(url, answer); + } + return data.Count == 0 ? null : Text(data[0], "algoClOrdId") is { Length: > 0 } id ? id : Text(data[0], "clOrdId"); } diff --git a/src/Anubis/Trading/OrderManager.Protection.cs b/src/Anubis/Trading/OrderManager.Protection.cs index cd7ef7e..5760ee2 100644 --- a/src/Anubis/Trading/OrderManager.Protection.cs +++ b/src/Anubis/Trading/OrderManager.Protection.cs @@ -345,7 +345,13 @@ public sealed partial class OrderManager /// A stable id for the stops of a position: account, instrument and strategy. private Guid StopKey(Guid instrumentId, string strategy) { - var bytes = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(_account.AccountId.ToString("N") + instrumentId.ToString("N") + strategy)); + var text = _account.AccountId.ToString("N") + instrumentId.ToString("N") + strategy; + if (StopGeneration != 0) + { + text += StopGeneration.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + var bytes = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text)); return new Guid(bytes.AsSpan(0, 16)); } } diff --git a/src/Anubis/Trading/OrderManager.Rebuild.cs b/src/Anubis/Trading/OrderManager.Rebuild.cs new file mode 100644 index 0000000..33029c8 --- /dev/null +++ b/src/Anubis/Trading/OrderManager.Rebuild.cs @@ -0,0 +1,196 @@ +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Trading; + +/// What the broker knew of this installation and the database did not (SPEC 15.1). +public sealed record RebuildReport(int Orders, int Fills, IReadOnlyList Unclear, bool OnlyRestingStops = false) +{ + public static RebuildReport Nothing { get; } = new(0, 0, []); + + /// + /// The account did something the database never saw: the database is older than the account. Stops that never fired + /// are not enough to say so: the guard may have put them while the engine was off, and lost the note about it. + /// + public bool FoundAnything => (Orders > 0 && !OnlyRestingStops) || Unclear.Count > 0; +} + +/// +/// After a restore the ledger is older than the account (SPEC 15.1): the orders and the executions made after the +/// archive are written back from the broker. The client order id says which strategy and which environment each one +/// belongs to (SPEC 7.2), so nothing has to be guessed. +/// +public sealed partial class OrderManager +{ + /// + /// Tells apart the stops sent before a restore from those sent after it: the sequence numbers start again from + /// what the archive knew, and a name already used on the account must not come back. Zero until the first restore. + /// + public long StopGeneration { get; set; } + + /// + /// Writes back every order of this installation the database does not know, then its executions. Run at every + /// start, before reconciliation: on a database that is up to date it finds nothing and writes nothing. + /// + public async Task RebuildAsync(CancellationToken cancellationToken) + { + if (_account.Environment == TradingEnvironments.Simulation) + { + // The internal simulator lives in the database: it went back in time together with the ledger. + return RebuildReport.Nothing; + } + + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + return await RebuildCoreAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + private async Task RebuildCoreAsync(CancellationToken cancellationToken) + { + var since = await RebuildSinceAsync(cancellationToken).ConfigureAwait(false); + var fills = (await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false)).Where(f => IsMine(f.ClientOrderId)).OrderBy(f => f.ExecutedAt).ToList(); + var open = (await _broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false)).Where(o => IsMine(o.ClientOrderId)).ToList(); + var unclear = new List(); + var orders = 0; + var onlyStops = true; + foreach (var clientId in fills.Select(f => f.ClientOrderId).Concat(open.Select(o => o.ClientOrderId)).Distinct(StringComparer.Ordinal)) + { + if (await OrderByClientIdAsync(clientId, cancellationToken).ConfigureAwait(false) is not null) + { + continue; + } + + var parts = ClientOrderIds.Parse(clientId)!; + var own = fills.Where(f => f.ClientOrderId == clientId).ToList(); + var resting = open.FirstOrDefault(o => o.ClientOrderId == clientId); + var symbol = own.FirstOrDefault()?.Symbol ?? resting!.Symbol; + if (await InstrumentBySymbolAsync(symbol, cancellationToken).ConfigureAwait(false) is not { } instrumentId) + { + unclear.Add($"{symbol}: non è nel catalogo, l'ordine {clientId} resta da controllare a mano."); + continue; + } + + var remote = resting ?? await _broker.GetOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false); + if (resting is not null && parts.Purpose != OrderPurpose.Stop) + { + // A purchase or a sale nobody follows any more: canceled like every working order at a restart (SPEC 9.4). + await _broker.CancelOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false); + remote = await _broker.GetOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false) ?? resting with { Status = OrderStatus.Canceled }; + } + + await InsertRebuiltAsync(clientId, parts, instrumentId, remote, own, cancellationToken).ConfigureAwait(false); + onlyStops &= parts.Purpose == OrderPurpose.Stop && own.Count == 0; + orders++; + } + + if (orders > 0) + { + var recorded = await SyncFillsFromAsync(since, cancellationToken).ConfigureAwait(false); + await TakeStopLevelsAsync(open, cancellationToken).ConfigureAwait(false); + foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.Quantity > 0m && p.StopPrice is null)) + { + var symbol = (await _instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?"; + unclear.Add($"{symbol}: la posizione ricostruita non ha uno stop, controllala prima di ripartire."); + } + + var message = $"Conto {_account.Name}: sul conto c'erano {orders} ordini che il database non conosceva. Ho ricostruito dal broker {recorded} esecuzioni." + + (unclear.Count == 0 ? "" : " " + string.Join(" ", unclear)) + Beyond(since); + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken), cancellationToken).ConfigureAwait(false); + return new RebuildReport(orders, recorded, unclear, onlyStops); + } + + if (unclear.Count > 0) + { + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", $"Conto {_account.Name}: {string.Join(" ", unclear)}", cancellationToken), cancellationToken) + .ConfigureAwait(false); + } + + return new RebuildReport(0, 0, unclear); + } + + private string Beyond(DateTimeOffset since) => _broker.FillHistory is { } reach && since < _clock.UtcNow - reach + ? $" Il broker racconta solo gli ultimi {reach.Days} giorni: quello che è successo prima va confrontato a mano." + : ""; + + private bool IsMine(string? clientId) => + ClientOrderIds.Parse(clientId) is { } parts && parts.Installation == _installation && parts.Environment == _account.Environment; + + /// + /// A day before the last execution the database has, or before the birth of the installation when it has none: + /// whatever the archive holds is earlier than that, and an execution read twice is recorded once. + /// + private Task RebuildSinceAsync(CancellationToken cancellationToken) => _db.ReadAsync(async s => + { + var last = (await s.QueryAsync("SELECT executed_at FROM fills WHERE account_id = @a", r => r.Moment("executed_at"), ("a", _account.AccountId)).ConfigureAwait(false)) + .DefaultIfEmpty(DateTimeOffset.MinValue).Max(); + if (last != DateTimeOffset.MinValue) + { + return last.AddDays(-1); + } + + var born = (await s.QueryAsync("SELECT created_at FROM installation", r => r.Moment("created_at")).ConfigureAwait(false)).DefaultIfEmpty(_clock.UtcNow).Min(); + return born.AddDays(-1); + }, cancellationToken); + + private Task InstrumentBySymbolAsync(string symbol, CancellationToken cancellationToken) => _db.ReadAsync(async s => + { + var id = await s.FirstOrDefaultAsync("SELECT id FROM instruments WHERE venue = @v AND symbol = @s", r => r.Id("id"), ("v", _account.Broker), ("s", symbol)).ConfigureAwait(false); + return id == Guid.Empty ? (Guid?)null : id; + }, cancellationToken); + + private async Task InsertRebuiltAsync(string clientId, ClientOrderIdParts parts, Guid instrumentId, BrokerOrder? remote, List own, CancellationToken cancellationToken) + { + var filled = own.Sum(f => f.Quantity); + var side = remote?.Side ?? own[0].Side; + var kind = remote?.Kind ?? (parts.Purpose == OrderPurpose.Stop ? OrderKind.Stop : OrderKind.Limit); + var created = own.Count > 0 ? own[0].ExecutedAt : remote!.UpdatedAt; + var row = new OrderRow(Ids.NewId(_clock), null, instrumentId, parts.Strategy, clientId, side, kind, parts.Purpose, remote?.Quantity ?? filled, remote?.LimitPrice, + remote?.StopPrice, OrderStatus.Created, 0m, null, remote?.StopPrice ?? remote?.LimitPrice, null, remote?.TimeInForce ?? TimeInForce.Gtc, false, created); + await _db.WriteAsync(async s => + { + await InsertOrderAsync(s, row, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @at, reason = 'rebuilt from the broker' WHERE id = @id", cancellationToken, + ("b", remote?.BrokerOrderId), ("at", created), ("id", row.Id)).ConfigureAwait(false); + if (_account.Environment == TradingEnvironments.Live) + { + // The archive may be older than the promotion: what the bot holds on the real account gets its stops and + // its exits, and nothing else until the user confirms the strategy again. + await s.ExecuteAsync("UPDATE strategy_state SET live_account_id = @a, exit_only = @x, updated_at = @now WHERE strategy = @s AND live_account_id IS NULL", cancellationToken, + ("a", _account.AccountId), ("x", true), ("now", _clock.UtcNow), ("s", parts.Strategy)).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + remote ??= new BrokerOrder(clientId, null, own[0].Symbol, side, kind, filled, OrderStatus.Filled, filled, own[^1].ExecutedAt) + { + AverageFillPrice = DbValues.Money(own.Sum(f => f.Quantity * f.Price) / filled), + }; + await ApplyRemoteAsync(row, remote, "rebuilt from the broker", cancellationToken).ConfigureAwait(false); + } + + /// + /// The stop levels of the positions as they are on the account: a stop raised after the archive never goes back + /// down, and a rebuilt position takes the level its stop has. + /// + private async Task TakeStopLevelsAsync(List open, CancellationToken cancellationToken) + { + foreach (var stop in open.Where(o => o.Kind == OrderKind.Stop && o.Side == OrderSide.Sell && o.StopPrice is not null)) + { + var parts = ClientOrderIds.Parse(stop.ClientOrderId)!; + if (parts.Purpose != OrderPurpose.Stop || await InstrumentBySymbolAsync(stop.Symbol, cancellationToken).ConfigureAwait(false) is not { } instrumentId) + { + continue; + } + + var position = await _ledger.PositionAsync(_account.AccountId, instrumentId, parts.Strategy, cancellationToken).ConfigureAwait(false); + if (position is { Quantity: > 0m } && (position.StopPrice is null || position.StopPrice < stop.StopPrice)) + { + await _ledger.SetStopAsync(_account.AccountId, instrumentId, parts.Strategy, stop.StopPrice, cancellationToken).ConfigureAwait(false); + } + } + } +} diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index 7e2412f..05c592c 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -731,6 +731,11 @@ public sealed partial class OrderManager : IDisposable .DefaultIfEmpty(_clock.UtcNow).Min(); return last == DateTimeOffset.MinValue ? firstOrder.AddMinutes(-10) : last.AddMinutes(-10); }, cancellationToken).ConfigureAwait(false); + return await SyncFillsFromAsync(since, cancellationToken).ConfigureAwait(false); + } + + private async Task SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken) + { var fills = await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false); var recorded = 0; foreach (var fill in fills.OrderBy(f => f.ExecutedAt)) diff --git a/src/Anubis/Trading/Orders.cs b/src/Anubis/Trading/Orders.cs index 709b552..db66fbb 100644 --- a/src/Anubis/Trading/Orders.cs +++ b/src/Anubis/Trading/Orders.cs @@ -263,6 +263,9 @@ public interface IBrokerAccount /// The order with this client id, or null when the broker never received it. Task GetOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken); + /// How far back the broker tells executions; null when it tells them all. + TimeSpan? FillHistory => null; + Task> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken); Task> GetCashActivitiesAsync(DateTimeOffset since, CancellationToken cancellationToken); diff --git a/src/Anubis/Trading/ReasonCatalog.cs b/src/Anubis/Trading/ReasonCatalog.cs index 90ab5f6..53a5b1e 100644 --- a/src/Anubis/Trading/ReasonCatalog.cs +++ b/src/Anubis/Trading/ReasonCatalog.cs @@ -94,6 +94,7 @@ public static class ReasonCatalog ["order_in_progress"] = "Un ordine sullo stesso strumento era ancora in corso.", ["nothing_held"] = "Niente da vendere: la posizione era già chiusa.", ["restart"] = "Annullato alla ripartenza del bot: se era ancora dovuto, è stato riproposto.", + ["protected_restart"] = "Deciso prima del ripristino: non parte, potrebbe essere già partito allora.", ["recovered"] = "Recuperato dopo un'assenza.", }; diff --git a/src/Anubis/Trading/Stages.cs b/src/Anubis/Trading/Stages.cs index 85ebb7c..3f59aee 100644 --- a/src/Anubis/Trading/Stages.cs +++ b/src/Anubis/Trading/Stages.cs @@ -98,6 +98,9 @@ public sealed record StrategyStage( _ => LiveAccountId, }; + /// With real money but in exit only: a restore put it there, and only the user takes it out (SPEC 15.1). + public bool WaitsForReconfirmation => ExitOnly && StrategyStages.IsLive(Stage); + /// A strategy with real money keeps running in simulation too: the simulated twin (SPEC 12.3). public bool HasTwin => StrategyStages.IsLive(Stage); } @@ -412,6 +415,41 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, /// The phrase that confirms more risk while real money is in play. public const string RaisePhrase = "confermo più rischio con soldi veri"; + /// + /// After a restore every strategy with real money is in exit only until the user confirms it again (SPEC 15.1): + /// password and second factor. The counts of the stage go on and no requirement is measured a second time. + /// + public async Task ReconfirmAsync(string strategy, string password, string? code, string by, CancellationToken cancellationToken) + { + if (!consent.AllowLive) + { + throw new LiveConfirmationException(RiskReasons.NoConsent, $"La configurazione d'avvio non consente i soldi veri ({consent.Source})."); + } + + var stage = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy)); + if (!stage.WaitsForReconfirmation) + { + throw new LiveConfirmationException("stage", "Questa strategia non aspetta una riconferma."); + } + + if (!await reauthenticate(password, code, cancellationToken).ConfigureAwait(false)) + { + throw new LiveConfirmationException("password", "Password o codice a due fattori non corretti."); + } + + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE strategy_state SET exit_only = @no, updated_at = @t WHERE strategy = @s", cancellationToken, + ("no", false), ("t", now), ("s", strategy)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO strategy_stage_history (id, strategy, from_stage, to_stage, reason, created_at) VALUES (@id, @s, @f, @f, @r, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("s", strategy), ("f", stage.Stage), ("r", "reconfirmed_after_restore · " + by), ("t", now)).ConfigureAwait(false); + await LogChangeAsync(s, strategy, stage.Stage + " (da riconfermare)", stage.Stage, by, cancellationToken).ConfigureAwait(false); + await Diary.WriteAsync(s, clock, DiaryKinds.System, "strategy_reconfirmed", + $"{StrategyNames.Label(strategy, withMarket: true)}: riconfermata dopo il ripristino, può di nuovo comprare con soldi veri ({by}).", null, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + /// True when a strategy, of or of any broker when null, is in reduced or real. public async Task AnyLiveAsync(string? broker, CancellationToken cancellationToken) => (await AllAsync(cancellationToken).ConfigureAwait(false)).Any(s => StrategyStages.IsLive(s.Stage) && (broker is null || StrategyNames.BrokerOf(s.Strategy) == broker)); @@ -485,7 +523,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, { ArgumentNullException.ThrowIfNull(ledger); var released = 0; - foreach (var stage in (await AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => s.ExitOnly && s.LiveAccountId is not null)) + foreach (var stage in (await AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => s.ExitOnly && s.LiveAccountId is not null && !s.WaitsForReconfirmation)) { var open = (await ledger.PositionsAsync(stage.LiveAccountId, cancellationToken).ConfigureAwait(false)).Any(p => p.Strategy == stage.Strategy && p.Quantity > 0m); if (open) diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index a3c0ef4..8a1ea84 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -301,6 +301,7 @@ public sealed partial class TradingService : IDisposable await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false); Guard?.Step("connessione ai broker"); + var generation = await StopGenerationAsync(cancellationToken).ConfigureAwait(false); var hang = Fault == GuardChannel.HangMidSale; foreach (var account in accounts) { @@ -313,6 +314,7 @@ public sealed partial class TradingService : IDisposable _managers[account.AccountId] = new OrderManager(_db, _clock, Ledger, broker, account, InstallationCode, (id, ct) => _catalog.GetAsync(id, ct), Quotes.GetAsync) { + StopGeneration = generation, ConfirmPrice = Quotes.ConfirmAsync, MarketOpen = MarketOpenAsync, PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct), @@ -402,6 +404,8 @@ public sealed partial class TradingService : IDisposable else { await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); + Guard?.Step("esecuzioni dal broker " + name); + await RebuildAsync(manager, cancellationToken).ConfigureAwait(false); } Guard?.Step("riconciliazione " + name); @@ -417,6 +421,52 @@ public sealed partial class TradingService : IDisposable } } + /// + /// SPEC 15.1: what the account did after the archive is written back before anything compares ledger and account. + /// Finding something on a database nobody declared restored means it is an old copy put back by hand, or a dump: + /// the protected restart starts here, as it would have after an import. + /// + internal async Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken) + { + var report = await manager.RebuildAsync(cancellationToken).ConfigureAwait(false); + if (!report.FoundAnything) + { + return; + } + + if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is { ProtectedRestart: true } + && await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", SettingsStore.BotState.Key)), cancellationToken) + .ConfigureAwait(false) == "\"stopped\"") + { + return; + } + + await Platform.Installation.ProtectAsync(_db, _clock, cancellationToken).ConfigureAwait(false); + var generation = await StopGenerationAsync(cancellationToken).ConfigureAwait(false); + foreach (var each in _managers.Values) + { + each.StopGeneration = generation; + } + + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "protected_restart", + $"Sul conto {manager.Account.Name} ci sono ordini che questo database non conosce: è una copia più vecchia del conto. Ho fermato tutto: controlla e riparti dalla pagina Rischio.", + cancellationToken), cancellationToken).ConfigureAwait(false); + } + + /// Zero until the first restore, then the moment of the last one. + private async Task StopGenerationAsync(CancellationToken cancellationToken) => + await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is { } row && row.RenewedAt != row.CreatedAt ? row.RenewedAt.UtcTicks : 0; + + /// + /// The accounts whose executions after the archive are not rebuilt yet: until then the user cannot confirm the + /// protected restart (SPEC 15.1). The internal simulator has nothing to rebuild and holds nobody back. + /// + public IReadOnlyList AccountsToRebuild => + [.. _managers.Values.Where(m => m.Account.Environment != TradingEnvironments.Simulation && !AccountReady(m.Account.AccountId)).Select(m => m.Account.Name).Order(StringComparer.Ordinal)]; + + /// The startup of SPEC 9.4 went through: every account with keys was tried at least once. + public bool Started => _started; + /// /// The stops the guard put back while the engine was stopped become the engine's own, before anything compares /// them. A note goes in the diary and is deleted only when every stop it placed is adopted, for every account: a diff --git a/tests/Anubis.Tests/ArchiveTests.cs b/tests/Anubis.Tests/ArchiveTests.cs index 01454e8..b108ee5 100644 --- a/tests/Anubis.Tests/ArchiveTests.cs +++ b/tests/Anubis.Tests/ArchiveTests.cs @@ -117,7 +117,7 @@ public sealed class ArchiveTests File.WriteAllLines(cash, lines.Skip(1)); await using var target = await TestDb.CreateAsync().ConfigureAwait(false); await Assert.ThrowsAsync(() => Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false); - Assert.AreEqual(0L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["accounts"], "un'importazione fallita non lascia righe"); + Assert.IsEmpty(await Archive.CountsAsync(target.Db).ConfigureAwait(false), "un archivio guasto non lascia nemmeno lo schema"); await Assert.ThrowsAsync(() => Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false); } @@ -140,7 +140,7 @@ public sealed class ArchiveTests var backups = new Backups(new DataDirectory(folder), clock); for (var i = 0; i < 16; i++) { - await backups.TakeAsync(test.Db, i == 0 ? "prima-della-migrazione" : "notturno").ConfigureAwait(false); + await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false); clock.Advance(TimeSpan.FromDays(1)); } @@ -180,7 +180,176 @@ public sealed class ArchiveTests await test.Db.WriteAsync(s => s.ExecuteAsync($"DELETE FROM {Migrations.VersionTable} WHERE version = @v", ("v", Migrations.Latest))).ConfigureAwait(false); if (Migrations.Latest > 1) { - await Assert.ThrowsAsync(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false); + await Assert.ThrowsAsync(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false); } } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ADamagedArchiveLeavesTheDatabaseUntouchedAndTheGoodOneGoesInAfterwards() + { + await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + await SeedAsync(source.Db).ConfigureAwait(false); + var folder = TempFolder.Create("archive-retry"); + try + { + var good = Path.Combine(folder, "a"); + await Archive.ExportAsync(source.Db, good, _clock).ConfigureAwait(false); + await using var target = await TestDb.CreateAsync().ConfigureAwait(false); + + async Task RefusedAsync(string file, Func damage) + { + var path = Path.Combine(good, file); + var before = await File.ReadAllTextAsync(path).ConfigureAwait(false); + await File.WriteAllTextAsync(path, damage(before)).ConfigureAwait(false); + try + { + await Archive.ImportAsync(target.Db, good, _clock).ConfigureAwait(false); + Assert.Fail("Accepted: " + file); + } + catch (Exception ex) when (Anubis.Server.Forms.IsArchiveProblem(ex)) + { + } + + await File.WriteAllTextAsync(path, before).ConfigureAwait(false); + Assert.IsTrue((await Migrations.StatusAsync(target.Db, CancellationToken.None).ConfigureAwait(false)).IsEmpty, "Not even the schema: " + file); + } + + // A row less, a number that is not one, a total that changed, a row that is not an object. + await RefusedAsync("cash_ledger.jsonl", t => t[(t.IndexOf('\n', StringComparison.Ordinal) + 1)..]).ConfigureAwait(false); + await RefusedAsync("fills.jsonl", t => t.Replace("68950", "novanta", StringComparison.Ordinal)).ConfigureAwait(false); + await RefusedAsync("fills.jsonl", t => t.Replace("0.0182", "0.0183", StringComparison.Ordinal).Replace("-0.0183", "-0.0182", StringComparison.Ordinal)).ConfigureAwait(false); + await RefusedAsync("accounts.jsonl", _ => "[]\n").ConfigureAwait(false); + + // An index that points outside its folder, or names a table twice. + await RefusedAsync(Archive.IndexFile, t => t.Replace("\"fills.jsonl\"", "\"../fills.jsonl\"", StringComparison.Ordinal)).ConfigureAwait(false); + await RefusedAsync(Archive.IndexFile, t => t.Replace("\"fills\"", "\"accounts\"", StringComparison.Ordinal)).ConfigureAwait(false); + + await Archive.ImportAsync(target.Db, good, _clock).ConfigureAwait(false); + Assert.AreEqual(2L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["fills"]); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AnOlderArchiveGoesInAfterAnImportThatStoppedHalfWay() + { + await using var old = await TestDb.CreateAsync().ConfigureAwait(false); + await Migrations.MigrateAsync(old.Db, _clock, null, CancellationToken.None, upTo: 8).ConfigureAwait(false); + var folder = TempFolder.Create("archive-old"); + try + { + await Archive.ExportAsync(old.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false); + + // The first attempt created the schema of the archive and stopped there (power lost). + await using var target = await TestDb.CreateAsync().ConfigureAwait(false); + await Migrations.MigrateAsync(target.Db, _clock, null, CancellationToken.None, upTo: 5).ConfigureAwait(false); + await Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false); + Assert.AreEqual(Migrations.Latest, (await Migrations.StatusAsync(target.Db, CancellationToken.None).ConfigureAwait(false)).Current); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AnImportIsSealedUntilTheInstallationIsRenewedAndSoIsTheSqliteCopy() + { + await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var folder = TempFolder.Create("seal"); + try + { + var data = new DataDirectory(Path.Combine(folder, "data")); + await Installation.CheckAsync(source.Db, data, _clock).ConfigureAwait(false); + var backup = await new Backups(data, _clock).TakeAsync(source.Db, "a-mano").ConfigureAwait(false); + + // The same fingerprint as installation.json is in the archive: without the seal the import would be accepted as it is. + await using var target = await TestDb.CreateAsync().ConfigureAwait(false); + await Archive.ImportAsync(target.Db, Path.Combine(backup.Folder, Backups.ArchiveFolder), _clock).ConfigureAwait(false); + Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict); + + if (backup.HasSqliteCopy) + { + var copy = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = Path.Combine(backup.Folder, Backups.SqliteCopy) }; + await using var byHand = Database.Open(copy, allowCreate: false); + Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(byHand, data, _clock).ConfigureAwait(false)).Verdict); + Assert.IsTrue((await Installation.ReadRowAsync(byHand).ConfigureAwait(false))!.ProtectedRestart); + } + + // Renewed, the new one is accepted and the source becomes the old copy. + await Installation.RenewAsync(target.Db, data, _clock, "prova").ConfigureAwait(false); + Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict); + Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(source.Db, data, _clock).ConfigureAwait(false)).Verdict); + Assert.AreEqual(Installation.ReadFile(data)!.InstallationId, (await Installation.ReadRowAsync(source.Db).ConfigureAwait(false))!.Id, "The orders of the ledger keep their installation."); + + // Rows without an installation are never taken for an empty database. + await SeedAsync(target.Db).ConfigureAwait(false); + await target.Db.WriteAsync(s => s.ExecuteAsync("DELETE FROM installation")).ConfigureAwait(false); + Assert.AreEqual(IdentityVerdict.DifferentInstallation, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ASeriesOfBackupsOfOneKindNeverPushesOutTheNightlyOnes() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var folder = TempFolder.Create("kinds"); + try + { + var clock = new ManualClock(_clock.UtcNow); + var data = new DataDirectory(folder); + var backups = new Backups(data, clock); + await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false); + var left = Directory.CreateDirectory(Path.Combine(data.Backups, "20260901-010101-notturno.partial")); + left.LastWriteTimeUtc = clock.UtcNow.UtcDateTime.AddDays(-3); + for (var i = 0; i < Backups.Keep + 3; i++) + { + // The same second twice: the second one takes a number. + await backups.TakeAsync(test.Db, Backups.BeforeMigration).ConfigureAwait(false); + clock.Advance(TimeSpan.FromSeconds(i % 2)); + } + + Assert.HasCount(1, backups.List().Where(b => b.Reason == "notturno").ToList()); + Assert.HasCount(Backups.Keep, backups.List().Where(b => b.Reason.StartsWith(Backups.BeforeMigration, StringComparison.Ordinal)).ToList()); + Assert.IsFalse(Directory.Exists(left.FullName), "What a power failure left is cleaned."); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AMigrationThatFailsIsASchemaProblemAndLeavesTheVersionBefore() + { + await using var test = await TestDb.CreateAsync().ConfigureAwait(false); + await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None, upTo: 12).ConfigureAwait(false); + await test.Db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)")).ConfigureAwait(false); + var backups = 0; + var error = await Assert.ThrowsExactlyAsync(() => Migrations.MigrateAsync(test.Db, _clock, _ => + { + backups++; + return Task.CompletedTask; + }, CancellationToken.None)).ConfigureAwait(false); + Assert.Contains("0013", error.Message); + Assert.AreEqual(1, backups); + Assert.AreEqual(12, (await Migrations.StatusAsync(test.Db, CancellationToken.None).ConfigureAwait(false)).Current); + + // Without room for the backup nothing is migrated. + var full = await Assert.ThrowsExactlyAsync(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)) + .ConfigureAwait(false); + Assert.Contains("disco pieno", full.Message); + } } diff --git a/tests/Anubis.Tests/LiveEngineTests.cs b/tests/Anubis.Tests/LiveEngineTests.cs index 5c02e28..96764b1 100644 --- a/tests/Anubis.Tests/LiveEngineTests.cs +++ b/tests/Anubis.Tests/LiveEngineTests.cs @@ -175,4 +175,44 @@ public sealed class LiveEngineTests Assert.IsLessThan(live.Instruments[symbol].Spec.LotSize ?? 0m, Math.Abs(quantity - ledger[symbol]), symbol); } } + + /// + /// A purchase was working when the process stopped. Normally it is proposed again; after a restore (SPEC 15.1) the + /// archive may be older than the account, so nothing is proposed: the strategies decide again. + /// + [TestMethod] + [TestCategory(Category.Integration)] + [DataRow(false)] + [DataRow(true)] + public async Task AfterARestoreAnInterruptedPurchaseIsNotProposedAgain(bool restored) + { + var last = LiveFrom.AddDays(120); + await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false); + var found = false; + for (var day = LiveFrom; day <= last && !found; day = day.AddDays(1)) + { + await live.DayAsync(day, async _ => + { + if (found || await live.WorkingOrdersAsync().ConfigureAwait(false) == 0) + { + return; + } + + found = true; + await live.Rig.Db.WriteAsync(async s => + { + await s.ExecuteAsync("DELETE FROM installation").ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO installation (id, fingerprint, engine, protected_restart, created_at, renewed_at) VALUES (@id, @f, @e, @p, @now, @now)", CancellationToken.None, ("e", "sqlite"), + ("id", Guid.NewGuid()), ("f", Guid.NewGuid()), ("p", restored), ("now", live.Rig.Clock.UtcNow)).ConfigureAwait(false); + }).ConfigureAwait(false); + var again = await live.Engine.ResumeAsync(live.Manager, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(restored ? 0 : 1, Math.Min(again, 1)); + Assert.AreEqual(0, await live.WorkingOrdersAsync().ConfigureAwait(false), "What was working is canceled either way."); + Assert.HasCount(restored ? 0 : again, await live.Rig.QueryAsync("SELECT id FROM planned_orders WHERE status = @s AND execution_id IS NULL", r => r.Id("id"), + ("s", PlannedStates.Pending)).ConfigureAwait(false)); + }).ConfigureAwait(false); + } + + Assert.IsTrue(found, "A purchase must have been working."); + } } diff --git a/tests/Anubis.Tests/OkxHistoryTests.cs b/tests/Anubis.Tests/OkxHistoryTests.cs new file mode 100644 index 0000000..b3699e7 --- /dev/null +++ b/tests/Anubis.Tests/OkxHistoryTests.cs @@ -0,0 +1,74 @@ +using System.Globalization; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The executions of OKX after a long absence or a restore: recent and history, each counted once (issue #69). +[TestClass] +[TestCategory(Category.Unit)] +public sealed class OkxHistoryTests +{ + private static readonly DateTimeOffset _now = TradingRig.Start; + + private static string Fill(string trade, DateTimeOffset at, string client = "ANUtrnd00000000aE1") => + "{\"side\":\"buy\",\"fillSz\":\"0.01\",\"fillPx\":\"50000\",\"fee\":\"-0.5\",\"feeCcy\":\"EUR\",\"ordId\":\"1" + trade + "\",\"instId\":\"BTC-EUR\",\"instType\":\"SPOT\",\"clOrdId\":\"" + client + + "\",\"billId\":\"b" + trade + "\",\"tradeId\":\"" + trade + "\",\"fillTime\":\"" + Ms(at) + "\",\"ts\":\"" + Ms(at) + "\"}"; + + private static string Ms(DateTimeOffset at) => at.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture); + + private static string Envelope(IEnumerable items) => "{\"code\":\"0\",\"msg\":\"\",\"data\":[" + string.Join(',', items) + "]}"; + + private static OkxTrading Adapter(FakeHttp http) => + new(http.Client(), new ManualClock(_now), new OkxCredentials("doc-key", "doc-secret", "doc-pass"), new OkxTradingOptions { Environment = TradingEnvironments.Demo }, + TradingConsent.None); + + private static FakeHttp Http(IReadOnlyList history, IReadOnlyList recent) => new FakeHttp() + .On(u => u.AbsolutePath == "/api/v5/trade/fills-history", r => FakeHttp.Respond(Envelope( + r.RequestUri!.Query.Contains("after=", StringComparison.Ordinal) ? history.Skip(100) : history.Take(100)))) + .On(u => u.AbsolutePath == "/api/v5/trade/fills", _ => FakeHttp.Respond(Envelope(recent))) + .On(u => u.AbsolutePath == "/api/v5/trade/order", _ => FakeHttp.Respond("{\"code\":\"51603\",\"msg\":\"Order does not exist\",\"data\":[]}")); + + [TestMethod] + public async Task AfterALongAbsenceTheHistoryIsReadTooAndEachExecutionCountsOnce() + { + var since = _now.AddDays(-20); + string[] history = [.. Enumerable.Range(0, 150).Select(i => Fill((1000 + i).ToString(CultureInfo.InvariantCulture), _now.AddDays(-5).AddMinutes(-i)))]; + var http = Http(history, [Fill("2000", _now.AddHours(-1)), Fill("1000", _now.AddDays(-5))]); + var fills = await Adapter(http).GetFillsAsync(since, CancellationToken.None); + + Assert.HasCount(151, fills); + Assert.HasCount(151, fills.Select(f => f.ExecutionId).Distinct().ToList()); + var asked = http.Urls.Where(u => u.AbsolutePath.EndsWith("/fills-history", StringComparison.Ordinal)).ToList(); + Assert.HasCount(2, asked, "Two pages of history."); + StringAssert.Contains(asked[0].Query, "instType=SPOT"); + StringAssert.Contains(asked[0].Query, "begin=" + Ms(since)); + StringAssert.Contains(asked[1].Query, "after=b1099"); + } + + [TestMethod] + public async Task TheRecentOnesAloneAreEnoughForTheEverydayReading() + { + var http = Http([], [Fill("2000", _now.AddHours(-1))]); + Assert.HasCount(1, await Adapter(http).GetFillsAsync(_now.AddHours(-48), CancellationToken.None)); + Assert.IsTrue(http.Urls.All(u => u.AbsolutePath == "/api/v5/trade/fills")); + } + + [TestMethod] + public async Task TheHistoryIsAskedOnlyAsFarAsOkxKeepsIt() + { + var http = Http([], []); + var adapter = Adapter(http); + await adapter.GetFillsAsync(_now.AddDays(-400), CancellationToken.None); + StringAssert.Contains(http.Urls.First().Query, "begin=" + Ms(_now - OkxTrading.HistoryReach)); + Assert.AreEqual(OkxTrading.HistoryReach, adapter.FillHistory); + } + + [TestMethod] + public async Task AnOldExecutionWhoseOrderOkxForgotIsReadWithoutAName() + { + var http = Http([Fill("1000", _now.AddDays(-10), client: "")], []); + Assert.AreEqual("", (await Adapter(http).GetFillsAsync(_now.AddDays(-20), CancellationToken.None)).Single().ClientOrderId); + } +} diff --git a/tests/Anubis.Tests/RestoreServerTests.cs b/tests/Anubis.Tests/RestoreServerTests.cs new file mode 100644 index 0000000..32bc2b1 --- /dev/null +++ b/tests/Anubis.Tests/RestoreServerTests.cs @@ -0,0 +1,271 @@ +using System.Net; +using Anubis.Access; +using Anubis.Core; +using Anubis.Db; +using Anubis.Platform; +using Anubis.Server; + +namespace Anubis.Tests; + +/// Restore, old copies, failed migrations and a changed secret key as the user meets them (issue #69, SPEC 9.4, 15.1). +[TestClass] +[TestCategory(Category.Integration)] +public sealed class RestoreServerTests +{ + /// The database of the data folder is set aside and an empty one takes its place; the answer is how to put it back. + private static async Task<(Func PutBack, Func PutNew, TestDb? Empty)> EmptyDatabaseAsync(Dictionary env, string data, TestDb? postgres) + { + if (postgres is not null) + { + var empty = await TestDb.CreateAsync(DbEngine.Postgres); + ServerHarness.UsePostgres(env, empty); + return (() => + { + ServerHarness.UsePostgres(env, postgres); + return Task.CompletedTask; + }, () => + { + ServerHarness.UsePostgres(env, empty); + return Task.CompletedTask; + }, empty); + } + + var file = new DataDirectory(data).SqliteFile; + var old = data + "-vecchio.sqlite3"; + var fresh = data + "-nuovo.sqlite3"; + void Take(string from, string to) + { + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + File.Copy(from, to, overwrite: true); + foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!).Where(f => f.StartsWith(file, StringComparison.OrdinalIgnoreCase))) + { + File.Delete(f); + } + } + + Take(file, old); + await File.WriteAllBytesAsync(file, []); + return (() => + { + Take(file, fresh); + File.Copy(old, file); + return Task.CompletedTask; + }, () => + { + Take(file, old); + File.Copy(fresh, file); + return Task.CompletedTask; + }, null); + } + + [TestMethod] + public async Task AfterARestoreTheOldDatabaseIsRefusedAndTheNewOneWaitsForTheUser() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var engine = postgres; + var data = TempFolder.Create("protected"); + string password; + await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + password = await first.SignInFirstTimeAsync(); + using var saved = await first.PostFormAsync("/impostazioni", "/azioni/salvataggio"); + } + + var backup = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano"); + var (putBack, putNew, empty) = await EmptyDatabaseAsync(env, data, postgres); + await using var second = empty; + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false)) + { + await server.WaitForAsync(HostMode.IdentityProblem); + using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name))) + { + Assert.AreEqual("/", ServerHarness.Location(restore)); + } + + // Without the trading engine nothing can be rebuilt: the restart waits. + await server.WaitForAsync(HostMode.Ready); + using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password))) + { + Assert.AreEqual("/", ServerHarness.Location(signIn)); + } + + StringAssert.Contains(await server.TextAsync("/"), "Ripartenza protetta"); + using (var early = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva")) + { + Assert.AreEqual("stopped", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value); + } + + Assert.HasCount(1, await server.Host.Services!.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'protected_restart'", r => r.Text("message")))); + } + + // The database of before the restore comes back, by mistake: same installation, older fingerprint, engine off. + await putBack(); + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false)) + { + await server.WaitForAsync(HostMode.IdentityProblem); + Assert.AreEqual(IdentityVerdict.StaleDatabase, server.Host.Status.Identity!.Verdict); + StringAssert.Contains(await server.TextAsync("/"), "una copia più vecchia"); + using var health = await server.GetAsync("/health"); + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, health.StatusCode); + Assert.IsNull(server.Host.Services); + } + + // The right one: protected until the user confirms, then as before. + await putNew(); + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, trading: true)) + { + using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password))) + { + Assert.AreEqual("/", ServerHarness.Location(signIn)); + } + + for (var i = 0; i < 300 && server.Host.Services!.Trading is not { Started: true }; i++) + { + await Task.Delay(100); + } + + StringAssert.Contains(await server.TextAsync("/rischio"), "Sui conti non c'era niente che il database non conoscesse già"); + using (var go = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva")) + { + Assert.AreEqual(HttpStatusCode.Redirect, go.StatusCode); + } + + Assert.AreEqual("active", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value); + Assert.IsFalse((await Installation.ReadRowAsync(server.Host.Services.Db))!.ProtectedRestart); + Assert.IsFalse((await server.TextAsync("/rischio")).Contains("Ripartenza protetta", StringComparison.Ordinal)); + } + + TempFolder.Delete(data); + foreach (var left in new[] { data + "-vecchio.sqlite3", data + "-nuovo.sqlite3" }) + { + File.Delete(left); + } + } + + [TestMethod] + public async Task AFailedMigrationKeepsTheEngineOffAndTakesOneBackup() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var engine = postgres; + var data = TempFolder.Create("migration"); + var directory = new DataDirectory(data); + directory.Ensure(); + var settings = postgres?.Settings ?? new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = directory.SqliteFile }; + await using (var db = Database.Open(settings)) + { + await Migrations.MigrateAsync(db, SystemClock.Instance, null, CancellationToken.None, upTo: 12); + await Installation.CheckAsync(db, directory, SystemClock.Instance); + await db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)")); + } + + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false)) + { + await server.WaitForAsync(HostMode.SchemaProblem); + await Task.Delay(1000); + Assert.HasCount(1, new Backups(directory, SystemClock.Instance).List(), "One backup, however long the page stays open."); + var html = await server.TextAsync("/"); + StringAssert.Contains(html, "0013"); + StringAssert.Contains(html, "prima-della-migrazione"); + + using (var wrong = await server.PostFormAsync("/", "/azioni/servizio/riprova", ("password", "wrong-password-123"))) + { + StringAssert.Contains(ServerHarness.Location(wrong), "errore=password"); + } + + await using (var db = Database.Open(settings)) + { + await db.WriteAsync(s => s.ExecuteAsync("DROP TABLE cost_estimates")); + } + + using (var again = await server.PostFormAsync("/", "/azioni/servizio/riprova", ("password", ServerHarness.AdminPassword))) + { + Assert.AreEqual("/", ServerHarness.Location(again)); + } + + await server.WaitForAsync(HostMode.Ready); + } + + TempFolder.Delete(data); + } + + [TestMethod] + public async Task WithAnotherSecretKeyNothingCrashesAndTheAccessIsResetFromTheCommandLine() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var engine = postgres; + var data = TempFolder.Create("key"); + string password; + await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + password = await first.SignInFirstTimeAsync(); + 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))); + await services.Secrets.SetAsync("FINNHUB_API_KEY", "chiave-di-prova-1", "test"); + } + + env["ANUBIS_SECRET_KEY"] = "another-secret-key-0123456789-abcdefghij"; + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + using (var refused = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password), ("codice", "123456"))) + { + Assert.AreEqual("/accesso?errore=chiave", ServerHarness.Location(refused)); + } + + StringAssert.Contains(await server.TextAsync("/accesso?errore=chiave"), "ANUBIS_SECRET_KEY"); + using var output = new StringWriter(); + Assert.AreEqual(0, await AccessCommand.RunAsync(["reset", "--platform", "docker", "--data-dir", data], output, env, iterations: 1000), output.ToString()); + var temporary = output.ToString().Split("Password provvisoria: ")[1].Split('\n')[0].Trim(); + using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", temporary))) + { + Assert.AreEqual("/", ServerHarness.Location(signIn)); + } + + const string chosen = "chosen-test-pass-3"; + using (var change = await server.PostFormAsync("/primo-accesso", "/azioni/primo-accesso", ("attuale", temporary), ("nuova", chosen), ("conferma", chosen))) + { + Assert.AreEqual("/?ok=password", ServerHarness.Location(change)); + } + + StringAssert.Contains(await server.TextAsync("/impostazioni"), "Non si legge più: la chiave dei segreti è cambiata"); + } + + TempFolder.Delete(data); + } + + [TestMethod] + public async Task TheCommandLineImportsIntoANewSqliteFileOfTheSameFolder() + { + var data = TempFolder.Create("cli-same"); + var env = ServerHarness.DockerSqlite(); + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + await server.SignInFirstTimeAsync(); + } + + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + var root = TempFolder.Create("cli-same-archive"); + var archive = Path.Combine(root, "archivio"); + using var output = new StringWriter(); + Assert.AreEqual(0, await DatabaseCommand.RunAsync(["export", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString()); + var directory = new DataDirectory(data); + foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(directory.SqliteFile)!)) + { + File.Delete(f); + } + + // A wrong folder creates nothing. + Assert.AreEqual(1, await DatabaseCommand.RunAsync(["import", root, "--platform", "docker", "--data-dir", data], output, env)); + Assert.IsFalse(File.Exists(directory.SqliteFile)); + + Assert.AreEqual(0, await DatabaseCommand.RunAsync(["import", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString()); + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + Assert.IsTrue((await Installation.ReadRowAsync(server.Host.Services!.Db))!.ProtectedRestart); + } + + TempFolder.Delete(data); + TempFolder.Delete(root); + } +} diff --git a/tests/Anubis.Tests/RestoreTests.cs b/tests/Anubis.Tests/RestoreTests.cs new file mode 100644 index 0000000..978168f --- /dev/null +++ b/tests/Anubis.Tests/RestoreTests.cs @@ -0,0 +1,303 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Platform; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// After a restore (issue #69, SPEC 15.1): what the account did after the archive is written back from the broker, the +/// stops never go down, nothing planned before the archive leaves, and the bot waits for the user. +/// +[TestClass] +public sealed class RestoreTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + private static readonly TimeSpan _minute = TimeSpan.FromSeconds(60); + + /// A demo account: a simulator whose book lives outside the database, as a broker's does. + private sealed class Account : IAsyncDisposable + { + private int _archives; + + public required TradingRig Rig { get; init; } + + public required AccountContext Context { get; init; } + + public required Instrument Btc { get; init; } + + public required Instrument Eth { get; init; } + + public required PaperBroker Paper { get; init; } + + public required FaultyBroker Broker { get; init; } + + public required OrderManager Manager { get; init; } + + public required string Folder { get; init; } + + public List Restored { get; } = []; + + public static async Task OpenAsync() + { + var rig = await TradingRig.CreateAsync(); + var folder = TempFolder.Create("restore"); + await Installation.CheckAsync(rig.Db, new DataDirectory(Path.Combine(folder, "data")), rig.Clock, _none); + var context = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Demo); + var btc = await rig.InstrumentAsync(TradingRig.Btc); + var eth = await rig.InstrumentAsync(MarketDataStoreTests.Okx("ETH-EUR") with { TickSize = 0.01m, LotSize = 0.000001m, MinSize = 0.0001m }); + rig.Quote(btc.Symbol, 60_000m, 60_010m); + rig.Quote(eth.Symbol, 2_000m, 2_001m); + var paper = rig.Paper(PaperOptions.Okx(), context.AccountId, persist: false); + await paper.DepositAsync(100_000m, "EUR", _none); + await rig.Ledger.RecordCapitalAsync(context.AccountId, StrategyNames.CryptoTrend, 100_000m, "EUR", "test", _none); + var broker = new FaultyBroker(paper, TradingEnvironments.Demo); + return new Account { Rig = rig, Context = context, Btc = btc, Eth = eth, Paper = paper, Broker = broker, Manager = rig.Manager(broker, context), Folder = folder }; + } + + public async Task BuyAsync(Instrument instrument, decimal quantity, decimal stop) + { + Rig.Refresh(); + var (id, refusal) = await Manager.SubmitAsync(new TradeIntent(instrument.Id, StrategyNames.CryptoTrend, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(Rig.Clock)) + { + StopLevel = stop, + StartAggressive = true, + }, _none); + Assert.IsNull(refusal); + Assert.IsNotNull(id); + await TurnsAsync(Manager, 3); + } + + public async Task SellAsync(Instrument instrument, decimal quantity) + { + Rig.Refresh(); + var (_, refusal) = await Manager.SubmitAsync(new TradeIntent(instrument.Id, StrategyNames.CryptoTrend, OrderSide.Sell, quantity, OrderPurpose.Exit, Ids.NewId(Rig.Clock)) + { + StartAggressive = true, + }, _none); + Assert.IsNull(refusal); + await TurnsAsync(Manager, 3); + } + + public async Task TurnsAsync(OrderManager manager, int turns) + { + for (var i = 0; i < turns; i++) + { + Rig.Refresh(); + await Paper.PumpAsync(_none); + await manager.TickAsync(_none); + Rig.Clock.Advance(_minute); + } + } + + public async Task ArchiveAsync() + { + var folder = Path.Combine(Folder, "archivio" + (++_archives).ToString(System.Globalization.CultureInfo.InvariantCulture)); + await Archive.ExportAsync(Rig.Db, folder, Rig.Clock, _none); + return folder; + } + + public async Task<(TradingRig Rig, OrderManager Manager)> RestoreAsync(string archive, DbEngine? engine = null) + { + var rig = await Rig.RestoreAsync(archive, engine); + Restored.Add(rig); + await Installation.RenewAsync(rig.Db, new DataDirectory(Path.Combine(Folder, "data")), rig.Clock, "Salvataggio ripristinato", _none); + var manager = rig.Manager(Broker, Context); + manager.StopGeneration = rig.Clock.UtcNow.UtcTicks; + return (rig, manager); + } + + public async Task SameLedgerAsync(TradingRig restored, string message) + { + async Task> PositionsAsync(TradingRig rig) => [.. (await rig.Ledger.PositionsAsync(Context.AccountId, _none)).Where(p => p.Quantity > 0m) + .Select(p => $"{p.InstrumentId} {p.Strategy} {DbValues.MoneyText(p.Quantity)} {p.StopPrice}").Order(StringComparer.Ordinal)]; + async Task> FillsAsync(TradingRig rig) => [.. (await rig.QueryAsync("SELECT execution_id, side, quantity, price, fee FROM fills", + r => $"{r.Text("execution_id")} {r.Text("side")} {r.Money("quantity")} {r.Money("price")} {r.Money("fee")}")).Order(StringComparer.Ordinal)]; + + CollectionAssert.AreEqual(await PositionsAsync(Rig), await PositionsAsync(restored), message); + CollectionAssert.AreEqual(await FillsAsync(Rig), await FillsAsync(restored), message); + } + + public async ValueTask DisposeAsync() + { + foreach (var rig in Restored) + { + await rig.DisposeAsync(); + } + + await Rig.DisposeAsync(); + TempFolder.Delete(Folder); + } + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task WhatTheAccountDidAfterTheArchiveIsRebuiltFromTheBroker() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + + // After the archive: the BTC stop rises, part is sold, ETH is bought, and one purchase is still working. + a.Rig.Clock.Advance(TimeSpan.FromHours(5)); + await a.Rig.Ledger.SetStopAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, 58_500m, _none); + await a.TurnsAsync(a.Manager, 2); + await a.SellAsync(a.Btc, 0.004m); + await a.BuyAsync(a.Eth, 1m, 1_900m); + var stops = (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Stop).Select(o => o.ClientOrderId).ToList(); + Assert.HasCount(2, stops); + a.Rig.Refresh(); + Assert.IsNull((await a.Manager.SubmitAsync(new TradeIntent(a.Eth.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.5m, OrderPurpose.Entry, Ids.NewId(a.Rig.Clock)) { StopLevel = 1_900m }, _none)).Refusal); + await a.TurnsAsync(a.Manager, 1); + Assert.HasCount(1, (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Side == OrderSide.Buy).ToList()); + + // The broker repeats its fills, as brokers do. + a.Broker.DuplicateFills = true; + var (rig, manager) = await a.RestoreAsync(archive); + var report = await manager.RebuildAsync(_none); + Assert.IsTrue(report.FoundAnything); + Assert.IsEmpty(report.Unclear, string.Join(" | ", report.Unclear)); + Assert.IsEmpty((await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Side == OrderSide.Buy).ToList(), "The purchase nobody follows any more is canceled."); + await a.SameLedgerAsync(rig, "The rebuilt ledger is the one that was lost."); + Assert.AreEqual(58_500m, (await rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.StopPrice, + "A stop raised after the archive never goes back down."); + + // A second pass finds nothing, reconciliation agrees, and the stops on the account are exactly those needed. + var second = await manager.RebuildAsync(_none); + Assert.AreEqual((0, 0, false), (second.Orders, second.Fills, second.FoundAnything)); + var reconciled = await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(manager, _none); + Assert.IsEmpty(reconciled.Differences, string.Join(" | ", reconciled.Differences.Select(d => d.Message))); + await manager.AlignStopsAsync(_none); + await a.TurnsAsync(manager, 3); + var open = await a.Paper.GetOpenOrdersAsync(_none); + Assert.IsTrue(open.All(o => o.Kind == OrderKind.Stop), "Only stops."); + foreach (var position in (await rig.Ledger.PositionsAsync(a.Context.AccountId, _none)).Where(p => p.Quantity > 0m)) + { + var symbol = position.InstrumentId == a.Btc.Id ? a.Btc.Symbol : a.Eth.Symbol; + Assert.AreEqual(position.Quantity, open.Where(o => o.Symbol == symbol).Sum(o => o.Quantity), symbol); + } + + // A stop moved now takes a name of its own: the names used after the archive are gone from the ledger, not from the account. + await rig.Ledger.SetStopAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, 59_000m, _none); + await a.TurnsAsync(manager, 2); + var moved = (await a.Paper.GetOpenOrdersAsync(_none)).Single(o => o.Symbol == a.Btc.Symbol); + Assert.AreEqual(59_000m, moved.StopPrice); + Assert.DoesNotContain(moved.ClientOrderId, stops); + Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM journal WHERE code = 'ledger_rebuilt'", r => r.Text("message"))); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AStopThatFiredAfterTheArchiveClosesThePosition() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + a.Rig.Clock.Advance(TimeSpan.FromHours(2)); + a.Rig.Quote(a.Btc.Symbol, 56_500m, 56_510m); + await a.TurnsAsync(a.Manager, 3); + Assert.AreEqual(0m, (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity ?? 0m); + + var (rig, manager) = await a.RestoreAsync(archive); + await manager.RebuildAsync(_none); + await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(manager, _none); + Assert.AreEqual(0m, (await rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity ?? 0m); + await a.SameLedgerAsync(rig, "The sale made by the stop is in the rebuilt ledger."); + await a.TurnsAsync(manager, 2); + Assert.IsEmpty(await a.Paper.GetOpenOrdersAsync(_none), "Nothing is put back for a position that is gone."); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task OrdersOfAnotherInstallationAreNotTakenAndAnUpToDateLedgerFindsNothing() + { + await using var a = await Account.OpenAsync(); + var foreign = new[] + { + ClientOrderIds.Build("OTHR", TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Entry, "AAAAAAAA", 1), + ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Live, StrategyNames.CryptoTrend, OrderPurpose.Entry, "BBBBBBBB", 1), + "un-ordine-a-mano", + }; + foreach (var id in foreign) + { + await a.Paper.SubmitOrderAsync(new OrderRequest(id, a.Btc.Symbol, OrderSide.Buy, OrderKind.Limit, 0.001m, TimeInForce.Gtc) { LimitPrice = 50_000m }, _none); + } + + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + Assert.IsFalse((await a.Manager.RebuildAsync(_none)).FoundAnything); + Assert.HasCount(0, await a.Rig.QueryAsync("SELECT client_order_id FROM orders WHERE client_order_id IN (@a, @b, @c)", r => r.Text("client_order_id"), + ("a", foreign[0]), ("b", foreign[1]), ("c", foreign[2]))); + Assert.HasCount(3, (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => foreign.Contains(o.ClientOrderId)).ToList(), "Not ours, not touched."); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task ARestoreFromOneEngineToTheOtherRebuildsTheSame() + { + if (!await TestDb.PostgresAvailableAsync()) + { + Assert.Inconclusive("PostgreSQL per i test non raggiungibile: la prova tra motori gira in CI e con `tasks ci`."); + } + + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + await a.SellAsync(a.Btc, 0.003m); + var (rig, manager) = await a.RestoreAsync(archive, a.Rig.Db.Engine == DbEngine.Sqlite ? DbEngine.Postgres : DbEngine.Sqlite); + Assert.IsTrue((await manager.RebuildAsync(_none)).FoundAnything); + await a.SameLedgerAsync(rig, "The other engine gets the same ledger."); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AnOldCopyPutBackByHandIsRecognisedOnTheAccountAndStopsTheBot() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + await a.SellAsync(a.Btc, 0.003m); + + // A database dump put back with the fingerprint it had: nothing says it is old, except the account. + var rig = await a.Rig.RestoreAsync(archive); + a.Restored.Add(rig); + await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE installation SET protected_restart = @no", _none, ("no", false)), _none); + using var service = new TradingService(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32]), null, new FxStore(rig.Db, rig.Clock), + TradingConsent.None, new Guid("0193a7c0-0000-7000-8000-0000000000aa"), new FakeHttp()); + var manager = rig.Manager(a.Broker, a.Context); + await service.RebuildAsync(manager, _none); + + var settings = new SettingsStore(rig.Db, rig.Clock, new EventBus()); + Assert.AreEqual("stopped", (await settings.GetAsync(SettingsStore.BotState.Key)).Value); + Assert.IsTrue((await Installation.ReadRowAsync(rig.Db, _none))!.ProtectedRestart); + Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message"))); + await a.SameLedgerAsync(rig, "And the ledger is rebuilt all the same."); + + // Confirmed by the user, a start that finds nothing new leaves the bot as it is. + await settings.SetAsync(SettingsStore.BotState.Key, "active", "test"); + await Installation.ClearProtectedRestartAsync(rig.Db, _none); + await service.RebuildAsync(manager, _none); + Assert.AreEqual("active", (await settings.GetAsync(SettingsStore.BotState.Key)).Value); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AStopTheDatabaseDoesNotKnowIsAdoptedWithoutStoppingTheBot() + { + // The guard put a stop while the engine was off, and its note got lost. + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var own = (await a.Paper.GetOpenOrdersAsync(_none)).Single(); + await a.Paper.CancelOrderAsync(own.ClientOrderId, own.Symbol, _none); + var guard = ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Stop, "GGGGGGGG", 1); + await a.Paper.SubmitOrderAsync(new OrderRequest(guard, a.Btc.Symbol, OrderSide.Sell, OrderKind.Stop, own.Quantity, TimeInForce.Gtc) { StopPrice = 57_000m }, _none); + + var report = await a.Manager.RebuildAsync(_none); + Assert.AreEqual((1, false), (report.Orders, report.FoundAnything)); + await new Reconciler(a.Rig.Db, a.Rig.Clock, a.Rig.Ledger).ReconcileAsync(a.Manager, _none); + await a.Manager.AlignStopsAsync(_none); + await a.TurnsAsync(a.Manager, 2); + var open = await a.Paper.GetOpenOrdersAsync(_none); + Assert.AreEqual(own.Quantity, open.Sum(o => o.Quantity), "One stop, for the whole quantity."); + } +} diff --git a/tests/Anubis.Tests/RiskEngineTests.cs b/tests/Anubis.Tests/RiskEngineTests.cs index f9fcf75..782b204 100644 --- a/tests/Anubis.Tests/RiskEngineTests.cs +++ b/tests/Anubis.Tests/RiskEngineTests.cs @@ -480,6 +480,61 @@ public sealed class RiskEngineTests } } + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AfterARestoreRealMoneyWaitsForThePasswordOfTheUser() + { + await using var s = await CreateAsync(Consent()); + var live = await FakeRealAccountAsync(s); + await s.Rig.Ledger.RecordCapitalAsync(live.Account.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none); + await RequirementsMetAsync(s); + await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.Account.AccountId, + StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced), Password, null, "utente"), _none); + var before = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual("stage", (await Assert.ThrowsExactlyAsync(() => s.Stages.ReconfirmAsync(StrategyNames.CryptoTrend, Password, null, "utente", _none))).Code, + "nothing to confirm before a restore"); + s.Rig.Refresh(); + await live.Manager.SubmitAsync(Buy(s, 0.002m) with { StartAggressive = true }, _none); + await s.Rig.TurnsAsync(live.Manager, 3, _minute); + var planned = Ids.NewId(s.Rig.Clock); + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync( + "INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, reference_price, reason, due_at, valid_until, status, created_at, updated_at) " + + "VALUES (@id, @id, 'crypto_trend', @a, @i, 'buy', 'entry', 0.001, @no, 60000, 'trend_entry', @t, @t, 'pending', @t, @t)", _none, + ("id", planned), ("a", live.Account.AccountId), ("i", s.Btc.Id), ("no", false), ("t", s.Rig.Clock.UtcNow)), _none); + + await Installation.CheckAsync(s.Rig.Db, new DataDirectory(TempFolder.Create("reconfirm")), s.Rig.Clock, _none); + await Installation.ProtectAsync(s.Rig.Db, s.Rig.Clock, _none); + + // Stopped, exit only, with its counts untouched; what was planned does not leave; the stop stays. + Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value); + var waiting = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual((StrategyStages.Reduced, true, true, before.StageSince), (waiting.Stage, waiting.ExitOnly, waiting.WaitsForReconfirmation, waiting.StageSince)); + Assert.AreEqual("dropped/protected_restart", (await s.Rig.QueryAsync("SELECT status, outcome FROM planned_orders WHERE id = @id", + r => r.Text("status") + "/" + r.TextOrNull("outcome"), ("id", planned))).Single()); + Assert.HasCount(1, await s.Rig.QueryAsync("SELECT reason FROM strategy_stage_history WHERE reason = 'exit_only_after_restore'", r => r.Text("reason"))); + Assert.HasCount(1, await live.Paper.GetOpenOrdersAsync(_none), "the stop on the real account"); + + // The bot restarted: still no purchase with real money, while a sale goes; holding nothing does not free it. + await s.Risk.RestartAsync("utente", _none); + Assert.AreEqual(RiskReasons.ExitOnly, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal); + var held = (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity; + Assert.IsNull((await live.Manager.SubmitAsync(Sell(s, held) with { StartAggressive = true }, _none)).Refusal); + await s.Rig.TurnsAsync(live.Manager, 3, _minute); + Assert.AreEqual(0m, (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity ?? 0m); + await s.Stages.ReleaseExitOnlyAsync(s.Rig.Ledger, _none); + Assert.IsTrue((await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.WaitsForReconfirmation, "only the user takes it out"); + + Assert.AreEqual("password", (await Assert.ThrowsExactlyAsync(() => s.Stages.ReconfirmAsync(StrategyNames.CryptoTrend, "sbagliata", null, "utente", _none))).Code); + var closed = new StageBook(s.Rig.Db, s.Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(true)); + Assert.AreEqual(RiskReasons.NoConsent, (await Assert.ThrowsExactlyAsync(() => closed.ReconfirmAsync(StrategyNames.CryptoTrend, Password, null, "utente", _none))).Code); + await s.Stages.ReconfirmAsync(StrategyNames.CryptoTrend, Password, null, "utente", _none); + var back = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual((StrategyStages.Reduced, false, before.StageSince), (back.Stage, back.ExitOnly, back.StageSince)); + s.Rig.Refresh(); + Assert.IsNull((await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal); + Assert.HasCount(2, await s.Rig.QueryAsync("SELECT key FROM config_history WHERE key = @k", r => r.Text("key"), ("k", "strategy.crypto_trend.stage"))); + } + [TestMethod] [TestCategory(Category.Simulation)] public async Task ADemotedStrategyKeepsManagingItsRealPositionsDownToZero() diff --git a/tests/Anubis.Tests/StoresTests.cs b/tests/Anubis.Tests/StoresTests.cs index cef8229..92ef78a 100644 --- a/tests/Anubis.Tests/StoresTests.cs +++ b/tests/Anubis.Tests/StoresTests.cs @@ -27,12 +27,15 @@ public sealed class StoresTests Assert.IsTrue(File.Exists(data.InstallationFile)); Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict); - // Data folder lost: rewritten from the database. + // The file of the data folder is lost: nobody can tell this database from an old copy, so the engine does not start. + var before = Installation.ReadFile(data)!; File.Delete(data.InstallationFile); - Assert.AreEqual(IdentityVerdict.FileRestored, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict); + var missing = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false); + Assert.AreEqual(IdentityVerdict.MissingFile, missing.Verdict); + Assert.IsFalse(missing.CanStart); + Assert.IsFalse(File.Exists(data.InstallationFile)); // A stale copy of the database: same installation, older fingerprint. - var before = Installation.ReadFile(data)!; Installation.WriteFile(data, before with { Fingerprint = "newer" }); var stale = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false); Assert.AreEqual(IdentityVerdict.StaleDatabase, stale.Verdict); @@ -43,7 +46,7 @@ public sealed class StoresTests Assert.AreEqual(IdentityVerdict.DifferentInstallation, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict); // The user adopts this database: new fingerprint on both sides, protected restart on. - var renewed = await Installation.RenewAsync(test.Db, data, clock, adoptDatabaseIdentity: true).ConfigureAwait(false); + var renewed = await Installation.RenewAsync(test.Db, data, clock, "prova").ConfigureAwait(false); Assert.AreEqual(before.InstallationId, renewed.InstallationId); Assert.AreNotEqual(before.Fingerprint, renewed.Fingerprint); var row = await Installation.ReadRowAsync(test.Db).ConfigureAwait(false); @@ -124,10 +127,11 @@ public sealed class StoresTests Assert.IsTrue((await secrets.StatusAsync("OKX_API_KEY_DEMO").ConfigureAwait(false)).FromEnvironment); await Assert.ThrowsAsync(() => secrets.SetAsync("OKX_API_KEY_DEMO", "x-123456789", "admin")).ConfigureAwait(false); - // With another key the value cannot be read: the error says to enter it again. + // With another key the value cannot be read: whoever asks goes on without it, and the status says it must be entered again. var otherKey = new SecretStore(test.Db, clock, Enumerable.Repeat((byte)7, 32).ToArray()); - var error = await Assert.ThrowsAsync(() => otherKey.RevealAsync("ALPACA_API_SECRET_DEMO")).ConfigureAwait(false); - Assert.Contains("Reinserisci", error.Message); + Assert.IsNull(await otherKey.RevealAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)); + Assert.IsTrue((await otherKey.StatusAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)).Unreadable); + Assert.IsFalse((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)).Unreadable); // A value sealed under one name does not open under another. var sealedValue = secrets.Seal("A", "x"); diff --git a/tests/Anubis.Tests/TradingSupport.cs b/tests/Anubis.Tests/TradingSupport.cs index 9456b3a..06b9ae4 100644 --- a/tests/Anubis.Tests/TradingSupport.cs +++ b/tests/Anubis.Tests/TradingSupport.cs @@ -29,6 +29,26 @@ internal sealed class TradingRig : IAsyncDisposable Catalog = new InstrumentCatalog(test.Db, Clock); } + // The same market and the same clock on another database: the account goes on while the ledger went back (SPEC 15.1). + private TradingRig(TestDb test, TradingRig before) + { + Test = test; + Clock = before.Clock; + Ledger = new Ledger(test.Db, Clock); + Catalog = new InstrumentCatalog(test.Db, Clock); + _quotes = before._quotes; + _specs = before._specs; + _instruments = before._instruments; + } + + /// An archive of this rig loaded in a new database of (that of the run when null). + public async Task RestoreAsync(string archive, Anubis.Platform.DbEngine? engine = null) + { + var test = engine is { } e ? await TestDb.CreateAsync(e).ConfigureAwait(false) : await TestDb.CreateAsync().ConfigureAwait(false); + await Archive.ImportAsync(test.Db, archive, Clock).ConfigureAwait(false); + return new TradingRig(test, this); + } + public TestDb Test { get; } public Database Db => Test.Db; -- 2.54.1 From 4d92a39fef74f42b8dffa0c9648b37e672a0b264 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 1 Dec 2026 19:11:11 +0100 Subject: [PATCH 02/15] 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."); + } } -- 2.54.1 From 3cd214ae78d2035c80464919c474c08fb32a1960 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 1 Dec 2026 19:21:40 +0100 Subject: [PATCH 03/15] Publish the image on version tags and test what is delivered A v* tag now builds, tries and publishes the image: the version must be the one of Directory.Build.props, latest only moves forward and the registry token is in one step, given to docker on its input. The same script works by hand. The image says its version and commit, and its health check also covers the engine loop and the live prices. The Unraid template is final: a test compares it with appendix E and with the variables the loader really reads, and another reads the workflow. refs #70 refs #71 Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 48 ++- Directory.Build.props | 2 +- README.md | 4 +- deploy/docker/Dockerfile | 19 +- deploy/docker/publish.sh | 47 +++ deploy/unraid/anubis.xml | 2 +- docs/SVILUPPO.md | 8 +- src/Anubis.Server/Endpoints.cs | 33 +- src/Anubis.Server/SystemView.cs | 15 +- src/Anubis/Data/Collector.cs | 9 + src/Anubis/Data/MarketDataService.cs | 3 + src/Anubis/Platform/PlatformLoader.cs | 4 + src/Anubis/Trading/TradingService.cs | 4 + tests/Anubis.Tests/DeliveryTests.cs | 477 ++++++++++++++++++++++++++ tests/Anubis.Tests/MiniYaml.cs | 177 ++++++++++ tools/Anubis.Tasks/Program.cs | 34 +- 16 files changed, 859 insertions(+), 27 deletions(-) create mode 100644 deploy/docker/publish.sh create mode 100644 tests/Anubis.Tests/DeliveryTests.cs create mode 100644 tests/Anubis.Tests/MiniYaml.cs diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 1e7aa75..7671a18 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -1,10 +1,11 @@ # CI (SPEC 15.5, ADR 0003/0004): only run steps with git, dotnet and docker, no external actions. -# Publishing to the registry on v* tags arrives in phase 9 (issue #70). +# The image is published only on v* tags, after the tests and the drill (SPEC 15.5, ADR 0002 and 0020); never on fase-N. name: ci on: push: branches: ["**"] + tags: ["v*"] pull_request: jobs: @@ -44,10 +45,15 @@ jobs: TESTINGPLATFORM_TELEMETRY_OPTOUT: "1" steps: - name: Checkout + # The token goes to git through its environment, so it is on no command line. + env: + GIT_CONFIG_COUNT: "1" + GIT_CONFIG_KEY_0: http.extraHeader + GIT_CONFIG_VALUE_0: "Authorization: token ${{ github.token }}" run: | git init -q . git remote add origin "${{ github.server_url }}/${{ github.repository }}.git" - git -c http.extraHeader="Authorization: token ${{ github.token }}" fetch -q --depth 1 origin "${{ github.sha }}" + git fetch -q --depth 1 origin "${{ github.sha }}" git checkout -q FETCH_HEAD - name: Check run: sh ./tasks.sh check @@ -59,20 +65,42 @@ jobs: image: needs: test runs-on: ubuntu-latest - # Registry settings for phase 9 (issue #70): declared here, not used before then. env: - REGISTRY: gitea.encke-hake.ts.net - REGISTRY_USER: ${{ github.repository_owner }} - REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + # The Docker daemon of the runner is shared between runs: a name of this run only, so what is published is what was tried. + IMAGE: anubis:ci-${{ github.run_id }}-${{ github.run_attempt }} steps: - name: Checkout + # The token goes to git through its environment, so it is on no command line. + env: + GIT_CONFIG_COUNT: "1" + GIT_CONFIG_KEY_0: http.extraHeader + GIT_CONFIG_VALUE_0: "Authorization: token ${{ github.token }}" run: | git init -q . git remote add origin "${{ github.server_url }}/${{ github.repository }}.git" - git -c http.extraHeader="Authorization: token ${{ github.token }}" fetch -q --depth 1 origin "${{ github.sha }}" + git fetch -q --depth 1 origin "${{ github.sha }}" git checkout -q FETCH_HEAD - - name: Build image (no publish) - run: docker build -f deploy/docker/Dockerfile -t anubis:ci . + - name: Build image + env: + REF: ${{ github.ref }} + REF_NAME: ${{ github.ref_name }} + run: | + case "$REF" in refs/tags/v*) version=${REF_NAME#v} ;; *) version=dev ;; esac + docker build -f deploy/docker/Dockerfile --build-arg "ANUBIS_VERSION=$version" --build-arg "ANUBIS_COMMIT=$(git rev-parse HEAD)" -t "$IMAGE" . # The guard drill inside the image (issue #48): offline, its own SQLite database in a temporary folder. - name: Guard drill in the image - run: docker run --rm anubis:ci drill + run: docker run --rm "$IMAGE" drill + - name: Publish image + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + env: + REGISTRY: ${{ vars.REGISTRY || 'gitea.encke-hake.ts.net' }} + REGISTRY_USER: ${{ vars.REGISTRY_USER || github.actor }} + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + TAG: ${{ github.ref_name }} + GIT_CONFIG_COUNT: "1" + GIT_CONFIG_KEY_0: http.extraHeader + GIT_CONFIG_VALUE_0: "Authorization: token ${{ github.token }}" + run: sh ./deploy/docker/publish.sh "$IMAGE" "$TAG" + - name: Remove the image of this run + if: always() + run: docker image rm -f "$IMAGE" || true diff --git a/Directory.Build.props b/Directory.Build.props index 8bd1fc2..0d197c7 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -13,7 +13,7 @@ it;en BalboSoft Anubis - 0.7.0 + 0.9.0 diff --git a/README.md b/README.md index 8e78e1c..12fbe5c 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Database a scelta: PostgreSQL oppure SQLite. Scritto in C# su .NET 10, con inter Nell'antico Egitto Anubis, il dio con la testa di sciacallo, pesava il cuore dei defunti contro la piuma di Maat, la verità e l'equilibrio, e custodiva le tombe. Il bot fa lo stesso con i soldi: **pesa** ogni operazione contro il rischio prima di farla e **protegge** il capitale. Il logo è quella bilancia, con il cuore e la piuma in equilibrio (ADR 0005). -> Stato: **progettazione completata, sviluppo non ancora iniziato.** Il piano è nelle [milestone](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestones) del repository. +> Stato: **in simulazione, pronto da installare in Docker.** Il piano è nelle [milestone](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestones) del repository. ![Panoramica](docs/design/01-panoramica.jpg) @@ -29,7 +29,7 @@ Nell'antico Egitto Anubis, il dio con la testa di sciacallo, pesava il cuore dei | [docs/SVILUPPO.md](docs/SVILUPPO.md) | Come si lavora: flusso su Gitea, regole, prove | | [docs/adr/](docs/adr/) | Decisioni prese: nome (0001), Gitea (0002), linguaggio C# (0003), componenti esterni (0004), logo (0005) | | [docs/design/](docs/design/) | Schermate di riferimento e logo | -| [deploy/unraid/anubis.xml](deploy/unraid/anubis.xml) | Template Docker per Unraid (bozza) | +| [deploy/unraid/anubis.xml](deploy/unraid/anubis.xml) | Template Docker per Unraid | ## Schermate di riferimento diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index 6c2f15d..511c295 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -17,9 +17,11 @@ COPY docs/design/logo/ docs/design/logo/ # The backtest outcomes are read at the first start (SPEC 12.3); .dockerignore lets only their JSON files through. COPY docs/backtests/ docs/backtests/ COPY docs/learning/ docs/learning/ -RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app +# The commit goes into the version shown by the diagnostics report; empty when not given. +ARG ANUBIS_COMMIT= +RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app ${ANUBIS_COMMIT:+-p:SourceRevisionId=$ANUBIS_COMMIT} # The guard (SPEC 9.3, ADR 0012) is the main process and starts the engine next to it, from the same folder. -RUN dotnet publish src/Anubis.Guard/Anubis.Guard.csproj -c Release --no-restore -o /app +RUN dotnet publish src/Anubis.Guard/Anubis.Guard.csproj -c Release --no-restore -o /app ${ANUBIS_COMMIT:+-p:SourceRevisionId=$ANUBIS_COMMIT} FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app @@ -35,7 +37,16 @@ EXPOSE 8787 VOLUME /data # Starts as root only to give /data to PUID:PGID, then runs the guard as that user (entrypoint.sh); the guard starts # the engine. "docker run --rm drill" runs the guard drill instead (issue #48). -# Health through bash's /dev/tcp: no curl or wget in the image. 503 (database down) counts as unhealthy. -HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \ +# Health through bash's /dev/tcp: no curl or wget in the image. 503 (database down, loops stopped, no prices) counts as unhealthy. +HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ CMD ["bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/${PORT:-8787} && printf 'GET /health HTTP/1.0\r\nHost: localhost\r\n\r\n' >&3 && head -n 1 <&3 | grep -q ' 200 '"] ENTRYPOINT ["anubis-entrypoint"] +ARG ANUBIS_VERSION=dev +ARG ANUBIS_COMMIT= +LABEL org.opencontainers.image.title="Anubis" \ + org.opencontainers.image.description="Bot di trading personale: azioni USA e crypto spot, senza leva" \ + org.opencontainers.image.vendor="BalboSoft" \ + org.opencontainers.image.url="https://gitea.encke-hake.ts.net/BalboSoft/Anubis" \ + org.opencontainers.image.source="https://gitea.encke-hake.ts.net/BalboSoft/Anubis" \ + org.opencontainers.image.version="$ANUBIS_VERSION" \ + org.opencontainers.image.revision="$ANUBIS_COMMIT" diff --git a/deploy/docker/publish.sh b/deploy/docker/publish.sh new file mode 100644 index 0000000..1b67eb7 --- /dev/null +++ b/deploy/docker/publish.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# Publishes an image already built and tried (SPEC 15.5, ADR 0002 and 0020). +# Usage: publish.sh +# From the environment: REGISTRY, REGISTRY_USER, REGISTRY_TOKEN (write:package). The token reaches docker only on its +# input and stays in a temporary folder removed at the end. +set -eu + +image="$1" +tag="$2" +root=$(cd "$(dirname "$0")/../.." && pwd) +fail() { + echo "Pubblicazione non riuscita: $1" >&2 + exit 1 +} + +printf '%s\n' "$tag" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$' || fail "il tag '$tag' non è una versione (vX.Y.Z)." +version=${tag#v} +expected=$(sed -n 's:.*\(.*\).*:\1:p' "$root/Directory.Build.props") +[ "${version%%-*}" = "$expected" ] || fail "il tag $tag non corrisponde alla versione $expected di Directory.Build.props." +[ -n "${REGISTRY:-}" ] || fail "manca REGISTRY." +[ -n "${REGISTRY_USER:-}" ] || fail "manca REGISTRY_USER." +[ -n "${REGISTRY_TOKEN:-}" ] || fail "manca il segreto REGISTRY_TOKEN (token Gitea con il permesso write:package)." +name="$REGISTRY/balbosoft/anubis" + +# latest moves only for the highest plain version among the tags of the repository. +latest="" +case "$version" in + *-*) ;; + *) + tags=$(git -C "$root" ls-remote --tags --refs origin 'v*') || fail "non riesco a leggere i tag del repository." + newest=$(printf '%s\n' "$tags" "x refs/tags/$tag" | sed -n 's:.*refs/tags/v\([0-9]*\.[0-9]*\.[0-9]*\)$:\1:p' | sort -t. -k1,1n -k2,2n -k3,3n | tail -n 1) + if [ "$newest" = "$version" ]; then latest=1; fi + ;; +esac + +DOCKER_CONFIG=$(mktemp -d) +export DOCKER_CONFIG +trap 'rm -rf "$DOCKER_CONFIG"' EXIT +printf '%s' "$REGISTRY_TOKEN" | docker login "$REGISTRY" --username "$REGISTRY_USER" --password-stdin +docker tag "$image" "$name:$version" +docker push "$name:$version" +if [ -n "$latest" ]; then + docker tag "$image" "$name:latest" + docker push "$name:latest" +fi + +echo "Pubblicata $name:$version${latest:+ (e latest)}." diff --git a/deploy/unraid/anubis.xml b/deploy/unraid/anubis.xml index c078524..9515c12 100644 --- a/deploy/unraid/anubis.xml +++ b/deploy/unraid/anubis.xml @@ -1,6 +1,6 @@