Files
Anubis/tests/Anubis.Tests/PlatformTests.cs
T
Alby96andClaude Opus 5.5 53ca01b7c3 feat(core): platform layer, portable database, archives and access (refs #7 #8 #9 #10 #11)
Phase 1 foundations in the Anubis library:
- Platform: startup configuration from environment variables (Docker) or
  config.toml (desktop, in-house TOML subset), data folder layout, secret key
  custody (ANUBIS_SECRET_KEY, DPAPI on Windows, restricted file elsewhere),
  installation identity and database fingerprint.
- Db: ADO.NET with Npgsql and Microsoft.Data.Sqlite, money as NUMERIC(38,18)
  or canonical text rounded to 18 decimals, UTC moments, UUIDv7 ids; numbered
  SQL migrations with type tokens and a version table; engine-independent
  export/import with count and accounting-total checks; backups keeping 14.
- Core: injectable clock, channel event bus, scheduler with fixed, interval
  and market-relative times, settings with change log, AES-GCM secrets, log
  redaction, Italian formats.
- Access: PBKDF2-SHA512 hashes, RFC 6238 TOTP, hashed session tokens,
  sign-in attempt limit.

SQLitePCLRaw (Apache-2.0) arrives with Microsoft.Data.Sqlite and is declared
in DependencyPolicyTests and API-NOTES.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 11:09:42 +01:00

200 lines
8.2 KiB
C#

using Anubis.Platform;
namespace Anubis.Tests;
/// <summary>Startup configuration in Docker and on desktop (issue #7, SPEC 15.1, 15.6).</summary>
[TestClass]
public sealed class PlatformTests
{
private static readonly string _key = new('k', 40);
private static Dictionary<string, string?> Env(params (string Key, string? Value)[] values)
{
var env = new Dictionary<string, string?>
{
["ANUBIS_DB_ENGINE"] = "sqlite",
["ANUBIS_SECRET_KEY"] = _key,
["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1",
};
foreach (var (key, value) in values)
{
env[key] = value;
}
return env;
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DockerWithSqliteNeedsNothingElse()
{
var config = DockerPlatform.Load(Env(), "/data");
Assert.IsTrue(config.IsComplete, string.Join("; ", config.Problems.Select(p => p.What)));
Assert.AreEqual(DbEngine.Sqlite, config.Db!.Engine);
Assert.AreEqual(Path.Combine("/data", "db", "anubis.sqlite3"), config.Db.SqlitePath);
Assert.AreEqual(8787, config.Port);
Assert.AreEqual(99, config.Puid);
Assert.AreEqual(100, config.Pgid);
Assert.IsFalse(config.AllowLive);
Assert.AreEqual("Europe/Rome", config.TimeZone.Id);
Assert.IsTrue(config.SecretKey.HasKey);
Assert.HasCount(32, config.SecretKey.GetOrCreateKey());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DockerPostgresUsesDefaultsAndNeverShowsThePassword()
{
var config = DockerPlatform.Load(Env(("ANUBIS_DB_ENGINE", "postgres"), ("ANUBIS_DB_HOST", "192.168.30.23"), ("ANUBIS_DB_PASSWORD", "pg-password-xyz")));
Assert.IsTrue(config.IsComplete);
Assert.AreEqual(5432, config.Db!.Port);
Assert.AreEqual("anubis", config.Db.Database);
Assert.AreEqual("anubis", config.Db.User);
Assert.IsFalse(config.Db.Describe().Contains("pg-password-xyz", StringComparison.Ordinal));
Assert.IsFalse(config.Db.ToString().Contains("pg-password-xyz", StringComparison.Ordinal));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void MissingOrWrongValuesBecomeProblemsAndNoDatabaseIsChosen()
{
var empty = DockerPlatform.Load(new Dictionary<string, string?>());
Assert.IsNull(empty.Db, "senza ANUBIS_DB_ENGINE nessun database viene scelto al posto dell'utente");
CollectionAssert.IsSubsetOf(new[] { "ANUBIS_DB_ENGINE", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD" }, empty.Problems.Select(p => p.Setting).ToList());
Assert.IsTrue(empty.Problems.All(p => p.Remedy.Length > 0));
var wrong = DockerPlatform.Load(Env(("ANUBIS_DB_ENGINE", "mysql")));
Assert.IsNull(wrong.Db);
Assert.IsFalse(wrong.IsComplete);
var postgresWithoutHost = DockerPlatform.Load(Env(("ANUBIS_DB_ENGINE", "postgres")));
Assert.IsNull(postgresWithoutHost.Db, "PostgreSQL incompleto non ripiega su SQLite");
CollectionAssert.IsSubsetOf(new[] { "ANUBIS_DB_HOST", "ANUBIS_DB_PASSWORD" }, postgresWithoutHost.Problems.Select(p => p.Setting).ToList());
var shortKey = DockerPlatform.Load(Env(("ANUBIS_SECRET_KEY", "short")));
Assert.IsTrue(shortKey.Problems.Any(p => p.Setting == "ANUBIS_SECRET_KEY"));
var badLive = DockerPlatform.Load(Env(("ANUBIS_ALLOW_LIVE", "yes")));
Assert.IsFalse(badLive.AllowLive);
Assert.IsTrue(badLive.Problems.Any(p => p.Setting == "ANUBIS_ALLOW_LIVE"));
var badZone = DockerPlatform.Load(Env(("TZ", "Mars/Olympus")));
Assert.IsTrue(badZone.Problems.Any(p => p.Setting == "TZ"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OptionalKeysAreReadWithTheDemoSuffix()
{
var config = DockerPlatform.Load(Env(("OKX_API_KEY_DEMO", "demo-key-123456"), ("TELEGRAM_CHAT_ID", "12345")));
Assert.AreEqual("demo-key-123456", config.EnvironmentKeys["OKX_API_KEY_DEMO"]);
Assert.AreEqual("12345", config.EnvironmentKeys["TELEGRAM_CHAT_ID"]);
Assert.IsFalse(config.EnvironmentKeys.ContainsKey("OKX_API_KEY"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TomlSubsetParsesAndRejectsWithLineNumbers()
{
var values = Toml.Parse("""
# comment
allow_live = false
port = 8_787 # trailing comment
name = "a \"quoted\" # not a comment"
[database]
engine = "postgres"
""");
Assert.IsFalse((bool)values["allow_live"]);
Assert.AreEqual(8787L, values["port"]);
Assert.AreEqual("a \"quoted\" # not a comment", values["name"]);
Assert.AreEqual("postgres", values["database.engine"]);
var error = Assert.Throws<FormatException>(() => Toml.Parse("a = 1\nb = [1, 2]\n"));
Assert.Contains("Riga 2", error.Message);
Assert.Throws<FormatException>(() => Toml.Parse("a = 1\na = 2"));
Assert.Throws<FormatException>(() => Toml.Parse("a = \"open"));
}
[TestMethod]
[TestCategory(Category.Integration)]
public void DesktopStartsFromAnEmptyFolderAndKeepsSecretsOutOfConfigToml()
{
var folder = TempFolder.Create("desktop");
try
{
var data = new DataDirectory(folder);
var store = ProtectedSecretKey.DefaultStore(data);
var first = DesktopPlatform.Load(data, store);
Assert.IsTrue(first.NeedsFirstRun);
Assert.IsFalse(first.IsComplete);
var key = first.SecretKey.GetOrCreateKey();
DesktopPlatform.WriteConfig(data, store, new DbSettings { Engine = DbEngine.Postgres, Host = "localhost", Password = "fake-pg-pass-1" });
var text = File.ReadAllText(data.ConfigFile);
Assert.Contains("allow_live = false", text);
Assert.IsFalse(text.Contains("fake-pg-pass-1", StringComparison.Ordinal), "la password del database non va in config.toml");
Assert.IsFalse(text.Contains(Convert.ToBase64String(key), StringComparison.Ordinal), "la chiave dei segreti non va in config.toml");
Assert.IsFalse(text.Contains("secret", StringComparison.OrdinalIgnoreCase) && text.Contains("key =", StringComparison.Ordinal));
var second = DesktopPlatform.Load(data, store);
Assert.IsTrue(second.IsComplete, string.Join("; ", second.Problems.Select(p => p.What)));
Assert.AreEqual("fake-pg-pass-1", second.Db!.Password);
CollectionAssert.AreEqual(key, second.SecretKey.GetOrCreateKey(), "la chiave resta la stessa tra un avvio e l'altro");
Assert.IsFalse(second.AllowLive);
Assert.IsFalse(second.AllowNetwork);
DesktopPlatform.WriteConfig(data, store, new DbSettings { Engine = DbEngine.Sqlite });
var sqlite = DesktopPlatform.Load(data, store);
Assert.AreEqual(data.SqliteFile, sqlite.Db!.SqlitePath);
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void BrokenConfigTomlIsAProblemNotAGuess()
{
var folder = TempFolder.Create("desktop-bad");
try
{
var data = new DataDirectory(folder);
File.WriteAllText(data.ConfigFile, "[database]\nengine = sqlite\n");
var config = DesktopPlatform.Load(data, ProtectedSecretKey.DefaultStore(data));
Assert.IsNull(config.Db);
Assert.IsFalse(config.IsComplete);
Assert.Contains("Riga 2", config.Problems[0].What);
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DataFolderHasTheLayoutOfSpec152()
{
var folder = TempFolder.Create("layout");
try
{
var data = new DataDirectory(Path.Combine(folder, "data"));
data.Ensure();
foreach (var name in new[] { "db", "models", "research", "import", "backups", "logs" })
{
Assert.IsTrue(Directory.Exists(Path.Combine(data.Root, name)), name);
}
Assert.AreEqual(Path.Combine(data.Root, "installation.json"), data.InstallationFile);
}
finally
{
TempFolder.Delete(folder);
}
}
}