Rebuild the state from the brokers after a restore and refuse an older copy

A restore, an import or an adopted database restarts protected: the engine
stays stopped, reads from the broker what the archive does not know (orders,
stops, executions, also from the OKX history up to 89 days), cancels orders
left working, protects what it finds and waits for the user. Strategies with
real money stay exit only until confirmed again. The database of before the
restore, put back by mistake, is refused by its fingerprint.

A failed migration leaves the engine off with one backup and a way to try
again; an archive is checked whole before the database is touched; a changed
secret key no longer crashes anything, and "anubis access reset" gives the
access back to whoever holds the computer. The image runs the db and access
commands without the guard.

refs #69

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 18:52:08 +01:00
1 parent 3da9b00f44
commit 4897594b87
40 files changed
+1871 -90

No files matched your search

+271
View File
@@ -0,0 +1,271 @@
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.IsTrue(await services.Access.EnableSecondFactorAsync(user.Id, secret, Totp.Compute(secret, DateTimeOffset.UtcNow)));
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);
}
}