Files
Anubis/tests/Anubis.Tests/StoresTests.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

265 lines
16 KiB
C#

using System.Text;
using Anubis.Access;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Tests;
/// <summary>Installation identity, settings, secrets (issues #7, #10).</summary>
[TestClass]
public sealed class StoresTests
{
private static readonly byte[] _key = Enumerable.Range(1, 32).Select(i => (byte)i).ToArray();
[TestMethod]
[TestCategory(Category.Integration)]
public async Task InstallationIdentityAndFingerprint()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var folder = TempFolder.Create("installation");
try
{
var data = new DataDirectory(folder);
var first = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false);
Assert.AreEqual(IdentityVerdict.Created, first.Verdict);
Assert.IsTrue(File.Exists(data.InstallationFile));
Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
// Data folder lost: rewritten from the database.
File.Delete(data.InstallationFile);
Assert.AreEqual(IdentityVerdict.FileRestored, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
// A stale copy of the database: same installation, older fingerprint.
var before = Installation.ReadFile(data)!;
Installation.WriteFile(data, before with { Fingerprint = "newer" });
var stale = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false);
Assert.AreEqual(IdentityVerdict.StaleDatabase, stale.Verdict);
Assert.IsFalse(stale.CanStart);
// Another installation's folder.
Installation.WriteFile(data, before with { InstallationId = Guid.NewGuid() });
Assert.AreEqual(IdentityVerdict.DifferentInstallation, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
// The user adopts this database: new fingerprint on both sides, protected restart on.
var renewed = await Installation.RenewAsync(test.Db, data, clock, adoptDatabaseIdentity: true).ConfigureAwait(false);
Assert.AreEqual(before.InstallationId, renewed.InstallationId);
Assert.AreNotEqual(before.Fingerprint, renewed.Fingerprint);
var row = await Installation.ReadRowAsync(test.Db).ConfigureAwait(false);
Assert.IsTrue(row!.ProtectedRestart);
Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
// An empty database while the folder belongs to an installation: nothing is created.
await using var empty = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var check = await Installation.CheckAsync(empty.Db, data, clock).ConfigureAwait(false);
Assert.AreEqual(IdentityVerdict.EmptyDatabase, check.Verdict);
Assert.IsNull(await Installation.ReadRowAsync(empty.Db).ConfigureAwait(false));
Installation.StartOver(data, clock);
Assert.AreEqual(IdentityVerdict.Created, (await Installation.CheckAsync(empty.Db, data, clock).ConfigureAwait(false)).Verdict);
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SettingsKeepAChangeLogAndStartupValuesAreReadOnly()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var bus = new EventBus();
using var changes = bus.Subscribe<SettingChanged>();
var settings = new SettingsStore(test.Db, clock, bus, new Dictionary<string, StartupOverride>
{
["appearance.currency"] = new("USD", "variabile d'ambiente di prova"),
});
Assert.AreEqual("auto", (await settings.GetAsync("appearance.theme").ConfigureAwait(false)).Value);
await settings.SetAsync("appearance.theme", "dark", "admin").ConfigureAwait(false);
clock.Advance(TimeSpan.FromMinutes(1));
await settings.SetAsync("appearance.theme", "light", "admin").ConfigureAwait(false);
await settings.SetAsync("appearance.theme", "light", "admin").ConfigureAwait(false);
Assert.AreEqual("light", (await settings.GetAsync("appearance.theme").ConfigureAwait(false)).Value);
var history = await settings.HistoryAsync("appearance.theme").ConfigureAwait(false);
Assert.HasCount(2, history, "un valore uguale non crea una voce");
Assert.AreEqual(("dark", "light"), (history[0].OldValue, history[0].NewValue));
Assert.AreEqual(("auto", "dark"), (history[1].OldValue, history[1].NewValue));
var currency = await settings.GetAsync("appearance.currency").ConfigureAwait(false);
Assert.IsTrue(currency.ReadOnly);
Assert.AreEqual("USD", currency.Value);
await Assert.ThrowsAsync<ReadOnlySettingException>(() => settings.SetAsync("appearance.currency", "EUR", "admin")).ConfigureAwait(false);
await Assert.ThrowsAsync<ArgumentException>(() => settings.SetAsync("appearance.theme", "pink", "admin")).ConfigureAwait(false);
Assert.IsTrue(changes.TryRead(out var changed));
Assert.AreEqual("dark", changed!.Value);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SecretsAreEncryptedNeverLoggedAndEnvironmentWins()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var secrets = new SecretStore(test.Db, clock, _key, new Dictionary<string, string> { ["OKX_API_KEY_DEMO"] = "from-environment-1" });
const string value = "alpaca-paper-secret-0123456789";
await secrets.SetAsync("ALPACA_API_SECRET_DEMO", value, "admin").ConfigureAwait(false);
var stored = await test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT ciphertext FROM secrets", r => r.Bytes("ciphertext"))).ConfigureAwait(false);
Assert.IsFalse(Encoding.UTF8.GetString(stored!).Contains(value, StringComparison.Ordinal), "nel database il segreto è cifrato");
Assert.AreEqual(value, await secrets.RevealAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false));
Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)).IsSet);
Assert.IsFalse(Redactor.Redact("got " + value).Contains(value, StringComparison.Ordinal), "un segreto letto viene filtrato dai registri");
var history = await new SettingsStore(test.Db, clock, new EventBus()).HistoryAsync("secret:ALPACA_API_SECRET_DEMO").ConfigureAwait(false);
Assert.AreEqual("impostato", history.Single().NewValue);
Assert.IsFalse(history.Any(h => (h.NewValue ?? "").Contains(value, StringComparison.Ordinal) || (h.OldValue ?? "").Contains(value, StringComparison.Ordinal)));
// Environment keys win and cannot be overwritten from the interface.
Assert.AreEqual("from-environment-1", await secrets.RevealAsync("OKX_API_KEY_DEMO").ConfigureAwait(false));
Assert.IsTrue((await secrets.StatusAsync("OKX_API_KEY_DEMO").ConfigureAwait(false)).FromEnvironment);
await Assert.ThrowsAsync<ReadOnlySettingException>(() => secrets.SetAsync("OKX_API_KEY_DEMO", "x-123456789", "admin")).ConfigureAwait(false);
// With another key the value cannot be read: the error says to enter it again.
var otherKey = new SecretStore(test.Db, clock, Enumerable.Repeat((byte)7, 32).ToArray());
var error = await Assert.ThrowsAsync<System.Security.Cryptography.CryptographicException>(() => otherKey.RevealAsync("ALPACA_API_SECRET_DEMO")).ConfigureAwait(false);
Assert.Contains("Reinserisci", error.Message);
// A value sealed under one name does not open under another.
var sealedValue = secrets.Seal("A", "x");
Assert.Throws<System.Security.Cryptography.CryptographicException>(() => secrets.Open("B", sealedValue));
Assert.IsTrue(await secrets.RemoveAsync("ALPACA_API_SECRET_DEMO", "admin").ConfigureAwait(false));
Assert.IsNull(await secrets.RevealAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false));
}
}
/// <summary>Passwords, TOTP, sessions and the attempt limit (issue #11).</summary>
[TestClass]
public sealed class AccessTests
{
[TestMethod]
[TestCategory(Category.Unit)]
public void PasswordHashesVerifyAndCarryTheirCost()
{
var hash = Passwords.Hash("correct horse battery", 1000);
Assert.StartsWith("pbkdf2-sha512$1000$", hash);
Assert.IsTrue(Passwords.Verify("correct horse battery", hash));
Assert.IsFalse(Passwords.Verify("correct horse batterY", hash));
Assert.IsFalse(Passwords.Verify("x", "garbage"));
Assert.IsFalse(Passwords.Verify("x", "pbkdf2-sha512$abc$$"));
Assert.AreNotEqual(Passwords.Hash("same", 1000), Passwords.Hash("same", 1000), "sale diverso a ogni hash");
Assert.IsNotNull(Passwords.Problem("short"));
Assert.IsNotNull(Passwords.Problem("initial-pass-1", "initial-pass-1"));
Assert.IsNull(Passwords.Problem("una password lunga"));
}
// RFC 6238, appendix B: the official test vectors.
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow(59L, "94287082", "46119246", "90693936")]
[DataRow(1111111109L, "07081804", "68084774", "25091201")]
[DataRow(1111111111L, "14050471", "67062674", "99943326")]
[DataRow(1234567890L, "89005924", "91819424", "93441116")]
[DataRow(2000000000L, "69279037", "90698825", "38618901")]
[DataRow(20000000000L, "65353130", "77737706", "47863826")]
public void TotpMatchesTheRfcVectors(long unixSeconds, string sha1, string sha256, string sha512)
{
var at = DateTimeOffset.FromUnixTimeSeconds(unixSeconds);
Assert.AreEqual(sha1, Totp.Compute("12345678901234567890"u8, at, 8, 30, "SHA1"));
Assert.AreEqual(sha256, Totp.Compute("12345678901234567890123456789012"u8, at, 8, 30, "SHA256"));
Assert.AreEqual(sha512, Totp.Compute("1234567890123456789012345678901234567890123456789012345678901234"u8, at, 8, 30, "SHA512"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TotpAcceptsOneStepOfDriftAndBase32RoundTrips()
{
var secret = Totp.NewSecret();
var now = new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero);
Assert.IsTrue(Totp.Verify(secret, Totp.Compute(secret, now), now));
Assert.IsTrue(Totp.Verify(secret, Totp.Compute(secret, now.AddSeconds(-30)), now));
Assert.IsFalse(Totp.Verify(secret, Totp.Compute(secret, now.AddSeconds(-90)), now));
Assert.IsFalse(Totp.Verify(secret, "12a456", now));
CollectionAssert.AreEqual(secret, Base32.Decode(Base32.Encode(secret)));
Assert.AreEqual("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", Base32.Encode("12345678901234567890"u8));
Assert.StartsWith("otpauth://totp/Anubis:admin?secret=", Totp.Uri("Anubis", "admin", secret));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void LoginLimiterBlocksAnAddressAfterFiveFailures()
{
var clock = new ManualClock(DateTimeOffset.UnixEpoch);
var limiter = new LoginLimiter(clock);
for (var i = 0; i < LoginLimiter.PerAddress; i++)
{
Assert.AreEqual(TimeSpan.Zero, limiter.Wait("10.0.0.2"));
limiter.Failed("10.0.0.2");
}
Assert.AreEqual(LoginLimiter.Window, limiter.Wait("10.0.0.2"));
Assert.AreEqual(TimeSpan.Zero, limiter.Wait("10.0.0.3"), "un altro indirizzo non è bloccato");
clock.Advance(LoginLimiter.Window);
Assert.AreEqual(TimeSpan.Zero, limiter.Wait("10.0.0.2"));
for (var i = 0; i < LoginLimiter.Overall; i++)
{
limiter.Failed("host-" + i);
}
Assert.IsGreaterThan(TimeSpan.Zero, limiter.Wait("10.0.0.9"), "troppi errori in tutto: aspettano tutti");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SignInSessionsSecondFactorAndPasswordChange()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var secrets = new SecretStore(test.Db, clock, new byte[32]);
var access = new AccessStore(test.Db, clock, secrets, iterations: 1000);
Assert.IsTrue(await access.EnsureUserAsync("initial-pass-1", mustChange: true).ConfigureAwait(false));
Assert.IsFalse(await access.EnsureUserAsync("other-password", mustChange: false).ConfigureAwait(false), "un solo utente");
Assert.AreEqual(LoginResult.WrongPassword, (await access.SignInAsync("wrong", null, null, null).ConfigureAwait(false)).Result);
var (result, token) = await access.SignInAsync("initial-pass-1", null, "test", "127.0.0.1").ConfigureAwait(false);
Assert.AreEqual(LoginResult.Ok, result);
var session = await access.ValidateAsync(token).ConfigureAwait(false);
Assert.IsNotNull(session);
Assert.IsTrue(session.User.MustChangePassword);
var stored = await test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT token_hash FROM sessions", r => r.Text("token_hash"))).ConfigureAwait(false);
Assert.AreNotEqual(token, stored, "nel database c'è solo l'impronta del token");
// Second session, then a password change ends every other session.
var (_, other) = await access.SignInAsync("initial-pass-1", null, null, null).ConfigureAwait(false);
Assert.IsTrue(await access.ChangePasswordAsync(session.User.Id, "initial-pass-1", "una password nuova", session.Id).ConfigureAwait(false));
Assert.IsNotNull(await access.ValidateAsync(token).ConfigureAwait(false));
Assert.IsNull(await access.ValidateAsync(other).ConfigureAwait(false));
Assert.IsFalse((await access.ValidateAsync(token).ConfigureAwait(false))!.User.MustChangePassword);
// Second factor.
var secret = Totp.NewSecret();
Assert.IsFalse(await access.EnableSecondFactorAsync(session.User.Id, secret, Totp.Compute(secret, clock.UtcNow.AddMinutes(10))).ConfigureAwait(false));
Assert.IsTrue(await access.EnableSecondFactorAsync(session.User.Id, secret, Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false));
Assert.AreEqual(LoginResult.SecondFactorNeeded, (await access.SignInAsync("una password nuova", null, null, null).ConfigureAwait(false)).Result);
var badCode = Totp.Compute(secret, clock.UtcNow.AddMinutes(10));
Assert.AreEqual(LoginResult.WrongSecondFactor, (await access.SignInAsync("una password nuova", badCode, null, null).ConfigureAwait(false)).Result);
Assert.AreEqual(LoginResult.Ok, (await access.SignInAsync("una password nuova", Totp.Compute(secret, clock.UtcNow), null, null).ConfigureAwait(false)).Result);
Assert.IsTrue(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova").ConfigureAwait(false));
// Idle and absolute timeouts.
clock.Advance(AccessStore.IdleTimeout);
Assert.IsNull(await access.ValidateAsync(token).ConfigureAwait(false));
var history = await new SettingsStore(test.Db, clock, new EventBus()).HistoryAsync().ConfigureAwait(false);
CollectionAssert.IsSubsetOf(new[] { "security.password", "security.second_factor" }, history.Select(h => h.Key).Distinct().ToList());
}
}