From 2d59c4e94d47424208f83c7b2c27900063d6a1c7 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Thu, 1 Oct 2026 15:59:15 +0200 Subject: [PATCH] =?UTF-8?q?5.1=20revisione,=20segreti=20e=20web:=20un=20fi?= =?UTF-8?q?le=205.0=20Live+demo=20resta=20sul=20conto=20demo,=20password?= =?UTF-8?q?=20errate=20pagate=20anche=20via=20Bearer=20e=20cookie,=20richi?= =?UTF-8?q?este=20da=20altri=20siti=20rifiutate,=20--sample=20senza=20file?= =?UTF-8?q?=20n=C3=A9=20segreti=20dell'operatore,=20rete=20solo=20nel=20co?= =?UTF-8?q?ntainer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Quando etoro.environment esce dal file (salvataggio dalle Impostazioni o importazione) viene scritta la modalità che il file intendeva: un Live (o LiveAuto/LiveApprove) accanto a "demo" era letto Demo ma diventava Live al primo salvataggio qualsiasi, scavalcando la guardia del cambio di conto, il controllo delle chiavi e la frase. La verifica sulla copia usa esattamente ciò che verrà scritto, letto con l'overlay vero. - Una password errata via Bearer o cookie (derivato dalla password, quindi anch'esso un tentativo) costa come al login, con un'attesa per indirizzo condivisa da tutte le porte d'ingresso: 1, 2, 4... fino a 30 s. Nel frattempo nessuna password di quell'indirizzo viene controllata (429), così i tentativi in parallelo non servono più; gli altri indirizzi non aspettano. - Sotto /api/ POST e DELETE solo con Content-Type application/json (415 altrimenti); 403 per Sec-Fetch-Site di un'altra origine o per un Origin estraneo (login e logout solo l'Origin); senza password 403 a ogni Host diverso da localhost, contro il DNS rebinding. - --sample lavora in cartelle temporanee cancellate all'uscita: non legge né scrive configurazione, segreti e dati dell'operatore e non apre il suo bot Telegram (un secondo poller rubava i comandi); le Impostazioni mostrano i valori di fabbrica e ogni scrittura risponde 400. - Il server ascolta sulla rete solo nel container o con --listen-all: F5 e run-dev tengono la password per i segreti della sandbox ma restano su localhost. - Il tick porta statusLines (righe della striscia di attività, 20-2000): il valore veniva salvato e mai letto. Non è più legato a bufferedLines. - L'importazione segue l'ordine della 5.0: chiavi dell'ambiente, poi quelle del file, poi etoro.keys.enc. - Un numero di iterazioni PBKDF2 fuori da 100 000-10 000 000 nell'intestazione di secrets.enc è un file danneggiato, bloccato senza derivare la chiave (prima: minuti di avvio fermo). - /api/learning: strategy.json entra nell'impronta dell'ETag e ogni salvataggio di un campo strategy: fa avanzare la versione, così a motore fermo la pagina non resta sui vecchi interruttori. - run-docker non stampa più la password: dice da dove viene. Co-Authored-By: Claude Opus 5.5 --- Encelado/.vscode/launch.json | 7 +- Encelado/docs/API.md | 29 +- Encelado/scripts/run-dev.ps1 | 10 +- Encelado/scripts/run-dev.sh | 8 +- Encelado/scripts/run-docker.ps1 | 6 +- Encelado/scripts/run-docker.sh | 10 +- .../Baskets/LearningDiskReader.cs | 20 +- .../Encelado.Engine/Configuration/AppPaths.cs | 22 +- .../Configuration/BotConfig.cs | 12 +- .../Configuration/ConfigLoader.cs | 39 ++- .../Configuration/EnvironmentImport.cs | 27 +- .../Configuration/SecretStore.cs | 21 +- .../Encelado.Engine/Engine/BotSupervisor.cs | 17 -- .../Encelado.Engine/Engine/SampleReadModel.cs | 10 +- .../Settings/SettingsCatalogue.cs | 6 +- .../Settings/SettingsRuntime.cs | 45 ++- .../Settings/SettingsService.cs | 29 +- Encelado/src/Encelado.Server/Program.cs | 68 ++++- Encelado/src/Encelado.Server/SampleFolders.cs | 96 ++++++ .../src/Encelado.Server/Web/AuthBackoff.cs | 143 +++++++++ .../src/Encelado.Server/Web/SettingsApi.cs | 93 +++++- .../src/Encelado.Server/Web/TickWriter.cs | 3 + Encelado/src/Encelado.Server/Web/WebHost.cs | 214 +++++++++++-- Encelado/tests/Encelado.Tests/ApiV2Tests.cs | 126 +++++++- .../Encelado.Tests/EnvironmentImportTests.cs | 67 ++++ .../Encelado.Tests/LearningReportTests.cs | 54 ++++ .../tests/Encelado.Tests/SecretStoreTests.cs | 38 +++ .../Encelado.Tests/SettingsRuntimeTests.cs | 81 +++++ Encelado/tests/Encelado.Tests/WebTests.cs | 288 +++++++++++++++++- 29 files changed, 1461 insertions(+), 128 deletions(-) create mode 100644 Encelado/src/Encelado.Server/SampleFolders.cs create mode 100644 Encelado/src/Encelado.Server/Web/AuthBackoff.cs diff --git a/Encelado/.vscode/launch.json b/Encelado/.vscode/launch.json index c1ea929..d20c5c3 100644 --- a/Encelado/.vscode/launch.json +++ b/Encelado/.vscode/launch.json @@ -4,9 +4,12 @@ // stesse cartelle che il compose monta come /config e /data). Il browser si apre da // solo appena Kestrel è in ascolto. La password dell'interfaccia è "sviluppo", la // stessa del compose: i segreti cifrati della sandbox (chiavi eToro, token Telegram, - // inseriti da Impostazioni) restano leggibili sia da F5 sia dal container. + // inseriti da Impostazioni) restano leggibili sia da F5 sia dal container. La password + // serve ai segreti, non apre la rete: fuori dal container il server ascolta solo su + // localhost (per la rete servirebbe l'argomento --listen-all). // "Encelado (campione)" serve l'interfaccia con dati finti, senza chiavi né mercato e - // senza password: è quello che si usa per lavorare sulle pagine. + // senza password, in cartelle temporanee: non legge né scrive Documenti\Encelado o la + // sandbox, non tocca segreti né Telegram. È quello che si usa per lavorare sulle pagine. "version": "0.2.0", "configurations": [ { diff --git a/Encelado/docs/API.md b/Encelado/docs/API.md index b197564..b6335ef 100644 --- a/Encelado/docs/API.md +++ b/Encelado/docs/API.md @@ -10,8 +10,10 @@ Aggiornato: 2026-10-01. È il contratto fra il server (`src/Encelado.Server/Web` - Numeri non finiti (NaN, ∞) → `null`. Un valore sconosciuto è `null`, mai `0`. - Testi per l'operatore (motivazioni, intenti, messaggi) in italiano. - Le risposte dei comandi e delle scritture hanno sempre `{ "ok": bool, "message": string }` più i campi propri. -- Autenticazione: se il container ha `ENCELADO_PASSWORD` (alias deprecato `ENCELADO_WEB_TOKEN`) ogni rotta chiede il cookie `encelado_session` o `Authorization: Bearer `; senza sessione le rotte `/api/*` rispondono **401**, le pagine rimandano a `/login`. Libere: `/login`, `/api/health`, `/css/*`, `/img/*`, `/icon.svg`, `/manifest.webmanifest`. Senza password il server ascolta solo su localhost e non chiede niente. -- `--sample`: ogni rotta risponde con dati d'esempio realistici e coerenti fra loro (nessuna chiave, nessun mercato), per lavorare sulle pagine e fotografarle. +- Autenticazione: se il container ha `ENCELADO_PASSWORD` (alias deprecato `ENCELADO_WEB_TOKEN`) ogni rotta chiede il cookie `encelado_session` o `Authorization: Bearer `; senza sessione le rotte `/api/*` rispondono **401**, le pagine rimandano a `/login`. Libere: `/login`, `/api/health`, `/css/*`, `/img/*`, `/icon.svg`, `/manifest.webmanifest`. Una password errata — dal form, dall'header Bearer o dal cookie (derivato dalla password, quindi anch'esso un tentativo) — costa al suo indirizzo un'attesa che raddoppia fino a 30 s (vedi [Accesso](#accesso)). +- Rete: il server ascolta su tutte le interfacce solo con una password **e** nel container (o con l'argomento `--listen-all`); fuori dal container (F5, `run-dev`) resta su localhost anche con la password, che lì serve ai segreti della sandbox. Senza password ascolta solo su localhost e non chiede niente. +- Richieste da altrove: vedi [Richieste che cambiano qualcosa](#richieste-che-cambiano-qualcosa) (`Content-Type: application/json`, `Origin`, `Sec-Fetch-Site`, Host senza password). +- `--sample`: ogni rotta risponde con dati d'esempio realistici e coerenti fra loro (nessuna chiave, nessun mercato), per lavorare sulle pagine e fotografarle. Il server campione lavora in cartelle temporanee (cancellate all'uscita): non legge né scrive la configurazione, i segreti o i dati dell'operatore e non apre il bot Telegram. Le impostazioni sono quelle di fabbrica e ogni scrittura (comandi, impostazioni, segreti) risponde **400** «modalità dimostrativa (--sample)». ## File statici @@ -22,8 +24,21 @@ L'interfaccia (docs/UI_GUIDELINES.md): `index.html` carica `/css/tokens.css`, `/ ## Accesso - `GET /login` — la pagina. -- `POST /login` — form `password` (accettato anche `token`, il nome della 5.0). Corretta: cookie `encelado_session` (HttpOnly, SameSite=Strict, 30 giorni) e **302** su `/`. Il cookie è un HMAC derivato dalla password, mai la password: cambiarla invalida le sessioni. Errata: dopo un secondo di attesa, **401** con la pagina di login e il messaggio (`Where the learning files of a data folder are. -public sealed record LearningPaths(string DataDir, string KnowledgeDir) +/// +/// Where the learning files of a data folder are, and the strategy.json a stopped engine's page +/// takes its switches, pMin and baskets from (empty: none, the stamp leaves it out). +/// +public sealed record LearningPaths(string DataDir, string KnowledgeDir, string StrategyFile = "") { public string ModelsDir => Path.Combine(DataDir, "models"); @@ -20,7 +23,7 @@ public sealed record LearningPaths(string DataDir, string KnowledgeDir) public static LearningPaths From(BotConfig config) { ArgumentNullException.ThrowIfNull(config); - return new LearningPaths(config.Run.DataPath, config.Run.KnowledgePath); + return new LearningPaths(config.Run.DataPath, config.Run.KnowledgePath, config.Run.StrategyPath); } } @@ -48,17 +51,22 @@ public static class LearningDiskReader // Stamps // ----------------------------------------------------------------------- - /// A fingerprint of every file the page reads (models, knowledge, the ledger's basket rows and decision files): the disk half of the ETag. Recomputed at most every two seconds. + /// + /// A fingerprint of every file the page reads (models, knowledge, the ledger's basket rows and decision + /// files, and strategy.json, whose switches a stopped engine's page shows): the disk half of the + /// ETag. Recomputed at most every two seconds. + /// public static string Stamp(LearningPaths p, DateTime nowUtc) { ArgumentNullException.ThrowIfNull(p); - string key = p.DataDir + "|" + p.KnowledgeDir; + string key = p.DataDir + "|" + p.KnowledgeDir + "|" + p.StrategyFile; if (Stamps.TryGetValue(key, out (DateTime At, string Stamp) s) && nowUtc - s.At < TimeSpan.FromSeconds(2) && nowUtc >= s.At) { return s.Stamp; } - string stamp = StampOf([.. Files(p.ModelsDir, "*.json"), .. Files(p.KnowledgeDir, "*"), Path.Combine(p.LedgerDir, "baskets.csv"), .. Ledger.DecisionFiles(p.LedgerDir)]); + string[] strategy = p.StrategyFile.Length > 0 ? [p.StrategyFile] : []; + string stamp = StampOf([.. Files(p.ModelsDir, "*.json"), .. Files(p.KnowledgeDir, "*"), Path.Combine(p.LedgerDir, "baskets.csv"), .. Ledger.DecisionFiles(p.LedgerDir), .. strategy]); Stamps[key] = (nowUtc, stamp); return stamp; } diff --git a/Encelado/src/Encelado.Engine/Configuration/AppPaths.cs b/Encelado/src/Encelado.Engine/Configuration/AppPaths.cs index fb3db77..58666ef 100644 --- a/Encelado/src/Encelado.Engine/Configuration/AppPaths.cs +++ b/Encelado/src/Encelado.Engine/Configuration/AppPaths.cs @@ -33,15 +33,35 @@ public static class AppPaths /// What happened at first run, for the log; null when the files already existed. public static string? SeedNote { get; private set; } + /// Folders the process chose itself, winning over the variables and the container (). + private static (string Config, string Data)? _chosen; + /// True when the process runs inside the container (the config volume is mounted). public static bool InContainer => Environment.GetEnvironmentVariable("ENCELADO_IN_CONTAINER") is "1" or "true" || (!OperatingSystem.IsWindows() && Directory.Exists(ContainerConfigDirectory)); + /// + /// The configuration and data folders the process uses instead of the operator's, before + /// : --sample works on a throwaway pair, so it never reads or writes the + /// operator's configuration, secrets or data (5.1 review). + /// + public static void UseFolders(string configDirectory, string dataDirectory) + { + ArgumentException.ThrowIfNullOrWhiteSpace(configDirectory); + ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory); + _chosen = (configDirectory, dataDirectory); + } + public static string ConfigDirectory { get { + if (_chosen is { } chosen) + { + return chosen.Config; + } + string? custom = Environment.GetEnvironmentVariable("ENCELADO_CONFIG_DIR"); if (!string.IsNullOrWhiteSpace(custom)) { @@ -67,7 +87,7 @@ public static class AppPaths // A data folder separate from the configuration folder: /data in the container, // ENCELADO_DATA_DIR anywhere (the local sandbox in deploy/local mirrors the // container's layout, so F5 and docker compose write the same tree). - string? dataDir = Environment.GetEnvironmentVariable("ENCELADO_DATA_DIR"); + string? dataDir = _chosen?.Data ?? Environment.GetEnvironmentVariable("ENCELADO_DATA_DIR"); bool separateData = !string.IsNullOrWhiteSpace(dataDir) || (InContainer && string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ENCELADO_CONFIG_DIR"))); if (separateData) diff --git a/Encelado/src/Encelado.Engine/Configuration/BotConfig.cs b/Encelado/src/Encelado.Engine/Configuration/BotConfig.cs index 3d4f4fb..a2461dc 100644 --- a/Encelado/src/Encelado.Engine/Configuration/BotConfig.cs +++ b/Encelado/src/Encelado.Engine/Configuration/BotConfig.cs @@ -296,7 +296,10 @@ public sealed class LoggingOptions /// How many rotated application logs to keep. public int MaxFiles { get; set; } = 10; - /// Lines kept in the activity strip of the dashboard. + /// The most lines the dashboard's activity strip can show: the browser keeps the last 2000 log lines. The settings page offers up to this and the tick never says more. + public const int MaxStripLines = 2_000; + + /// Lines kept in the activity strip of the dashboard (the tick's statusLines). public int StatusLines { get; set; } = 200; /// Lines kept by the log page: the memory ceiling for the in-app log. The file on disk stays complete. @@ -332,14 +335,11 @@ public sealed class LoggingOptions throw new InvalidOperationException("logging.statusLines deve essere fra 20 e 5000."); } + // The Log page's window and the dashboard's strip are independent (5.1 review): a window smaller + // than the strip only means the strip fills as new lines arrive after the page is opened. if (BufferedLines is < 100 or > 200_000) { throw new InvalidOperationException("logging.bufferedLines deve essere fra 100 e 200000."); } - - if (BufferedLines < StatusLines) - { - throw new InvalidOperationException("logging.bufferedLines deve essere >= logging.statusLines."); - } } } diff --git a/Encelado/src/Encelado.Engine/Configuration/ConfigLoader.cs b/Encelado/src/Encelado.Engine/Configuration/ConfigLoader.cs index ce01f8b..fada089 100644 --- a/Encelado/src/Encelado.Engine/Configuration/ConfigLoader.cs +++ b/Encelado/src/Encelado.Engine/Configuration/ConfigLoader.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Text.Json; +using System.Text.Json.Nodes; using Encelado.Core.Baskets; namespace Encelado.Engine.Configuration; @@ -57,7 +58,14 @@ public static class ConfigLoader "notifications.telegram.botToken", ]; - public static BotConfig Load(string path, out List warnings) + /// The configuration file. + /// What the files said that is not a setting any more, or not at all. + /// + /// The overlay to apply; encelado.local.json beside when null. The + /// settings page checks a save on a copy in the temp folder with the real overlay, so the copy loads + /// as the bot will after the save. + /// + public static BotConfig Load(string path, out List warnings, string? overlayPath = null) { warnings = []; BotConfig config = new(); @@ -85,7 +93,7 @@ public static class ConfigLoader } // A sibling *.local.json overlays machine-specific overrides. - string localPath = LocalPath(path); + string localPath = overlayPath ?? LocalPath(path); if (File.Exists(localPath)) { using FileStream stream = File.OpenRead(localPath); @@ -107,6 +115,33 @@ public static class ConfigLoader /// The overlay beside a configuration file: encelado.local.json. public static string LocalPath(string path) => Path.ChangeExtension(path, null) + ".local.json"; + /// + /// Adds to a write of the removal of the the file + /// still holds. When etoro.environment is one of them and the write does not set the mode + /// itself, the mode the files mean now (the merge of decision C6) is written with it: a 5.0 + /// Live (or 4.0 LiveAuto/LiveApprove) beside demo trades the demo + /// account, while the bare Live left behind would read as the real one and switch account + /// past every guard of the settings page (5.1 review). Every writer of the file goes through here: + /// the settings page — for its check on a copy as well as for the file — and the import. + /// + public static void RemoveObsoleteKeys(string path, IDictionary changes, ICollection deletions) + { + ArgumentNullException.ThrowIfNull(changes); + ArgumentNullException.ThrowIfNull(deletions); + foreach (string key in ObsoleteKeys.Where(k => ConfigWriter.Contains(path, k))) + { + if (!deletions.Contains(key)) + { + deletions.Add(key); + } + } + + if (deletions.Contains("etoro.environment") && !changes.ContainsKey("run.executionMode")) + { + changes["run.executionMode"] = JsonValue.Create(Load(path, out _).Run.Mode.ToString()); + } + } + /// /// The secrets a file of 5.0 may carry (the main file or the overlay; the overlay /// wins): read only by the one-time import, which moves them to the encrypted store. diff --git a/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs b/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs index 864d317..3089d2b 100644 --- a/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs +++ b/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs @@ -21,16 +21,18 @@ public sealed record ImportOutcome(bool Ran, bool Deferred, IReadOnlyList -/// secrets go into the encrypted store, only into empty slots and only when the store is open: -/// ETORO_API_KEY/ETORO_USER_KEY into the account the old mode/environment pair -/// meant (the merge rule), the old etoro.keys.enc (with ENCELADO_KEY_PASSPHRASE) -/// for both accounts — then renamed .migrato —, TELEGRAM_BOT_TOKEN, and the keys a -/// 5.0 file may carry; +/// secrets go into the encrypted store, only into empty slots and only when the store is open, +/// in 5.0's order of precedence: ETORO_API_KEY/ETORO_USER_KEY into the account the old +/// mode/environment pair meant (the merge rule), then the keys a 5.0 file may carry, then the old +/// etoro.keys.enc (with ENCELADO_KEY_PASSPHRASE) for both accounts — then renamed +/// .migrato —; and TELEGRAM_BOT_TOKEN; /// settings go into encelado.json only when the variable differs from the factory /// default and the file still holds the factory default (a template default such as /// USD or Demo is not an intent): TELEGRAM_CHAT_ID (when the chat id is empty), /// ENCELADO_DISPLAY_CURRENCY, ENCELADO_LOG_LEVEL, -/// ENCELADO_EXECUTION_MODE+ETORO_ENVIRONMENT, ENCELADO_AUTOSTART=0; +/// ENCELADO_EXECUTION_MODE+ETORO_ENVIRONMENT, ENCELADO_AUTOSTART=0; a write +/// removes the obsolete keys and writes the mode the file meant in place of etoro.environment +/// (); /// TZ and ENCELADO_CONFIRM_LIVE are never imported. /// /// It runs once: <config>/import-5.1.json records what it did (a locked store @@ -100,7 +102,9 @@ public static class EnvironmentImport } else { - ImportLegacyKeyFile(directory, store, Env(KeyStores.PassphraseVariable), imported, notes); + // In 5.0's order of precedence (5.1 review): the keys of the environment, then those written + // in the file, then the old etoro.keys.enc — each only into a slot still empty, so the keys + // 5.0 was trading with are the ones kept. // The keys of the environment belong to the account 5.0 used them on. bool envDemo = !MergedMode(envMode ?? fileModeRaw, envEnvironment ?? fileEnvironmentRaw, out _).IsLive(); @@ -129,6 +133,8 @@ public static class EnvironmentImport } } + ImportLegacyKeyFile(directory, store, Env(KeyStores.PassphraseVariable), imported, notes); + string? telegram = Env("TELEGRAM_BOT_TOKEN") ?? (fileSecrets.TelegramToken.Length > 0 ? fileSecrets.TelegramToken : null); if (telegram is not null) { @@ -225,8 +231,11 @@ public static class EnvironmentImport if (changes.Count > 0 || secretDeletions.Count > 0) { - List deletions = [.. secretDeletions, .. ConfigLoader.ObsoleteKeys.Where(k => ConfigWriter.Contains(configPath, k))]; - ConfigWriter.Apply(configPath, Settings.SettingsService.WithDocumentation(configPath, ConfigDefaults.Json, changes), deletions); + // With the obsolete keys goes etoro.environment, and the mode the file meant is written in its place. + Dictionary write = Settings.SettingsService.WithDocumentation(configPath, ConfigDefaults.Json, changes); + List deletions = [.. secretDeletions]; + ConfigLoader.RemoveObsoleteKeys(configPath, write, deletions); + ConfigWriter.Apply(configPath, write, deletions); configChanged = true; } } diff --git a/Encelado/src/Encelado.Engine/Configuration/SecretStore.cs b/Encelado/src/Encelado.Engine/Configuration/SecretStore.cs index 7f85461..09839dc 100644 --- a/Encelado/src/Encelado.Engine/Configuration/SecretStore.cs +++ b/Encelado/src/Encelado.Engine/Configuration/SecretStore.cs @@ -48,7 +48,9 @@ public sealed record SecretInfo(bool Present, string Masked, DateTime? SavedUtc) /// /// Layout: ENC2 | key source (1 password, 2 local key) | PBKDF2 iterations (int32, /// little endian) | salt 16 | nonce 12 | tag 16 | ciphertext. The header is authenticated -/// with the ciphertext. Writes are atomic and the file is readable by its owner only. +/// with the ciphertext; an iteration count outside - +/// is a damaged file, locked before any key is derived. Writes are atomic and the file is +/// readable by its owner only. /// A changed password leaves the store : the web /// login still works (it uses the variable), and the settings page offers to unlock with /// the previous password or to start again with an empty store (the old file stays as a @@ -63,6 +65,12 @@ public sealed class SecretStore public const int DefaultIterations = 600_000; + /// The fewest PBKDF2 iterations a store of the default cost accepts in a file's header (a store built with fewer, as the tests do, accepts its own). + public const int MinIterations = 100_000; + + /// The most PBKDF2 iterations a header may claim: past this the file is damaged, not slow. + public const int MaxIterations = 10_000_000; + private static readonly byte[] Magic = "ENC2"u8.ToArray(); private const byte SourcePassword = 1; private const byte SourceLocalKey = 2; @@ -502,7 +510,16 @@ public sealed class SecretStore source = raw[4]; iterations = BinaryPrimitives.ReadInt32LittleEndian(raw.AsSpan(5, 4)); salt = raw.AsSpan(9, SaltSize).ToArray(); - return source is SourcePassword or SourceLocalKey && (source == SourceLocalKey || iterations > 0); + + // The count is used before AES-GCM can prove the header genuine: one that this store could not + // have written (a flipped bit can claim a billion rounds, minutes of PBKDF2 before the web host is + // up and again at every unlock) is a damaged file, never a derivation (5.1 review). + return source switch + { + SourceLocalKey => true, + SourcePassword => iterations >= Math.Min(MinIterations, _iterations) && iterations <= MaxIterations, + _ => false, + }; } private static bool TryDecrypt(byte[] raw, byte[] key, out Payload payload) diff --git a/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs b/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs index 1f53218..6617284 100644 --- a/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs +++ b/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs @@ -51,7 +51,6 @@ public sealed class BotSupervisor : IAsyncDisposable private readonly BotConfig _config; private readonly Func _factory; - private int _eventCapacity; private IEngine? _engine; private CancellationTokenSource? _engineCts; private Task? _engineTask; @@ -95,7 +94,6 @@ public sealed class BotSupervisor : IAsyncDisposable _config = config ?? throw new ArgumentNullException(nameof(config)); Versions = versions ?? new SectionVersions(); _factory = factory ?? ((c, confirmed) => new BasketEngine(c, null, confirmed, null, notifier, Versions)); - _eventCapacity = Math.Max(20, config.Logging.StatusLines); _offline.Changed = () => Versions.Bump(Section.Learning); } @@ -134,12 +132,6 @@ public sealed class BotSupervisor : IAsyncDisposable /// The section versions of the process: the supervisor bumps them all when an engine starts or stops (the source of every page changes). public SectionVersions Versions { get; } - /// The lines the dashboard's activity strip keeps (logging.statusLines): a hint for the interface. - public int EventCapacity - { - get { lock (_gate) { return _eventCapacity; } } - } - /// The secret store's state and the ignored variables, merged into every snapshot (set by the host). public Func? HostStatusProvider { get; set; } @@ -165,15 +157,6 @@ public sealed class BotSupervisor : IAsyncDisposable public void DetachLogSink() => Log.Sink = null; - /// How many lines the activity strip keeps (logging.statusLines, applied at once). - public void SetEventCapacity(int capacity) - { - lock (_gate) - { - _eventCapacity = Math.Max(20, capacity); - } - } - // ----------------------------------------------------------------------- // Lifecycle // ----------------------------------------------------------------------- diff --git a/Encelado/src/Encelado.Engine/Engine/SampleReadModel.cs b/Encelado/src/Encelado.Engine/Engine/SampleReadModel.cs index 429b658..60cb039 100644 --- a/Encelado/src/Encelado.Engine/Engine/SampleReadModel.cs +++ b/Encelado/src/Encelado.Engine/Engine/SampleReadModel.cs @@ -11,9 +11,10 @@ namespace Encelado.Engine; /// basket, one entry waiting for its leg, two refused signals, an orphan and two foreign /// positions, a week of calendar, headlines, sentiment, quotas and a Telegram channel — no /// keys, no market. Numbers drift a little every second and the clock moves, so the pages -/// can be developed and photographed as they will look. The baskets follow the strategy file -/// (a basket switched off in Impostazioni shows as disabled), everything else is -/// 's scenario anchored at . +/// can be developed and photographed as they will look. The baskets follow the strategy it +/// is given — the factory one in --sample, which reads and writes no file of the +/// operator (5.1 review) —, everything else is 's scenario anchored +/// at . /// public sealed class SampleReadModel : IBotReadModel { @@ -98,5 +99,8 @@ public sealed class SampleReadModel : IBotReadModel private static readonly Lazy Factory = new(static () => BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _)); + /// The factory strategy, parsed once and shared (read only): the sample's own. + public static BasketStrategyConfig FactoryStrategy => Factory.Value; + private static BasketStrategyConfig DefaultStrategy() => Factory.Value; } diff --git a/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs b/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs index 7b0a0e8..bca1a29 100644 --- a/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs +++ b/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs @@ -508,10 +508,10 @@ public static class SettingsCatalogue "Superata questa dimensione il file viene ruotato: encelado.1.log, encelado.2.log e così via.")); g.Fields.Add(Integer("logging.maxFiles", "File di log conservati", config.Logging.MaxFiles, "file ruotati", 1, 500, SettingScope.Immediate, "Quanti file ruotati tenere prima di cancellare il più vecchio.")); - g.Fields.Add(Integer("logging.statusLines", "Righe di attività in dashboard", config.Logging.StatusLines, "righe", 20, 5000, SettingScope.Immediate, - "Quante righe tiene la striscia di attività della dashboard.")); + g.Fields.Add(Integer("logging.statusLines", "Righe di attività in dashboard", config.Logging.StatusLines, "righe", 20, LoggingOptions.MaxStripLines, SettingScope.Immediate, + "Quante righe tiene la striscia di attività della dashboard (al più 2000, quante ne tiene il browser). Vale subito, anche nelle pagine già aperte.")); g.Fields.Add(Integer("logging.bufferedLines", "Righe tenute in memoria", config.Logging.BufferedLines, "righe", 100, 200_000, SettingScope.Immediate, - "Quante righe tiene la pagina Log (almeno quante quelle della dashboard). Il file su disco resta completo comunque.")); + "Quante righe tiene la pagina Log, ed è anche quante la dashboard ne può recuperare quando la apri; il resto della striscia si riempie con le righe nuove. Il file su disco resta completo comunque.")); return g; } diff --git a/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs b/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs index 243d2d5..a059254 100644 --- a/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs +++ b/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs @@ -148,20 +148,40 @@ public sealed class SettingsRuntime { BotConfig file = ConfigFromFileOrMemory(); IReadOnlyList groups = SettingsCatalogue.Build(file, Strategy.Current()); + return Describe(ConfigPath, Strategy.Path, Version, Supervisor.State, Config.Run.Mode.Account(), Supervisor.IsRunning, groups, DescribeSecrets()); + } + + /// What every write of the settings and the secrets answers in --sample: nothing is saved, nothing is proved on eToro or Telegram. + public const string SampleRefusal = "modalità dimostrativa (--sample): le impostazioni e i segreti non vengono salvati"; + + /// + /// The answer of GET /api/settings for --sample (5.1 review): the factory configuration and + /// strategy — the sample server reads and writes none of the operator's files — with the sample's engine + /// and secrets, the ones the other pages show. The two paths say where the values come from instead. + /// + public static string DescribeSample(SecretsSummary secrets, BotState state, string account, long version) + { + ArgumentNullException.ThrowIfNull(secrets); + IReadOnlyList groups = SettingsCatalogue.Build(ConfigDefaults.Parse(), BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _)); + return Describe("campione (--sample): valori di fabbrica", "niente viene salvato", version, state, account, state is BotState.Running or BotState.Starting, groups, secrets); + } + + private static string Describe(string configPath, string strategyPath, long version, BotState state, string account, bool running, IReadOnlyList groups, SecretsSummary secrets) + { using MemoryStream ms = new(); using (Utf8JsonWriter w = new(ms)) { w.WriteStartObject(); - w.WriteString("configPath", ConfigPath); - w.WriteString("strategyPath", Strategy.Path); - w.WriteNumber("version", Version); + w.WriteString("configPath", configPath); + w.WriteString("strategyPath", strategyPath); + w.WriteNumber("version", version); w.WriteStartObject("engine"); - w.WriteString("state", Supervisor.State.ToString().ToLowerInvariant()); - w.WriteString("account", Config.Run.Mode.Account()); - w.WriteBoolean("running", Supervisor.IsRunning); + w.WriteString("state", state.ToString().ToLowerInvariant()); + w.WriteString("account", account); + w.WriteBoolean("running", running); w.WriteEndObject(); SettingsService.WriteGroups(w, groups); - SettingsService.WriteSecrets(w, "secrets", DescribeSecrets()); + SettingsService.WriteSecrets(w, "secrets", secrets); w.WriteEndObject(); } @@ -305,7 +325,7 @@ public sealed class SettingsRuntime saved = guarded ? FilesBefore.Read(ConfigPath, Strategy.Path) : FilesBefore.None; SettingsService.Write(ConfigPath, Strategy.Path, plan); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or JsonException) { return Failure($"salvataggio non riuscito: {ex.Message}"); } @@ -519,8 +539,15 @@ public sealed class SettingsRuntime Strategy.Invalidate(); Changed(); + + // The learning page of a stopped engine shows strategy.json's switches, pMin and baskets: + // it reads again now rather than at its next poll (5.1 review). + if (changedPaths.Any(static p => p.StartsWith(SettingField.StrategyPrefix, StringComparison.OrdinalIgnoreCase))) + { + Supervisor.Versions.Bump(Section.Learning); + } + _hooks.ReconfigureProcess?.Invoke(Config); - Supervisor.SetEventCapacity(Config.Logging.StatusLines); if (changedPaths.Any(static p => p.StartsWith("notifications.", StringComparison.OrdinalIgnoreCase))) { await ReconfigureNotifierAsync().ConfigureAwait(false); diff --git a/Encelado/src/Encelado.Engine/Settings/SettingsService.cs b/Encelado/src/Encelado.Engine/Settings/SettingsService.cs index e6c0dda..5f035ff 100644 --- a/Encelado/src/Encelado.Engine/Settings/SettingsService.cs +++ b/Encelado/src/Encelado.Engine/Settings/SettingsService.cs @@ -98,7 +98,13 @@ public static class SettingsService BasketStrategyConfig? strategy = null; try { - config = OnCopy(configPath, plan.ConfigChanges, plan.ConfigDeletions, static p => ConfigLoader.Load(p, out _).Validate(), plan.TouchesConfig); + // Exactly what Write will write, read with the real overlay: the copy is the configuration + // the bot holds after the save, so the account guards see the real outcome (5.1 review). + (Dictionary changes, List deletions) = plan.TouchesConfig + ? ConfigWrite(configPath, plan) + : (new Dictionary(StringComparer.Ordinal), new List()); + string overlay = ConfigLoader.LocalPath(configPath); + config = OnCopy(configPath, changes, deletions, p => ConfigLoader.Load(p, out _, overlay).Validate(), plan.TouchesConfig); } catch (Exception ex) when (ex is InvalidOperationException or IOException or ArgumentException or UnauthorizedAccessException or JsonException) { @@ -164,18 +170,33 @@ public static class SettingsService if (plan.TouchesConfig) { - List deletions = [.. plan.ConfigDeletions, .. ConfigLoader.ObsoleteKeys.Where(k => ConfigWriter.Contains(configPath, k))]; try { - ConfigWriter.Apply(configPath, WithDocumentation(configPath, ConfigDefaults.Json, plan.ConfigChanges), deletions); + (Dictionary changes, List deletions) = ConfigWrite(configPath, plan); + ConfigWriter.Apply(configPath, changes, deletions); } - catch (Exception ex) when (plan.TouchesStrategy && ex is IOException or UnauthorizedAccessException or InvalidOperationException) + catch (Exception ex) when (plan.TouchesStrategy && ex is IOException or UnauthorizedAccessException or InvalidOperationException or JsonException) { throw new IOException($"strategy.json salvato, encelado.json NO: {ex.Message}", ex); } } } + /// + /// What a save writes to encelado.json, worked out once for the check on the copy and for the + /// file: the batch, the documentation lines an older version wrote, the keys of 5.0 that no longer + /// exist and — when etoro.environment leaves — the mode the file meant + /// (). + /// + public static (Dictionary Changes, List Deletions) ConfigWrite(string configPath, SettingsPlan plan) + { + ArgumentNullException.ThrowIfNull(plan); + Dictionary changes = WithDocumentation(configPath, ConfigDefaults.Json, plan.ConfigChanges); + List deletions = [.. plan.ConfigDeletions]; + ConfigLoader.RemoveObsoleteKeys(configPath, changes, deletions); + return (changes, deletions); + } + /// The edits plus the documentation lines of the file that an older version wrote (). public static Dictionary WithDocumentation(string path, string factoryJson, IReadOnlyDictionary changes) { diff --git a/Encelado/src/Encelado.Server/Program.cs b/Encelado/src/Encelado.Server/Program.cs index eedf45c..ca68deb 100644 --- a/Encelado/src/Encelado.Server/Program.cs +++ b/Encelado/src/Encelado.Server/Program.cs @@ -22,12 +22,13 @@ namespace Encelado.Server; /// engine's lock. /// /// Arguments: --health (probe the running server and exit 0/1), --sample -/// (serve a sample snapshot, no market), --no-autostart, --bonifica, -/// --minutes N, --port N. Environment: ENCELADO_PASSWORD (the only -/// setting a container needs; ENCELADO_WEB_TOKEN is its deprecated alias) and the -/// image's own ENCELADO_WEB_PORT, ENCELADO_CONFIG_DIR, ENCELADO_DATA_DIR. -/// Everything else is set from the interface (5.1); Live never starts without a person -/// typing the phrase there. +/// (serve sample data, no market, on throwaway folders: none of the operator's files, secrets or +/// Telegram bot is touched), --no-autostart, --bonifica, --minutes N, +/// --port N, --listen-all (with a password, the network outside the container too). +/// Environment: ENCELADO_PASSWORD (the only setting a container needs; +/// ENCELADO_WEB_TOKEN is its deprecated alias) and the image's own ENCELADO_WEB_PORT, +/// ENCELADO_CONFIG_DIR, ENCELADO_DATA_DIR. Everything else is set from the +/// interface (5.1); Live never starts without a person typing the phrase there. /// /// public static class Program @@ -41,6 +42,25 @@ public static class Program InterfacePassword password = InterfacePassword.Resolve(Environment.GetEnvironmentVariable); + // --sample works on a throwaway pair of folders (5.1 review): it never reads or writes the + // operator's configuration, secrets or data, so it never opens the real Telegram bot either. + bool sample = Has(args, "--sample"); + string? sampleRoot = null; + if (sample) + { + try + { + sampleRoot = SampleFolders.Create(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Console.Error.WriteLine($"Impossibile creare le cartelle temporanee del campione: {ex.Message}"); + return 2; + } + + AppPaths.UseFolders(SampleFolders.ConfigOf(sampleRoot), SampleFolders.DataOf(sampleRoot)); + } + BotConfig config; try { @@ -76,7 +96,11 @@ public static class Program Log.Warn($"password dell'interfaccia: {warning}"); } - bool sample = Has(args, "--sample"); + if (sampleRoot is not null) + { + Log.Info($"modalità dimostrativa (--sample): configurazione e dati in una cartella temporanea ({sampleRoot}), cancellata all'uscita; le tue impostazioni, i segreti e i dati non vengono letti né scritti"); + } + bool bonifica = Has(args, "--bonifica"); int minutes = IntArg(args, "--minutes"); int port = IntArg(args, "--port") is > 0 and var p ? p : WebHost.Port; @@ -138,13 +162,17 @@ public static class Program ContextRefresher? idleRefresher = context is null ? null : new ContextRefresher(context); - await using NotifierHub hub = new(config.Notifications.Telegram, () => secrets.TelegramToken, static m => Log.Info(m)); + // The sample never builds a Telegram channel: no token, no command poller taking another bot's updates. + await using NotifierHub hub = new(config.Notifications.Telegram, sample ? static () => string.Empty : () => secrets.TelegramToken, static m => Log.Info(m)); await using BotSupervisor supervisor = new(config, (c, confirmed) => new BasketEngine(c, secrets.Etoro(demo: !c.Run.Mode.IsLive()), confirmed, context, hub, versions) { OrphanPolicy = bonifica ? OrphanPolicy.Report : OrphanPolicy.Close }, hub, versions); - hub.CommandHandler = new TelegramCommands(supervisor, () => hub.Status).HandleAsync; - await hub.ReconfigureAsync().ConfigureAwait(false); + if (!sample) + { + hub.CommandHandler = new TelegramCommands(supervisor, () => hub.Status).HandleAsync; + await hub.ReconfigureAsync().ConfigureAwait(false); + } supervisor.EventLogged += buffer.Add; supervisor.AttachLogSink(); @@ -158,14 +186,14 @@ public static class Program buffer.Resize(c.Logging.BufferedLines); UiClock.Zone = c.Ui.ResolveTimeZone(out _); }, - ReconfigureNotifier = hub.ReconfigureAsync, + ReconfigureNotifier = sample ? null : hub.ReconfigureAsync, InvalidateHistory = () => { history.Invalidate(); versions.Bump(Section.History); versions.Bump(Section.Positions); }, - SendTelegramTest = hub.SendTestAsync, + SendTelegramTest = sample ? null : hub.SendTestAsync, }) { Import = import, @@ -188,7 +216,10 @@ public static class Program Telegram = hub.Describe, }; - WebApplication web = WebHost.Build(ctx, port, password.Value, listenAll: password.IsSet); + // The network only in the container, or when asked (5.1 review): F5 and run-dev set the password + // for the sandbox's secrets, not to open the computer to the network. + bool listenAll = WebHost.ListensOnTheNetwork(password.IsSet, AppPaths.InContainer, Has(args, WebHost.ListenAllFlag)); + WebApplication web = WebHost.Build(ctx, port, password.Value, listenAll); try { await web.StartAsync().ConfigureAwait(false); @@ -200,9 +231,11 @@ public static class Program } // "in ascolto su " is what VS Code's serverReadyAction waits for to open the browser. - Log.Info(password.IsSet + Log.Info(listenAll ? $"interfaccia web in ascolto su http://localhost:{port}/ (anche dalla rete, password da {password.Source})" - : $"interfaccia web in ascolto su http://localhost:{port}/ (solo localhost: senza {InterfacePassword.Variable} il server non ascolta fuori dal computer e non chiede la password)"); + : password.IsSet + ? $"interfaccia web in ascolto su http://localhost:{port}/ (solo localhost, password da {password.Source}: fuori dal container la rete si apre solo con {WebHost.ListenAllFlag})" + : $"interfaccia web in ascolto su http://localhost:{port}/ (solo localhost: senza {InterfacePassword.Variable} il server non ascolta fuori dal computer e non chiede la password)"); using CancellationTokenSource stopping = new(); Console.CancelKeyPress += (_, e) => @@ -309,6 +342,11 @@ public static class Program await Log.FlushAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); await Log.ShutdownAsync().ConfigureAwait(false); + if (sampleRoot is not null) + { + SampleFolders.Delete(sampleRoot); + } + return 0; } diff --git a/Encelado/src/Encelado.Server/SampleFolders.cs b/Encelado/src/Encelado.Server/SampleFolders.cs new file mode 100644 index 0000000..3053294 --- /dev/null +++ b/Encelado/src/Encelado.Server/SampleFolders.cs @@ -0,0 +1,96 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; + +namespace Encelado.Server; + +/// +/// The throwaway folders of --sample (5.1 review): a fresh configuration and data pair under +/// the temp folder, so the sample server never reads or writes the operator's files — not +/// encelado.json, not the secrets (so never the Telegram token: no second poller takes the +/// real bot's commands), not the data. The pair goes when the server stops; the ones a killed +/// sample server left behind go at the next sample start. +/// +internal static class SampleFolders +{ + public const string Prefix = "encelado-campione-"; + + /// Creates a pair under (the temp folder when null), after removing the leftovers of sample servers that no longer run; returns its root. + public static string Create(string? tempRoot = null) + { + string temp = tempRoot ?? Path.GetTempPath(); + RemoveLeftovers(temp); + string root = Path.Combine(temp, string.Create(CultureInfo.InvariantCulture, $"{Prefix}{Environment.ProcessId}-{Guid.NewGuid():N}")); + Directory.CreateDirectory(ConfigOf(root)); + Directory.CreateDirectory(DataOf(root)); + return root; + } + + public static string ConfigOf(string root) => Path.Combine(root, "config"); + + public static string DataOf(string root) => Path.Combine(root, "data"); + + /// Deletes a pair; one still held (the log file on Windows) is left for the next sample start. + public static void Delete(string root) + { + try + { + Directory.Delete(root, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Removed at the next sample start. + } + } + + /// Removes the pairs whose sample server (the process number in the name) no longer runs. + internal static void RemoveLeftovers(string temp) + { + List folders; + try + { + folders = [.. Directory.EnumerateDirectories(temp, Prefix + "*")]; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return; + } + + foreach (string folder in folders) + { + string name = Path.GetFileName(folder); + int dash = name.IndexOf('-', Prefix.Length); + if (dash > Prefix.Length + && int.TryParse(name.AsSpan(Prefix.Length, dash - Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out int pid) + && Running(pid)) + { + continue; + } + + Delete(folder); + } + } + + private static bool Running(int pid) + { + if (pid == Environment.ProcessId) + { + return true; + } + + try + { + using Process process = Process.GetProcessById(pid); + return !process.HasExited; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + { + return false; + } + catch (Win32Exception) + { + // Someone else's process: not ours to judge, the folder stays. + return true; + } + } +} diff --git a/Encelado/src/Encelado.Server/Web/AuthBackoff.cs b/Encelado/src/Encelado.Server/Web/AuthBackoff.cs new file mode 100644 index 0000000..760c81a --- /dev/null +++ b/Encelado/src/Encelado.Server/Web/AuthBackoff.cs @@ -0,0 +1,143 @@ +using System.Net; +using System.Net.Sockets; + +namespace Encelado.Server.Web; + +/// What a presented password got from . +internal enum AuthVerdict +{ + /// Right: the request goes on and the address's count is cleared. + Ok = 0, + + /// Wrong: counted; the answer waits retryAfter, and so does every password of the address. + Wrong, + + /// Not checked at all: the address is still waiting after a wrong one. + Blocked, +} + +/// +/// The price of a wrong password (5.1 review), the same for every way one arrives: the login form, the +/// Authorization: Bearer header and the session cookie — the cookie is derived from the password +/// with nothing secret beside it, so it can be computed for every guess and is a guess too. +/// +/// Per client address (an IPv6 client by its /64, which one host can fill with addresses at will): after +/// a wrong password the address waits one second, then two, four, eight, sixteen, at most thirty for each +/// wrong one in a row. The wrong answer itself comes only when the wait is over, so a person typing gets +/// "Password errata." and simply tries again; meanwhile no password of that address is even checked — a +/// right one included, or a lucky guess sent in parallel with many wrong ones would stand out — and those +/// requests get 429 with Retry-After. Checking and recording happen under one lock, so parallel +/// guesses get one check per wait. A right password clears the count; ten quiet minutes forget it. +/// Another address is never slowed: a guesser on the network cannot lock the operator out of the +/// kill-switch from their own computer (only behind a proxy that hides every address behind its own). +/// +/// +internal sealed class AuthBackoff(TimeProvider? time = null) +{ + /// The longest wait after a wrong password. + public static readonly TimeSpan Longest = TimeSpan.FromSeconds(30); + + /// After this long without a wrong password the address starts again from one second. + public static readonly TimeSpan Forget = TimeSpan.FromMinutes(10); + + /// Addresses remembered at most; the ones forgotten (or the oldest) make room. + private const int MaxClients = 4_096; + + private readonly TimeProvider _time = time ?? TimeProvider.System; + private readonly Lock _gate = new(); + private readonly Dictionary _clients = new(StringComparer.Ordinal); + + private sealed class Entry + { + public int Failures { get; set; } + + public DateTime LastFailureUtc { get; set; } + + public DateTime WaitUntilUtc { get; set; } + } + + /// The wait after the -th wrong password in a row: 1, 2, 4, 8, 16, then 30 s. + public static TimeSpan Wait(int failures) => + TimeSpan.FromSeconds(Math.Min(Longest.TotalSeconds, WebHost.FailedLoginDelay.TotalSeconds * Math.Pow(2, Math.Clamp(failures, 1, 16) - 1))); + + /// + /// Checks one presented password of with — unless the + /// address is still waiting, and then is not called. + /// is how long the address waits from now (zero when right). + /// + public AuthVerdict Check(string client, Func proof, out TimeSpan retryAfter) + { + ArgumentNullException.ThrowIfNull(client); + ArgumentNullException.ThrowIfNull(proof); + DateTime now = _time.GetUtcNow().UtcDateTime; + lock (_gate) + { + _clients.TryGetValue(client, out Entry? entry); + if (entry is not null && now < entry.WaitUntilUtc) + { + retryAfter = entry.WaitUntilUtc - now; + return AuthVerdict.Blocked; + } + + if (proof()) + { + _clients.Remove(client); + retryAfter = TimeSpan.Zero; + return AuthVerdict.Ok; + } + + if (entry is null || now - entry.LastFailureUtc >= Forget) + { + MakeRoom(now); + entry = new Entry(); + _clients[client] = entry; + } + + entry.Failures++; + entry.LastFailureUtc = now; + retryAfter = Wait(entry.Failures); + entry.WaitUntilUtc = now + retryAfter; + return AuthVerdict.Wrong; + } + } + + /// The key of a client: its IPv4 address (an IPv4 mapped into IPv6 included), the /64 of an IPv6 one, ? when unknown. + public static string ClientKey(IPAddress? address) + { + if (address is null) + { + return "?"; + } + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (address.AddressFamily != AddressFamily.InterNetworkV6) + { + return address.ToString(); + } + + byte[] bytes = address.GetAddressBytes(); + return Convert.ToHexString(bytes, 0, 8).ToLowerInvariant() + "::/64"; + } + + private void MakeRoom(DateTime now) + { + if (_clients.Count < MaxClients) + { + return; + } + + foreach (string forgotten in _clients.Where(c => now - c.Value.LastFailureUtc >= Forget && now >= c.Value.WaitUntilUtc).Select(static c => c.Key).ToList()) + { + _clients.Remove(forgotten); + } + + if (_clients.Count >= MaxClients) + { + _clients.Remove(_clients.MinBy(static c => c.Value.LastFailureUtc).Key); + } + } +} diff --git a/Encelado/src/Encelado.Server/Web/SettingsApi.cs b/Encelado/src/Encelado.Server/Web/SettingsApi.cs index 6c3c9b7..beacc11 100644 --- a/Encelado/src/Encelado.Server/Web/SettingsApi.cs +++ b/Encelado/src/Encelado.Server/Web/SettingsApi.cs @@ -1,5 +1,7 @@ using System.Text; using System.Text.Json; +using Encelado.Core.Baskets; +using Encelado.Engine; using Encelado.Engine.Settings; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; @@ -11,17 +13,32 @@ namespace Encelado.Server.Web; /// the batch of edits applied by the running bot, the secrets of both eToro accounts and of /// Telegram, the secret store's unlock and reset, the restore of the factory file. Every /// decision is 's; this is the HTTP skin around it. +/// +/// In --sample (5.1 review) the page is sample data — the factory values, the sample's +/// secrets — and every write answers 400 «modalità dimostrativa», like the commands: the sample +/// server never reads or writes the operator's configuration or secrets, and never asks eToro or +/// Telegram anything. +/// /// internal static class SettingsApi { public static void Map(WebApplication app, WebContext ctx) { - app.MapGet("/api/settings", async http => await WriteAsync(http, 200, ctx.Settings.Describe()).ConfigureAwait(false)); + app.MapGet("/api/settings", async http => await WriteAsync(http, 200, ctx.Sample ? SampleDescription(ctx) : ctx.Settings.Describe()).ConfigureAwait(false)); app.MapPost("/api/settings", async http => { - (Dictionary edits, string? confirm) = await ReadEditsAsync(http).ConfigureAwait(false); - SettingsResult r = await ctx.Settings.ApplyAsync(edits, confirm, http.RequestAborted).ConfigureAwait(false); + SettingsResult r; + if (ctx.Sample) + { + r = new SettingsResult(false, SettingsRuntime.SampleRefusal, [], SettingsResult.RestartNone, new Dictionary()); + } + else + { + (Dictionary edits, string? confirm) = await ReadEditsAsync(http).ConfigureAwait(false); + r = await ctx.Settings.ApplyAsync(edits, confirm, http.RequestAborted).ConfigureAwait(false); + } + await WriteAsync(http, r.HttpStatus, Json.Object(w => { w.WriteBoolean("ok", r.Ok); @@ -50,39 +67,99 @@ internal static class SettingsApi })).ConfigureAwait(false); }); + // In --sample every secret route answers the sample's refusal before it reads a body or asks anyone. app.MapPost("/api/settings/keys", async http => { + if (await SampleRefusedAsync(http, ctx).ConfigureAwait(false)) + { + return; + } + Dictionary body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); await SecretAsync(http, ctx, await ctx.Settings.SaveKeysAsync( body.GetValueOrDefault("account"), body.GetValueOrDefault("apiKey"), body.GetValueOrDefault("userKey"), body.GetValueOrDefault("confirm"), http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); }); app.MapDelete("/api/settings/keys", async http => - await SecretAsync(http, ctx, await ctx.Settings.DeleteKeysAsync(http.Request.Query["account"], http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false)); + { + if (!await SampleRefusedAsync(http, ctx).ConfigureAwait(false)) + { + await SecretAsync(http, ctx, await ctx.Settings.DeleteKeysAsync(http.Request.Query["account"], http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); + } + }); app.MapPost("/api/settings/telegram-token", async http => { + if (await SampleRefusedAsync(http, ctx).ConfigureAwait(false)) + { + return; + } + Dictionary body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); await SecretAsync(http, ctx, await ctx.Settings.SaveTelegramTokenAsync(body.GetValueOrDefault("token"), http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); }); app.MapDelete("/api/settings/telegram-token", async http => - await SecretAsync(http, ctx, await ctx.Settings.DeleteTelegramTokenAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false)); + { + if (!await SampleRefusedAsync(http, ctx).ConfigureAwait(false)) + { + await SecretAsync(http, ctx, await ctx.Settings.DeleteTelegramTokenAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); + } + }); app.MapPost("/api/settings/telegram-test", async http => - await SecretAsync(http, ctx, await ctx.Settings.TelegramTestAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false)); + { + if (!await SampleRefusedAsync(http, ctx).ConfigureAwait(false)) + { + await SecretAsync(http, ctx, await ctx.Settings.TelegramTestAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); + } + }); app.MapPost("/api/settings/secrets/unlock", async http => { + if (await SampleRefusedAsync(http, ctx).ConfigureAwait(false)) + { + return; + } + Dictionary body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); await SecretAsync(http, ctx, await ctx.Settings.UnlockAsync(body.GetValueOrDefault("previous"), http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); }); app.MapPost("/api/settings/secrets/reset", async http => - await SecretAsync(http, ctx, await ctx.Settings.ResetSecretsAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false)); + { + if (!await SampleRefusedAsync(http, ctx).ConfigureAwait(false)) + { + await SecretAsync(http, ctx, await ctx.Settings.ResetSecretsAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); + } + }); app.MapPost("/api/settings/restore", async http => - await SecretAsync(http, ctx, await ctx.Settings.RestoreAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false)); + { + if (!await SampleRefusedAsync(http, ctx).ConfigureAwait(false)) + { + await SecretAsync(http, ctx, await ctx.Settings.RestoreAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); + } + }); + } + + /// The settings page of --sample: the factory values with the sample's engine and secrets (no file is read). + private static string SampleDescription(WebContext ctx) + { + EngineStatus status = ctx.Read.Engine(); + return SettingsRuntime.DescribeSample(ctx.Read.Secrets(), status.State, status.Live?.Account ?? ctx.Config.Run.Mode.Account(), ctx.Settings.Version); + } + + /// In --sample: answers the refusal (400) and says so; otherwise does nothing. + private static async Task SampleRefusedAsync(HttpContext http, WebContext ctx) + { + if (!ctx.Sample) + { + return false; + } + + await SecretAsync(http, ctx, new SecretActionResult(false, SettingsRuntime.SampleRefusal, HttpStatus: 400)).ConfigureAwait(false); + return true; } private static Task SecretAsync(HttpContext http, WebContext ctx, SecretActionResult r) => diff --git a/Encelado/src/Encelado.Server/Web/TickWriter.cs b/Encelado/src/Encelado.Server/Web/TickWriter.cs index 7f04dec..d642f2e 100644 --- a/Encelado/src/Encelado.Server/Web/TickWriter.cs +++ b/Encelado/src/Encelado.Server/Web/TickWriter.cs @@ -69,6 +69,9 @@ internal sealed class TickWriter(WebContext ctx, Func sseClients) w.WriteString("displayCurrency", ctx.Config.Ui.DisplayCurrency); w.WriteString("theme", ctx.Config.Ui.Theme); w.WriteBoolean("navExpanded", ctx.Config.Ui.NavExpanded); + + // The dashboard strip's length (logging.statusLines, applied at once), within what the browser keeps. + w.WriteNumber("statusLines", Math.Clamp(ctx.Config.Logging.StatusLines, 20, LoggingOptions.MaxStripLines)); WriteFx(w, v ?? status.LastView, now); WriteBaskets(w, v, strategy, thresholds, now); WriteQuotes(w, v, now); diff --git a/Encelado/src/Encelado.Server/Web/WebHost.cs b/Encelado/src/Encelado.Server/Web/WebHost.cs index 988328b..e17b60c 100644 --- a/Encelado/src/Encelado.Server/Web/WebHost.cs +++ b/Encelado/src/Encelado.Server/Web/WebHost.cs @@ -62,7 +62,7 @@ public sealed class WebContext /// A read model given by the caller (the tests); otherwise built from the members above. public IBotReadModel? ReadModel { get; init; } - /// Where every endpoint reads from: published pictures only (the sample's with --sample). + /// Where every endpoint reads from: published pictures only (the sample's with --sample, on the factory strategy). public IBotReadModel Read { get @@ -71,14 +71,14 @@ public sealed class WebContext { return _read ??= ReadModel ?? (Sample - ? new SampleReadModel(Settings.Strategy.Current, StartedUtc) + ? new SampleReadModel(null, StartedUtc) : new LiveReadModel(Supervisor, Context, Telegram, Settings.DescribeSecrets)); } } } - /// strategy.json as the file says now (cached by time and size). - public BasketStrategyConfig Strategy() => Settings.Strategy.Current(); + /// strategy.json as the file says now (cached by time and size); the factory strategy in --sample, which reads no file of the operator. + public BasketStrategyConfig Strategy() => Sample ? SampleReadModel.FactoryStrategy : Settings.Strategy.Current(); /// The stream's hub (set by ). internal SnapshotHub? Hub { get; set; } @@ -92,9 +92,16 @@ public sealed class WebContext /// container's only variable) is asked once on the login page; the browser then carries /// the session cookie encelado_session — an HMAC derived from the password, never /// the password itself, so changing the password closes every session. Scripts may send -/// Authorization: Bearer <password>. Every comparison is constant-time and a -/// wrong password costs a second. Without a password the server listens on localhost only -/// and asks for nothing (development). +/// Authorization: Bearer <password>. Every comparison is constant-time, and a +/// wrong password — by the form, the header or the cookie — costs its address a wait that +/// doubles up to thirty seconds (, 5.1 review). The network sees the +/// interface only in the container or with --listen-all, and only with a password; +/// without one the server is on localhost and asks for nothing (development). +/// +/// +/// Requests from elsewhere (5.1 review, ): a write must be JSON and come +/// from this very origin, or it is refused before anything reads it; without a password only a +/// Host naming this computer is answered, so a page that rebinds its name to 127.0.0.1 gets nothing. /// /// /// Load (5.1, decisions E1-E4): one tick per second built once for every client by the @@ -110,14 +117,24 @@ public static class WebHost public const string CookieName = "encelado_session"; public const int DefaultPort = 8080; - /// What a wrong password costs, so guessing it over the network is slow. + /// What the first wrong password costs its address; each one after it in a row doubles it, up to . public static readonly TimeSpan FailedLoginDelay = TimeSpan.FromSeconds(1); + /// The flag that opens the interface to the network outside the container (with a password only). + public const string ListenAllFlag = "--listen-all"; + /// The placeholder the login page may carry: a wrong password replaces it with the message. public const string LoginErrorPlaceholder = ""; public static int Port => int.TryParse(Environment.GetEnvironmentVariable(PortVariable), NumberStyles.Integer, CultureInfo.InvariantCulture, out int p) && p is > 0 and < 65536 ? p : DefaultPort; + /// + /// Whether the server listens on every interface (5.1 review): only with a password, and only in the + /// container or with . F5 and the run-dev scripts set the password to keep + /// the sandbox's secrets readable, not to open the computer to the network: they stay on localhost. + /// + public static bool ListensOnTheNetwork(bool passwordSet, bool inContainer, bool listenAllFlag) => passwordSet && (inContainer || listenAllFlag); + /// /// The session cookie's value for a password: Base64Url(HMAC-SHA256(key = SHA-256("encelado/cookie/v1" ‖ password), "session")). /// @@ -175,8 +192,10 @@ public static class WebHost SampleLogFeeder.Start(ctx.Log, sample, app.Lifetime.ApplicationStopping); } - app.Use(Auth(password)); - MapLogin(app, password); + AuthBackoff backoff = new(); + app.Use(RequestGuard(hasPassword: password.Length > 0)); + app.Use(Auth(password, backoff)); + MapLogin(app, password, backoff); MapApi(app, ctx, hub); SettingsApi.Map(app, ctx); MapStatic(app); @@ -193,7 +212,13 @@ public static class WebHost path.StartsWith("/css/", StringComparison.Ordinal) || path.StartsWith("/img/", StringComparison.Ordinal); - private static Func Auth(string password) + /// + /// The session cookie or the Bearer password, checked through the address's : a + /// request that carries neither is simply not signed in (401 or the login page, at once); one that carries + /// a wrong one is answered only when its address's wait is over, and while it waits nothing of that + /// address is checked (429). + /// + private static Func Auth(string password, AuthBackoff backoff) { string session = password.Length > 0 ? SessionValue(password) : string.Empty; return async (http, next) => @@ -205,12 +230,25 @@ public static class WebHost return; } - bool ok = (http.Request.Cookies.TryGetValue(CookieName, out string? cookie) && Constant(cookie, session)) - || (http.Request.Headers.Authorization.ToString() is { Length: > 7 } auth && auth.StartsWith("Bearer ", StringComparison.Ordinal) && Constant(auth[7..].Trim(), password)); - if (ok) + string? cookie = http.Request.Cookies.TryGetValue(CookieName, out string? c) && c.Length > 0 ? c : null; + string? bearer = http.Request.Headers.Authorization.ToString() is { Length: > 7 } auth && auth.StartsWith("Bearer ", StringComparison.Ordinal) && auth[7..].Trim() is { Length: > 0 } b ? b : null; + if (cookie is not null || bearer is not null) { - await next(http).ConfigureAwait(false); - return; + AuthVerdict verdict = backoff.Check(AuthBackoff.ClientKey(http.Connection.RemoteIpAddress), + () => (cookie is not null && Constant(cookie, session)) | (bearer is not null && Constant(bearer, password)), out TimeSpan wait); + if (verdict == AuthVerdict.Ok) + { + await next(http).ConfigureAwait(false); + return; + } + + if (verdict == AuthVerdict.Blocked) + { + await TooManyAsync(http, path, wait).ConfigureAwait(false); + return; + } + + await Task.Delay(wait, http.RequestAborted).ConfigureAwait(false); } if (path.StartsWith("/api/", StringComparison.Ordinal)) @@ -224,6 +262,129 @@ public static class WebHost }; } + /// 429 while the address waits after a wrong password: JSON under /api/, the login page with the message elsewhere. + private static async Task TooManyAsync(HttpContext http, string path, TimeSpan wait) + { + int seconds = Math.Max(1, (int)Math.Ceiling(wait.TotalSeconds)); + http.Response.StatusCode = StatusCodes.Status429TooManyRequests; + http.Response.Headers.RetryAfter = seconds.ToString(CultureInfo.InvariantCulture); + if (path.StartsWith("/api/", StringComparison.Ordinal)) + { + string message = string.Create(CultureInfo.InvariantCulture, $"troppi tentativi con una password errata da questo indirizzo: riprova fra {seconds} s"); + await Text(http, Json.Result(false, message), "application/json").ConfigureAwait(false); + return; + } + + string page = LoginPageWithError(string.Create(CultureInfo.InvariantCulture, $"Troppi tentativi con una password errata: riprova fra {seconds} secondi.")); + await Text(http, page, "text/html; charset=utf-8").ConfigureAwait(false); + } + + // ----------------------------------------------------------------------- + // Requests from elsewhere + // ----------------------------------------------------------------------- + + /// The names of this computer: without a password the server answers no other Host. + private static readonly string[] LocalHosts = ["localhost", "127.0.0.1", "[::1]"]; + + /// + /// What a page of another site, or one that rebinds its own name to this computer, cannot do (5.1 review), + /// checked before any password is looked at: + /// + /// without a password, a Host other than localhost, 127.0.0.1 or [::1] gets 403 + /// on every route (DNS rebinding: such a page sends its own name); + /// a request that changes something (any method but GET, HEAD, OPTIONS) gets 403 when the browser says + /// it comes from elsewhere (Sec-Fetch-Site other than same-origin or none) or its + /// Origin is another host or port; /login and /logout, plain forms, have the Origin + /// check only; + /// under /api/ such a request must say Content-Type: application/json, with or without + /// a body (415 otherwise): a form or a "simple" cross-site fetch cannot, and anything else needs a CORS + /// preflight this server never grants. + /// + /// + private static Func RequestGuard(bool hasPassword) => async (http, next) => + { + HttpRequest request = http.Request; + string path = request.Path.Value ?? "/"; + bool api = path.StartsWith("/api/", StringComparison.Ordinal); + if (!hasPassword && !LocalHosts.Contains(request.Host.Host, StringComparer.OrdinalIgnoreCase)) + { + await RefuseAsync(http, StatusCodes.Status403Forbidden, api, "richiesta rifiutata: senza password il server risponde solo a localhost").ConfigureAwait(false); + return; + } + + if (!HttpMethods.IsGet(request.Method) && !HttpMethods.IsHead(request.Method) && !HttpMethods.IsOptions(request.Method)) + { + if (FromElsewhere(request, checkFetchSite: path is not ("/login" or "/logout")) is { } why) + { + await RefuseAsync(http, StatusCodes.Status403Forbidden, api, $"richiesta rifiutata: {why}").ConfigureAwait(false); + return; + } + + if (api && !IsJson(request.ContentType)) + { + await RefuseAsync(http, StatusCodes.Status415UnsupportedMediaType, api, "richiesta rifiutata: chi cambia qualcosa manda Content-Type: application/json").ConfigureAwait(false); + return; + } + } + + await next(http).ConfigureAwait(false); + }; + + /// Why the browser says a request comes from another site or origin; null when it comes from this one (or says nothing, as a script). + internal static string? FromElsewhere(HttpRequest request, bool checkFetchSite) + { + ArgumentNullException.ThrowIfNull(request); + if (checkFetchSite && request.Headers["Sec-Fetch-Site"].ToString().Trim() is { Length: > 0 } site + && !site.Equals("same-origin", StringComparison.OrdinalIgnoreCase) && !site.Equals("none", StringComparison.OrdinalIgnoreCase)) + { + return $"arriva da un'altra origine (Sec-Fetch-Site: {site})"; + } + + return request.Headers.Origin.ToString().Trim() is { Length: > 0 } origin && !SameHost(origin, request) + ? $"arriva da un'altra origine ({origin})" + : null; + } + + /// + /// Whether an Origin names this server: its host and port against the request's Host, or against + /// X-Forwarded-Host when a reverse proxy rewrote the Host. A Host without a port (a proxy on the + /// default port, or one that drops it) compares the name only; null and other schemes never match. + /// + internal static bool SameHost(string origin, HttpRequest request) + { + ArgumentNullException.ThrowIfNull(request); + if (!Uri.TryCreate(origin, UriKind.Absolute, out Uri? o) || o.Scheme is not ("http" or "https")) + { + return false; + } + + string forwarded = request.Headers["X-Forwarded-Host"].ToString().Split(',')[0].Trim(); + foreach (string candidate in new[] { request.Host.Value ?? string.Empty, forwarded }) + { + if (candidate.Length == 0) + { + continue; + } + + HostString host = new(candidate); + if (host.Host.Equals(o.Host, StringComparison.OrdinalIgnoreCase) && (host.Port is not { } port || port == o.Port)) + { + return true; + } + } + + return false; + } + + private static bool IsJson(string? contentType) => + (contentType ?? string.Empty).Split(';')[0].Trim().Equals("application/json", StringComparison.OrdinalIgnoreCase); + + private static Task RefuseAsync(HttpContext http, int status, bool api, string message) + { + http.Response.StatusCode = status; + return api ? Text(http, Json.Result(false, message), "application/json") : Text(http, message, "text/plain; charset=utf-8"); + } + /// Equality in constant time, lengths included: both sides are hashed to the same size first. private static bool Constant(string a, string b) { @@ -236,7 +397,7 @@ public static class WebHost // Login, static files // ----------------------------------------------------------------------- - private static void MapLogin(WebApplication app, string password) + private static void MapLogin(WebApplication app, string password, AuthBackoff backoff) { app.MapPost("/login", async http => { @@ -244,14 +405,23 @@ public static class WebHost // "password" since 5.1; "token" is the field of the 5.0 login page, still accepted. string given = (body.GetValueOrDefault("password") is { Length: > 0 } p ? p : body.GetValueOrDefault("token") ?? string.Empty).Trim(); - if (password.Length > 0 && given.Length > 0 && Constant(given, password)) + TimeSpan wait = FailedLoginDelay; + if (password.Length > 0 && given.Length > 0) { - http.Response.Cookies.Append(CookieName, SessionValue(password), new CookieOptions { HttpOnly = true, SameSite = SameSiteMode.Strict, IsEssential = true, Path = "/", MaxAge = TimeSpan.FromDays(30) }); - http.Response.Redirect("/"); - return; + // The same backoff as the Bearer header and the cookie: one wait per address, whatever the door. + switch (backoff.Check(AuthBackoff.ClientKey(http.Connection.RemoteIpAddress), () => Constant(given, password), out wait)) + { + case AuthVerdict.Ok: + http.Response.Cookies.Append(CookieName, SessionValue(password), new CookieOptions { HttpOnly = true, SameSite = SameSiteMode.Strict, IsEssential = true, Path = "/", MaxAge = TimeSpan.FromDays(30) }); + http.Response.Redirect("/"); + return; + case AuthVerdict.Blocked: + await TooManyAsync(http, "/login", wait).ConfigureAwait(false); + return; + } } - await Task.Delay(FailedLoginDelay, http.RequestAborted).ConfigureAwait(false); + await Task.Delay(wait, http.RequestAborted).ConfigureAwait(false); http.Response.StatusCode = 401; await Text(http, LoginPageWithError(password.Length > 0 ? "Password errata." : "Questo server non ha una password: apri direttamente la pagina."), "text/html; charset=utf-8").ConfigureAwait(false); }); diff --git a/Encelado/tests/Encelado.Tests/ApiV2Tests.cs b/Encelado/tests/Encelado.Tests/ApiV2Tests.cs index 0b820d9..fd5632c 100644 --- a/Encelado/tests/Encelado.Tests/ApiV2Tests.cs +++ b/Encelado/tests/Encelado.Tests/ApiV2Tests.cs @@ -134,7 +134,7 @@ public abstract class ApiHostFixture : IAsyncLifetime "closeForeignOnKill", "equity", "balance", "availableBalance", "usedMargin", "marginRatio", "peakEquity", "drawdownPct", "equityStopPct", "dailyLossPct", "dailyLossUsedPct", "dailyLossLatched", "cumulativeCashFlow", "todayPnl", "todayPnlPct", "todayPnlProvisional", "todayEquityChange", "dayStartEquity", "todayClosed", "openPnl", "accountOpenPnl", - "openBaskets", "maxBaskets", "pendingBaskets", "pendingOrders", "orphanLegs", "foreignPositions", "displayCurrency", "theme", "navExpanded", "fxRates", + "openBaskets", "maxBaskets", "pendingBaskets", "pendingOrders", "orphanLegs", "foreignPositions", "displayCurrency", "theme", "navExpanded", "statusLines", "fxRates", "baskets", "quotes", "health", "learning", "nextEvent", "events", "eventsSeq", "versions", ]; @@ -502,6 +502,64 @@ public sealed class SampleApiTests : ApiHostFixture } } + /// + /// --sample reads and writes none of the operator's files (5.1 review): the settings page is the factory + /// configuration with the sample's engine and secrets, and every write — settings, keys, token, test + /// message, unlock, reset, restore — answers 400 «modalità dimostrativa» and touches nothing. + /// + [Fact] + public async Task TheSettingsAreSampleDataAndNothingCanBeSaved() + { + // The folder's own file says light and its store holds a token: the sample reads neither. + ConfigWriter.Apply(Context.ConfigPath, new Dictionary { ["ui.theme"] = System.Text.Json.Nodes.JsonValue.Create("light") }); + new SecretStore(Folder, HostPassword, 1_000).SaveTelegramToken("123456:token-vero"); + string config = File.ReadAllText(Context.ConfigPath); + byte[] secrets = File.ReadAllBytes(Path.Combine(Folder, SecretStore.FileName)); + + using (JsonDocument doc = await GetJsonAsync("/api/settings")) + { + JsonElement r = doc.RootElement; + Assert.Contains("--sample", r.GetProperty("configPath").GetString(), StringComparison.Ordinal); + Assert.Equal("dark", Field(r, "ui.theme")); + Assert.Equal("Moderate", Field(r, "strategy:preset")); + Assert.Equal("running", r.GetProperty("engine").GetProperty("state").GetString()); + Assert.Equal("open", r.GetProperty("secrets").GetProperty("state").GetString()); + Assert.True(r.GetProperty("secrets").GetProperty("etoro").GetProperty("demo").GetProperty("present").GetBoolean()); + } + + (HttpMethod Method, string Path, string Body)[] writes = + [ + (HttpMethod.Post, "/api/settings", """{"edits":{"ui.theme":"light"}}"""), + (HttpMethod.Post, "/api/settings/keys", """{"account":"demo","apiKey":"api","userKey":"user"}"""), + (HttpMethod.Delete, "/api/settings/keys?account=demo", string.Empty), + (HttpMethod.Post, "/api/settings/telegram-token", """{"token":"123:abc"}"""), + (HttpMethod.Delete, "/api/settings/telegram-token", string.Empty), + (HttpMethod.Post, "/api/settings/telegram-test", string.Empty), + (HttpMethod.Post, "/api/settings/secrets/unlock", """{"previous":"un'altra"}"""), + (HttpMethod.Post, "/api/settings/secrets/reset", string.Empty), + (HttpMethod.Post, "/api/settings/restore", string.Empty), + ]; + foreach ((HttpMethod method, string path, string body) in writes) + { + HttpRequestMessage req = new(method, path) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; + HttpResponseMessage res = await Client.SendAsync(req); + string text = await res.Content.ReadAsStringAsync(); + Assert.True(res.StatusCode == HttpStatusCode.BadRequest, $"{method} {path}: {(int)res.StatusCode} {text}"); + using JsonDocument answer = JsonDocument.Parse(text); + Assert.False(answer.RootElement.GetProperty("ok").GetBoolean()); + Assert.Contains("modalità dimostrativa (--sample)", answer.RootElement.GetProperty("message").GetString(), StringComparison.Ordinal); + } + + Assert.Equal(config, File.ReadAllText(Context.ConfigPath)); + Assert.Equal(secrets, File.ReadAllBytes(Path.Combine(Folder, SecretStore.FileName))); + + static string? Field(JsonElement r, string path) => r.GetProperty("groups").EnumerateArray() + .SelectMany(static g => g.GetProperty("fields").EnumerateArray()) + .Where(f => f.GetProperty("path").GetString() == path) + .Select(static f => f.GetProperty("value").GetString()) + .FirstOrDefault(); + } + [Fact] public async Task TheStoricoHasTheSampleHistory() { @@ -558,6 +616,38 @@ public sealed class StoppedApiTests : ApiHostFixture Assert.Equal("off", tick.GetProperty("health").GetProperty("telegram").GetString()); Assert.Equal("ombra-disabilitato", tick.GetProperty("learning").GetProperty("mode").GetString()); Assert.False(tick.GetProperty("alarms").GetProperty("liveNeedsConfirmation").GetBoolean()); + Assert.Equal(200, tick.GetProperty("statusLines").GetInt32()); + } + + /// + /// «Righe di attività in dashboard» (logging.statusLines) is applied at once: the tick carries it, the + /// strip follows. It is no longer tied to the Log page's window (5.1 review: nothing read it before). + /// + [Fact] + public async Task TheDashboardStripFollowsTheLogSettingAtOnce() + { + Engine.Settings.SettingsResult r = await Context.Settings.ApplyAsync(new Dictionary { ["logging.statusLines"] = "50" }, null, CancellationToken.None); + Assert.True(r.Ok, r.Message); + Assert.Equal("immediate", Assert.Single(r.Results).Applied); + await Task.Delay(1100); + using (JsonDocument doc = await GetJsonAsync("/api/snapshot")) + { + Assert.Equal(50, doc.RootElement.GetProperty("statusLines").GetInt32()); + } + + // The Log page's window may be smaller than the strip: the strip simply fills as lines arrive. + Engine.Settings.SettingsResult buffered = await Context.Settings.ApplyAsync(new Dictionary { ["logging.statusLines"] = "300", ["logging.bufferedLines"] = "150" }, null, CancellationToken.None); + Assert.True(buffered.Ok, buffered.Message); + + // The browser keeps 2000 lines: the page offers no more, and a bigger number written by hand is told as 2000. + Engine.Settings.SettingsResult tooMany = await Context.Settings.ApplyAsync(new Dictionary { ["logging.statusLines"] = "2500" }, null, CancellationToken.None); + Assert.False(tooMany.Ok); + Assert.True(tooMany.Errors.ContainsKey("logging.statusLines")); + ConfigWriter.Apply(Context.ConfigPath, new Dictionary { ["logging.statusLines"] = System.Text.Json.Nodes.JsonValue.Create(4000) }); + Context.Config.CopyFrom(ConfigLoader.Load(Context.ConfigPath, out _)); + await Task.Delay(1100); + using JsonDocument capped = await GetJsonAsync("/api/snapshot"); + Assert.Equal(2000, capped.RootElement.GetProperty("statusLines").GetInt32()); } [Fact] @@ -592,6 +682,40 @@ public sealed class StoppedApiTests : ApiHostFixture Assert.Equal("Encelado", system.RootElement.GetProperty("about").GetProperty("name").GetString()); } + /// + /// Without a password the server is this computer's only: a page that rebinds its own name to 127.0.0.1 + /// (DNS rebinding) sends that name as Host and gets 403 on every route; what changes something must + /// still be JSON from this very origin (5.1 review: a no-cors text/plain POST from a page on another + /// port of the computer saved a setting). + /// + [Fact] + public async Task WithoutAPasswordOnlyThisComputerIsAnswered() + { + int port = Client.BaseAddress!.Port; + foreach (string host in new[] { "evil.example", $"evil.example:{port}", $"192.168.1.20:{port}" }) + { + HttpRequestMessage req = new(HttpMethod.Get, "/api/snapshot"); + req.Headers.Host = host; + Assert.Equal(HttpStatusCode.Forbidden, (await Client.SendAsync(req)).StatusCode); + } + + foreach (string host in new[] { $"localhost:{port}", $"127.0.0.1:{port}", $"[::1]:{port}", "LOCALHOST" }) + { + HttpRequestMessage req = new(HttpMethod.Get, "/api/health"); + req.Headers.Host = host; + Assert.Equal(HttpStatusCode.OK, (await Client.SendAsync(req)).StatusCode); + } + + HttpRequestMessage plain = new(HttpMethod.Post, "/api/settings") { Content = new StringContent("""{"edits":{"run.statusSeconds":"77"}}""", Encoding.UTF8, "text/plain") }; + Assert.Equal(HttpStatusCode.UnsupportedMediaType, (await Client.SendAsync(plain)).StatusCode); + HttpRequestMessage otherPort = new(HttpMethod.Post, "/api/settings") { Content = new StringContent("""{"edits":{"run.statusSeconds":"77"}}""", Encoding.UTF8, "application/json") }; + otherPort.Headers.Add("Origin", "http://localhost:8133"); + Assert.Equal(HttpStatusCode.Forbidden, (await Client.SendAsync(otherPort)).StatusCode); + HttpRequestMessage start = new(HttpMethod.Post, "/api/commands/start") { Content = new StringContent("""{"confirm":"CONFERMO LIVE"}""", Encoding.UTF8, "text/plain") }; + Assert.Equal(HttpStatusCode.UnsupportedMediaType, (await Client.SendAsync(start)).StatusCode); + Assert.NotEqual(77, ConfigLoader.Load(Context.ConfigPath, out _).Run.StatusSeconds); + } + /// A section that did not change answers 304 with no body (decision E2): the page keeps what it has. [Theory] [InlineData("/api/positions")] diff --git a/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs b/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs index d422e03..75e9bee 100644 --- a/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs +++ b/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs @@ -198,6 +198,73 @@ public sealed class EnvironmentImportTests : IDisposable Assert.Contains(o.Notes, static n => n.Contains("rimandata", StringComparison.Ordinal)); } + /// + /// A 5.0 file with a Live mode on the demo account reads as Demo; when the import writes the file (here + /// for the chat id) the obsolete etoro.environment leaves with the mode the file meant written + /// beside it, never a bare "Live" that would read as the real account (5.1 review). + /// + [Theory] + [InlineData("Live")] + [InlineData("LiveAuto")] + [InlineData("LiveApprove")] + public void TheImportKeepsAMerged50FileOnTheDemoAccount(string mode) + { + ConfigWriter.Apply(ConfigPath, new Dictionary + { + ["run.executionMode"] = JsonValue.Create(mode), + ["run.allowLive"] = JsonValue.Create(true), + ["etoro.environment"] = JsonValue.Create("demo"), + }); + Assert.Equal(ExecutionMode.Demo, Saved().Run.Mode); + + ImportOutcome o = EnvironmentImport.Run(ConfigPath, Store(), Env(("TELEGRAM_CHAT_ID", "4242")), Now); + + Assert.True(o.ConfigChanged); + Assert.Equal("4242", Saved().Notifications.Telegram.ChatId); + Assert.False(ConfigWriter.Contains(ConfigPath, "etoro.environment")); + Assert.Equal(ExecutionMode.Demo, Saved().Run.Mode); + } + + /// 5.0 traded with the keys of the environment first, then those of the file, then etoro.keys.enc: the import keeps that order (5.1 review). + [Fact] + public void TheEnvironmentKeysBeatTheOldKeyFileAsIn50() + { + string legacy = Path.Combine(_dir, KeyStores.FileName); + EncryptedFileKeyStore old = new(legacy, "passphrase-della-5.0"); + old.Save(demo: true, new EtoroKeys("api-demo-file", "user-demo-file", Now)); + old.Save(demo: false, new EtoroKeys("api-real-file", "user-real-file", Now)); + SecretStore store = Store(); + + ImportOutcome o = EnvironmentImport.Run(ConfigPath, store, Env( + (KeyStores.PassphraseVariable, "passphrase-della-5.0"), + ("ETORO_API_KEY", "api-env"), + ("ETORO_USER_KEY", "user-env")), Now); + + Assert.Equal("api-env", store.Etoro(demo: true)!.ApiKey); + Assert.Contains("ETORO_API_KEY", o.Imported); + + // The real slot was empty: the old file still fills it, and it is migrated. + Assert.Equal("api-real-file", store.Etoro(demo: false)!.ApiKey); + Assert.Contains(o.Notes, static n => n.Contains("già nel deposito", StringComparison.Ordinal) && n.Contains(KeyStores.FileName, StringComparison.Ordinal)); + Assert.True(System.IO.File.Exists(legacy + ".migrato")); + } + + [Fact] + public void TheKeysWrittenInTheFileBeatTheOldKeyFile() + { + ConfigWriter.Apply(ConfigPath, new Dictionary + { + ["etoro.apiKey"] = JsonValue.Create("api-in-chiaro"), + ["etoro.userKey"] = JsonValue.Create("user-in-chiaro"), + }); + new EncryptedFileKeyStore(Path.Combine(_dir, KeyStores.FileName), "passphrase").Save(demo: true, new EtoroKeys("api-cifrata", "user-cifrata", Now)); + SecretStore store = Store(); + + EnvironmentImport.Run(ConfigPath, store, Env((KeyStores.PassphraseVariable, "passphrase")), Now); + + Assert.Equal("api-in-chiaro", store.Etoro(demo: true)!.ApiKey); + } + [Fact] public void SecretsWrittenInTheFileMoveToTheStoreAndLeaveTheFile() { diff --git a/Encelado/tests/Encelado.Tests/LearningReportTests.cs b/Encelado/tests/Encelado.Tests/LearningReportTests.cs index aa297b3..9753a75 100644 --- a/Encelado/tests/Encelado.Tests/LearningReportTests.cs +++ b/Encelado/tests/Encelado.Tests/LearningReportTests.cs @@ -766,6 +766,29 @@ public sealed class LearningDiskReaderTests : TempFolderTests Assert.NotEqual(emptyStamp, LearningDiskReader.Stamp(Paths, t.AddSeconds(3))); } + /// + /// A stopped engine's page takes its switches, pMin and the basket list from strategy.json: the file + /// is in the stamp, so a hand edit moves the ETag as a model or a ledger file does (5.1 review). + /// + [Fact] + public void TheStampFollowsTheStrategyFile() + { + string strategy = Path.Combine(Root, "strategy.json"); + File.WriteAllText(strategy, BasketStrategyConfig.DefaultJson); + LearningPaths paths = new(Root, KnowledgeDir, strategy); + DateTime t = LearningScenery.T0; + string before = LearningDiskReader.Stamp(paths, t); + + File.WriteAllText(strategy, BasketStrategyConfig.DefaultJson + "\n"); + File.SetLastWriteTimeUtc(strategy, File.GetLastWriteTimeUtc(strategy).AddSeconds(5)); + + Assert.NotEqual(before, LearningDiskReader.Stamp(paths, t.AddSeconds(3))); + + string configPath = Path.Combine(Root, "encelado.json"); + File.WriteAllText(configPath, ConfigDefaults.Json); + Assert.Equal(strategy, LearningPaths.From(ConfigLoader.Load(configPath, out _)).StrategyFile); + } + [Fact] public void TheHeadlineOfAStoppedBotComesFromItsStateFile() { @@ -1096,6 +1119,37 @@ public sealed class StoppedLearningApiTests : ApiHostFixture Assert.NotEqual(etag, moved.Headers.ETag!.Tag); } + /// + /// With the engine stopped the page reads its switches from strategy.json: a save of the learning + /// settings moves the section's version and the ETag at once, so the page never keeps the old flags + /// behind a 304 while the tick already says otherwise (5.1 review). + /// + [Fact] + public async Task ASavedStrategyMovesTheLearningPageAtOnce() + { + HttpResponseMessage first = await Client.GetAsync("/api/learning"); + Assert.Equal(HttpStatusCode.OK, first.StatusCode); + string etag = first.Headers.ETag!.Tag; + using (JsonDocument doc = JsonDocument.Parse(await first.Content.ReadAsStringAsync())) + { + Assert.False(doc.RootElement.GetProperty("status").GetProperty("enabled").GetBoolean()); + } + + long version = Context.Supervisor.Versions[Section.Learning]; + Engine.Settings.SettingsResult r = await Context.Settings.ApplyAsync(new Dictionary { ["strategy:learning.enabled"] = "true" }, null, CancellationToken.None); + Assert.True(r.Ok, r.Message); + Assert.True(Context.Supervisor.Versions[Section.Learning] > version); + + HttpRequestMessage again = new(HttpMethod.Get, "/api/learning"); + again.Headers.TryAddWithoutValidation("If-None-Match", etag); + HttpResponseMessage moved = await Client.SendAsync(again); + Assert.Equal(HttpStatusCode.OK, moved.StatusCode); + Assert.NotEqual(etag, moved.Headers.ETag!.Tag); + using JsonDocument now = JsonDocument.Parse(await moved.Content.ReadAsStringAsync()); + Assert.True(now.RootElement.GetProperty("status").GetProperty("enabled").GetBoolean()); + Assert.Equal("ombra", now.RootElement.GetProperty("status").GetProperty("mode").GetString()); + } + [Fact] public async Task EseguiCicloOnAStoppedBotIsAMaintenanceAndASecondOneIs409() { diff --git a/Encelado/tests/Encelado.Tests/SecretStoreTests.cs b/Encelado/tests/Encelado.Tests/SecretStoreTests.cs index b85019c..2125e4b 100644 --- a/Encelado/tests/Encelado.Tests/SecretStoreTests.cs +++ b/Encelado/tests/Encelado.Tests/SecretStoreTests.cs @@ -109,6 +109,44 @@ public sealed class SecretStoreTests : IDisposable Assert.Equal(SecretStoreState.Locked, Open("password").State); } + /// + /// The iteration count comes from the header, which only AES-GCM proves genuine — after the key is + /// derived. A count outside what this store could have written (a flipped bit can claim a billion + /// rounds: minutes of PBKDF2 before the web host is even up, and again at every «Sblocca») is a + /// damaged file, locked without deriving anything (5.1 review). + /// + [Theory] + [InlineData(10_000_001)] + [InlineData(1_073_742_824)] // 1 000 with one bit flipped in the count's last byte + [InlineData(int.MaxValue)] + [InlineData(Fast - 1)] + public void AnImplausibleIterationCountIsADamagedFileLockedAtOnce(int iterations) + { + Open("password-lunga").SaveTelegramToken("123456:token-segretissimo"); + byte[] raw = File.ReadAllBytes(FilePath); + BinaryPrimitives.WriteInt32LittleEndian(raw.AsSpan(5, 4), iterations); + File.WriteAllBytes(FilePath, raw); + + System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); + SecretStore store = Open("password-lunga"); + bool unlocked = store.Unlock("password-lunga", out string message); + sw.Stop(); + + Assert.Equal(SecretStoreState.Locked, store.State); + Assert.Contains("danneggiato", store.Problem, StringComparison.Ordinal); + Assert.False(unlocked); + Assert.Contains("danneggiato", message, StringComparison.Ordinal); + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(1), $"{sw.Elapsed.TotalMilliseconds:F0} ms"); + } + + [Fact] + public void ThePlausibleRangeIsTheProductionOneForAStoreOfTheDefaultCost() + { + Assert.Equal(100_000, SecretStore.MinIterations); + Assert.Equal(10_000_000, SecretStore.MaxIterations); + Assert.InRange(SecretStore.DefaultIterations, SecretStore.MinIterations, SecretStore.MaxIterations); + } + [Fact] public void WithoutAPasswordALocalKeyProtectsTheStoreAndMovesUnderThePasswordWhenOneAppears() { diff --git a/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs b/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs index b69359b..6ac1a82 100644 --- a/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs +++ b/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs @@ -670,6 +670,87 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime Assert.Contains("\"light\"", text, StringComparison.Ordinal); } + /// + /// A 5.0 file with a Live mode on the demo account (or 4.0's LiveAuto/LiveApprove) reads as Demo + /// (decision C6). Any save removes the obsolete etoro.environment and writes the mode the file + /// meant with it: the bare "Live" left behind would turn the demo account into the real one past the + /// account guard, the keys check and the phrase (5.1 review). + /// + [Theory] + [InlineData("Live")] + [InlineData("LiveAuto")] + [InlineData("LiveApprove")] + public async Task AnUnrelatedSaveKeepsAMerged50FileOnTheDemoAccount(string mode) + { + Build(p => + { + Set(p, "run.executionMode", mode); + Set(p, "run.allowLive", true); + Set(p, "etoro.environment", "demo"); + }); + Assert.Equal(ExecutionMode.Demo, Runtime.Config.Run.Mode); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + _engines[0].OpenBaskets = 1; + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["ui.theme"] = "light" }, null, CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal(SettingsResult.RestartNone, r.Restart); + Assert.False(ConfigWriter.Contains(ConfigPath, "etoro.environment")); + Assert.Equal("Demo", JsonNode.Parse(File.ReadAllText(ConfigPath))!["run"]!["executionMode"]!.GetValue()); + Assert.Equal(ExecutionMode.Demo, ConfigLoader.Load(ConfigPath, out _).Run.Mode); + Assert.Equal(ExecutionMode.Demo, Runtime.Config.Run.Mode); + Assert.Equal("demo", Runtime.Config.Etoro.Environment); + Assert.Empty(_engines[0].Commands); + + // FERMA and AVVIA: the demo account again, without the phrase. + Assert.True((await Supervisor.StopAsync()).Ok); + CommandResult again = await Runtime.StartEngineAsync(null); + Assert.True(again.Ok, again.Message); + Assert.Equal(ExecutionMode.Demo, _engines[^1].Mode); + } + + /// The same file with a restart-scoped field in the batch: the engine starts again on the demo account it was on. + [Fact] + public async Task ARestartSaveOfAMerged50FileStartsAgainOnTheDemoAccount() + { + Build(static p => + { + Set(p, "run.executionMode", "Live"); + Set(p, "run.allowLive", true); + Set(p, "etoro.environment", "demo"); + }); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["ui.theme"] = "light", ["strategy:preferDirectCross"] = "true" }, null, CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal(SettingsResult.RestartDone, r.Restart); + Assert.Equal(2, _engines.Count); + Assert.Equal(ExecutionMode.Demo, _engines[1].Mode); + Assert.False(_engines[1].LiveConfirmed); + Assert.Equal(ExecutionMode.Demo, ConfigLoader.Load(ConfigPath, out _).Run.Mode); + } + + /// The control: a 5.0 Live file on the real account stays Live (the phrase still guards every start). + [Fact] + public async Task ALive50FileOnTheRealAccountStaysLiveAfterASave() + { + Build(static p => + { + Set(p, "run.executionMode", "Live"); + Set(p, "run.allowLive", true); + Set(p, "etoro.environment", "real"); + }); + + Assert.True((await Runtime.ApplyAsync(new Dictionary { ["ui.theme"] = "light" }, null, CancellationToken.None)).Ok); + + Assert.False(ConfigWriter.Contains(ConfigPath, "etoro.environment")); + Assert.Equal(ExecutionMode.Live, ConfigLoader.Load(ConfigPath, out _).Run.Mode); + Assert.Equal(ExecutionMode.Live, Runtime.Config.Run.Mode); + Assert.Equal(CommandResult.NeedsPhrase, (await Runtime.StartEngineAsync(null)).Code); + } + [Fact] public async Task KeysAreProvedOnTheirOwnAccountAndTheActiveOnesRestartTheEngine() { diff --git a/Encelado/tests/Encelado.Tests/WebTests.cs b/Encelado/tests/Encelado.Tests/WebTests.cs index bfa79d4..73a4402 100644 --- a/Encelado/tests/Encelado.Tests/WebTests.cs +++ b/Encelado/tests/Encelado.Tests/WebTests.cs @@ -353,6 +353,9 @@ public sealed class WebHostTests : IAsyncLifetime _supervisor = new BotSupervisor(config); _history = new HistoryService(config); SecretStore secrets = new(_dir, Password, 1_000); + + // The sample's pictures (a running bot, its history) with the real settings of the folder: + // --sample itself never saves a setting. WebContext ctx = new() { Config = config, @@ -361,7 +364,7 @@ public sealed class WebHostTests : IAsyncLifetime History = _history, ConfigPath = configPath, Settings = new Engine.Settings.SettingsRuntime(config, configPath, secrets, _supervisor), - Sample = true, + ReadModel = new SampleReadModel(null, DateTime.UtcNow), Start = static _ => Task.FromResult(new CommandResult(false, "non in questo test")), Learn = static () => Task.FromResult(new CommandResult(false, "non in questo test")), }; @@ -408,6 +411,16 @@ public sealed class WebHostTests : IAsyncLifetime return req; } + /// A request that changes something, as the interface sends it: JSON, even without a body. + private HttpRequestMessage AuthorisedJson(HttpMethod method, string path, string body = "{}") + { + HttpRequestMessage req = Authorised(method, path); + req.Content = new StringContent(body, Encoding.UTF8, "application/json"); + return req; + } + + private string Origin => _client!.BaseAddress!.GetLeftPart(UriPartial.Authority); + [Fact] public async Task WithoutTheSessionTheApiSays401AndThePageRedirectsToLogin() { @@ -450,13 +463,14 @@ public sealed class WebHostTests : IAsyncLifetime withCookie.Headers.Add("Cookie", $"{WebHost.CookieName}={value}"); Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(withCookie)).StatusCode); + using FormUrlEncodedContent legacy = new([new KeyValuePair("token", Password)]); + Assert.Equal(HttpStatusCode.Redirect, (await _client.PostAsync("/login", legacy)).StatusCode); + + // Last: a wrong cookie is a wrong password, and the address then waits (see the backoff's test). HttpRequestMessage rawPassword = new(HttpMethod.Get, "/api/snapshot"); rawPassword.Headers.Add("Cookie", $"{WebHost.CookieName}={Password}"); Assert.Equal(HttpStatusCode.Unauthorized, (await _client.SendAsync(rawPassword)).StatusCode); - using FormUrlEncodedContent legacy = new([new KeyValuePair("token", Password)]); - Assert.Equal(HttpStatusCode.Redirect, (await _client.PostAsync("/login", legacy)).StatusCode); - HttpResponseMessage logout = await _client.PostAsync("/logout", null); Assert.Equal(HttpStatusCode.Redirect, logout.StatusCode); Assert.Equal("/login", logout.Headers.Location?.ToString()); @@ -483,6 +497,163 @@ public sealed class WebHostTests : IAsyncLifetime Assert.False(refused.Headers.Contains("Set-Cookie")); } + /// + /// A wrong Bearer or session cookie is a guess of the password like a wrong login (the cookie is derived + /// from it, so it can be computed for every guess): one address gets one password checked at a time, the + /// wrong one answered only when its wait ends — 1 s, then 2, 4… up to 30 s in a row — and meanwhile no + /// password of that address is even checked, a right one included: parallel guesses do not help (5.1 + /// review: 200 wrong Bearers took 53 ms, 40 parallel logins one second). + /// + [Fact] + public async Task AWrongBearerOrCookieIsAGuessAndTheAddressWaitsBeforeTheNext() + { + System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); + HttpResponseMessage[] guesses = await Task.WhenAll(Enumerable.Range(0, 12).Select(i => + { + HttpRequestMessage req = new(HttpMethod.Get, "/api/settings"); + req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", $"tentativo-{i}"); + return _client!.SendAsync(req); + })); + sw.Stop(); + + HttpResponseMessage wrong = Assert.Single(guesses, static r => r.StatusCode == HttpStatusCode.Unauthorized); + Assert.All(guesses.Where(r => r != wrong), static r => Assert.Equal(HttpStatusCode.TooManyRequests, r.StatusCode)); + Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(900), $"risposta in {sw.Elapsed.TotalMilliseconds:F0} ms"); + HttpResponseMessage blocked = guesses.First(static r => r.StatusCode == HttpStatusCode.TooManyRequests); + Assert.NotNull(blocked.Headers.RetryAfter?.Delta); + using (JsonDocument body = JsonDocument.Parse(await blocked.Content.ReadAsStringAsync())) + { + Assert.Contains("riprova", body.RootElement.GetProperty("message").GetString(), StringComparison.Ordinal); + } + + // The second guess in a row, a wrong session cookie: its answer comes after two seconds, and while it + // waits even the right password from the same address is not checked. + HttpRequestMessage cookie = new(HttpMethod.Get, "/api/snapshot"); + cookie.Headers.Add("Cookie", $"{WebHost.CookieName}={WebHost.SessionValue("una-password-sbagliata")}"); + sw.Restart(); + Task second = _client!.SendAsync(cookie); + await Task.Delay(300); + HttpResponseMessage right = await _client.SendAsync(Authorised(HttpMethod.Get, "/api/settings")); + Assert.Equal(HttpStatusCode.TooManyRequests, right.StatusCode); + using FormUrlEncodedContent form = new([new KeyValuePair("password", Password)]); + HttpResponseMessage login = await _client.PostAsync("/login", form); + Assert.Equal(HttpStatusCode.TooManyRequests, login.StatusCode); + Assert.Contains("login-error", await login.Content.ReadAsStringAsync(), StringComparison.Ordinal); + Assert.False(login.Headers.Contains("Set-Cookie")); + Assert.Equal(HttpStatusCode.Unauthorized, (await second).StatusCode); + Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(1_900), $"risposta in {sw.Elapsed.TotalMilliseconds:F0} ms"); + + // After the wait the right password opens again and clears the count: the next wrong one costs one second again. + Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(Authorised(HttpMethod.Get, "/api/settings"))).StatusCode); + HttpRequestMessage again = new(HttpMethod.Get, "/api/snapshot"); + again.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "dopo-il-successo"); + sw.Restart(); + Assert.Equal(HttpStatusCode.Unauthorized, (await _client.SendAsync(again)).StatusCode); + Assert.InRange(sw.Elapsed, TimeSpan.FromMilliseconds(900), TimeSpan.FromMilliseconds(1_900)); + } + + /// + /// What another site's page can send without a preflight (a form, a no-cors fetch with text/plain) never + /// changes anything: under /api/ a write must say application/json (415 otherwise, bodyless + /// DELETE included), and the browser's Sec-Fetch-Site or Origin naming another site is a + /// 403 before the password is even looked at (5.1 review). + /// + [Fact] + public async Task ARequestFromAnotherSiteOrNotInJsonChangesNothing() + { + string before = File.ReadAllText(Path.Combine(_dir, "encelado.json")); + + HttpRequestMessage plain = Authorised(HttpMethod.Post, "/api/settings"); + plain.Content = new StringContent("""{"edits":{"ui.theme":"light"}}""", Encoding.UTF8, "text/plain"); + Assert.Equal(HttpStatusCode.UnsupportedMediaType, (await _client!.SendAsync(plain)).StatusCode); + + HttpRequestMessage form = Authorised(HttpMethod.Post, "/api/commands/kill"); + form.Content = new FormUrlEncodedContent([new KeyValuePair("foreign", "true")]); + Assert.Equal(HttpStatusCode.UnsupportedMediaType, (await _client.SendAsync(form)).StatusCode); + + Assert.Equal(HttpStatusCode.UnsupportedMediaType, (await _client.SendAsync(Authorised(HttpMethod.Delete, "/api/settings/telegram-token"))).StatusCode); + Assert.Equal(HttpStatusCode.UnsupportedMediaType, (await _client.SendAsync(Authorised(HttpMethod.Post, "/api/settings/secrets/reset"))).StatusCode); + + HttpRequestMessage foreignOrigin = AuthorisedJson(HttpMethod.Post, "/api/settings", """{"edits":{"ui.theme":"light"}}"""); + foreignOrigin.Headers.Add("Origin", "https://evil.example"); + HttpResponseMessage refused = await _client.SendAsync(foreignOrigin); + Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode); + using (JsonDocument body = JsonDocument.Parse(await refused.Content.ReadAsStringAsync())) + { + Assert.False(body.RootElement.GetProperty("ok").GetBoolean()); + } + + foreach (string site in new[] { "cross-site", "same-site" }) + { + HttpRequestMessage fetch = AuthorisedJson(HttpMethod.Post, "/api/commands/pause"); + fetch.Headers.Add("Sec-Fetch-Site", site); + Assert.Equal(HttpStatusCode.Forbidden, (await _client.SendAsync(fetch)).StatusCode); + } + + HttpRequestMessage otherPort = AuthorisedJson(HttpMethod.Delete, "/api/settings/keys?account=live"); + otherPort.Headers.Add("Origin", "http://127.0.0.1:1"); + Assert.Equal(HttpStatusCode.Forbidden, (await _client.SendAsync(otherPort)).StatusCode); + + HttpRequestMessage opaque = AuthorisedJson(HttpMethod.Post, "/api/settings", """{"edits":{"ui.theme":"light"}}"""); + opaque.Headers.Add("Origin", "null"); + Assert.Equal(HttpStatusCode.Forbidden, (await _client.SendAsync(opaque)).StatusCode); + + Assert.Equal(before, File.ReadAllText(Path.Combine(_dir, "encelado.json"))); + + // The interface itself: JSON, its own origin, the browser saying same-origin. + HttpRequestMessage own = AuthorisedJson(HttpMethod.Post, "/api/settings", """{"edits":{"ui.theme":"light"}}"""); + own.Headers.Add("Origin", Origin); + own.Headers.Add("Sec-Fetch-Site", "same-origin"); + HttpResponseMessage saved = await _client.SendAsync(own); + Assert.Equal(HttpStatusCode.OK, saved.StatusCode); + Assert.Contains("\"light\"", File.ReadAllText(Path.Combine(_dir, "encelado.json")), StringComparison.Ordinal); + + // Behind a reverse proxy that keeps the name and drops the port, and one that says it in X-Forwarded-Host. + HttpRequestMessage proxied = AuthorisedJson(HttpMethod.Post, "/api/commands/nonesiste"); + proxied.Headers.Host = "encelado.example"; + proxied.Headers.Add("Origin", "https://encelado.example"); + Assert.Equal(HttpStatusCode.BadRequest, (await _client.SendAsync(proxied)).StatusCode); + HttpRequestMessage forwarded = AuthorisedJson(HttpMethod.Post, "/api/commands/nonesiste"); + forwarded.Headers.Add("X-Forwarded-Host", "encelado.example:8443"); + forwarded.Headers.Add("Origin", "https://encelado.example:8443"); + Assert.Equal(HttpStatusCode.BadRequest, (await _client.SendAsync(forwarded)).StatusCode); + } + + /// The login and the logout are plain forms: only the Origin is checked, before the password. + [Fact] + public async Task AFormFromAnotherSiteCannotLogInOrOut() + { + HttpRequestMessage login = new(HttpMethod.Post, "/login") { Content = new FormUrlEncodedContent([new KeyValuePair("password", Password)]) }; + login.Headers.Add("Origin", "https://evil.example"); + HttpResponseMessage refused = await _client!.SendAsync(login); + Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode); + Assert.False(refused.Headers.Contains("Set-Cookie")); + + HttpRequestMessage logout = new(HttpMethod.Post, "/logout"); + logout.Headers.Add("Origin", "https://evil.example"); + Assert.Equal(HttpStatusCode.Forbidden, (await _client.SendAsync(logout)).StatusCode); + + HttpRequestMessage own = new(HttpMethod.Post, "/login") { Content = new FormUrlEncodedContent([new KeyValuePair("password", Password)]) }; + own.Headers.Add("Origin", Origin); + Assert.Equal(HttpStatusCode.Redirect, (await _client.SendAsync(own)).StatusCode); + } + + /// + /// The network sees the interface only in the container, or when asked with --listen-all, and only + /// with a password: F5 and run-dev keep the password for the secret store and stay on localhost (5.1 review). + /// + [Fact] + public void TheServerListensOnTheNetworkOnlyInTheContainerOrWhenAsked() + { + Assert.True(WebHost.ListensOnTheNetwork(passwordSet: true, inContainer: true, listenAllFlag: false)); + Assert.True(WebHost.ListensOnTheNetwork(passwordSet: true, inContainer: false, listenAllFlag: true)); + Assert.False(WebHost.ListensOnTheNetwork(passwordSet: true, inContainer: false, listenAllFlag: false)); + Assert.False(WebHost.ListensOnTheNetwork(passwordSet: false, inContainer: true, listenAllFlag: true)); + + // This host was built without the network: it is on the loopback. + Assert.True(IPAddress.IsLoopback(IPAddress.Parse(_client!.BaseAddress!.Host.Trim('[', ']')))); + } + /// /// Every embedded file of the interface is served at its path with its type — the modules /// as text/javascript, or the browser refuses them — and the shell's files need the @@ -607,7 +778,7 @@ public sealed class WebHostTests : IAsyncLifetime Assert.False(secrets.GetProperty("etoro").GetProperty("live").GetProperty("present").GetBoolean()); Assert.Equal(JsonValueKind.Array, secrets.GetProperty("ignoredEnv").ValueKind); - HttpResponseMessage unknown = await _client.SendAsync(Authorised(HttpMethod.Post, "/api/commands/nonesiste")); + HttpResponseMessage unknown = await _client.SendAsync(AuthorisedJson(HttpMethod.Post, "/api/commands/nonesiste")); Assert.Equal(HttpStatusCode.BadRequest, unknown.StatusCode); } @@ -656,3 +827,110 @@ public sealed class WebHostTests : IAsyncLifetime Assert.Contains("\"value\":\"07-16,20-22\"", after, StringComparison.Ordinal); } } + +/// The price of a wrong password (5.1 review): per address, doubling from one second to thirty, shared by every way a password arrives. +public sealed class AuthBackoffTests +{ + private static readonly DateTime T0 = new(2026, 10, 1, 8, 0, 0, DateTimeKind.Utc); + + private sealed class Clock(DateTime start) : TimeProvider + { + public DateTime Now { get; set; } = start; + + public override DateTimeOffset GetUtcNow() => new(Now, TimeSpan.Zero); + } + + [Fact] + public void EachWrongPasswordInARowDoublesTheWaitUpToThirtySeconds() + { + Clock clock = new(T0); + AuthBackoff backoff = new(clock); + List waits = []; + for (int i = 0; i < 8; i++) + { + Assert.Equal(AuthVerdict.Wrong, backoff.Check("10.0.0.5", static () => false, out TimeSpan wait)); + waits.Add(wait.TotalSeconds); + + // Meanwhile nothing of that address is checked, not even the right password. + bool asked = false; + Assert.Equal(AuthVerdict.Blocked, backoff.Check("10.0.0.5", () => asked = true, out TimeSpan left)); + Assert.False(asked); + Assert.Equal(wait, left); + clock.Now += wait; + } + + Assert.Equal([1, 2, 4, 8, 16, 30, 30, 30], waits); + + // Another address is not touched; the right password clears the count. + Assert.Equal(AuthVerdict.Ok, backoff.Check("10.0.0.6", static () => true, out _)); + Assert.Equal(AuthVerdict.Ok, backoff.Check("10.0.0.5", static () => true, out _)); + Assert.Equal(AuthVerdict.Wrong, backoff.Check("10.0.0.5", static () => false, out TimeSpan fresh)); + Assert.Equal(TimeSpan.FromSeconds(1), fresh); + } + + [Fact] + public void TenQuietMinutesForgetTheCount() + { + Clock clock = new(T0); + AuthBackoff backoff = new(clock); + for (int i = 0; i < 3; i++) + { + backoff.Check("10.0.0.5", static () => false, out TimeSpan wait); + clock.Now += wait; + } + + clock.Now += AuthBackoff.Forget; + Assert.Equal(AuthVerdict.Wrong, backoff.Check("10.0.0.5", static () => false, out TimeSpan again)); + Assert.Equal(TimeSpan.FromSeconds(1), again); + } + + [Fact] + public void AnIPv6ClientIsItsSlash64AndAMappedIPv4IsItsAddress() + { + Assert.Equal(AuthBackoff.ClientKey(IPAddress.Parse("2001:db8:1:2::1")), AuthBackoff.ClientKey(IPAddress.Parse("2001:db8:1:2:ffff::9"))); + Assert.NotEqual(AuthBackoff.ClientKey(IPAddress.Parse("2001:db8:1:2::1")), AuthBackoff.ClientKey(IPAddress.Parse("2001:db8:1:3::1"))); + Assert.Equal("192.0.2.7", AuthBackoff.ClientKey(IPAddress.Parse("::ffff:192.0.2.7"))); + Assert.Equal("192.0.2.7", AuthBackoff.ClientKey(IPAddress.Parse("192.0.2.7"))); + Assert.Equal("?", AuthBackoff.ClientKey(null)); + } +} + +/// The throwaway folders of --sample (5.1 review): its own pair, never the operator's; the leftovers of a killed sample server go at the next start. +public sealed class SampleFoldersTests : IDisposable +{ + private readonly string _temp = Path.Combine(Path.GetTempPath(), $"encelado-sample-folders-{Guid.NewGuid():N}"); + + public SampleFoldersTests() => Directory.CreateDirectory(_temp); + + public void Dispose() + { + if (Directory.Exists(_temp)) + { + Directory.Delete(_temp, recursive: true); + } + } + + [Fact] + public void ASampleServerGetsItsOwnPairAndTheDeadOnesLeftoversGo() + { + string dead = Path.Combine(_temp, $"{Encelado.Server.SampleFolders.Prefix}{int.MaxValue}-vecchia"); + Directory.CreateDirectory(Path.Combine(dead, "config")); + File.WriteAllText(Path.Combine(dead, "config", "encelado.json"), "{}"); + string alive = Path.Combine(_temp, $"{Encelado.Server.SampleFolders.Prefix}{Environment.ProcessId}-ancora-viva"); + Directory.CreateDirectory(alive); + string unrelated = Path.Combine(_temp, "un-altra-cartella"); + Directory.CreateDirectory(unrelated); + + string root = Encelado.Server.SampleFolders.Create(_temp); + + Assert.StartsWith(_temp, root, StringComparison.Ordinal); + Assert.True(Directory.Exists(Encelado.Server.SampleFolders.ConfigOf(root))); + Assert.True(Directory.Exists(Encelado.Server.SampleFolders.DataOf(root))); + Assert.False(Directory.Exists(dead)); + Assert.True(Directory.Exists(alive)); + Assert.True(Directory.Exists(unrelated)); + + Encelado.Server.SampleFolders.Delete(root); + Assert.False(Directory.Exists(root)); + } +}