A session alone could change the password, switch the second factor on or off, send the key of the language model to another address and remove the rules that stop purchases. Each now needs the password and the code, with one limit on wrong attempts that a restart of the services does not clear, and the other sessions end when the password or the factor changes. Requests to the brokers pass a list of allowed calls, never follow a redirect with a key and are signed by one client only. Pages are closed by default, nothing is cached, requests are limited to 1 MB, secrets are masked in logs and notifications, exported tables cannot run as formulas, archives carry no sessions and the container refuses to run as root. refs #68 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
272 lines
12 KiB
C#
272 lines
12 KiB
C#
using System.Net;
|
|
using Anubis.Access;
|
|
using Anubis.Core;
|
|
using Anubis.Db;
|
|
using Anubis.Platform;
|
|
using Anubis.Server;
|
|
|
|
namespace Anubis.Tests;
|
|
|
|
/// <summary>Restore, old copies, failed migrations and a changed secret key as the user meets them (issue #69, SPEC 9.4, 15.1).</summary>
|
|
[TestClass]
|
|
[TestCategory(Category.Integration)]
|
|
public sealed class RestoreServerTests
|
|
{
|
|
/// <summary>The database of the data folder is set aside and an empty one takes its place; the answer is how to put it back.</summary>
|
|
private static async Task<(Func<Task> PutBack, Func<Task> PutNew, TestDb? Empty)> EmptyDatabaseAsync(Dictionary<string, string?> env, string data, TestDb? postgres)
|
|
{
|
|
if (postgres is not null)
|
|
{
|
|
var empty = await TestDb.CreateAsync(DbEngine.Postgres);
|
|
ServerHarness.UsePostgres(env, empty);
|
|
return (() =>
|
|
{
|
|
ServerHarness.UsePostgres(env, postgres);
|
|
return Task.CompletedTask;
|
|
}, () =>
|
|
{
|
|
ServerHarness.UsePostgres(env, empty);
|
|
return Task.CompletedTask;
|
|
}, empty);
|
|
}
|
|
|
|
var file = new DataDirectory(data).SqliteFile;
|
|
var old = data + "-vecchio.sqlite3";
|
|
var fresh = data + "-nuovo.sqlite3";
|
|
void Take(string from, string to)
|
|
{
|
|
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
|
File.Copy(from, to, overwrite: true);
|
|
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!).Where(f => f.StartsWith(file, StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
File.Delete(f);
|
|
}
|
|
}
|
|
|
|
Take(file, old);
|
|
await File.WriteAllBytesAsync(file, []);
|
|
return (() =>
|
|
{
|
|
Take(file, fresh);
|
|
File.Copy(old, file);
|
|
return Task.CompletedTask;
|
|
}, () =>
|
|
{
|
|
Take(file, old);
|
|
File.Copy(fresh, file);
|
|
return Task.CompletedTask;
|
|
}, null);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AfterARestoreTheOldDatabaseIsRefusedAndTheNewOneWaitsForTheUser()
|
|
{
|
|
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
|
await using var engine = postgres;
|
|
var data = TempFolder.Create("protected");
|
|
string password;
|
|
await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data))
|
|
{
|
|
password = await first.SignInFirstTimeAsync();
|
|
using var saved = await first.PostFormAsync("/impostazioni", "/azioni/salvataggio");
|
|
}
|
|
|
|
var backup = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano");
|
|
var (putBack, putNew, empty) = await EmptyDatabaseAsync(env, data, postgres);
|
|
await using var second = empty;
|
|
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
|
|
{
|
|
await server.WaitForAsync(HostMode.IdentityProblem);
|
|
using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name)))
|
|
{
|
|
Assert.AreEqual("/", ServerHarness.Location(restore));
|
|
}
|
|
|
|
// Without the trading engine nothing can be rebuilt: the restart waits.
|
|
await server.WaitForAsync(HostMode.Ready);
|
|
using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password)))
|
|
{
|
|
Assert.AreEqual("/", ServerHarness.Location(signIn));
|
|
}
|
|
|
|
StringAssert.Contains(await server.TextAsync("/"), "Ripartenza protetta");
|
|
using (var early = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva"))
|
|
{
|
|
Assert.AreEqual("stopped", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
|
}
|
|
|
|
Assert.HasCount(1, await server.Host.Services!.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'protected_restart'", r => r.Text("message"))));
|
|
}
|
|
|
|
// The database of before the restore comes back, by mistake: same installation, older fingerprint, engine off.
|
|
await putBack();
|
|
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
|
|
{
|
|
await server.WaitForAsync(HostMode.IdentityProblem);
|
|
Assert.AreEqual(IdentityVerdict.StaleDatabase, server.Host.Status.Identity!.Verdict);
|
|
StringAssert.Contains(await server.TextAsync("/"), "una copia più vecchia");
|
|
using var health = await server.GetAsync("/health");
|
|
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, health.StatusCode);
|
|
Assert.IsNull(server.Host.Services);
|
|
}
|
|
|
|
// The right one: protected until the user confirms, then as before.
|
|
await putNew();
|
|
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, trading: true))
|
|
{
|
|
using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password)))
|
|
{
|
|
Assert.AreEqual("/", ServerHarness.Location(signIn));
|
|
}
|
|
|
|
for (var i = 0; i < 300 && server.Host.Services!.Trading is not { Started: true }; i++)
|
|
{
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
StringAssert.Contains(await server.TextAsync("/rischio"), "Sui conti non c'era niente che il database non conoscesse già");
|
|
using (var go = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva"))
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.Redirect, go.StatusCode);
|
|
}
|
|
|
|
Assert.AreEqual("active", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
|
Assert.IsFalse((await Installation.ReadRowAsync(server.Host.Services.Db))!.ProtectedRestart);
|
|
Assert.IsFalse((await server.TextAsync("/rischio")).Contains("Ripartenza protetta", StringComparison.Ordinal));
|
|
}
|
|
|
|
TempFolder.Delete(data);
|
|
foreach (var left in new[] { data + "-vecchio.sqlite3", data + "-nuovo.sqlite3" })
|
|
{
|
|
File.Delete(left);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AFailedMigrationKeepsTheEngineOffAndTakesOneBackup()
|
|
{
|
|
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
|
await using var engine = postgres;
|
|
var data = TempFolder.Create("migration");
|
|
var directory = new DataDirectory(data);
|
|
directory.Ensure();
|
|
var settings = postgres?.Settings ?? new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = directory.SqliteFile };
|
|
await using (var db = Database.Open(settings))
|
|
{
|
|
await Migrations.MigrateAsync(db, SystemClock.Instance, null, CancellationToken.None, upTo: 12);
|
|
await Installation.CheckAsync(db, directory, SystemClock.Instance);
|
|
await db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)"));
|
|
}
|
|
|
|
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
|
|
{
|
|
await server.WaitForAsync(HostMode.SchemaProblem);
|
|
await Task.Delay(1000);
|
|
Assert.HasCount(1, new Backups(directory, SystemClock.Instance).List(), "One backup, however long the page stays open.");
|
|
var html = await server.TextAsync("/");
|
|
StringAssert.Contains(html, "0013");
|
|
StringAssert.Contains(html, "prima-della-migrazione");
|
|
|
|
using (var wrong = await server.PostFormAsync("/", "/azioni/servizio/riprova", ("password", "wrong-password-123")))
|
|
{
|
|
StringAssert.Contains(ServerHarness.Location(wrong), "errore=password");
|
|
}
|
|
|
|
await using (var db = Database.Open(settings))
|
|
{
|
|
await db.WriteAsync(s => s.ExecuteAsync("DROP TABLE cost_estimates"));
|
|
}
|
|
|
|
using (var again = await server.PostFormAsync("/", "/azioni/servizio/riprova", ("password", ServerHarness.AdminPassword)))
|
|
{
|
|
Assert.AreEqual("/", ServerHarness.Location(again));
|
|
}
|
|
|
|
await server.WaitForAsync(HostMode.Ready);
|
|
}
|
|
|
|
TempFolder.Delete(data);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task WithAnotherSecretKeyNothingCrashesAndTheAccessIsResetFromTheCommandLine()
|
|
{
|
|
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
|
await using var engine = postgres;
|
|
var data = TempFolder.Create("key");
|
|
string password;
|
|
await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data))
|
|
{
|
|
password = await first.SignInFirstTimeAsync();
|
|
var services = first.Host.Services!;
|
|
var secret = Totp.NewSecret();
|
|
var user = (await services.Access.GetUserAsync())!;
|
|
Assert.AreEqual(AccessChange.Done, await services.Access.EnableSecondFactorAsync(user.Id, secret, password, Totp.Compute(secret, DateTimeOffset.UtcNow), Guid.Empty));
|
|
await services.Secrets.SetAsync("FINNHUB_API_KEY", "chiave-di-prova-1", "test");
|
|
}
|
|
|
|
env["ANUBIS_SECRET_KEY"] = "another-secret-key-0123456789-abcdefghij";
|
|
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data))
|
|
{
|
|
using (var refused = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password), ("codice", "123456")))
|
|
{
|
|
Assert.AreEqual("/accesso?errore=chiave", ServerHarness.Location(refused));
|
|
}
|
|
|
|
StringAssert.Contains(await server.TextAsync("/accesso?errore=chiave"), "ANUBIS_SECRET_KEY");
|
|
using var output = new StringWriter();
|
|
Assert.AreEqual(0, await AccessCommand.RunAsync(["reset", "--platform", "docker", "--data-dir", data], output, env, iterations: 1000), output.ToString());
|
|
var temporary = output.ToString().Split("Password provvisoria: ")[1].Split('\n')[0].Trim();
|
|
using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", temporary)))
|
|
{
|
|
Assert.AreEqual("/", ServerHarness.Location(signIn));
|
|
}
|
|
|
|
const string chosen = "chosen-test-pass-3";
|
|
using (var change = await server.PostFormAsync("/primo-accesso", "/azioni/primo-accesso", ("attuale", temporary), ("nuova", chosen), ("conferma", chosen)))
|
|
{
|
|
Assert.AreEqual("/?ok=password", ServerHarness.Location(change));
|
|
}
|
|
|
|
StringAssert.Contains(await server.TextAsync("/impostazioni"), "Non si legge più: la chiave dei segreti è cambiata");
|
|
}
|
|
|
|
TempFolder.Delete(data);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task TheCommandLineImportsIntoANewSqliteFileOfTheSameFolder()
|
|
{
|
|
var data = TempFolder.Create("cli-same");
|
|
var env = ServerHarness.DockerSqlite();
|
|
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data))
|
|
{
|
|
await server.SignInFirstTimeAsync();
|
|
}
|
|
|
|
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
|
var root = TempFolder.Create("cli-same-archive");
|
|
var archive = Path.Combine(root, "archivio");
|
|
using var output = new StringWriter();
|
|
Assert.AreEqual(0, await DatabaseCommand.RunAsync(["export", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString());
|
|
var directory = new DataDirectory(data);
|
|
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(directory.SqliteFile)!))
|
|
{
|
|
File.Delete(f);
|
|
}
|
|
|
|
// A wrong folder creates nothing.
|
|
Assert.AreEqual(1, await DatabaseCommand.RunAsync(["import", root, "--platform", "docker", "--data-dir", data], output, env));
|
|
Assert.IsFalse(File.Exists(directory.SqliteFile));
|
|
|
|
Assert.AreEqual(0, await DatabaseCommand.RunAsync(["import", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString());
|
|
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data))
|
|
{
|
|
Assert.IsTrue((await Installation.ReadRowAsync(server.Host.Services!.Db))!.ProtectedRestart);
|
|
}
|
|
|
|
TempFolder.Delete(data);
|
|
TempFolder.Delete(root);
|
|
}
|
|
}
|