Files
Alby96andClaude Opus 5.5 f9d71559e8
ci / test (postgres) (push) Successful in 2m22s
ci / test (sqlite) (push) Failing after 2m27s
ci / image (push) Skipped
feat(server): web server, interface shell, demo mode and Docker image (refs #11 #12 #13 #14 #15 #16 #17)
Phase 1 completed on top of the library foundations:
- Server: startup state machine (config, first run, database down, schema,
  identity, ready) with an error page that retries by itself; the configured
  database is the only one ever opened, and a vanished SQLite file is never
  recreated. REST API and status WebSocket; session cookie auth, CSRF on
  every form and write call; desktop and demo answer only the computer itself.
- Interface: static Blazor rendering with plain forms (no interactive
  runtime), menu, top bar and phone bottom bar as in the mockups, light and
  dark themes with appendix C tokens and a contrast test, Panoramica, Diario,
  Rischio, Impostazioni; service pages for sign-in, first access, desktop
  first run and the database error page with its choices.
- Demo mode (tasks seed-demo): appendix F in a database of its own under the
  temp folder, frozen clock, never touches the configured installation.
- Docker: entrypoint gives /data to PUID:PGID and drops root with setpriv,
  HEALTHCHECK through bash /dev/tcp; proven with SQLite, PostgreSQL, a wrong
  configuration and a database that goes away and comes back.
- tasks screenshots drives the installed Edge/Chrome through DevTools for
  exact 1440 and 390 pixel shots; anubis db export|import on the command line.

Fixes from the independent review: return paths without control characters,
Host check against DNS rebinding, attempt limit counted before the check and
also on the error-page password, one-use TOTP codes and a code to switch the
second factor off, error-page choices serialized with the startup loop,
identity checked before migrating, restore restarts with "Ferma tutto" on,
damaged archives reported instead of crashing. Running the server tests on
PostgreSQL exposed pages rendered before their data arrived; data-loading
components now load first (LoadedComponent).

Decisions in ADR 0007. Tests: 100 on SQLite and on PostgreSQL.

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

454 lines
22 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Net.WebSockets;
using System.Text;
using Anubis.Core;
using Anubis.Db;
using Anubis.Demo;
using Anubis.Platform;
using Anubis.Server;
namespace Anubis.Tests;
[TestClass]
[TestCategory(Category.Integration)]
public sealed class ServerTests
{
[TestMethod]
public async Task SignInFirstAccessAndApi()
{
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
await using var engine = postgres;
await using var server = await ServerHarness.StartAsync("docker", env);
// A return address that leaves the site never reaches the form.
StringAssert.Contains(await server.TextAsync("/accesso?ritorno=%2F%09%2Fevil.example"), "name=\"ritorno\" value=\"/\"");
// Without a session: pages go to sign-in, the API answers 401.
using (var page = await server.GetAsync("/"))
{
Assert.AreEqual(HttpStatusCode.Redirect, page.StatusCode);
StringAssert.StartsWith(ServerHarness.Location(page), "/accesso");
}
using (var api = await server.GetAsync("/api/status"))
{
Assert.AreEqual(HttpStatusCode.Unauthorized, api.StatusCode);
}
// Wrong password: back to the form with the reason.
using (var wrong = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", "not-the-password")))
{
StringAssert.Contains(ServerHarness.Location(wrong), "errore=password");
}
// A form without the CSRF field is refused.
using (var noCsrf = await server.Http.PostAsync(new Uri("/azioni/accesso", UriKind.Relative),
new FormUrlEncodedContent([new("password", ServerHarness.AdminPassword)])))
{
Assert.AreEqual(HttpStatusCode.BadRequest, noCsrf.StatusCode);
}
// The initial password lets in only to change it.
using (var login = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", ServerHarness.AdminPassword)))
{
Assert.AreEqual("/", ServerHarness.Location(login));
var cookie = login.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith("anubis_session=", StringComparison.Ordinal));
StringAssert.Contains(cookie, "httponly");
StringAssert.Contains(cookie, "samesite=strict");
}
using (var forced = await server.GetAsync("/"))
{
Assert.AreEqual("/primo-accesso", ServerHarness.Location(forced));
}
using (var same = await server.PostFormAsync("/primo-accesso", "/azioni/primo-accesso",
("attuale", ServerHarness.AdminPassword), ("nuova", ServerHarness.AdminPassword), ("conferma", ServerHarness.AdminPassword)))
{
StringAssert.Contains(ServerHarness.Location(same), "errore=uguale");
}
const string chosen = "chosen-test-pass-2";
using (var change = await server.PostFormAsync("/primo-accesso", "/azioni/primo-accesso",
("attuale", ServerHarness.AdminPassword), ("nuova", chosen), ("conferma", chosen)))
{
Assert.AreEqual("/?ok=password", ServerHarness.Location(change));
}
var home = await server.TextAsync("/");
StringAssert.Contains(home, "Panoramica");
StringAssert.Contains(home, "Simulazione: nessun soldo reale");
StringAssert.Contains(home, "Ancora nessun risultato", "Production never shows invented numbers.");
// API: reading works, writing needs the CSRF header.
var status = await server.Http.GetFromJsonAsync<Dictionary<string, object>>(new Uri("/api/status", UriKind.Relative));
Assert.AreEqual("Ready", status!["mode"].ToString());
using (var noHeader = await server.Http.PutAsJsonAsync(new Uri("/api/settings/appearance.theme", UriKind.Relative), new { value = "dark" }))
{
Assert.AreEqual(HttpStatusCode.BadRequest, noHeader.StatusCode);
}
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
using (var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/appearance.theme", UriKind.Relative)) { Content = JsonContent.Create(new { value = "dark" }) })
{
request.Headers.Add(csrf!["header"], csrf["token"]);
using var put = await server.Http.SendAsync(request);
Assert.AreEqual(HttpStatusCode.NoContent, put.StatusCode);
}
StringAssert.Contains(await server.TextAsync("/"), "data-theme=\"dark\"");
// Secrets: status only, never the value.
var secret = await server.TextAsync("/api/secrets/ALPACA_API_KEY");
StringAssert.Contains(secret, "\"isSet\":false");
// Pause, resume, stop; resume never undoes "Ferma tutto".
Assert.AreEqual("paused", await BotAsync(server, csrf, "pause"));
Assert.AreEqual("active", await BotAsync(server, csrf, "resume"));
Assert.AreEqual("stopped", await BotAsync(server, csrf, "stop"));
Assert.IsNull(await BotAsync(server, csrf, "resume"));
// Sign out ends the session.
using (var bye = await server.PostFormAsync("/impostazioni", "/azioni/esci"))
{
Assert.AreEqual("/accesso", ServerHarness.Location(bye));
}
using var after = await server.GetAsync("/api/status");
Assert.AreEqual(HttpStatusCode.Unauthorized, after.StatusCode);
}
private static async Task<string?> BotAsync(ServerHarness server, Dictionary<string, string> csrf, string command)
{
using var request = new HttpRequestMessage(HttpMethod.Post, new Uri("/api/bot/" + command, UriKind.Relative));
request.Headers.Add(csrf["header"], csrf["token"]);
using var response = await server.Http.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
return null;
}
var body = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
return body!["state"];
}
[TestMethod]
[DataRow("/impostazioni#aspetto", true)]
[DataRow("/?periodo=30", true)]
[DataRow("//evil.example", false)]
[DataRow("/\\evil.example", false)]
[DataRow("/\t/evil.example", false)]
[DataRow("/a\nb", false)]
[DataRow("https://evil.example", false)]
[DataRow("", false)]
public void ReturnAddressesStayOnTheSite(string path, bool local) => Assert.AreEqual(local, Forms.IsLocalPath(path));
[TestMethod]
public async Task ComputerOnlyModesRefuseForeignHostNames()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
using (var mine = await server.GetAsync("/api/me"))
{
Assert.AreEqual(HttpStatusCode.OK, mine.StatusCode);
}
// DNS rebinding: a page whose name now points at 127.0.0.1 arrives from the loopback with its own Host.
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri("/api/me", UriKind.Relative));
request.Headers.Host = "evil.example:" + server.BaseAddress.Port.ToString(System.Globalization.CultureInfo.InvariantCulture);
using var foreign = await server.Http.SendAsync(request);
Assert.AreEqual(HttpStatusCode.Forbidden, foreign.StatusCode);
TempFolder.Delete(demoRoot);
}
[TestMethod]
public async Task RestoreFromTheErrorPageRestartsWithEverythingStopped()
{
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
await using var engine = postgres;
var data = TempFolder.Create("restore");
await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data))
{
await first.SignInFirstTimeAsync();
using var saved = await first.PostFormAsync("/impostazioni", "/azioni/salvataggio");
Assert.AreEqual("/impostazioni?ok=salvataggio#sistema", ServerHarness.Location(saved));
}
var backup = new Backups(new DataDirectory(data), new ManualClock(DemoMode.Now)).List().Single(b => b.Reason == "a-mano");
// An empty database takes the place of the real one; the data folder still belongs to the installation.
await using var empty = postgres is null ? null : await TestDb.CreateAsync(DbEngine.Postgres);
if (empty is null)
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
var file = new DataDirectory(data).SqliteFile;
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!))
{
File.Delete(f);
}
await File.WriteAllBytesAsync(file, []);
}
else
{
ServerHarness.UsePostgres(env, empty);
}
await using var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false);
await server.WaitForAsync(HostMode.IdentityProblem);
Assert.AreEqual(IdentityVerdict.EmptyDatabase, server.Host.Status.Identity!.Verdict);
using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name)))
{
Assert.AreEqual("/", ServerHarness.Location(restore));
}
await server.WaitForAsync(HostMode.Ready);
// SPEC 15.1: back with "Ferma tutto" on, a new fingerprint, and nobody signed in.
var state = await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key);
Assert.AreEqual("stopped", state.Value);
var row = await Installation.ReadRowAsync(server.Host.Services.Db);
Assert.IsTrue(row!.ProtectedRestart);
Assert.AreEqual(row.Fingerprint, Installation.ReadFile(new DataDirectory(data))!.Fingerprint);
Assert.AreEqual(0, await server.Host.Services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions")));
TempFolder.Delete(data);
}
[TestMethod]
public async Task MissingConfigurationShowsTheErrorPageAndCreatesNoDatabase()
{
var env = ServerHarness.DockerSqlite();
env.Remove("ANUBIS_DB_ENGINE");
await using var server = await ServerHarness.StartAsync("docker", env, waitReady: false);
await server.WaitForAsync(HostMode.ConfigProblem);
using var page = await server.GetAsync("/qualsiasi/pagina");
var html = WebUtility.HtmlDecode(await page.Content.ReadAsStringAsync());
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, page.StatusCode);
StringAssert.Contains(html, "Manca qualcosa nella configurazione d'avvio");
StringAssert.Contains(html, "ANUBIS_DB_ENGINE");
using var health = await server.GetAsync("/health");
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, health.StatusCode);
// Trap 20: no database appears anywhere in the data folder.
Assert.IsEmpty(Directory.EnumerateFiles(server.DataDir, "*.sqlite3*", SearchOption.AllDirectories).ToList());
}
[TestMethod]
public async Task DetachedDatabaseShowsTheErrorPageAndTheAppResumesAlone()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var file = new DataDirectory(server.DataDir).SqliteFile;
var away = file + ".altrove";
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
File.Move(file, away);
await server.WaitForAsync(HostMode.DatabaseUnavailable);
using (var page = await server.GetAsync("/"))
{
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, page.StatusCode);
StringAssert.Contains(WebUtility.HtmlDecode(await page.Content.ReadAsStringAsync()), "Il database non risponde");
}
Assert.IsFalse(File.Exists(file), "No new empty database while the real one is away.");
File.Move(away, file);
await server.WaitForAsync(HostMode.Ready);
using var back = await server.GetAsync("/");
Assert.AreEqual(HttpStatusCode.OK, back.StatusCode, "Same session, no restart.");
}
[TestMethod]
public async Task EmptyDatabaseOfAKnownInstallationAsksTheUser()
{
var data = TempFolder.Create("identity");
await using (var first = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data))
{
await first.Http.GetAsync(new Uri("/health", UriKind.Relative));
}
// The database is replaced by an empty one; the data folder still belongs to the installation.
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
var file = new DataDirectory(data).SqliteFile;
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!))
{
File.Delete(f);
}
await File.WriteAllBytesAsync(file, []);
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data, waitReady: false);
await server.WaitForAsync(HostMode.IdentityProblem);
var html = await server.TextAsync("/");
StringAssert.Contains(html, "Il database è vuoto");
StringAssert.Contains(html, "Comincia da capo");
using (var wrong = await server.PostFormAsync("/", "/azioni/servizio/da-capo", ("password", "wrong-password-123")))
{
StringAssert.Contains(ServerHarness.Location(wrong), "errore=password");
}
Assert.AreEqual(HostMode.IdentityProblem, server.Host.Status.Mode);
using (var ok = await server.PostFormAsync("/", "/azioni/servizio/da-capo", ("password", ServerHarness.AdminPassword)))
{
Assert.AreEqual("/", ServerHarness.Location(ok));
}
await server.WaitForAsync(HostMode.Ready);
Assert.IsNotEmpty(Directory.EnumerateFiles(data, "installation.json.precedente-*").ToList(), "The old identity is set aside, not deleted.");
}
[TestMethod]
public async Task DesktopStartsFromAnEmptyFolderAndKeepsTheKeyOutOfConfig()
{
await using var server = await ServerHarness.StartAsync("desktop", new Dictionary<string, string?>(), waitReady: false);
await server.WaitForAsync(HostMode.FirstRun);
using (var redirect = await server.GetAsync("/"))
{
Assert.AreEqual("/primo-avvio", ServerHarness.Location(redirect));
}
const string password = "fake-desktop-pass-3";
using (var done = await server.PostFormAsync("/primo-avvio", "/azioni/primo-avvio", ("motore", "sqlite"), ("password", password), ("conferma", password)))
{
Assert.AreEqual("/", ServerHarness.Location(done));
}
Assert.AreEqual(HostMode.Ready, server.Host.Status.Mode);
using (var home = await server.GetAsync("/"))
{
Assert.AreEqual(HttpStatusCode.OK, home.StatusCode, "Signed in by the wizard.");
}
var data = new DataDirectory(server.DataDir);
Assert.IsTrue(File.Exists(data.SqliteFile));
var config = await File.ReadAllTextAsync(data.ConfigFile);
StringAssert.Contains(config, "engine = \"sqlite\"");
StringAssert.Contains(config, "allow_live = false");
Assert.IsFalse(System.Text.RegularExpressions.Regex.IsMatch(config, @"^\s*\w*(secret|key|password)\w*\s*=", System.Text.RegularExpressions.RegexOptions.Multiline),
"Neither the secret key nor a password goes into config.toml.");
Assert.IsNotEmpty(Directory.EnumerateFiles(Path.Combine(data.Root, "keys")).ToList());
}
[TestMethod]
public async Task DemoModeNeverTouchesTheConfiguredDatabase()
{
// A real installation with its database, then the demo started with the same configuration.
var configured = TempFolder.Create("configured");
await using (var real = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: configured))
{
await real.SignInFirstTimeAsync();
}
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
var before = Snapshot(configured);
Assert.IsTrue(before.Keys.Any(k => k.EndsWith(".sqlite3", StringComparison.Ordinal)));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: configured, extraArgs: ["--demo"]);
// Its own folder under the temporary directory, the configured one untouched.
var demoRoot = server.Host.Config.Data.Root;
StringAssert.StartsWith(demoRoot, Path.Combine(Path.GetTempPath(), "anubis-demo"));
// Appendix F on screen, frozen clock, signed in by itself, the footer says it.
var html = await server.TextAsync("/");
StringAssert.Contains(html, "+412,46 €");
StringAssert.Contains(html, "Venerdì 9 ottobre 2026, ore 08:21");
StringAssert.Contains(html, "Sorveglio 10 posizioni, ognuna con il suo stop.");
StringAssert.Contains(html, "Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio.");
// The live status arrives over the WebSocket.
using var socket = new ClientWebSocket();
await socket.ConnectAsync(new Uri(server.BaseAddress.ToString().Replace("http", "ws", StringComparison.Ordinal) + "ws"), CancellationToken.None);
var buffer = new byte[4096];
var received = await socket.ReceiveAsync(buffer, CancellationToken.None);
var message = Encoding.UTF8.GetString(buffer, 0, received.Count);
StringAssert.Contains(message, "\"type\":\"status\"");
StringAssert.Contains(message, "\"bot\":\"active\"");
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
var after = Snapshot(configured);
CollectionAssert.AreEquivalent(before.Keys.ToList(), after.Keys.ToList(), "No file added or removed in the configured data folder.");
foreach (var (name, hash) in before)
{
Assert.AreEqual(hash, after[name], name + " changed");
}
TempFolder.Delete(demoRoot);
TempFolder.Delete(configured);
}
private static Dictionary<string, string> Snapshot(string folder) =>
Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).ToDictionary(
f => Path.GetRelativePath(folder, f),
f => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(f))),
StringComparer.Ordinal);
[TestMethod]
public async Task DemoSeedRefusesAnyOtherDatabase()
{
var demo = DemoMode.CreateFolder(new Anubis.Core.SystemClock());
var elsewhere = TempFolder.Create("elsewhere");
await using var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = Path.Combine(elsewhere, "x.sqlite3") });
await Migrations.MigrateAsync(db, new ManualClock(DemoMode.Now), null, CancellationToken.None);
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => DemoMode.SeedAsync(db, demo, new ManualClock(DemoMode.Now)));
TempFolder.Delete(elsewhere);
TempFolder.Delete(demo.Root);
}
[TestMethod]
public async Task HealthChecksDatabaseAndScheduler()
{
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
await using var engine = postgres;
await using var server = await ServerHarness.StartAsync("docker", env);
var health = await server.Http.GetFromJsonAsync<HealthResponse>(new Uri("/health", UriKind.Relative));
Assert.AreEqual("ok", health!.Status);
Assert.AreEqual("ok", health.Checks!["database"]);
Assert.AreEqual("ok", health.Checks["scheduler"]);
}
[TestMethod]
public async Task SecurityHeadersAndLogoFromTheDesignFolder()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
using var logo = await server.GetAsync("/brand/anubis.svg");
Assert.AreEqual(HttpStatusCode.OK, logo.StatusCode);
var served = await logo.Content.ReadAsByteArrayAsync();
CollectionAssert.AreEqual(await File.ReadAllBytesAsync(Path.Combine(Repo.Root.FullName, "docs", "design", "logo", "anubis.svg")), served);
Assert.Contains("frame-ancestors 'none'", logo.Headers.GetValues("Content-Security-Policy").Single());
Assert.AreEqual("nosniff", logo.Headers.GetValues("X-Content-Type-Options").Single());
}
[TestMethod]
public async Task DatabaseCommandExportsAndImports()
{
var data = TempFolder.Create("cli");
var env = ServerHarness.DockerSqlite();
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data))
{
await server.SignInFirstTimeAsync();
}
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
var archive = Path.Combine(TempFolder.Create("cli-archive"), "archivio");
using var output = new StringWriter();
Assert.AreEqual(0, await DatabaseCommand.RunAsync(["export", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString());
var target = TempFolder.Create("cli-target");
Assert.AreEqual(0, await DatabaseCommand.RunAsync(["import", archive, "--platform", "docker", "--data-dir", target], output, env), output.ToString());
StringAssert.Contains(output.ToString(), "conteggi e totali coincidono");
Assert.IsTrue(File.Exists(new DataDirectory(target).InstallationFile));
// Import only into an empty database.
Assert.AreEqual(1, await DatabaseCommand.RunAsync(["import", archive, "--platform", "docker", "--data-dir", target], output, env));
TempFolder.Delete(data);
TempFolder.Delete(target);
TempFolder.Delete(Path.GetDirectoryName(archive)!);
}
}