5.1 revisione, segreti e web: un file 5.0 Live+demo resta sul conto demo, password errate pagate anche via Bearer e cookie, richieste da altri siti rifiutate, --sample senza file né segreti dell'operatore, rete solo nel container

- 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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-01 15:59:15 +02:00
1 parent 7e3ace4ae7
commit 2d59c4e94d
29 files changed
+1461 -128

No files matched your search

+5 -2
View File
@@ -4,9 +4,12 @@
// stesse cartelle che il compose monta come /config e /data). Il browser si apre da // 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 // solo appena Kestrel è in ascolto. La password dell'interfaccia è "sviluppo", la
// stessa del compose: i segreti cifrati della sandbox (chiavi eToro, token Telegram, // 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 // "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", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
+24 -5
View File
@@ -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`. - Numeri non finiti (NaN, ∞) → `null`. Un valore sconosciuto è `null`, mai `0`.
- Testi per l'operatore (motivazioni, intenti, messaggi) in italiano. - 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. - 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 <password>`; 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. - Autenticazione: se il container ha `ENCELADO_PASSWORD` (alias deprecato `ENCELADO_WEB_TOKEN`) ogni rotta chiede il cookie `encelado_session` o `Authorization: Bearer <password>`; 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)).
- `--sample`: ogni rotta risponde con dati d'esempio realistici e coerenti fra loro (nessuna chiave, nessun mercato), per lavorare sulle pagine e fotografarle. - 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 ## File statici
@@ -22,8 +24,21 @@ L'interfaccia (docs/UI_GUIDELINES.md): `index.html` carica `/css/tokens.css`, `/
## Accesso ## Accesso
- `GET /login` — la pagina. - `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 (`<p class="login-error" role="alert">`), messo al posto del segnaposto `<!--login-error-->` se la pagina lo contiene, altrimenti prima di `</form>`. - `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: **401** con la pagina di login e il messaggio (`<p class="login-error" role="alert">`), messo al posto del segnaposto `<!--login-error-->` se la pagina lo contiene, altrimenti prima di `</form>`, dopo l'attesa qui sotto.
- `POST /logout` — cancella il cookie, **302** su `/login`. - `POST /logout` — cancella il cookie, **302** su `/login`.
- `/login` e `/logout` sono form semplici: **403** se l'`Origin` nomina un altro host o porta (vedi sotto); `Sec-Fetch-Site` e `Content-Type` non contano.
Il prezzo di una password errata (uguale per form, `Authorization: Bearer` e cookie, contato per indirizzo del client; un client IPv6 per il suo /64): la risposta errata arriva dopo 1 s, poi 2, 4, 8, 16 e al più 30 s per ogni errore di fila. Finché l'attesa non è finita nessuna password di quell'indirizzo viene controllata, nemmeno quella giusta: la richiesta riceve **429** con `Retry-After` (JSON `{ ok: false, message }` sotto `/api/`, la pagina di login con «Troppi tentativi…» altrove). Così i tentativi in parallelo non aiutano. Una password giusta azzera il conto; dieci minuti senza errori lo dimenticano. Una richiesta senza cookie né Bearer non è un tentativo: 401 (o la pagina di login) subito. Gli altri indirizzi non aspettano (dietro un reverse proxy che mostra a Encelado un solo indirizzo, l'attesa vale per tutti).
## Richieste che cambiano qualcosa
Controllate prima di guardare la password, su ogni rotta:
- **Senza password** il server risponde **403** a ogni richiesta (anche GET) il cui header `Host` non è `localhost`, `127.0.0.1` o `[::1]`, con o senza porta: una pagina che fa puntare il proprio nome a 127.0.0.1 (DNS rebinding) manda il suo nome.
- Ogni metodo diverso da GET, HEAD e OPTIONS riceve **403** se `Sec-Fetch-Site` è presente e diverso da `same-origin` o `none` (un'altra origine, anche `same-site`), oppure se `Origin` è presente e il suo host:porta è diverso da quello dell'header `Host` (o di `X-Forwarded-Host`, per un reverse proxy che riscrive l'Host; un `Host` senza porta confronta il solo nome). `Origin: null` è sempre un'altra origine. Senza `Origin` né `Sec-Fetch-Site` (uno script con curl) il controllo non scatta. `/login` e `/logout` hanno solo il controllo dell'`Origin`.
- Sotto `/api/` ogni POST e DELETE (ogni metodo diverso da GET, HEAD e OPTIONS) deve dire `Content-Type: application/json`, anche senza corpo (`DELETE /api/settings/keys?account=demo`, `POST /api/settings/secrets/reset`…): altrimenti **415**. Un form o una fetch "semplice" di un altro sito non possono mandarlo senza un preflight CORS, che il server non concede mai.
Le risposte di rifiuto sotto `/api/` sono `{ ok: false, message }`.
## Il flusso in tempo reale ## Il flusso in tempo reale
@@ -104,6 +119,8 @@ type Tick = {
displayCurrency: string; // USD, EUR, GBP, CHF, JPY, AUD, CAD, NZD displayCurrency: string; // USD, EUR, GBP, CHF, JPY, AUD, CAD, NZD
theme: "dark" | "light"; theme: "dark" | "light";
navExpanded: boolean; navExpanded: boolean;
statusLines: number; // logging.statusLines (Impostazioni ▸ Log ▸ righe di attività): quante righe tiene la striscia della dashboard,
// 20-2000 (il browser ne tiene 2000; un valore più grande scritto a mano nel file vale 2000); cambia subito
fxRates: Record<string, { usdPerUnit: number; ageSeconds: number | null }>; // USD compreso (1) fxRates: Record<string, { usdPerUnit: number; ageSeconds: number | null }>; // USD compreso (1)
baskets: TickBasket[]; baskets: TickBasket[];
quotes: Array<{ symbol: string; bid: number; ask: number; spreadPips: number; spreadMedianPips: number | null; ageSeconds: number | null }>; quotes: Array<{ symbol: string; bid: number; ask: number; spreadPips: number; spreadMedianPips: number | null; ageSeconds: number | null }>;
@@ -276,7 +293,7 @@ type SecretInfo = { present: boolean; masked: string; savedUtc: string | null };
### `GET /api/learning` ### `GET /api/learning`
Il rapporto sull'apprendimento. La parte viva la pubblica il motore (immutabile); a motore fermo e per i file di `knowledge/` la legge dal disco in sola lettura. Query: `features=all` aggiunge il vettore completo per basket. L'`ETag` è la versione della sezione (`versions.learning`) con l'impronta dei file letti: con `If-None-Match` uguale la risposta è **304** senza costruire niente. `generatedUtc` è l'ora in cui il motore ha pubblicato il rapporto (o quella della lettura dal disco). A motore fermo `baskets[].pMl` è quella dell'ultima riga di valutazione del ledger e `vol` porta solo σ prevista, σ media, rapporto e scala di `z_in` di quella riga (`bars` 0, `activeModel` vuoto, `context` −1), oppure `null`. Il rapporto sull'apprendimento. La parte viva la pubblica il motore (immutabile); a motore fermo e per i file di `knowledge/` la legge dal disco in sola lettura. Query: `features=all` aggiunge il vettore completo per basket. L'`ETag` è la versione della sezione (`versions.learning`) con l'impronta dei file letti — modelli, `knowledge/`, `baskets.csv`, i file delle decisioni e `strategy.json`, da cui un motore fermo prende interruttori, `pMin` e basket: anche una modifica a mano del file cambia l'`ETag` (entro 2 s) —: con `If-None-Match` uguale la risposta è **304** senza costruire niente. Ogni salvataggio di un campo `strategy:` dalle Impostazioni fa avanzare `versions.learning`, così la pagina rilegge subito. `generatedUtc` è l'ora in cui il motore ha pubblicato il rapporto (o quella della lettura dal disco). A motore fermo `baskets[].pMl` è quella dell'ultima riga di valutazione del ledger e `vol` porta solo σ prevista, σ media, rapporto e scala di `z_in` di quella riga (`bars` 0, `activeModel` vuoto, `context` −1), oppure `null`.
```ts ```ts
{ schema: 1; generatedUtc: string; source: "engine" | "disk"; engineState: string; { schema: 1; generatedUtc: string; source: "engine" | "disk"; engineState: string;
@@ -350,7 +367,7 @@ type ModelEvaluation = { model: string; rows: number; burnIn: number; auc: numbe
## Comandi ## Comandi
`POST /api/commands/{nome}` con corpo JSON facoltativo. Risposta `{ ok, message, needsPhrase, code?, … }`: `needsPhrase` è `true` (HTTP **409**) quando serve la frase `CONFERMO LIVE`; `code` (se presente) è `needsPhrase`, `restart`, `refused` o `timeout`. Anche `refused` risponde **409**: lo stato rifiuta il comando adesso (un ciclo di apprendimento già in corso, AVVIA durante la manutenzione a motore fermo, il motore che si avvia o si ferma, FERMA durante un kill-switch) e il messaggio dice perché. Un comando che il motore non ha eseguito perché si è fermato prima di prenderlo, o a metà, risponde subito `refused` con «comando interrotto: il motore si è fermato» (mai un'attesa di 120 s). `timeout` risponde **504**: il motore, occupato, non ha risposto entro 120 s; il comando resta in coda e l'esito va nel log. Nessun comando risponde 500 per un'attesa scaduta. `POST /api/commands/{nome}` con corpo JSON facoltativo, sempre con `Content-Type: application/json` (anche senza corpo; 415 altrimenti). Risposta `{ ok, message, needsPhrase, code?, … }`: `needsPhrase` è `true` (HTTP **409**) quando serve la frase `CONFERMO LIVE`; `code` (se presente) è `needsPhrase`, `restart`, `refused` o `timeout`. Anche `refused` risponde **409**: lo stato rifiuta il comando adesso (un ciclo di apprendimento già in corso, AVVIA durante la manutenzione a motore fermo, il motore che si avvia o si ferma, FERMA durante un kill-switch) e il messaggio dice perché. Un comando che il motore non ha eseguito perché si è fermato prima di prenderlo, o a metà, risponde subito `refused` con «comando interrotto: il motore si è fermato» (mai un'attesa di 120 s). `timeout` risponde **504**: il motore, occupato, non ha risposto entro 120 s; il comando resta in coda e l'esito va nel log. Nessun comando risponde 500 per un'attesa scaduta.
Il ciclo di vita del motore è serializzato: AVVIA, FERMA, i riavvii automatici delle impostazioni e il ciclo di apprendimento a motore fermo passano uno alla volta. FERMA durante un avvio aspetta il motore in costruzione e lo ferma; AVVIA subito dopo FERMA aspetta che il motore precedente abbia lasciato la cartella dati (lo stato resta `stopping` fino ad allora). Un kill-switch, una chiusura (`close`), la chiusura dei residui o una chiusura della bonifica in corso non vengono mai interrotti da FERMA o da un riavvio automatico (409 `refused`); solo l'arresto del processo (SIGTERM) li interrompe, dopo 30 s, e un kill-switch interrotto lascia il residuo registrato (Halted-Residuo). Il ciclo di vita del motore è serializzato: AVVIA, FERMA, i riavvii automatici delle impostazioni e il ciclo di apprendimento a motore fermo passano uno alla volta. FERMA durante un avvio aspetta il motore in costruzione e lo ferma; AVVIA subito dopo FERMA aspetta che il motore precedente abbia lasciato la cartella dati (lo stato resta `stopping` fino ad allora). Un kill-switch, una chiusura (`close`), la chiusura dei residui o una chiusura della bonifica in corso non vengono mai interrotti da FERMA o da un riavvio automatico (409 `refused`); solo l'arresto del processo (SIGTERM) li interrompe, dopo 30 s, e un kill-switch interrotto lascia il residuo registrato (Halted-Residuo).
@@ -398,6 +415,8 @@ Il comando `preset` non esiste più: il preset si cambia in Impostazioni.
L'input è tollerante: un numero può avere la virgola decimale (`0,65`), un booleano può essere `sì`/`no`; il valore restituito è sempre normalizzato (`0.65`, `true`). Le stringhe arrivano già in italiano. L'input è tollerante: un numero può avere la virgola decimale (`0,65`), un booleano può essere `sì`/`no`; il valore restituito è sempre normalizzato (`0.65`, `true`). Le stringhe arrivano già in italiano.
In `--sample` la risposta è un dato d'esempio: i valori di fabbrica di `encelado.json` e `strategy.json` (nessun file viene letto), il motore e i segreti del campione (gli stessi di `/api/system`); `configPath` e `strategyPath` dicono «campione (--sample): valori di fabbrica» e «niente viene salvato». Ogni scrittura di questa sezione e di [Segreti](#segreti) risponde **400** `{ ok: false, message: "modalità dimostrativa (--sample): le impostazioni e i segreti non vengono salvati", … }` senza leggere il corpo né chiamare eToro o Telegram.
### `POST /api/settings` ### `POST /api/settings`
Corpo `{ "edits": { "<path>": "<valore>", … }, "confirm"?: "CONFERMO LIVE" }` (accettato anche l'oggetto piatto `{ "<path>": "<valore>" }` della 5.0). Corpo `{ "edits": { "<path>": "<valore>", … }, "confirm"?: "CONFERMO LIVE" }` (accettato anche l'oggetto piatto `{ "<path>": "<valore>" }` della 5.0).
+6 -4
View File
@@ -6,12 +6,13 @@
Stessa disposizione del container: deploy/local/config (encelado.json, strategy.json, Stessa disposizione del container: deploy/local/config (encelado.json, strategy.json,
segreti cifrati) e deploy/local/data (ledger, stato, log). La cartella è ignorata da git. segreti cifrati) e deploy/local/data (ledger, stato, log). La cartella è ignorata da git.
La password dell'interfaccia è "sviluppo", come nel compose: i segreti cifrati della La password dell'interfaccia è "sviluppo", come nel compose: i segreti cifrati della
sandbox restano leggibili in entrambi i modi. Conto, chiavi eToro dei due conti e sandbox restano leggibili in entrambi i modi. La password serve ai segreti, non apre la
Telegram si impostano da Impostazioni nella pagina. rete: il server ascolta solo su localhost (la rete solo nel container o con --listen-all).
Conto, chiavi eToro dei due conti e Telegram si impostano da Impostazioni nella pagina.
scripts\run-dev.ps1 # motore fermo: premi AVVIA nella pagina scripts\run-dev.ps1 # motore fermo: premi AVVIA nella pagina
scripts\run-dev.ps1 -Autostart # motore avviato subito (servono le chiavi) scripts\run-dev.ps1 -Autostart # motore avviato subito (servono le chiavi)
scripts\run-dev.ps1 -Sample # dati finti, nessuna chiave: per guardare le pagine scripts\run-dev.ps1 -Sample # dati finti in cartelle temporanee: la sandbox, i segreti e Telegram non vengono toccati
scripts\run-dev.ps1 -Port 8090 scripts\run-dev.ps1 -Port 8090
#> #>
param( param(
@@ -36,7 +37,8 @@ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$args = @() $args = @()
if ($Sample) { $args += "--sample" } elseif (-not $Autostart) { $args += "--no-autostart" } if ($Sample) { $args += "--sample" } elseif (-not $Autostart) { $args += "--no-autostart" }
$url = "http://localhost:$Port/" $url = "http://localhost:$Port/"
Write-Host "Encelado in locale: $url password: sviluppo (configurazione in deploy\local\config, dati in deploy\local\data)" -ForegroundColor Cyan $where = if ($Sample) { "campione: cartelle temporanee, deploy\local non viene letto" } else { "configurazione in deploy\local\config, dati in deploy\local\data" }
Write-Host "Encelado in locale: $url password: quella della sandbox, sviluppo (solo localhost; $where)" -ForegroundColor Cyan
Write-Host "Comandi da tastiera: status, close <basket>, kill, residuo, reset <motivazione>, bonifica, stop. Ctrl+C = arresto." -ForegroundColor DarkGray Write-Host "Comandi da tastiera: status, close <basket>, kill, residuo, reset <motivazione>, bonifica, stop. Ctrl+C = arresto." -ForegroundColor DarkGray
if (-not $NoBrowser) { Start-Job -ScriptBlock { param($u) Start-Sleep -Seconds 3; Start-Process $u } -ArgumentList $url | Out-Null } if (-not $NoBrowser) { Start-Job -ScriptBlock { param($u) Start-Sleep -Seconds 3; Start-Process $u } -ArgumentList $url | Out-Null }
+6 -2
View File
@@ -2,10 +2,12 @@
# Builds and starts Encelado locally, without the container, in the deploy/local sandbox # Builds and starts Encelado locally, without the container, in the deploy/local sandbox
# (deploy/local/config as /config, deploy/local/data as /data; ignored by git). # (deploy/local/config as /config, deploy/local/data as /data; ignored by git).
# sh scripts/run-dev.sh # engine stopped: press AVVIA in the page # sh scripts/run-dev.sh # engine stopped: press AVVIA in the page
# sh scripts/run-dev.sh --sample # fake data, no keys: to look at the pages # sh scripts/run-dev.sh --sample # fake data in throwaway folders: the sandbox, its secrets and Telegram are not touched
# sh scripts/run-dev.sh --autostart # engine started at once (keys needed) # sh scripts/run-dev.sh --autostart # engine started at once (keys needed)
# The interface password is "sviluppo", as in docker-compose.yml: the encrypted secrets of # The interface password is "sviluppo", as in docker-compose.yml: the encrypted secrets of
# the sandbox (eToro keys, Telegram token, entered from Impostazioni) stay readable both ways. # the sandbox (eToro keys, Telegram token, entered from Impostazioni) stay readable both ways.
# The password is for the secrets, not for the network: the server listens on localhost only
# (the network only in the container or with --listen-all).
set -eu set -eu
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
export ENCELADO_CONFIG_DIR="$(pwd)/deploy/local/config" export ENCELADO_CONFIG_DIR="$(pwd)/deploy/local/config"
@@ -23,5 +25,7 @@ for a in "$@"; do
done done
dotnet build src/Encelado.Server -c Debug -nologo -v q dotnet build src/Encelado.Server -c Debug -nologo -v q
echo "Encelado in locale: http://localhost:$ENCELADO_WEB_PORT/ password: sviluppo (config in deploy/local/config, dati in deploy/local/data)" WHERE="config in deploy/local/config, dati in deploy/local/data"
[ "$MODE" = "--sample" ] && WHERE="campione: cartelle temporanee, deploy/local non viene letto"
echo "Encelado in locale: http://localhost:$ENCELADO_WEB_PORT/ password: quella della sandbox, sviluppo (solo localhost; $WHERE)"
exec dotnet src/Encelado.Server/bin/Debug/net10.0/Encelado.Server.dll $MODE exec dotnet src/Encelado.Server/bin/Debug/net10.0/Encelado.Server.dll $MODE
+5 -1
View File
@@ -32,7 +32,11 @@ if ($NoBuild) { docker compose up -d } else { docker compose up -d --build }
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$port = if ($env:ENCELADO_WEB_PORT) { $env:ENCELADO_WEB_PORT } else { "8080" } $port = if ($env:ENCELADO_WEB_PORT) { $env:ENCELADO_WEB_PORT } else { "8080" }
$password = if ($env:ENCELADO_PASSWORD) { "(da ENCELADO_PASSWORD)" } else { "sviluppo" } # Da dove viene la password, mai il suo valore (può essere una vera): la variabile, poi il .env della compose.
$envFile = Join-Path $root ".env"
$password = if ($env:ENCELADO_PASSWORD) { "(da ENCELADO_PASSWORD)" }
elseif ((Test-Path $envFile) -and (Select-String -Path $envFile -Pattern '^\s*ENCELADO_PASSWORD=.+' -Quiet)) { "(da .env)" }
else { "sviluppo (quella predefinita della compose)" }
$url = "http://localhost:$port/" $url = "http://localhost:$port/"
Write-Host "Encelado nel container: $url password: $password (docker compose down per fermare)" -ForegroundColor Cyan Write-Host "Encelado nel container: $url password: $password (docker compose down per fermare)" -ForegroundColor Cyan
if (-not $NoBrowser) { Start-Job -ScriptBlock { param($u) Start-Sleep -Seconds 4; Start-Process $u } -ArgumentList $url | Out-Null } if (-not $NoBrowser) { Start-Job -ScriptBlock { param($u) Start-Sleep -Seconds 4; Start-Process $u } -ArgumentList $url | Out-Null }
+9 -1
View File
@@ -14,5 +14,13 @@ esac
mkdir -p deploy/local/config deploy/local/data mkdir -p deploy/local/config deploy/local/data
export GIT_COMMIT="$(git rev-parse --short=12 HEAD 2>/dev/null || echo n/d)" export GIT_COMMIT="$(git rev-parse --short=12 HEAD 2>/dev/null || echo n/d)"
if [ "${1:-}" = "--no-build" ]; then docker compose up -d; else docker compose up -d --build; fi if [ "${1:-}" = "--no-build" ]; then docker compose up -d; else docker compose up -d --build; fi
echo "Encelado nel container: http://localhost:${ENCELADO_WEB_PORT:-8080}/ password: ${ENCELADO_PASSWORD:-sviluppo} (sh scripts/run-docker.sh --down per fermare)" # Where the password comes from, never its value (it may be a real one).
if [ -n "${ENCELADO_PASSWORD:-}" ]; then
PASSWORD_NOTE="(da ENCELADO_PASSWORD)"
elif [ -f .env ] && grep -Eq '^[[:space:]]*ENCELADO_PASSWORD=.+' .env; then
PASSWORD_NOTE="(da .env)"
else
PASSWORD_NOTE="sviluppo (quella predefinita della compose)"
fi
echo "Encelado nel container: http://localhost:${ENCELADO_WEB_PORT:-8080}/ password: $PASSWORD_NOTE (sh scripts/run-docker.sh --down per fermare)"
exec docker compose logs -f encelado exec docker compose logs -f encelado
@@ -10,8 +10,11 @@ using Encelado.Engine.Configuration;
namespace Encelado.Engine.Baskets; namespace Encelado.Engine.Baskets;
/// <summary>Where the learning files of a data folder are.</summary> /// <summary>
public sealed record LearningPaths(string DataDir, string KnowledgeDir) /// Where the learning files of a data folder are, and the <c>strategy.json</c> a stopped engine's page
/// takes its switches, <c>pMin</c> and baskets from (empty: none, the stamp leaves it out).
/// </summary>
public sealed record LearningPaths(string DataDir, string KnowledgeDir, string StrategyFile = "")
{ {
public string ModelsDir => Path.Combine(DataDir, "models"); 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) public static LearningPaths From(BotConfig config)
{ {
ArgumentNullException.ThrowIfNull(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 // Stamps
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
/// <summary>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.</summary> /// <summary>
/// A fingerprint of every file the page reads (models, knowledge, the ledger's basket rows and decision
/// files, and <c>strategy.json</c>, whose switches a stopped engine's page shows): the disk half of the
/// ETag. Recomputed at most every two seconds.
/// </summary>
public static string Stamp(LearningPaths p, DateTime nowUtc) public static string Stamp(LearningPaths p, DateTime nowUtc)
{ {
ArgumentNullException.ThrowIfNull(p); 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) if (Stamps.TryGetValue(key, out (DateTime At, string Stamp) s) && nowUtc - s.At < TimeSpan.FromSeconds(2) && nowUtc >= s.At)
{ {
return s.Stamp; 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); Stamps[key] = (nowUtc, stamp);
return stamp; return stamp;
} }
@@ -33,15 +33,35 @@ public static class AppPaths
/// <summary>What happened at first run, for the log; null when the files already existed.</summary> /// <summary>What happened at first run, for the log; null when the files already existed.</summary>
public static string? SeedNote { get; private set; } public static string? SeedNote { get; private set; }
/// <summary>Folders the process chose itself, winning over the variables and the container (<see cref="UseFolders"/>).</summary>
private static (string Config, string Data)? _chosen;
/// <summary>True when the process runs inside the container (the config volume is mounted).</summary> /// <summary>True when the process runs inside the container (the config volume is mounted).</summary>
public static bool InContainer => public static bool InContainer =>
Environment.GetEnvironmentVariable("ENCELADO_IN_CONTAINER") is "1" or "true" || Environment.GetEnvironmentVariable("ENCELADO_IN_CONTAINER") is "1" or "true" ||
(!OperatingSystem.IsWindows() && Directory.Exists(ContainerConfigDirectory)); (!OperatingSystem.IsWindows() && Directory.Exists(ContainerConfigDirectory));
/// <summary>
/// The configuration and data folders the process uses instead of the operator's, before
/// <see cref="Load"/>: <c>--sample</c> works on a throwaway pair, so it never reads or writes the
/// operator's configuration, secrets or data (5.1 review).
/// </summary>
public static void UseFolders(string configDirectory, string dataDirectory)
{
ArgumentException.ThrowIfNullOrWhiteSpace(configDirectory);
ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory);
_chosen = (configDirectory, dataDirectory);
}
public static string ConfigDirectory public static string ConfigDirectory
{ {
get get
{ {
if (_chosen is { } chosen)
{
return chosen.Config;
}
string? custom = Environment.GetEnvironmentVariable("ENCELADO_CONFIG_DIR"); string? custom = Environment.GetEnvironmentVariable("ENCELADO_CONFIG_DIR");
if (!string.IsNullOrWhiteSpace(custom)) if (!string.IsNullOrWhiteSpace(custom))
{ {
@@ -67,7 +87,7 @@ public static class AppPaths
// A data folder separate from the configuration folder: /data in the container, // A data folder separate from the configuration folder: /data in the container,
// ENCELADO_DATA_DIR anywhere (the local sandbox in deploy/local mirrors the // ENCELADO_DATA_DIR anywhere (the local sandbox in deploy/local mirrors the
// container's layout, so F5 and docker compose write the same tree). // 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) bool separateData = !string.IsNullOrWhiteSpace(dataDir)
|| (InContainer && string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ENCELADO_CONFIG_DIR"))); || (InContainer && string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ENCELADO_CONFIG_DIR")));
if (separateData) if (separateData)
@@ -296,7 +296,10 @@ public sealed class LoggingOptions
/// <summary>How many rotated application logs to keep.</summary> /// <summary>How many rotated application logs to keep.</summary>
public int MaxFiles { get; set; } = 10; public int MaxFiles { get; set; } = 10;
/// <summary>Lines kept in the activity strip of the dashboard.</summary> /// <summary>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.</summary>
public const int MaxStripLines = 2_000;
/// <summary>Lines kept in the activity strip of the dashboard (the tick's <c>statusLines</c>).</summary>
public int StatusLines { get; set; } = 200; public int StatusLines { get; set; } = 200;
/// <summary>Lines kept by the log page: the memory ceiling for the in-app log. The file on disk stays complete.</summary> /// <summary>Lines kept by the log page: the memory ceiling for the in-app log. The file on disk stays complete.</summary>
@@ -332,14 +335,11 @@ public sealed class LoggingOptions
throw new InvalidOperationException("logging.statusLines deve essere fra 20 e 5000."); 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) if (BufferedLines is < 100 or > 200_000)
{ {
throw new InvalidOperationException("logging.bufferedLines deve essere fra 100 e 200000."); throw new InvalidOperationException("logging.bufferedLines deve essere fra 100 e 200000.");
} }
if (BufferedLines < StatusLines)
{
throw new InvalidOperationException("logging.bufferedLines deve essere >= logging.statusLines.");
}
} }
} }
@@ -1,5 +1,6 @@
using System.Globalization; using System.Globalization;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Nodes;
using Encelado.Core.Baskets; using Encelado.Core.Baskets;
namespace Encelado.Engine.Configuration; namespace Encelado.Engine.Configuration;
@@ -57,7 +58,14 @@ public static class ConfigLoader
"notifications.telegram.botToken", "notifications.telegram.botToken",
]; ];
public static BotConfig Load(string path, out List<string> warnings) /// <param name="path">The configuration file.</param>
/// <param name="warnings">What the files said that is not a setting any more, or not at all.</param>
/// <param name="overlayPath">
/// The overlay to apply; <c>encelado.local.json</c> beside <paramref name="path"/> 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.
/// </param>
public static BotConfig Load(string path, out List<string> warnings, string? overlayPath = null)
{ {
warnings = []; warnings = [];
BotConfig config = new(); BotConfig config = new();
@@ -85,7 +93,7 @@ public static class ConfigLoader
} }
// A sibling *.local.json overlays machine-specific overrides. // A sibling *.local.json overlays machine-specific overrides.
string localPath = LocalPath(path); string localPath = overlayPath ?? LocalPath(path);
if (File.Exists(localPath)) if (File.Exists(localPath))
{ {
using FileStream stream = File.OpenRead(localPath); using FileStream stream = File.OpenRead(localPath);
@@ -107,6 +115,33 @@ public static class ConfigLoader
/// <summary>The overlay beside a configuration file: <c>encelado.local.json</c>.</summary> /// <summary>The overlay beside a configuration file: <c>encelado.local.json</c>.</summary>
public static string LocalPath(string path) => Path.ChangeExtension(path, null) + ".local.json"; public static string LocalPath(string path) => Path.ChangeExtension(path, null) + ".local.json";
/// <summary>
/// Adds to a write of <paramref name="path"/> the removal of the <see cref="ObsoleteKeys"/> the file
/// still holds. When <c>etoro.environment</c> 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
/// <c>Live</c> (or 4.0 <c>LiveAuto</c>/<c>LiveApprove</c>) beside <c>demo</c> trades the demo
/// account, while the bare <c>Live</c> 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.
/// </summary>
public static void RemoveObsoleteKeys(string path, IDictionary<string, JsonNode?> changes, ICollection<string> 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());
}
}
/// <summary> /// <summary>
/// The secrets a file of 5.0 may carry (the main file or the overlay; the overlay /// 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. /// wins): read only by the one-time import, which moves them to the encrypted store.
@@ -21,16 +21,18 @@ public sealed record ImportOutcome(bool Ran, bool Deferred, IReadOnlyList<string
/// variables in its Unraid definition until the owner edits it, and this makes that /// variables in its Unraid definition until the owner edits it, and this makes that
/// harmless: /// harmless:
/// <list type="bullet"> /// <list type="bullet">
/// <item>secrets go into the encrypted store, only into empty slots and only when the store is open: /// <item>secrets go into the encrypted store, only into empty slots and only when the store is open,
/// <c>ETORO_API_KEY</c>/<c>ETORO_USER_KEY</c> into the account the old mode/environment pair /// in 5.0's order of precedence: <c>ETORO_API_KEY</c>/<c>ETORO_USER_KEY</c> into the account the old
/// meant (the merge rule), the old <c>etoro.keys.enc</c> (with <c>ENCELADO_KEY_PASSPHRASE</c>) /// mode/environment pair meant (the merge rule), then the keys a 5.0 file may carry, then the old
/// for both accounts — then renamed <c>.migrato</c> —, <c>TELEGRAM_BOT_TOKEN</c>, and the keys a /// <c>etoro.keys.enc</c> (with <c>ENCELADO_KEY_PASSPHRASE</c>) for both accounts — then renamed
/// 5.0 file may carry;</item> /// <c>.migrato</c> —; and <c>TELEGRAM_BOT_TOKEN</c>;</item>
/// <item>settings go into <c>encelado.json</c> only when the variable differs from the factory /// <item>settings go into <c>encelado.json</c> only when the variable differs from the factory
/// default <b>and</b> the file still holds the factory default (a template default such as /// default <b>and</b> the file still holds the factory default (a template default such as
/// USD or Demo is not an intent): <c>TELEGRAM_CHAT_ID</c> (when the chat id is empty), /// USD or Demo is not an intent): <c>TELEGRAM_CHAT_ID</c> (when the chat id is empty),
/// <c>ENCELADO_DISPLAY_CURRENCY</c>, <c>ENCELADO_LOG_LEVEL</c>, /// <c>ENCELADO_DISPLAY_CURRENCY</c>, <c>ENCELADO_LOG_LEVEL</c>,
/// <c>ENCELADO_EXECUTION_MODE</c>+<c>ETORO_ENVIRONMENT</c>, <c>ENCELADO_AUTOSTART=0</c>;</item> /// <c>ENCELADO_EXECUTION_MODE</c>+<c>ETORO_ENVIRONMENT</c>, <c>ENCELADO_AUTOSTART=0</c>; a write
/// removes the obsolete keys and writes the mode the file meant in place of <c>etoro.environment</c>
/// (<see cref="ConfigLoader.RemoveObsoleteKeys"/>);</item>
/// <item><c>TZ</c> and <c>ENCELADO_CONFIRM_LIVE</c> are never imported.</item> /// <item><c>TZ</c> and <c>ENCELADO_CONFIRM_LIVE</c> are never imported.</item>
/// </list> /// </list>
/// It runs once: <c>&lt;config&gt;/import-5.1.json</c> records what it did (a locked store /// It runs once: <c>&lt;config&gt;/import-5.1.json</c> records what it did (a locked store
@@ -100,7 +102,9 @@ public static class EnvironmentImport
} }
else 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. // The keys of the environment belong to the account 5.0 used them on.
bool envDemo = !MergedMode(envMode ?? fileModeRaw, envEnvironment ?? fileEnvironmentRaw, out _).IsLive(); 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); string? telegram = Env("TELEGRAM_BOT_TOKEN") ?? (fileSecrets.TelegramToken.Length > 0 ? fileSecrets.TelegramToken : null);
if (telegram is not null) if (telegram is not null)
{ {
@@ -225,8 +231,11 @@ public static class EnvironmentImport
if (changes.Count > 0 || secretDeletions.Count > 0) if (changes.Count > 0 || secretDeletions.Count > 0)
{ {
List<string> deletions = [.. secretDeletions, .. ConfigLoader.ObsoleteKeys.Where(k => ConfigWriter.Contains(configPath, k))]; // With the obsolete keys goes etoro.environment, and the mode the file meant is written in its place.
ConfigWriter.Apply(configPath, Settings.SettingsService.WithDocumentation(configPath, ConfigDefaults.Json, changes), deletions); Dictionary<string, JsonNode?> write = Settings.SettingsService.WithDocumentation(configPath, ConfigDefaults.Json, changes);
List<string> deletions = [.. secretDeletions];
ConfigLoader.RemoveObsoleteKeys(configPath, write, deletions);
ConfigWriter.Apply(configPath, write, deletions);
configChanged = true; configChanged = true;
} }
} }
@@ -48,7 +48,9 @@ public sealed record SecretInfo(bool Present, string Masked, DateTime? SavedUtc)
/// <para> /// <para>
/// Layout: <c>ENC2</c> | key source (1 password, 2 local key) | PBKDF2 iterations (int32, /// Layout: <c>ENC2</c> | key source (1 password, 2 local key) | PBKDF2 iterations (int32,
/// little endian) | salt 16 | nonce 12 | tag 16 | ciphertext. The header is authenticated /// 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 <see cref="MinIterations"/>-<see cref="MaxIterations"/>
/// 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 <see cref="SecretStoreState.Locked"/>: the web /// A changed password leaves the store <see cref="SecretStoreState.Locked"/>: the web
/// login still works (it uses the variable), and the settings page offers to unlock with /// 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 /// 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; public const int DefaultIterations = 600_000;
/// <summary>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).</summary>
public const int MinIterations = 100_000;
/// <summary>The most PBKDF2 iterations a header may claim: past this the file is damaged, not slow.</summary>
public const int MaxIterations = 10_000_000;
private static readonly byte[] Magic = "ENC2"u8.ToArray(); private static readonly byte[] Magic = "ENC2"u8.ToArray();
private const byte SourcePassword = 1; private const byte SourcePassword = 1;
private const byte SourceLocalKey = 2; private const byte SourceLocalKey = 2;
@@ -502,7 +510,16 @@ public sealed class SecretStore
source = raw[4]; source = raw[4];
iterations = BinaryPrimitives.ReadInt32LittleEndian(raw.AsSpan(5, 4)); iterations = BinaryPrimitives.ReadInt32LittleEndian(raw.AsSpan(5, 4));
salt = raw.AsSpan(9, SaltSize).ToArray(); 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) private static bool TryDecrypt(byte[] raw, byte[] key, out Payload payload)
@@ -51,7 +51,6 @@ public sealed class BotSupervisor : IAsyncDisposable
private readonly BotConfig _config; private readonly BotConfig _config;
private readonly Func<BotConfig, bool, IEngine> _factory; private readonly Func<BotConfig, bool, IEngine> _factory;
private int _eventCapacity;
private IEngine? _engine; private IEngine? _engine;
private CancellationTokenSource? _engineCts; private CancellationTokenSource? _engineCts;
private Task? _engineTask; private Task? _engineTask;
@@ -95,7 +94,6 @@ public sealed class BotSupervisor : IAsyncDisposable
_config = config ?? throw new ArgumentNullException(nameof(config)); _config = config ?? throw new ArgumentNullException(nameof(config));
Versions = versions ?? new SectionVersions(); Versions = versions ?? new SectionVersions();
_factory = factory ?? ((c, confirmed) => new BasketEngine(c, null, confirmed, null, notifier, Versions)); _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); _offline.Changed = () => Versions.Bump(Section.Learning);
} }
@@ -134,12 +132,6 @@ public sealed class BotSupervisor : IAsyncDisposable
/// <summary>The section versions of the process: the supervisor bumps them all when an engine starts or stops (the source of every page changes).</summary> /// <summary>The section versions of the process: the supervisor bumps them all when an engine starts or stops (the source of every page changes).</summary>
public SectionVersions Versions { get; } public SectionVersions Versions { get; }
/// <summary>The lines the dashboard's activity strip keeps (<c>logging.statusLines</c>): a hint for the interface.</summary>
public int EventCapacity
{
get { lock (_gate) { return _eventCapacity; } }
}
/// <summary>The secret store's state and the ignored variables, merged into every snapshot (set by the host).</summary> /// <summary>The secret store's state and the ignored variables, merged into every snapshot (set by the host).</summary>
public Func<HostStatus>? HostStatusProvider { get; set; } public Func<HostStatus>? HostStatusProvider { get; set; }
@@ -165,15 +157,6 @@ public sealed class BotSupervisor : IAsyncDisposable
public void DetachLogSink() => Log.Sink = null; public void DetachLogSink() => Log.Sink = null;
/// <summary>How many lines the activity strip keeps (<c>logging.statusLines</c>, applied at once).</summary>
public void SetEventCapacity(int capacity)
{
lock (_gate)
{
_eventCapacity = Math.Max(20, capacity);
}
}
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// Lifecycle // Lifecycle
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -11,9 +11,10 @@ namespace Encelado.Engine;
/// basket, one entry waiting for its leg, two refused signals, an orphan and two foreign /// 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 /// 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 /// 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 /// can be developed and photographed as they will look. The baskets follow the strategy it
/// (a basket switched off in Impostazioni shows as disabled), everything else is /// is given — the factory one in <c>--sample</c>, which reads and writes no file of the
/// <see cref="SampleData"/>'s scenario anchored at <see cref="EpochUtc"/>. /// operator (5.1 review) —, everything else is <see cref="SampleData"/>'s scenario anchored
/// at <see cref="EpochUtc"/>.
/// </summary> /// </summary>
public sealed class SampleReadModel : IBotReadModel public sealed class SampleReadModel : IBotReadModel
{ {
@@ -98,5 +99,8 @@ public sealed class SampleReadModel : IBotReadModel
private static readonly Lazy<BasketStrategyConfig> Factory = new(static () => BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _)); private static readonly Lazy<BasketStrategyConfig> Factory = new(static () => BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _));
/// <summary>The factory strategy, parsed once and shared (read only): the sample's own.</summary>
public static BasketStrategyConfig FactoryStrategy => Factory.Value;
private static BasketStrategyConfig DefaultStrategy() => Factory.Value; private static BasketStrategyConfig DefaultStrategy() => Factory.Value;
} }
@@ -508,10 +508,10 @@ public static class SettingsCatalogue
"Superata questa dimensione il file viene ruotato: encelado.1.log, encelado.2.log e così via.")); "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, 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.")); "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, 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.")); "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, 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; return g;
} }
@@ -148,20 +148,40 @@ public sealed class SettingsRuntime
{ {
BotConfig file = ConfigFromFileOrMemory(); BotConfig file = ConfigFromFileOrMemory();
IReadOnlyList<SettingGroup> groups = SettingsCatalogue.Build(file, Strategy.Current()); IReadOnlyList<SettingGroup> groups = SettingsCatalogue.Build(file, Strategy.Current());
return Describe(ConfigPath, Strategy.Path, Version, Supervisor.State, Config.Run.Mode.Account(), Supervisor.IsRunning, groups, DescribeSecrets());
}
/// <summary>What every write of the settings and the secrets answers in <c>--sample</c>: nothing is saved, nothing is proved on eToro or Telegram.</summary>
public const string SampleRefusal = "modalità dimostrativa (--sample): le impostazioni e i segreti non vengono salvati";
/// <summary>
/// The answer of <c>GET /api/settings</c> for <c>--sample</c> (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.
/// </summary>
public static string DescribeSample(SecretsSummary secrets, BotState state, string account, long version)
{
ArgumentNullException.ThrowIfNull(secrets);
IReadOnlyList<SettingGroup> 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<SettingGroup> groups, SecretsSummary secrets)
{
using MemoryStream ms = new(); using MemoryStream ms = new();
using (Utf8JsonWriter w = new(ms)) using (Utf8JsonWriter w = new(ms))
{ {
w.WriteStartObject(); w.WriteStartObject();
w.WriteString("configPath", ConfigPath); w.WriteString("configPath", configPath);
w.WriteString("strategyPath", Strategy.Path); w.WriteString("strategyPath", strategyPath);
w.WriteNumber("version", Version); w.WriteNumber("version", version);
w.WriteStartObject("engine"); w.WriteStartObject("engine");
w.WriteString("state", Supervisor.State.ToString().ToLowerInvariant()); w.WriteString("state", state.ToString().ToLowerInvariant());
w.WriteString("account", Config.Run.Mode.Account()); w.WriteString("account", account);
w.WriteBoolean("running", Supervisor.IsRunning); w.WriteBoolean("running", running);
w.WriteEndObject(); w.WriteEndObject();
SettingsService.WriteGroups(w, groups); SettingsService.WriteGroups(w, groups);
SettingsService.WriteSecrets(w, "secrets", DescribeSecrets()); SettingsService.WriteSecrets(w, "secrets", secrets);
w.WriteEndObject(); w.WriteEndObject();
} }
@@ -305,7 +325,7 @@ public sealed class SettingsRuntime
saved = guarded ? FilesBefore.Read(ConfigPath, Strategy.Path) : FilesBefore.None; saved = guarded ? FilesBefore.Read(ConfigPath, Strategy.Path) : FilesBefore.None;
SettingsService.Write(ConfigPath, Strategy.Path, plan); 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}"); return Failure($"salvataggio non riuscito: {ex.Message}");
} }
@@ -519,8 +539,15 @@ public sealed class SettingsRuntime
Strategy.Invalidate(); Strategy.Invalidate();
Changed(); 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); _hooks.ReconfigureProcess?.Invoke(Config);
Supervisor.SetEventCapacity(Config.Logging.StatusLines);
if (changedPaths.Any(static p => p.StartsWith("notifications.", StringComparison.OrdinalIgnoreCase))) if (changedPaths.Any(static p => p.StartsWith("notifications.", StringComparison.OrdinalIgnoreCase)))
{ {
await ReconfigureNotifierAsync().ConfigureAwait(false); await ReconfigureNotifierAsync().ConfigureAwait(false);
@@ -98,7 +98,13 @@ public static class SettingsService
BasketStrategyConfig? strategy = null; BasketStrategyConfig? strategy = null;
try 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<string, JsonNode?> changes, List<string> deletions) = plan.TouchesConfig
? ConfigWrite(configPath, plan)
: (new Dictionary<string, JsonNode?>(StringComparer.Ordinal), new List<string>());
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) 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) if (plan.TouchesConfig)
{ {
List<string> deletions = [.. plan.ConfigDeletions, .. ConfigLoader.ObsoleteKeys.Where(k => ConfigWriter.Contains(configPath, k))];
try try
{ {
ConfigWriter.Apply(configPath, WithDocumentation(configPath, ConfigDefaults.Json, plan.ConfigChanges), deletions); (Dictionary<string, JsonNode?> changes, List<string> 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); throw new IOException($"strategy.json salvato, encelado.json NO: {ex.Message}", ex);
} }
} }
} }
/// <summary>
/// What a save writes to <c>encelado.json</c>, 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 <c>etoro.environment</c> leaves — the mode the file meant
/// (<see cref="ConfigLoader.RemoveObsoleteKeys"/>).
/// </summary>
public static (Dictionary<string, JsonNode?> Changes, List<string> Deletions) ConfigWrite(string configPath, SettingsPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
Dictionary<string, JsonNode?> changes = WithDocumentation(configPath, ConfigDefaults.Json, plan.ConfigChanges);
List<string> deletions = [.. plan.ConfigDeletions];
ConfigLoader.RemoveObsoleteKeys(configPath, changes, deletions);
return (changes, deletions);
}
/// <summary>The edits plus the documentation lines of the file that an older version wrote (<see cref="ConfigWriter.DocumentationUpdates"/>).</summary> /// <summary>The edits plus the documentation lines of the file that an older version wrote (<see cref="ConfigWriter.DocumentationUpdates"/>).</summary>
public static Dictionary<string, JsonNode?> WithDocumentation(string path, string factoryJson, IReadOnlyDictionary<string, JsonNode?> changes) public static Dictionary<string, JsonNode?> WithDocumentation(string path, string factoryJson, IReadOnlyDictionary<string, JsonNode?> changes)
{ {
+53 -15
View File
@@ -22,12 +22,13 @@ namespace Encelado.Server;
/// engine's lock. /// engine's lock.
/// <para> /// <para>
/// Arguments: <c>--health</c> (probe the running server and exit 0/1), <c>--sample</c> /// Arguments: <c>--health</c> (probe the running server and exit 0/1), <c>--sample</c>
/// (serve a sample snapshot, no market), <c>--no-autostart</c>, <c>--bonifica</c>, /// (serve sample data, no market, on throwaway folders: none of the operator's files, secrets or
/// <c>--minutes N</c>, <c>--port N</c>. Environment: <c>ENCELADO_PASSWORD</c> (the only /// Telegram bot is touched), <c>--no-autostart</c>, <c>--bonifica</c>, <c>--minutes N</c>,
/// setting a container needs; <c>ENCELADO_WEB_TOKEN</c> is its deprecated alias) and the /// <c>--port N</c>, <c>--listen-all</c> (with a password, the network outside the container too).
/// image's own <c>ENCELADO_WEB_PORT</c>, <c>ENCELADO_CONFIG_DIR</c>, <c>ENCELADO_DATA_DIR</c>. /// Environment: <c>ENCELADO_PASSWORD</c> (the only setting a container needs;
/// Everything else is set from the interface (5.1); Live never starts without a person /// <c>ENCELADO_WEB_TOKEN</c> is its deprecated alias) and the image's own <c>ENCELADO_WEB_PORT</c>,
/// typing the phrase there. /// <c>ENCELADO_CONFIG_DIR</c>, <c>ENCELADO_DATA_DIR</c>. Everything else is set from the
/// interface (5.1); Live never starts without a person typing the phrase there.
/// </para> /// </para>
/// </summary> /// </summary>
public static class Program public static class Program
@@ -41,6 +42,25 @@ public static class Program
InterfacePassword password = InterfacePassword.Resolve(Environment.GetEnvironmentVariable); 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; BotConfig config;
try try
{ {
@@ -76,7 +96,11 @@ public static class Program
Log.Warn($"password dell'interfaccia: {warning}"); 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"); bool bonifica = Has(args, "--bonifica");
int minutes = IntArg(args, "--minutes"); int minutes = IntArg(args, "--minutes");
int port = IntArg(args, "--port") is > 0 and var p ? p : WebHost.Port; 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); 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, 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 }, (c, confirmed) => new BasketEngine(c, secrets.Etoro(demo: !c.Run.Mode.IsLive()), confirmed, context, hub, versions) { OrphanPolicy = bonifica ? OrphanPolicy.Report : OrphanPolicy.Close },
hub, hub,
versions); versions);
hub.CommandHandler = new TelegramCommands(supervisor, () => hub.Status).HandleAsync; if (!sample)
await hub.ReconfigureAsync().ConfigureAwait(false); {
hub.CommandHandler = new TelegramCommands(supervisor, () => hub.Status).HandleAsync;
await hub.ReconfigureAsync().ConfigureAwait(false);
}
supervisor.EventLogged += buffer.Add; supervisor.EventLogged += buffer.Add;
supervisor.AttachLogSink(); supervisor.AttachLogSink();
@@ -158,14 +186,14 @@ public static class Program
buffer.Resize(c.Logging.BufferedLines); buffer.Resize(c.Logging.BufferedLines);
UiClock.Zone = c.Ui.ResolveTimeZone(out _); UiClock.Zone = c.Ui.ResolveTimeZone(out _);
}, },
ReconfigureNotifier = hub.ReconfigureAsync, ReconfigureNotifier = sample ? null : hub.ReconfigureAsync,
InvalidateHistory = () => InvalidateHistory = () =>
{ {
history.Invalidate(); history.Invalidate();
versions.Bump(Section.History); versions.Bump(Section.History);
versions.Bump(Section.Positions); versions.Bump(Section.Positions);
}, },
SendTelegramTest = hub.SendTestAsync, SendTelegramTest = sample ? null : hub.SendTestAsync,
}) })
{ {
Import = import, Import = import,
@@ -188,7 +216,10 @@ public static class Program
Telegram = hub.Describe, 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 try
{ {
await web.StartAsync().ConfigureAwait(false); await web.StartAsync().ConfigureAwait(false);
@@ -200,9 +231,11 @@ public static class Program
} }
// "in ascolto su <url>" is what VS Code's serverReadyAction waits for to open the browser. // "in ascolto su <url>" 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}/ (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(); using CancellationTokenSource stopping = new();
Console.CancelKeyPress += (_, e) => Console.CancelKeyPress += (_, e) =>
@@ -309,6 +342,11 @@ public static class Program
await Log.FlushAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); await Log.FlushAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
await Log.ShutdownAsync().ConfigureAwait(false); await Log.ShutdownAsync().ConfigureAwait(false);
if (sampleRoot is not null)
{
SampleFolders.Delete(sampleRoot);
}
return 0; return 0;
} }
@@ -0,0 +1,96 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
namespace Encelado.Server;
/// <summary>
/// The throwaway folders of <c>--sample</c> (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
/// <c>encelado.json</c>, 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.
/// </summary>
internal static class SampleFolders
{
public const string Prefix = "encelado-campione-";
/// <summary>Creates a pair under <paramref name="tempRoot"/> (the temp folder when null), after removing the leftovers of sample servers that no longer run; returns its root.</summary>
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");
/// <summary>Deletes a pair; one still held (the log file on Windows) is left for the next sample start.</summary>
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.
}
}
/// <summary>Removes the pairs whose sample server (the process number in the name) no longer runs.</summary>
internal static void RemoveLeftovers(string temp)
{
List<string> 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;
}
}
}
@@ -0,0 +1,143 @@
using System.Net;
using System.Net.Sockets;
namespace Encelado.Server.Web;
/// <summary>What a presented password got from <see cref="AuthBackoff.Check"/>.</summary>
internal enum AuthVerdict
{
/// <summary>Right: the request goes on and the address's count is cleared.</summary>
Ok = 0,
/// <summary>Wrong: counted; the answer waits <c>retryAfter</c>, and so does every password of the address.</summary>
Wrong,
/// <summary>Not checked at all: the address is still waiting after a wrong one.</summary>
Blocked,
}
/// <summary>
/// The price of a wrong password (5.1 review), the same for every way one arrives: the login form, the
/// <c>Authorization: Bearer</c> 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.
/// <para>
/// 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 <c>Retry-After</c>. 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).
/// </para>
/// </summary>
internal sealed class AuthBackoff(TimeProvider? time = null)
{
/// <summary>The longest wait after a wrong password.</summary>
public static readonly TimeSpan Longest = TimeSpan.FromSeconds(30);
/// <summary>After this long without a wrong password the address starts again from one second.</summary>
public static readonly TimeSpan Forget = TimeSpan.FromMinutes(10);
/// <summary>Addresses remembered at most; the ones forgotten (or the oldest) make room.</summary>
private const int MaxClients = 4_096;
private readonly TimeProvider _time = time ?? TimeProvider.System;
private readonly Lock _gate = new();
private readonly Dictionary<string, Entry> _clients = new(StringComparer.Ordinal);
private sealed class Entry
{
public int Failures { get; set; }
public DateTime LastFailureUtc { get; set; }
public DateTime WaitUntilUtc { get; set; }
}
/// <summary>The wait after the <paramref name="failures"/>-th wrong password in a row: 1, 2, 4, 8, 16, then 30 s.</summary>
public static TimeSpan Wait(int failures) =>
TimeSpan.FromSeconds(Math.Min(Longest.TotalSeconds, WebHost.FailedLoginDelay.TotalSeconds * Math.Pow(2, Math.Clamp(failures, 1, 16) - 1)));
/// <summary>
/// Checks one presented password of <paramref name="client"/> with <paramref name="proof"/> — unless the
/// address is still waiting, and then <paramref name="proof"/> is not called. <paramref name="retryAfter"/>
/// is how long the address waits from now (zero when right).
/// </summary>
public AuthVerdict Check(string client, Func<bool> 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;
}
}
/// <summary>The key of a client: its IPv4 address (an IPv4 mapped into IPv6 included), the /64 of an IPv6 one, <c>?</c> when unknown.</summary>
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);
}
}
}
@@ -1,5 +1,7 @@
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using Encelado.Core.Baskets;
using Encelado.Engine;
using Encelado.Engine.Settings; using Encelado.Engine.Settings;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http; 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 /// 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 /// Telegram, the secret store's unlock and reset, the restore of the factory file. Every
/// decision is <see cref="SettingsRuntime"/>'s; this is the HTTP skin around it. /// decision is <see cref="SettingsRuntime"/>'s; this is the HTTP skin around it.
/// <para>
/// In <c>--sample</c> (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.
/// </para>
/// </summary> /// </summary>
internal static class SettingsApi internal static class SettingsApi
{ {
public static void Map(WebApplication app, WebContext ctx) 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 => app.MapPost("/api/settings", async http =>
{ {
(Dictionary<string, string> edits, string? confirm) = await ReadEditsAsync(http).ConfigureAwait(false); SettingsResult r;
SettingsResult r = await ctx.Settings.ApplyAsync(edits, confirm, http.RequestAborted).ConfigureAwait(false); if (ctx.Sample)
{
r = new SettingsResult(false, SettingsRuntime.SampleRefusal, [], SettingsResult.RestartNone, new Dictionary<string, string>());
}
else
{
(Dictionary<string, string> 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 => await WriteAsync(http, r.HttpStatus, Json.Object(w =>
{ {
w.WriteBoolean("ok", r.Ok); w.WriteBoolean("ok", r.Ok);
@@ -50,39 +67,99 @@ internal static class SettingsApi
})).ConfigureAwait(false); })).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 => app.MapPost("/api/settings/keys", async http =>
{ {
if (await SampleRefusedAsync(http, ctx).ConfigureAwait(false))
{
return;
}
Dictionary<string, string> body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); Dictionary<string, string> body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false);
await SecretAsync(http, ctx, await ctx.Settings.SaveKeysAsync( 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); 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 => 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 => app.MapPost("/api/settings/telegram-token", async http =>
{ {
if (await SampleRefusedAsync(http, ctx).ConfigureAwait(false))
{
return;
}
Dictionary<string, string> body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); Dictionary<string, string> 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); 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 => 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 => 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 => app.MapPost("/api/settings/secrets/unlock", async http =>
{ {
if (await SampleRefusedAsync(http, ctx).ConfigureAwait(false))
{
return;
}
Dictionary<string, string> body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); Dictionary<string, string> 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); 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 => 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 => 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);
}
});
}
/// <summary>The settings page of <c>--sample</c>: the factory values with the sample's engine and secrets (no file is read).</summary>
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);
}
/// <summary>In <c>--sample</c>: answers the refusal (400) and says so; otherwise does nothing.</summary>
private static async Task<bool> 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) => private static Task SecretAsync(HttpContext http, WebContext ctx, SecretActionResult r) =>
@@ -69,6 +69,9 @@ internal sealed class TickWriter(WebContext ctx, Func<int> sseClients)
w.WriteString("displayCurrency", ctx.Config.Ui.DisplayCurrency); w.WriteString("displayCurrency", ctx.Config.Ui.DisplayCurrency);
w.WriteString("theme", ctx.Config.Ui.Theme); w.WriteString("theme", ctx.Config.Ui.Theme);
w.WriteBoolean("navExpanded", ctx.Config.Ui.NavExpanded); 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); WriteFx(w, v ?? status.LastView, now);
WriteBaskets(w, v, strategy, thresholds, now); WriteBaskets(w, v, strategy, thresholds, now);
WriteQuotes(w, v, now); WriteQuotes(w, v, now);
+192 -22
View File
@@ -62,7 +62,7 @@ public sealed class WebContext
/// <summary>A read model given by the caller (the tests); otherwise built from the members above.</summary> /// <summary>A read model given by the caller (the tests); otherwise built from the members above.</summary>
public IBotReadModel? ReadModel { get; init; } public IBotReadModel? ReadModel { get; init; }
/// <summary>Where every endpoint reads from: published pictures only (the sample's with <c>--sample</c>).</summary> /// <summary>Where every endpoint reads from: published pictures only (the sample's with <c>--sample</c>, on the factory strategy).</summary>
public IBotReadModel Read public IBotReadModel Read
{ {
get get
@@ -71,14 +71,14 @@ public sealed class WebContext
{ {
return _read ??= ReadModel return _read ??= ReadModel
?? (Sample ?? (Sample
? new SampleReadModel(Settings.Strategy.Current, StartedUtc) ? new SampleReadModel(null, StartedUtc)
: new LiveReadModel(Supervisor, Context, Telegram, Settings.DescribeSecrets)); : new LiveReadModel(Supervisor, Context, Telegram, Settings.DescribeSecrets));
} }
} }
} }
/// <summary><c>strategy.json</c> as the file says now (cached by time and size).</summary> /// <summary><c>strategy.json</c> as the file says now (cached by time and size); the factory strategy in <c>--sample</c>, which reads no file of the operator.</summary>
public BasketStrategyConfig Strategy() => Settings.Strategy.Current(); public BasketStrategyConfig Strategy() => Sample ? SampleReadModel.FactoryStrategy : Settings.Strategy.Current();
/// <summary>The stream's hub (set by <see cref="WebHost.Build"/>).</summary> /// <summary>The stream's hub (set by <see cref="WebHost.Build"/>).</summary>
internal SnapshotHub? Hub { get; set; } 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 /// container's only variable) is asked once on the login page; the browser then carries
/// the session cookie <c>encelado_session</c> — an HMAC derived from the password, never /// the session cookie <c>encelado_session</c> — an HMAC derived from the password, never
/// the password itself, so changing the password closes every session. Scripts may send /// the password itself, so changing the password closes every session. Scripts may send
/// <c>Authorization: Bearer &lt;password&gt;</c>. Every comparison is constant-time and a /// <c>Authorization: Bearer &lt;password&gt;</c>. Every comparison is constant-time, and a
/// wrong password costs a second. Without a password the server listens on localhost only /// wrong password — by the form, the header or the cookie — costs its address a wait that
/// and asks for nothing (development). /// doubles up to thirty seconds (<see cref="AuthBackoff"/>, 5.1 review). The network sees the
/// interface only in the container or with <c>--listen-all</c>, and only with a password;
/// without one the server is on localhost and asks for nothing (development).
/// </para>
/// <para>
/// Requests from elsewhere (5.1 review, <see cref="RequestGuard"/>): 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.
/// </para> /// </para>
/// <para> /// <para>
/// Load (5.1, decisions E1-E4): one tick per second built once for every client by the /// 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 string CookieName = "encelado_session";
public const int DefaultPort = 8080; public const int DefaultPort = 8080;
/// <summary>What a wrong password costs, so guessing it over the network is slow.</summary> /// <summary>What the first wrong password costs its address; each one after it in a row doubles it, up to <see cref="AuthBackoff.Longest"/>.</summary>
public static readonly TimeSpan FailedLoginDelay = TimeSpan.FromSeconds(1); public static readonly TimeSpan FailedLoginDelay = TimeSpan.FromSeconds(1);
/// <summary>The flag that opens the interface to the network outside the container (with a password only).</summary>
public const string ListenAllFlag = "--listen-all";
/// <summary>The placeholder the login page may carry: a wrong password replaces it with the message.</summary> /// <summary>The placeholder the login page may carry: a wrong password replaces it with the message.</summary>
public const string LoginErrorPlaceholder = "<!--login-error-->"; public const string LoginErrorPlaceholder = "<!--login-error-->";
public static int Port => int.TryParse(Environment.GetEnvironmentVariable(PortVariable), NumberStyles.Integer, CultureInfo.InvariantCulture, out int p) && p is > 0 and < 65536 ? p : DefaultPort; public static int Port => int.TryParse(Environment.GetEnvironmentVariable(PortVariable), NumberStyles.Integer, CultureInfo.InvariantCulture, out int p) && p is > 0 and < 65536 ? p : DefaultPort;
/// <summary>
/// Whether the server listens on every interface (5.1 review): only with a password, and only in the
/// container or with <see cref="ListenAllFlag"/>. 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.
/// </summary>
public static bool ListensOnTheNetwork(bool passwordSet, bool inContainer, bool listenAllFlag) => passwordSet && (inContainer || listenAllFlag);
/// <summary> /// <summary>
/// The session cookie's value for a password: <c>Base64Url(HMAC-SHA256(key = SHA-256("encelado/cookie/v1" ‖ password), "session"))</c>. /// The session cookie's value for a password: <c>Base64Url(HMAC-SHA256(key = SHA-256("encelado/cookie/v1" ‖ password), "session"))</c>.
/// </summary> /// </summary>
@@ -175,8 +192,10 @@ public static class WebHost
SampleLogFeeder.Start(ctx.Log, sample, app.Lifetime.ApplicationStopping); SampleLogFeeder.Start(ctx.Log, sample, app.Lifetime.ApplicationStopping);
} }
app.Use(Auth(password)); AuthBackoff backoff = new();
MapLogin(app, password); app.Use(RequestGuard(hasPassword: password.Length > 0));
app.Use(Auth(password, backoff));
MapLogin(app, password, backoff);
MapApi(app, ctx, hub); MapApi(app, ctx, hub);
SettingsApi.Map(app, ctx); SettingsApi.Map(app, ctx);
MapStatic(app); MapStatic(app);
@@ -193,7 +212,13 @@ public static class WebHost
path.StartsWith("/css/", StringComparison.Ordinal) || path.StartsWith("/css/", StringComparison.Ordinal) ||
path.StartsWith("/img/", StringComparison.Ordinal); path.StartsWith("/img/", StringComparison.Ordinal);
private static Func<HttpContext, RequestDelegate, Task> Auth(string password) /// <summary>
/// The session cookie or the Bearer password, checked through the address's <see cref="AuthBackoff"/>: 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).
/// </summary>
private static Func<HttpContext, RequestDelegate, Task> Auth(string password, AuthBackoff backoff)
{ {
string session = password.Length > 0 ? SessionValue(password) : string.Empty; string session = password.Length > 0 ? SessionValue(password) : string.Empty;
return async (http, next) => return async (http, next) =>
@@ -205,12 +230,25 @@ public static class WebHost
return; return;
} }
bool ok = (http.Request.Cookies.TryGetValue(CookieName, out string? cookie) && Constant(cookie, session)) string? cookie = http.Request.Cookies.TryGetValue(CookieName, out string? c) && c.Length > 0 ? c : null;
|| (http.Request.Headers.Authorization.ToString() is { Length: > 7 } auth && auth.StartsWith("Bearer ", StringComparison.Ordinal) && Constant(auth[7..].Trim(), password)); 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 (ok) if (cookie is not null || bearer is not null)
{ {
await next(http).ConfigureAwait(false); AuthVerdict verdict = backoff.Check(AuthBackoff.ClientKey(http.Connection.RemoteIpAddress),
return; () => (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)) if (path.StartsWith("/api/", StringComparison.Ordinal))
@@ -224,6 +262,129 @@ public static class WebHost
}; };
} }
/// <summary>429 while the address waits after a wrong password: JSON under <c>/api/</c>, the login page with the message elsewhere.</summary>
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
// -----------------------------------------------------------------------
/// <summary>The names of this computer: without a password the server answers no other Host.</summary>
private static readonly string[] LocalHosts = ["localhost", "127.0.0.1", "[::1]"];
/// <summary>
/// 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:
/// <list type="bullet">
/// <item>without a password, a Host other than <c>localhost</c>, <c>127.0.0.1</c> or <c>[::1]</c> gets 403
/// on every route (DNS rebinding: such a page sends its own name);</item>
/// <item>a request that changes something (any method but GET, HEAD, OPTIONS) gets 403 when the browser says
/// it comes from elsewhere (<c>Sec-Fetch-Site</c> other than <c>same-origin</c> or <c>none</c>) or its
/// <c>Origin</c> is another host or port; <c>/login</c> and <c>/logout</c>, plain forms, have the Origin
/// check only;</item>
/// <item>under <c>/api/</c> such a request must say <c>Content-Type: application/json</c>, 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.</item>
/// </list>
/// </summary>
private static Func<HttpContext, RequestDelegate, Task> 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);
};
/// <summary>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).</summary>
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;
}
/// <summary>
/// Whether an <c>Origin</c> names this server: its host and port against the request's Host, or against
/// <c>X-Forwarded-Host</c> 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; <c>null</c> and other schemes never match.
/// </summary>
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");
}
/// <summary>Equality in constant time, lengths included: both sides are hashed to the same size first.</summary> /// <summary>Equality in constant time, lengths included: both sides are hashed to the same size first.</summary>
private static bool Constant(string a, string b) private static bool Constant(string a, string b)
{ {
@@ -236,7 +397,7 @@ public static class WebHost
// Login, static files // 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 => 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. // "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(); 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) }); // The same backoff as the Bearer header and the cookie: one wait per address, whatever the door.
http.Response.Redirect("/"); switch (backoff.Check(AuthBackoff.ClientKey(http.Connection.RemoteIpAddress), () => Constant(given, password), out wait))
return; {
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; 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); 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);
}); });
+125 -1
View File
@@ -134,7 +134,7 @@ public abstract class ApiHostFixture : IAsyncLifetime
"closeForeignOnKill", "closeForeignOnKill",
"equity", "balance", "availableBalance", "usedMargin", "marginRatio", "peakEquity", "drawdownPct", "equityStopPct", "dailyLossPct", "dailyLossUsedPct", "dailyLossLatched", "equity", "balance", "availableBalance", "usedMargin", "marginRatio", "peakEquity", "drawdownPct", "equityStopPct", "dailyLossPct", "dailyLossUsedPct", "dailyLossLatched",
"cumulativeCashFlow", "todayPnl", "todayPnlPct", "todayPnlProvisional", "todayEquityChange", "dayStartEquity", "todayClosed", "openPnl", "accountOpenPnl", "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", "baskets", "quotes", "health", "learning", "nextEvent", "events", "eventsSeq", "versions",
]; ];
@@ -502,6 +502,64 @@ public sealed class SampleApiTests : ApiHostFixture
} }
} }
/// <summary>
/// --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.
/// </summary>
[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<string, System.Text.Json.Nodes.JsonNode?> { ["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] [Fact]
public async Task TheStoricoHasTheSampleHistory() public async Task TheStoricoHasTheSampleHistory()
{ {
@@ -558,6 +616,38 @@ public sealed class StoppedApiTests : ApiHostFixture
Assert.Equal("off", tick.GetProperty("health").GetProperty("telegram").GetString()); Assert.Equal("off", tick.GetProperty("health").GetProperty("telegram").GetString());
Assert.Equal("ombra-disabilitato", tick.GetProperty("learning").GetProperty("mode").GetString()); Assert.Equal("ombra-disabilitato", tick.GetProperty("learning").GetProperty("mode").GetString());
Assert.False(tick.GetProperty("alarms").GetProperty("liveNeedsConfirmation").GetBoolean()); Assert.False(tick.GetProperty("alarms").GetProperty("liveNeedsConfirmation").GetBoolean());
Assert.Equal(200, tick.GetProperty("statusLines").GetInt32());
}
/// <summary>
/// «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).
/// </summary>
[Fact]
public async Task TheDashboardStripFollowsTheLogSettingAtOnce()
{
Engine.Settings.SettingsResult r = await Context.Settings.ApplyAsync(new Dictionary<string, string> { ["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<string, string> { ["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<string, string> { ["logging.statusLines"] = "2500" }, null, CancellationToken.None);
Assert.False(tooMany.Ok);
Assert.True(tooMany.Errors.ContainsKey("logging.statusLines"));
ConfigWriter.Apply(Context.ConfigPath, new Dictionary<string, System.Text.Json.Nodes.JsonNode?> { ["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] [Fact]
@@ -592,6 +682,40 @@ public sealed class StoppedApiTests : ApiHostFixture
Assert.Equal("Encelado", system.RootElement.GetProperty("about").GetProperty("name").GetString()); Assert.Equal("Encelado", system.RootElement.GetProperty("about").GetProperty("name").GetString());
} }
/// <summary>
/// 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).
/// </summary>
[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);
}
/// <summary>A section that did not change answers 304 with no body (decision E2): the page keeps what it has.</summary> /// <summary>A section that did not change answers 304 with no body (decision E2): the page keeps what it has.</summary>
[Theory] [Theory]
[InlineData("/api/positions")] [InlineData("/api/positions")]
@@ -198,6 +198,73 @@ public sealed class EnvironmentImportTests : IDisposable
Assert.Contains(o.Notes, static n => n.Contains("rimandata", StringComparison.Ordinal)); Assert.Contains(o.Notes, static n => n.Contains("rimandata", StringComparison.Ordinal));
} }
/// <summary>
/// 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 <c>etoro.environment</c> leaves with the mode the file meant written
/// beside it, never a bare "Live" that would read as the real account (5.1 review).
/// </summary>
[Theory]
[InlineData("Live")]
[InlineData("LiveAuto")]
[InlineData("LiveApprove")]
public void TheImportKeepsAMerged50FileOnTheDemoAccount(string mode)
{
ConfigWriter.Apply(ConfigPath, new Dictionary<string, JsonNode?>
{
["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);
}
/// <summary>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).</summary>
[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<string, JsonNode?>
{
["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] [Fact]
public void SecretsWrittenInTheFileMoveToTheStoreAndLeaveTheFile() public void SecretsWrittenInTheFileMoveToTheStoreAndLeaveTheFile()
{ {
@@ -766,6 +766,29 @@ public sealed class LearningDiskReaderTests : TempFolderTests
Assert.NotEqual(emptyStamp, LearningDiskReader.Stamp(Paths, t.AddSeconds(3))); Assert.NotEqual(emptyStamp, LearningDiskReader.Stamp(Paths, t.AddSeconds(3)));
} }
/// <summary>
/// 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).
/// </summary>
[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] [Fact]
public void TheHeadlineOfAStoppedBotComesFromItsStateFile() public void TheHeadlineOfAStoppedBotComesFromItsStateFile()
{ {
@@ -1096,6 +1119,37 @@ public sealed class StoppedLearningApiTests : ApiHostFixture
Assert.NotEqual(etag, moved.Headers.ETag!.Tag); Assert.NotEqual(etag, moved.Headers.ETag!.Tag);
} }
/// <summary>
/// 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).
/// </summary>
[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<string, string> { ["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] [Fact]
public async Task EseguiCicloOnAStoppedBotIsAMaintenanceAndASecondOneIs409() public async Task EseguiCicloOnAStoppedBotIsAMaintenanceAndASecondOneIs409()
{ {
@@ -109,6 +109,44 @@ public sealed class SecretStoreTests : IDisposable
Assert.Equal(SecretStoreState.Locked, Open("password").State); Assert.Equal(SecretStoreState.Locked, Open("password").State);
} }
/// <summary>
/// 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).
/// </summary>
[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] [Fact]
public void WithoutAPasswordALocalKeyProtectsTheStoreAndMovesUnderThePasswordWhenOneAppears() public void WithoutAPasswordALocalKeyProtectsTheStoreAndMovesUnderThePasswordWhenOneAppears()
{ {
@@ -670,6 +670,87 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime
Assert.Contains("\"light\"", text, StringComparison.Ordinal); Assert.Contains("\"light\"", text, StringComparison.Ordinal);
} }
/// <summary>
/// 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 <c>etoro.environment</c> 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).
/// </summary>
[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<string, string> { ["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<string>());
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);
}
/// <summary>The same file with a restart-scoped field in the batch: the engine starts again on the demo account it was on.</summary>
[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<string, string> { ["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);
}
/// <summary>The control: a 5.0 Live file on the real account stays Live (the phrase still guards every start).</summary>
[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<string, string> { ["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] [Fact]
public async Task KeysAreProvedOnTheirOwnAccountAndTheActiveOnesRestartTheEngine() public async Task KeysAreProvedOnTheirOwnAccountAndTheActiveOnesRestartTheEngine()
{ {
+283 -5
View File
@@ -353,6 +353,9 @@ public sealed class WebHostTests : IAsyncLifetime
_supervisor = new BotSupervisor(config); _supervisor = new BotSupervisor(config);
_history = new HistoryService(config); _history = new HistoryService(config);
SecretStore secrets = new(_dir, Password, 1_000); 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() WebContext ctx = new()
{ {
Config = config, Config = config,
@@ -361,7 +364,7 @@ public sealed class WebHostTests : IAsyncLifetime
History = _history, History = _history,
ConfigPath = configPath, ConfigPath = configPath,
Settings = new Engine.Settings.SettingsRuntime(config, configPath, secrets, _supervisor), 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")), Start = static _ => Task.FromResult(new CommandResult(false, "non in questo test")),
Learn = 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; return req;
} }
/// <summary>A request that changes something, as the interface sends it: JSON, even without a body.</summary>
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] [Fact]
public async Task WithoutTheSessionTheApiSays401AndThePageRedirectsToLogin() public async Task WithoutTheSessionTheApiSays401AndThePageRedirectsToLogin()
{ {
@@ -450,13 +463,14 @@ public sealed class WebHostTests : IAsyncLifetime
withCookie.Headers.Add("Cookie", $"{WebHost.CookieName}={value}"); withCookie.Headers.Add("Cookie", $"{WebHost.CookieName}={value}");
Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(withCookie)).StatusCode); Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(withCookie)).StatusCode);
using FormUrlEncodedContent legacy = new([new KeyValuePair<string, string>("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"); HttpRequestMessage rawPassword = new(HttpMethod.Get, "/api/snapshot");
rawPassword.Headers.Add("Cookie", $"{WebHost.CookieName}={Password}"); rawPassword.Headers.Add("Cookie", $"{WebHost.CookieName}={Password}");
Assert.Equal(HttpStatusCode.Unauthorized, (await _client.SendAsync(rawPassword)).StatusCode); Assert.Equal(HttpStatusCode.Unauthorized, (await _client.SendAsync(rawPassword)).StatusCode);
using FormUrlEncodedContent legacy = new([new KeyValuePair<string, string>("token", Password)]);
Assert.Equal(HttpStatusCode.Redirect, (await _client.PostAsync("/login", legacy)).StatusCode);
HttpResponseMessage logout = await _client.PostAsync("/logout", null); HttpResponseMessage logout = await _client.PostAsync("/logout", null);
Assert.Equal(HttpStatusCode.Redirect, logout.StatusCode); Assert.Equal(HttpStatusCode.Redirect, logout.StatusCode);
Assert.Equal("/login", logout.Headers.Location?.ToString()); Assert.Equal("/login", logout.Headers.Location?.ToString());
@@ -483,6 +497,163 @@ public sealed class WebHostTests : IAsyncLifetime
Assert.False(refused.Headers.Contains("Set-Cookie")); Assert.False(refused.Headers.Contains("Set-Cookie"));
} }
/// <summary>
/// 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).
/// </summary>
[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<HttpResponseMessage> 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<string, string>("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));
}
/// <summary>
/// What another site's page can send without a preflight (a form, a no-cors fetch with text/plain) never
/// changes anything: under <c>/api/</c> a write must say <c>application/json</c> (415 otherwise, bodyless
/// DELETE included), and the browser's <c>Sec-Fetch-Site</c> or <c>Origin</c> naming another site is a
/// 403 before the password is even looked at (5.1 review).
/// </summary>
[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<string, string>("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);
}
/// <summary>The login and the logout are plain forms: only the Origin is checked, before the password.</summary>
[Fact]
public async Task AFormFromAnotherSiteCannotLogInOrOut()
{
HttpRequestMessage login = new(HttpMethod.Post, "/login") { Content = new FormUrlEncodedContent([new KeyValuePair<string, string>("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<string, string>("password", Password)]) };
own.Headers.Add("Origin", Origin);
Assert.Equal(HttpStatusCode.Redirect, (await _client.SendAsync(own)).StatusCode);
}
/// <summary>
/// The network sees the interface only in the container, or when asked with <c>--listen-all</c>, and only
/// with a password: F5 and run-dev keep the password for the secret store and stay on localhost (5.1 review).
/// </summary>
[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('[', ']'))));
}
/// <summary> /// <summary>
/// Every embedded file of the interface is served at its path with its type — the modules /// Every embedded file of the interface is served at its path with its type — the modules
/// as <c>text/javascript</c>, or the browser refuses them — and the shell's files need the /// as <c>text/javascript</c>, 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.False(secrets.GetProperty("etoro").GetProperty("live").GetProperty("present").GetBoolean());
Assert.Equal(JsonValueKind.Array, secrets.GetProperty("ignoredEnv").ValueKind); 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); 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); Assert.Contains("\"value\":\"07-16,20-22\"", after, StringComparison.Ordinal);
} }
} }
/// <summary>The price of a wrong password (5.1 review): per address, doubling from one second to thirty, shared by every way a password arrives.</summary>
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<double> 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));
}
}
/// <summary>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.</summary>
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));
}
}