Files
Anubis/src/Anubis.Server/Forms.cs
T
Alby96andClaude Opus 5.5 953ffe5e9b Add the Laboratorio screen: new test, report, comparison (refs #36)
The laboratory starts with the host (off in demo mode) and runs its
queue next to market data and trading. The page lists every trial with
status, verdict and headline figures, refreshing itself while one is
queued or running, and offers the form for a new test: strategy, data
origin and market, instruments, period, initial capital and the grid,
with the thresholds stated before the run. The form posts with the
antiforgery token; errors come back as a short code.

The report page shows the protocol checks, the chosen variant against
buy and hold (table and chart), results per year, cost sensitivity,
the Deflated Sharpe Ratio, PBO, walk-forward windows, purged CV paths,
the look-ahead result, every variant with its zone score, what the
backtest does not model, the data used and the trades. A comparison
page puts two finished tests side by side and says whether they read
the same data. The improvements of 8.7 and the cost estimates of 11.6
have their sections, empty until Phases 9 and 8.

The equity chart takes amounts in their own currency and its labels as
parameters. The profit factor has no value without a losing trade.

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

710 lines
32 KiB
C#

using Anubis.Access;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>
/// Form actions of the pages: plain HTML forms with the CSRF field, answered with a redirect (post, redirect, get).
/// Errors travel back as a short code in the address, never with the values typed in.
/// </summary>
internal static partial class Forms
{
public static void Map(WebApplication app)
{
var open = app.MapGroup("/azioni").AllowAnonymous();
open.MapPost("/accesso", SignInAsync);
open.MapPost("/primo-avvio/prova", TestDatabaseAsync);
open.MapPost("/primo-avvio", FirstRunAsync);
open.MapPost("/servizio/{choice}", ServiceChoiceAsync);
var signed = app.MapGroup("/azioni").RequireAuthorization();
signed.MapPost("/esci", SignOutAsync);
signed.MapPost("/primo-accesso", (IFormCollection form, AnubisHost host, StartupConfig config, HttpContext context, CancellationToken ct) =>
ChangePasswordAsync(form, host, context, config.AdminPassword, "/primo-accesso", "/", ct));
signed.MapPost("/password", (IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) =>
ChangePasswordAsync(form, host, context, null, "/impostazioni", "/impostazioni", ct));
signed.MapPost("/due-fattori/attiva", EnableSecondFactorAsync);
signed.MapPost("/due-fattori/disattiva", DisableSecondFactorAsync);
signed.MapPost("/impostazioni/{key}", SetSettingAsync);
signed.MapPost("/bot/{command}", BotAsync);
signed.MapPost("/salvataggio", BackupAsync);
signed.MapPost("/conti/{id:guid}/{choice}", ResolveAccountAsync);
signed.MapPost("/chiavi/{broker}", SaveKeysAsync);
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
signed.MapPost("/laboratorio", PlanTrialAsync);
}
private static string Back(IFormCollection form, string fallback)
{
var back = form["ritorno"].ToString();
return IsLocalPath(back) ? back : fallback;
}
/// <summary>
/// Only paths of this site: "/x" yes; "//other.site", "https://..." no; no backslash and no control characters,
/// which browsers drop or turn into "/" while reading an address ("/\t/other.site" becomes "//other.site").
/// </summary>
internal static bool IsLocalPath(string path) =>
path.StartsWith('/') && !path.StartsWith("//", StringComparison.Ordinal) && !path.Any(c => char.IsControl(c) || c == '\\');
private static string With(string path, string key, string value)
{
var hash = path.IndexOf('#', StringComparison.Ordinal);
var anchor = hash >= 0 ? path[hash..] : "";
var bare = hash >= 0 ? path[..hash] : path;
return bare + (bare.Contains('?', StringComparison.Ordinal) ? "&" : "?") + key + "=" + Uri.EscapeDataString(value) + anchor;
}
private static async Task<IResult> SignInAsync(IFormCollection form, AnubisHost host, LoginLimiter limiter, HttpContext context, CancellationToken ct)
{
var services = host.Services;
if (services is null)
{
return Results.Redirect("/");
}
var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto";
var back = Back(form, "/");
var wait = limiter.Begin(address);
if (wait > TimeSpan.Zero)
{
var minutes = Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes));
return Results.Redirect(With(With("/accesso", "errore", "attesa"), "minuti", minutes.ToString(System.Globalization.CultureInfo.InvariantCulture)));
}
var code = form["codice"].ToString();
var (result, token) = await services.Access.SignInAsync(form["password"].ToString(), code, context.Request.Headers.UserAgent.ToString(), address, ct)
.ConfigureAwait(false);
switch (result)
{
case LoginResult.Ok:
limiter.Succeeded(address);
SessionAuthentication.WriteCookie(context, token!);
return Results.Redirect(back);
case LoginResult.SecondFactorNeeded:
limiter.Forgive(address);
return Results.Redirect(With(With("/accesso", "fattore", "1"), "ritorno", back));
case LoginResult.WrongSecondFactor:
return Results.Redirect(With(With(With("/accesso", "fattore", "1"), "errore", "codice"), "ritorno", back));
default:
return Results.Redirect(With(With("/accesso", "errore", "password"), "ritorno", back));
}
}
private static async Task<IResult> SignOutAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
if (context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token) && host.Services is { } services)
{
await services.Access.SignOutAsync(token, ct).ConfigureAwait(false);
}
SessionAuthentication.ClearCookie(context);
return Results.Redirect("/accesso");
}
private static async Task<IResult> ChangePasswordAsync(IFormCollection form, AnubisHost host, HttpContext context, string? initial, string page, string done, CancellationToken ct)
{
if (host.IsDemo)
{
return Results.Redirect(With(page, "errore", "demo"));
}
var replacement = form["nuova"].ToString();
if (replacement != form["conferma"].ToString())
{
return Results.Redirect(With(page, "errore", "diverse"));
}
if (Passwords.Problem(replacement, initial) is not null)
{
return Results.Redirect(With(page, "errore", replacement.Length < Passwords.MinimumLength ? "corta" : "uguale"));
}
var ok = await host.Services!.Access.ChangePasswordAsync(CurrentUser.Id(context.User), form["attuale"].ToString(), replacement, CurrentUser.Session(context.User), ct)
.ConfigureAwait(false);
return Results.Redirect(ok ? With(done, "ok", "password") : With(page, "errore", "attuale"));
}
private static async Task<IResult> EnableSecondFactorAsync(IFormCollection form, AnubisHost host, SecondFactorDrafts drafts, HttpContext context, CancellationToken ct)
{
// The secret shown on the page stays on the server, tied to this session: it never travels in a form or an address.
var session = CurrentUser.Session(context.User);
if (host.IsDemo || drafts.Peek(session) is not { } secret)
{
return Results.Redirect("/impostazioni?errore=segreto#sicurezza");
}
var ok = await host.Services!.Access.EnableSecondFactorAsync(CurrentUser.Id(context.User), secret, form["codice"].ToString(), ct).ConfigureAwait(false);
if (ok)
{
drafts.Remove(session);
}
return Results.Redirect(ok ? "/impostazioni?ok=due-fattori#sicurezza" : "/impostazioni?errore=codice#sicurezza");
}
private static async Task<IResult> DisableSecondFactorAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var ok = !host.IsDemo && await host.Services!.Access.DisableSecondFactorAsync(CurrentUser.Id(context.User), form["password"].ToString(), form["codice"].ToString(), ct).ConfigureAwait(false);
return Results.Redirect(ok ? "/impostazioni?ok=due-fattori-tolti#sicurezza" : "/impostazioni?errore=attuale#sicurezza");
}
private static async Task<IResult> SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/impostazioni");
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null)
{
return Results.Redirect(With(back, "errore", "riunioni"));
}
var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false);
return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione"));
}
private static async Task<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/");
var (ok, _) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
return Results.Redirect(ok ? back : With(back, "errore", "bot"));
}
/// <summary>The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out.</summary>
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
private static async Task<IResult> ResolveAccountAsync(Guid id, string choice, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
{
if (choice is not ("allinea" or "escludi"))
{
return Results.Redirect("/conti?errore=scelta");
}
if (host.IsDemo || host.Services?.Trading is not { } trading || trading.ManagerOf(id) is not { } manager)
{
return Results.Redirect("/conti?errore=motore");
}
var state = await trading.Reconciler.StateAsync(id, ct).ConfigureAwait(false);
if (state.ModeReason == Anubis.Trading.Reconciler.KeyReason)
{
return Results.Redirect("/conti?errore=chiave");
}
if (!state.WaitsForUser(clock.UtcNow, trading.Reconciler.Grace))
{
// The choice exists only after the 15 minutes (SPEC 7.4): before, the difference may still explain itself.
return Results.Redirect("/conti?errore=presto");
}
await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude,
context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.Redirect("/conti?ok=" + choice);
}
/// <summary>
/// New practice keys for a broker (SPEC 13.5): asked to the broker first, kept only if they may trade and may not
/// withdraw (SPEC 2.2), saved encrypted, never shown again. The engine then restarts to use them.
/// </summary>
private static async Task<IResult> SaveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
{
return Results.Redirect(back + "?errore=conto#conti");
}
if (host.IsDemo || host.Services is not { Trading: { } trading } services)
{
return Results.Redirect(back + "?errore=motore#conti");
}
var fields = Anubis.Trading.TradingService.KeyFields(broker);
foreach (var (name, _) in fields)
{
if ((await services.Secrets.StatusAsync(name, ct).ConfigureAwait(false)).FromEnvironment)
{
return Results.Redirect(back + "?errore=ambiente#conti");
}
}
var values = fields.Select(f => form[f.Name].ToString().Trim()).ToList();
if (values.Any(v => v.Length == 0 || v.Length > 512))
{
return Results.Redirect(back + "?errore=chiavi-vuote#conti");
}
Anubis.Trading.KeyPermissions permissions;
try
{
permissions = await trading.TestKeysAsync(broker, values, ct).ConfigureAwait(false);
}
catch (Anubis.Trading.BrokerException)
{
return Results.Redirect(back + "?errore=chiavi-rifiutate#conti");
}
if (permissions.CanWithdraw)
{
return Results.Redirect(back + "?errore=prelievo#conti");
}
if (!permissions.CanTrade)
{
return Results.Redirect(back + "?errore=sola-lettura#conti");
}
var who = context.User.Identity?.Name ?? "utente";
for (var i = 0; i < fields.Count; i++)
{
await services.Secrets.SetAsync(fields[i].Name, values[i], who, ct).ConfigureAwait(false);
}
await host.RestartServicesAsync(ct).ConfigureAwait(false);
await WaitBrieflyAsync(host).ConfigureAwait(false);
return Results.Redirect(back + "?ok=chiavi#conti");
}
private static async Task<IResult> RemoveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca) || host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=conto#conti");
}
var who = context.User.Identity?.Name ?? "utente";
foreach (var (name, _) in Anubis.Trading.TradingService.KeyFields(broker))
{
await services.Secrets.RemoveAsync(name, who, ct).ConfigureAwait(false);
}
await host.RestartServicesAsync(ct).ConfigureAwait(false);
await WaitBrieflyAsync(host).ConfigureAwait(false);
return Results.Redirect(back + "?ok=chiavi-tolte#conti");
}
/// <summary>The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it.</summary>
private static async Task<IResult> SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
{
return Results.Redirect(back + "?errore=conto#conti");
}
if (host.IsDemo || host.Services?.Trading is not { } trading)
{
return Results.Redirect(back + "?errore=motore#conti");
}
if (ParseEuro(form["euro"].ToString()) is not { } amount || amount < 0m || amount > 100_000_000m)
{
return Results.Redirect(back + "?errore=importo#conti");
}
try
{
await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
}
catch (Anubis.Trading.CapitalException ex) when (ex.Message.StartsWith("Manca il cambio", StringComparison.Ordinal))
{
return Results.Redirect(back + "?errore=cambio#conti");
}
catch (Anubis.Trading.CapitalException)
{
return Results.Redirect(back + "?errore=capitale#conti");
}
return Results.Redirect(back + "?ok=capitale#conti");
}
/// <summary>
/// A new backtest trial (SPEC 12.2): the plan is written and queued at once, then the page of the trial follows it.
/// A field that cannot be read goes back as a code; the chosen strategy is kept, nothing typed travels in the address.
/// </summary>
private static async Task<IResult> PlanTrialAsync(IFormCollection form, AnubisHost host, CancellationToken ct)
{
var family = Anubis.Strategies.StrategyCatalog.Find(form["strategia"].ToString());
string Back(string code) => "/laboratorio?errore=" + code + (family is null ? "" : "&strategia=" + Uri.EscapeDataString(family.Id)) + "#nuovo";
if (host.IsDemo || host.Services?.Lab is not { } lab)
{
return Results.Redirect(Back("motore"));
}
if (family is null)
{
return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Strategy));
}
var source = form["origine"].ToString();
var venue = source == Anubis.Backtest.TrialSources.Research ? Anubis.Data.Venues.Binance : form["mercato"].ToString();
if (source == Anubis.Backtest.TrialSources.Database && venue is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
{
return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Source));
}
if (ParseDay(form["dal"].ToString()) is not { } from || ParseDay(form["al"].ToString()) is not { } to)
{
return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Dates));
}
if (ParseEuro(form["capitale"].ToString()) is not { } capital)
{
return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Capital));
}
var grid = new Dictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal);
foreach (var p in family.Parameters)
{
var text = form["griglia_" + p.Name].ToString();
if (string.IsNullOrWhiteSpace(text))
{
continue;
}
if (ParseList(text) is not { } values)
{
return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Grid));
}
grid[p.Name] = values;
}
var symbols = form["strumenti"].ToString()
.Split([',', ';', ' ', '\n', '\r', '\t'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(x => x.ToUpperInvariant())
.ToList();
try
{
var trial = await lab.PlanAsync(new Anubis.Backtest.TrialRequest(family.Id, source, venue, symbols, from, to, capital, grid), ct).ConfigureAwait(false);
return Results.Redirect("/laboratorio/" + trial.Id.ToString("D"));
}
catch (Anubis.Backtest.TrialRequestException ex)
{
return Results.Redirect(Back(ex.Code));
}
}
private static DateOnly? ParseDay(string text) =>
DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day) ? day : null;
/// <summary>Values of a grid as people type them: "10, 20, 30" or "10 20 30"; decimals with a point.</summary>
internal static IReadOnlyList<decimal>? ParseList(string text)
{
var result = new List<decimal>();
foreach (var item in (text ?? "").Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (!decimal.TryParse(item, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var value))
{
return null;
}
result.Add(value);
}
return result.Count is > 0 and <= 20 ? result : null;
}
/// <summary>An amount as people type it: "1500", "1.500", "1500,50", "1.500,50", "1500.50".</summary>
internal static decimal? ParseEuro(string text)
{
var clean = (text ?? "").Replace(" ", "", StringComparison.Ordinal).Replace("€", "", StringComparison.Ordinal);
if (clean.Contains(',', StringComparison.Ordinal))
{
clean = clean.Replace(".", "", StringComparison.Ordinal).Replace(',', '.');
}
else if (clean.LastIndexOf('.') is var dot and >= 0 && clean.Length - dot - 1 == 3)
{
clean = clean.Replace(".", "", StringComparison.Ordinal);
}
return decimal.TryParse(clean, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var value)
? Math.Round(value, 2, MidpointRounding.ToZero)
: null;
}
private static async Task<IResult> BackupAsync(IFormCollection form, AnubisHost host, ILogger<AnubisHost> logger, CancellationToken ct)
{
var services = host.Services!;
try
{
await services.Backups.TakeAsync(services.Db, "a-mano", ct).ConfigureAwait(false);
return Results.Redirect("/impostazioni?ok=salvataggio#sistema");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException)
{
LogBackupFailed(logger, ex);
return Results.Redirect("/impostazioni?errore=salvataggio#sistema");
}
}
// ---- Desktop first run (SPEC 15.6): only from the computer itself, only while the wizard is due. ----
private static DbSettings ReadDatabase(IFormCollection form, StartupConfig config)
{
if (form["motore"].ToString() != "postgres")
{
return new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = config.Data.SqliteFile };
}
return new DbSettings
{
Engine = DbEngine.Postgres,
Host = form["host"].ToString().Trim(),
Port = int.TryParse(form["porta"].ToString(), out var port) && port is > 0 and < 65536 ? port : 5432,
Database = string.IsNullOrWhiteSpace(form["nome"]) ? "anubis" : form["nome"].ToString().Trim(),
User = string.IsNullOrWhiteSpace(form["utente"]) ? "anubis" : form["utente"].ToString().Trim(),
Password = form["dbpassword"].ToString(),
};
}
/// <summary>Opens the database without creating anything and asks it one question.</summary>
private static async Task<string?> TryConnectAsync(DbSettings settings, CancellationToken ct)
{
if (settings.Engine == DbEngine.Postgres && string.IsNullOrWhiteSpace(settings.Host))
{
return "Manca l'indirizzo del server PostgreSQL.";
}
Redactor.Register(settings.Password);
try
{
await using var db = Database.Open(settings, allowCreate: settings.Engine == DbEngine.Sqlite);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(8));
await db.PingAsync(timeout.Token).ConfigureAwait(false);
return null;
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
return Redactor.Redact(ex.Message);
}
}
private static bool WizardAllowed(AnubisHost host, HttpContext context) =>
host.Status.Mode == HostMode.FirstRun && host.Config.Platform == PlatformKind.Desktop && CurrentUser.IsLocal(context);
private static async Task<IResult> TestDatabaseAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
if (!WizardAllowed(host, context))
{
return Endpoints.Error(StatusCodes.Status403Forbidden, "non_ammesso", "La procedura guidata si usa solo dal computer su cui gira Anubis, al primo avvio.");
}
var problem = await TryConnectAsync(ReadDatabase(form, host.Config), ct).ConfigureAwait(false);
return Results.Json(new { ok = problem is null, message = problem ?? "Connessione riuscita." });
}
private static async Task<IResult> FirstRunAsync(IFormCollection form, AnubisHost host, HttpContext context, ILogger<AnubisHost> logger, CancellationToken ct)
{
if (!WizardAllowed(host, context))
{
return Results.Redirect("/");
}
var password = form["password"].ToString();
if (password != form["conferma"].ToString())
{
return Results.Redirect("/primo-avvio?errore=diverse");
}
if (Passwords.Problem(password) is not null)
{
return Results.Redirect("/primo-avvio?errore=corta");
}
var config = host.Config;
if (!config.IsComplete)
{
var settings = ReadDatabase(form, config);
if (await TryConnectAsync(settings, ct).ConfigureAwait(false) is not null)
{
return Results.Redirect("/primo-avvio?errore=database");
}
// config.toml without the database password: that goes to the protected store (SPEC 15.6).
DesktopPlatform.WriteConfig(config.Data, ProtectedSecretKey.DefaultStore(config.Data), settings, config.Port, allowNetwork: false);
}
host.PendingPassword = password;
host.Wake();
try
{
await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(60)).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
LogFirstRunSlow(logger);
return Results.Redirect("/");
}
var (result, token) = await host.Services!.Access.SignInAsync(password, null, context.Request.Headers.UserAgent.ToString(),
context.Connection.RemoteIpAddress?.ToString(), ct).ConfigureAwait(false);
if (result == LoginResult.Ok)
{
SessionAuthentication.WriteCookie(context, token!);
}
return Results.Redirect("/");
}
// ---- Choices of the error page (SPEC 15.1): Docker asks the startup password, desktop only the computer itself. ----
private static async Task<IResult> ServiceChoiceAsync(string choice, IFormCollection form, AnubisHost host, IClock clock, LoginLimiter limiter,
HttpContext context, ILogger<AnubisHost> logger, CancellationToken ct)
{
var config = host.Config;
if (config.Platform == PlatformKind.Docker)
{
// The startup password, asked by a page anyone on the network can open: same attempt limit as the sign-in.
var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto";
if (limiter.Begin(address) > TimeSpan.Zero)
{
return Results.Redirect("/?errore=attesa");
}
if (!Endpoints.SameSecret(form["password"].ToString(), config.AdminPassword))
{
LogChoiceRefused(logger, choice);
return Results.Redirect("/?errore=password");
}
limiter.Succeeded(address);
}
else if (!CurrentUser.IsLocal(context))
{
return Results.Redirect("/?errore=password");
}
// The startup loop stays still until the choice is done and the installation renewed.
using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false);
var status = host.Status;
var db = host.Database;
if (status.Mode != HostMode.IdentityProblem || status.Identity is null || db is null)
{
return Results.Redirect("/");
}
var verdict = status.Identity.Verdict;
try
{
switch (choice)
{
case "ripristina" when verdict == IdentityVerdict.EmptyDatabase:
var backup = new Backups(config.Data, clock).List().FirstOrDefault(b => b.Name == form["salvataggio"].ToString());
if (backup is null)
{
return Results.Redirect("/?errore=scelta");
}
await Archive.ImportAsync(db, Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false);
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false);
break;
case "importa" when verdict == IdentityVerdict.EmptyDatabase:
var folder = ServiceChoices.ImportFolders(config.Data).FirstOrDefault(f => Path.GetFileName(f) == form["archivio"].ToString());
if (folder is null)
{
return Results.Redirect("/?errore=scelta");
}
await Archive.ImportAsync(db, folder, clock, ct).ConfigureAwait(false);
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false);
break;
case "da-capo" when verdict == IdentityVerdict.EmptyDatabase:
Installation.StartOver(config.Data, clock);
break;
case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase:
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: true, ct).ConfigureAwait(false);
break;
default:
return Results.Redirect("/?errore=scelta");
}
}
catch (Exception ex) when (IsArchiveProblem(ex))
{
LogChoiceFailed(logger, ex, choice);
return Results.Redirect("/?errore=importazione");
}
LogChoice(logger, choice);
// Reset while the loop is still held: released first, it could start the application again before the reset
// and then lose the services it had just built while showing "ready".
await host.ResetAsync().ConfigureAwait(false);
exclusive.Dispose();
await WaitBrieflyAsync(host).ConfigureAwait(false);
return Results.Redirect("/");
}
/// <summary>What a damaged or unsuitable archive throws: reported on the page, not as a crash.</summary>
internal static bool IsArchiveProblem(Exception ex) =>
ex is IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException or FormatException or OverflowException
or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException;
private static async Task WaitBrieflyAsync(AnubisHost host)
{
try
{
await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(10)).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
[LoggerMessage(Level = LogLevel.Error, Message = "Backup on request failed")]
private static partial void LogBackupFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Warning, Message = "First run: the application is not ready after 60 seconds")]
private static partial void LogFirstRunSlow(ILogger logger);
[LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} confirmed")]
private static partial void LogChoice(ILogger logger, string choice);
[LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} refused: wrong startup password")]
private static partial void LogChoiceRefused(ILogger logger, string choice);
[LoggerMessage(Level = LogLevel.Error, Message = "Error page choice {Choice} failed")]
private static partial void LogChoiceFailed(ILogger logger, Exception exception, string choice);
}
/// <summary>Second-factor secrets being set up, one per session, kept for 15 minutes.</summary>
internal sealed class SecondFactorDrafts(IClock clock)
{
private static readonly TimeSpan _life = TimeSpan.FromMinutes(15);
private readonly System.Collections.Concurrent.ConcurrentDictionary<Guid, (byte[] Secret, DateTimeOffset Until)> _drafts = new();
/// <summary>The draft of this session, or a new one.</summary>
public byte[] For(Guid session)
{
var now = clock.UtcNow;
foreach (var expired in _drafts.Where(d => d.Value.Until <= now).Select(d => d.Key).ToList())
{
_drafts.TryRemove(expired, out _);
}
return _drafts.AddOrUpdate(session, _ => (Totp.NewSecret(), now + _life), (_, d) => d.Until > now ? d : (Totp.NewSecret(), now + _life)).Secret;
}
public byte[]? Peek(Guid session) => _drafts.TryGetValue(session, out var d) && d.Until > clock.UtcNow ? d.Secret : null;
public void Remove(Guid session) => _drafts.TryRemove(session, out _);
}
/// <summary>What the error page can offer.</summary>
internal static class ServiceChoices
{
/// <summary>Archives under data/import, one folder each with its index.json.</summary>
public static IReadOnlyList<string> ImportFolders(DataDirectory data) =>
!Directory.Exists(data.Import)
? []
: Directory.EnumerateDirectories(data.Import).Where(d => File.Exists(Path.Combine(d, Archive.IndexFile))).Order(StringComparer.Ordinal).ToList();
}