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>
167 lines
6.7 KiB
C#
167 lines
6.7 KiB
C#
using System.Net;
|
|
using System.Text.RegularExpressions;
|
|
using Anubis.Server;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace Anubis.Tests;
|
|
|
|
/// <summary>
|
|
/// The real server on a free local port, with a fake environment and its own data folder: never %APPDATA%, never
|
|
/// the developer's database. A cookie-keeping client that does not follow redirects, so tests see each step.
|
|
/// </summary>
|
|
internal sealed partial class ServerHarness : IAsyncDisposable
|
|
{
|
|
public const string AdminPassword = "fake-initial-pass-1";
|
|
public const string SecretKey = "fake-secret-key-0123456789-abcdefghij";
|
|
|
|
private readonly WebApplication _app;
|
|
|
|
private bool _ownsData;
|
|
|
|
private ServerHarness(WebApplication app, string dataDir, CookieContainer cookies, HttpClient http)
|
|
{
|
|
_app = app;
|
|
DataDir = dataDir;
|
|
Cookies = cookies;
|
|
Http = http;
|
|
}
|
|
|
|
public string DataDir { get; }
|
|
|
|
public CookieContainer Cookies { get; }
|
|
|
|
public HttpClient Http { get; }
|
|
|
|
public Uri BaseAddress => Http.BaseAddress!;
|
|
|
|
internal AnubisHost Host => _app.Services.GetRequiredService<AnubisHost>();
|
|
|
|
/// <summary>Docker configuration with SQLite in the data folder: what most tests need.</summary>
|
|
public static Dictionary<string, string?> DockerSqlite() => new(StringComparer.Ordinal)
|
|
{
|
|
["ANUBIS_DB_ENGINE"] = "sqlite",
|
|
["ANUBIS_SECRET_KEY"] = SecretKey,
|
|
["ANUBIS_ADMIN_PASSWORD"] = AdminPassword,
|
|
["TZ"] = "Europe/Rome",
|
|
};
|
|
|
|
/// <summary>
|
|
/// Docker configuration on the engine of this run (ANUBIS_TEST_DB): SQLite in the data folder, or a new PostgreSQL
|
|
/// database that the caller disposes.
|
|
/// </summary>
|
|
public static async Task<(Dictionary<string, string?> Env, TestDb? Postgres)> DockerOnEngineAsync()
|
|
{
|
|
var env = DockerSqlite();
|
|
if (TestDatabase.Engine != "postgres")
|
|
{
|
|
return (env, null);
|
|
}
|
|
|
|
var db = await TestDb.CreateAsync(Anubis.Platform.DbEngine.Postgres).ConfigureAwait(false);
|
|
UsePostgres(env, db);
|
|
return (env, db);
|
|
}
|
|
|
|
public static void UsePostgres(Dictionary<string, string?> env, TestDb db)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(env);
|
|
ArgumentNullException.ThrowIfNull(db);
|
|
env["ANUBIS_DB_ENGINE"] = "postgres";
|
|
env["ANUBIS_DB_HOST"] = db.Settings.Host;
|
|
env["ANUBIS_DB_PORT"] = db.Settings.Port.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
|
env["ANUBIS_DB_NAME"] = db.Settings.Database;
|
|
env["ANUBIS_DB_USER"] = db.Settings.User;
|
|
env["ANUBIS_DB_PASSWORD"] = db.Settings.Password;
|
|
}
|
|
|
|
public static async Task<ServerHarness> StartAsync(string platform, IReadOnlyDictionary<string, string?> environment, string? dataDir = null,
|
|
string[]? extraArgs = null, bool waitReady = true)
|
|
{
|
|
var owns = dataDir is null;
|
|
dataDir ??= TempFolder.Create("server");
|
|
string[] args = ["--platform", platform, "--data-dir", dataDir, "--urls", "http://127.0.0.1:0", .. extraArgs ?? []];
|
|
var app = ServerApp.Build(args, new ServerOverrides
|
|
{
|
|
Environment = environment,
|
|
PasswordIterations = 1000,
|
|
DatabaseCheckInterval = TimeSpan.FromMilliseconds(100),
|
|
});
|
|
await app.StartAsync().ConfigureAwait(false);
|
|
var cookies = new CookieContainer();
|
|
#pragma warning disable CA2000 // The handler belongs to the client, disposed with the harness.
|
|
var http = new HttpClient(new HttpClientHandler { CookieContainer = cookies, AllowAutoRedirect = false })
|
|
#pragma warning restore CA2000
|
|
{
|
|
BaseAddress = new Uri(app.Urls.Single()),
|
|
Timeout = TimeSpan.FromSeconds(60),
|
|
};
|
|
var harness = new ServerHarness(app, dataDir, cookies, http) { _ownsData = owns };
|
|
if (waitReady)
|
|
{
|
|
await harness.Host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(30)).ConfigureAwait(false);
|
|
}
|
|
|
|
return harness;
|
|
}
|
|
|
|
public async Task WaitForAsync(HostMode mode) => await Host.WaitForAsync(mode, TimeSpan.FromSeconds(30)).ConfigureAwait(false);
|
|
|
|
public Task<HttpResponseMessage> GetAsync(string path) => Http.GetAsync(new Uri(path, UriKind.Relative));
|
|
|
|
public async Task<string> TextAsync(string path)
|
|
{
|
|
using var response = await GetAsync(path).ConfigureAwait(false);
|
|
return WebUtility.HtmlDecode(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
|
|
}
|
|
|
|
/// <summary>The CSRF field of a page's forms.</summary>
|
|
public async Task<string> CsrfAsync(string page)
|
|
{
|
|
using var response = await GetAsync(page).ConfigureAwait(false);
|
|
var html = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
|
var match = CsrfField().Match(html);
|
|
Assert.IsTrue(match.Success, "No CSRF field on " + page);
|
|
return WebUtility.HtmlDecode(match.Groups[1].Value);
|
|
}
|
|
|
|
/// <summary>Posts a form the way the browser does, with the CSRF field of <paramref name="page"/>.</summary>
|
|
public async Task<HttpResponseMessage> PostFormAsync(string page, string action, params (string Name, string Value)[] fields)
|
|
{
|
|
var token = await CsrfAsync(page).ConfigureAwait(false);
|
|
using var content = new FormUrlEncodedContent([new("__csrf", token), .. fields.Select(f => new KeyValuePair<string, string>(f.Name, f.Value))]);
|
|
return await Http.PostAsync(new Uri(action, UriKind.Relative), content).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>Signs in with the initial password and replaces it, as the first access in Docker requires.</summary>
|
|
public async Task<string> SignInFirstTimeAsync()
|
|
{
|
|
using (var login = await PostFormAsync("/accesso", "/azioni/accesso", ("password", AdminPassword)).ConfigureAwait(false))
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.Redirect, login.StatusCode);
|
|
}
|
|
|
|
const string chosen = "chosen-test-pass-2";
|
|
using var change = await PostFormAsync("/primo-accesso", "/azioni/primo-accesso", ("attuale", AdminPassword), ("nuova", chosen), ("conferma", chosen))
|
|
.ConfigureAwait(false);
|
|
Assert.AreEqual("/?ok=password", change.Headers.Location?.OriginalString);
|
|
return chosen;
|
|
}
|
|
|
|
public static string Location(HttpResponseMessage response) => response.Headers.Location?.OriginalString ?? "";
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
Http.Dispose();
|
|
await _app.StopAsync().ConfigureAwait(false);
|
|
await _app.DisposeAsync().ConfigureAwait(false);
|
|
if (_ownsData)
|
|
{
|
|
TempFolder.Delete(DataDir);
|
|
}
|
|
}
|
|
|
|
[GeneratedRegex("name=\"__csrf\" value=\"([^\"]+)\"")]
|
|
private static partial Regex CsrfField();
|
|
}
|