The manual, the runbook and the go-live list are written and checked claim by claim against the code, and the installation is done from zero by following them on both engines. That found real defects, now fixed: - with SQLite a missing database file left no way to restore a backup: the choices appear, and the file is created only by the user's choice; - an account whose difference vanished after the 15 minutes stayed prudent with no button, a missing stop could be left out for good, and a choice made while the broker was silent used old numbers; - after "Ferma tutto" the positions could not be closed without restarting; - a refused key looked like a silent broker: it has its own notice now; - the split of the capital between the strategies of a broker (SPEC 13.5) could not be changed from the interface. refs #72 #68 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
344 lines
16 KiB
C#
344 lines
16 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 AMissingSqliteFileOffersTheRestoreAndNeverCreatesADatabaseByItself()
|
|
{
|
|
var data = TempFolder.Create("missing-file");
|
|
var file = new DataDirectory(data).SqliteFile;
|
|
await using (var first = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data))
|
|
{
|
|
await first.SignInFirstTimeAsync();
|
|
using var saved = await first.PostFormAsync("/impostazioni", "/azioni/salvataggio");
|
|
}
|
|
|
|
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
|
var away = data + "-altrove.sqlite3";
|
|
File.Copy(file, away, overwrite: true);
|
|
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!))
|
|
{
|
|
File.Delete(f);
|
|
}
|
|
|
|
// The file comes back while the page waits: it is used, with no choice to make.
|
|
await using (var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data, waitReady: false))
|
|
{
|
|
await server.WaitForAsync(HostMode.IdentityProblem);
|
|
StringAssert.Contains(await server.TextAsync("/"), "Il file del database non c'è");
|
|
using var health = await server.GetAsync("/health");
|
|
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, health.StatusCode);
|
|
using (var wrong = await server.PostFormAsync("/", "/azioni/servizio/da-capo", ("password", "wrong-password-123")))
|
|
{
|
|
StringAssert.Contains(ServerHarness.Location(wrong), "errore=password");
|
|
}
|
|
|
|
using (var unknown = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", "inesistente")))
|
|
{
|
|
StringAssert.Contains(ServerHarness.Location(unknown), "errore=scelta");
|
|
}
|
|
|
|
Assert.IsFalse(File.Exists(file), "Trap 20: no database by itself.");
|
|
File.Copy(away, file);
|
|
await server.WaitForAsync(HostMode.Ready);
|
|
}
|
|
|
|
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
|
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!))
|
|
{
|
|
File.Delete(f);
|
|
}
|
|
|
|
await using (var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data, waitReady: false))
|
|
{
|
|
await server.WaitForAsync(HostMode.IdentityProblem);
|
|
var backup = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano");
|
|
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);
|
|
Assert.IsTrue((await Installation.ReadRowAsync(server.Host.Services!.Db))!.ProtectedRestart);
|
|
Assert.AreEqual("stopped", (await server.Host.Services.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
|
}
|
|
|
|
File.Delete(away);
|
|
TempFolder.Delete(data);
|
|
}
|
|
|
|
[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);
|
|
}
|
|
|
|
// Nor is anything sold from a ledger that has not read the accounts yet.
|
|
Assert.IsFalse((await server.TextAsync("/rischio")).Contains("Chiudi tutte le posizioni", StringComparison.Ordinal));
|
|
using (var close = await server.PostFormAsync("/rischio", "/azioni/bot/chiudi"))
|
|
{
|
|
StringAssert.Contains(ServerHarness.Location(close), "errore");
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|