ADR 0021-0026 for the new course of 2 December 2026, roadmap of phases 10-24. The desktop application is gone: Docker is the only form, and outside a container the server runs only for development and tests with --data-dir, on this computer only. Lighter image (829 MB to 410 MB), rotating logs, backtest and learning as one-shot commands. refs #113 #114 #115 #78 #80 #81 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
576 lines
27 KiB
C#
576 lines
27 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()
|
|
{
|
|
// The server stops before its folder is deleted: on Windows an open database cannot be deleted.
|
|
string demoRoot;
|
|
{
|
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
|
|
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);
|
|
|
|
// A development run outside a container: the same refusal, even when bound to every address (ADR 0022).
|
|
await using var dev = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
|
|
using var rebinding = new HttpRequestMessage(HttpMethod.Get, new Uri("/health", UriKind.Relative));
|
|
rebinding.Headers.Host = "evil.example:" + dev.BaseAddress.Port.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
|
using var refused = await dev.Http.SendAsync(rebinding);
|
|
Assert.AreEqual(HttpStatusCode.Forbidden, refused.StatusCode);
|
|
}
|
|
|
|
[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);
|
|
}
|
|
|
|
// The server stops before its data folder is removed: a running one may still hold the database file.
|
|
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";
|
|
|
|
await MoveWhenFreeAsync(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.");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Moves the database file as soon as no connection holds it: a request or a background job of the running server
|
|
/// can have one open for a moment, and Windows refuses to move an open file.
|
|
/// </summary>
|
|
private static async Task MoveWhenFreeAsync(string from, string to)
|
|
{
|
|
for (var attempt = 1; ; attempt++)
|
|
{
|
|
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
|
try
|
|
{
|
|
File.Move(from, to);
|
|
return;
|
|
}
|
|
catch (IOException) when (attempt < 50)
|
|
{
|
|
await Task.Delay(100);
|
|
}
|
|
}
|
|
}
|
|
|
|
[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 void TheDesktopIsGoneAndOutsideAContainerTheFolderIsGivenByHand()
|
|
{
|
|
var env = ServerHarness.DockerSqlite();
|
|
var desktop = Assert.Throws<StartupRefusedException>(() => ServerOptions.Parse(["--platform", "desktop"], env));
|
|
Assert.Contains("solo in un container Docker", desktop.Message);
|
|
|
|
// "--platform docker" still works, for the commands already written in the manuals.
|
|
var outside = ServerOptions.Parse(["--platform", "docker"], env);
|
|
Assert.IsFalse(outside.InContainer);
|
|
Assert.IsTrue(outside.LocalOnly);
|
|
var refused = Assert.Throws<StartupRefusedException>(() => outside.LoadConfig(env));
|
|
Assert.Contains("--data-dir", refused.Message);
|
|
|
|
var inside = new Dictionary<string, string?>(env, StringComparer.Ordinal) { ["DOTNET_RUNNING_IN_CONTAINER"] = "true" };
|
|
var container = ServerOptions.Parse([], inside);
|
|
Assert.IsTrue(container.InContainer);
|
|
Assert.IsFalse(container.LocalOnly);
|
|
Assert.AreEqual("/data", container.LoadConfig(inside).Data.Root);
|
|
}
|
|
|
|
[TestMethod]
|
|
[DataRow(false, "http://127.0.0.1:")]
|
|
[DataRow(true, "http://0.0.0.0:")]
|
|
public async Task OutsideAContainerTheServerListensOnlyOnThisComputer(bool inContainer, string address)
|
|
{
|
|
var folder = TempFolder.Create("listen");
|
|
try
|
|
{
|
|
var env = ServerHarness.DockerSqlite();
|
|
env["PORT"] = "18787";
|
|
if (inContainer)
|
|
{
|
|
env["DOTNET_RUNNING_IN_CONTAINER"] = "true";
|
|
}
|
|
|
|
await using (var app = ServerApp.Build(["--data-dir", folder], new ServerOverrides { Environment = env, PasswordIterations = 1000 }))
|
|
{
|
|
Assert.AreEqual(address + "18787", app.Configuration["urls"]);
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
TempFolder.Delete(folder);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[DataRow("Anubis.Server.dll", "--platform desktop", "solo in un container Docker")]
|
|
[DataRow("Anubis.Server.dll", "", "--data-dir")]
|
|
[DataRow("Anubis.Guard.dll", "--platform desktop", "solo in un container Docker")]
|
|
[DataRow("Anubis.Guard.dll", "--platform desktop --data-dir .", "solo in un container Docker")]
|
|
[DataRow("Anubis.Guard.dll", "", "--data-dir")]
|
|
public async Task TheServerSaysInItalianWhyItDoesNotStart(string program, string arguments, string message)
|
|
{
|
|
var info = new System.Diagnostics.ProcessStartInfo(Anubis.Supervision.GuardLaunch.Dotnet())
|
|
{
|
|
RedirectStandardError = true,
|
|
RedirectStandardOutput = true,
|
|
UseShellExecute = false,
|
|
};
|
|
// The guard too: a refused start ends with the message, not with an engine restarted again and again.
|
|
info.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, program));
|
|
foreach (var argument in arguments.Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
|
{
|
|
info.ArgumentList.Add(argument);
|
|
}
|
|
|
|
// Outside a container, even when the suite runs in one (the CI).
|
|
info.Environment.Remove("DOTNET_RUNNING_IN_CONTAINER");
|
|
using var process = System.Diagnostics.Process.Start(info)!;
|
|
var errors = process.StandardError.ReadToEndAsync();
|
|
_ = process.StandardOutput.ReadToEndAsync();
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(60));
|
|
try
|
|
{
|
|
await process.WaitForExitAsync(timeout.Token);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
// A guard that does not refuse would restart the engine for ever: it goes, with what it started.
|
|
process.Kill(entireProcessTree: true);
|
|
Assert.Fail(program + " did not end within a minute.");
|
|
}
|
|
|
|
Assert.AreEqual(2, process.ExitCode);
|
|
Assert.Contains(message, await errors);
|
|
Assert.DoesNotContain(" at ", await errors, "A message, not a stack trace.");
|
|
}
|
|
|
|
[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)));
|
|
// The server stops before its folder is deleted: on Windows an open database cannot be deleted.
|
|
string demoRoot;
|
|
{
|
|
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.
|
|
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);
|
|
|
|
// The demo has no startup password and answers only this computer: the error-page choices go through without one.
|
|
using (var choice = await server.PostFormAsync("/", "/azioni/servizio/riprova"))
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.Redirect, choice.StatusCode);
|
|
Assert.DoesNotContain("errore", ServerHarness.Location(choice));
|
|
}
|
|
|
|
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);
|
|
|
|
// A computer stopped for more than the five seconds of the check is told unhealthy, as it should: here the
|
|
// answer that counts is the one it settles on, within thirty seconds.
|
|
HealthResponse? health = null;
|
|
for (var watch = System.Diagnostics.Stopwatch.StartNew(); health?.Status != "ok" && watch.Elapsed < TimeSpan.FromSeconds(30); await Task.Delay(100))
|
|
{
|
|
using var response = await server.GetAsync("/health");
|
|
health = await response.Content.ReadFromJsonAsync<HealthResponse>();
|
|
}
|
|
|
|
Assert.AreEqual("ok", health!.Status, string.Join(", ", health.Checks!.Select(c => c.Key + " " + c.Value)));
|
|
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());
|
|
|
|
// The typeface travels with the app, with its licence beside it (ADR 0004).
|
|
using var font = await server.GetAsync("/assets/InstrumentSans.ttf");
|
|
Assert.AreEqual(HttpStatusCode.OK, font.StatusCode);
|
|
Assert.AreEqual("font/ttf", font.Content.Headers.ContentType!.MediaType);
|
|
var fontPath = Path.Combine(Repo.Root.FullName, "src", "Anubis.Server", "Assets", "InstrumentSans.ttf");
|
|
CollectionAssert.AreEqual(await File.ReadAllBytesAsync(fontPath), await font.Content.ReadAsByteArrayAsync());
|
|
StringAssert.Contains(await server.TextAsync("/assets/InstrumentSans-OFL.txt"), "SIL Open Font License, Version 1.1");
|
|
StringAssert.Contains(await server.TextAsync("/assets/app.css"), "url(\"/assets/InstrumentSans.ttf\")");
|
|
}
|
|
|
|
[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)!);
|
|
}
|
|
}
|