using Anubis.Access;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Server;
///
/// 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.
///
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);
}
private static string Back(IFormCollection form, string fallback)
{
var back = form["ritorno"].ToString();
return IsLocalPath(back) ? back : fallback;
}
///
/// 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").
///
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 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 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 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 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 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 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)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
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 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"));
}
private static async Task BackupAsync(IFormCollection form, AnubisHost host, ILogger 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(),
};
}
/// Opens the database without creating anything and asks it one question.
private static async Task 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 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 FirstRunAsync(IFormCollection form, AnubisHost host, HttpContext context, ILogger 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 ServiceChoiceAsync(string choice, IFormCollection form, AnubisHost host, IClock clock, LoginLimiter limiter,
HttpContext context, ILogger 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("/");
}
/// What a damaged or unsuitable archive throws: reported on the page, not as a crash.
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);
}
/// Second-factor secrets being set up, one per session, kept for 15 minutes.
internal sealed class SecondFactorDrafts(IClock clock)
{
private static readonly TimeSpan _life = TimeSpan.FromMinutes(15);
private readonly System.Collections.Concurrent.ConcurrentDictionary _drafts = new();
/// The draft of this session, or a new one.
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 _);
}
/// What the error page can offer.
internal static class ServiceChoices
{
/// Archives under data/import, one folder each with its index.json.
public static IReadOnlyList ImportFolders(DataDirectory data) =>
!Directory.Exists(data.Import)
? []
: Directory.EnumerateDirectories(data.Import).Where(d => File.Exists(Path.Combine(d, Archive.IndexFile))).Order(StringComparer.Ordinal).ToList();
}