An independent review of the phase found nine defects. The ones that could lose money or orders: - Exits at the close of equity_meanrev are now planned orders written in the same transaction that claims the decision, so a restart can neither lose them nor send them twice. A sell with a deadline starts aggressive. - Resume also finds a planned order not yet linked to its execution (restart between sending and linking) and closes it before re-planning. - An account is "ready" only after adopting the guard's stops, checking the key, reconciling, resuming and aligning stops. Until then nothing is decided on it or sent to it, and the loop retries its startup each minute. The guard's note is deleted only when every stop it placed is in the ledger. - Each account's turn is cut after 45 s (60 s for a retried startup), so a slow broker no longer silences the heartbeat until the guard kills a healthy engine; the beat is also withheld when the scheduler has been silent for 30 minutes. Smaller ones: a stock decision made after the open is marked late; the Telegram loops survive unexpected errors; a long absence is shown on the Panoramica until "Ho visto" (SPEC 5.6); plain-http heartbeats are only accepted to home-network addresses; the soak report gives a daily close 30 minutes to be decided before expecting it. ADR 0012 point 12 records these choices; #51 and the two screen criteria are ticked in the roadmap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
496 lines
24 KiB
C#
496 lines
24 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);
|
|
}
|
|
|
|
[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 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)));
|
|
// 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);
|
|
|
|
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());
|
|
|
|
// 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)!);
|
|
}
|
|
}
|