An independent review found these, now fixed and tested: - Risk limits could be raised through PUT /api/settings without the phrase and the password. The API now refuses risk keys. - The reference equity counted results twice after reduced to real and after a demotion. Each ledger now keeps a baseline, and carried results stay in the ledger's currency until the reference is computed. - An instrument could be bought by a second strategy in the same account (SPEC 8.6), and purchases under way did not hold their cash, so several purchases sent together could exceed it. Both are refused or shrunk now. - After an automatic trip of the switch there was no way to restart from the interface. Rischio now shows the trip of both worlds and the restart. - The fresh password of SPEC 12.4 could be tried without limit. Five wrong attempts in 15 minutes now lock it. - Observation to simulation skipped the 90 days of live signals. - A new build changed the qualification of a strategy with real money, "Ferma tutto" counted as a critical incident, raising risk ignored demotion conditions in progress, and weekends counted as stock sessions. - The 12.4 confirmation now summarises capital, first purchases and limits, and live strategies show the gap with their simulated twin. The backtest converts each bar with the rate fixed before it opens, the day before, and the report now counts how often correctives and risk changed a decision. crypto_trend is still not passed: the broad universe now falls 32.8%. The outcome file also keeps the qualified parameters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
318 lines
18 KiB
C#
318 lines
18 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.Unit)]
|
|
public void LoginLimiterCountsAnAttemptBeforeItsCheckEnds()
|
|
{
|
|
var clock = new ManualClock(DateTimeOffset.UnixEpoch);
|
|
var limiter = new LoginLimiter(clock);
|
|
|
|
// Five attempts started together, none finished yet: the sixth already waits.
|
|
for (var i = 0; i < LoginLimiter.PerAddress; i++)
|
|
{
|
|
Assert.AreEqual(TimeSpan.Zero, limiter.Begin("10.0.0.2"));
|
|
}
|
|
|
|
Assert.IsGreaterThan(TimeSpan.Zero, limiter.Begin("10.0.0.2"));
|
|
|
|
// A correct password still waiting for its code is taken back; a success clears the address.
|
|
limiter.Forgive("10.0.0.2");
|
|
Assert.AreEqual(TimeSpan.Zero, limiter.Begin("10.0.0.2"));
|
|
limiter.Succeeded("10.0.0.2");
|
|
Assert.AreEqual(TimeSpan.Zero, limiter.Wait("10.0.0.2"));
|
|
}
|
|
|
|
[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);
|
|
|
|
// Each code works once: the one used to switch it on does not sign in, the next one does, and only once.
|
|
Assert.AreEqual(LoginResult.WrongSecondFactor, (await access.SignInAsync("una password nuova", Totp.Compute(secret, clock.UtcNow), null, null).ConfigureAwait(false)).Result);
|
|
clock.Advance(TimeSpan.FromSeconds(30));
|
|
var code = Totp.Compute(secret, clock.UtcNow);
|
|
Assert.AreEqual(LoginResult.Ok, (await access.SignInAsync("una password nuova", code, null, null).ConfigureAwait(false)).Result);
|
|
Assert.AreEqual(LoginResult.WrongSecondFactor, (await access.SignInAsync("una password nuova", code, null, null).ConfigureAwait(false)).Result);
|
|
|
|
// Switching it off asks for the password and a fresh code.
|
|
clock.Advance(TimeSpan.FromSeconds(30));
|
|
Assert.IsFalse(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", null).ConfigureAwait(false));
|
|
Assert.IsTrue(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", Totp.Compute(secret, clock.UtcNow)).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());
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task TheFreshPasswordOfTheProcedureStopsAfterFiveWrongAttempts()
|
|
{
|
|
// SPEC 12.4: a stolen session must not be able to try passwords on the confirmation forms.
|
|
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
|
|
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
|
var access = new AccessStore(test.Db, clock, new SecretStore(test.Db, clock, new byte[32]), iterations: 1000);
|
|
Assert.IsTrue(await access.EnsureUserAsync("password-giusta", mustChange: false).ConfigureAwait(false));
|
|
Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false));
|
|
|
|
for (var i = 0; i < LoginLimiter.PerAddress; i++)
|
|
{
|
|
Assert.IsFalse(await access.ReauthenticateAsync("sbagliata-" + i, null).ConfigureAwait(false));
|
|
}
|
|
|
|
Assert.IsFalse(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false), "even the right password waits");
|
|
clock.Advance(LoginLimiter.Window);
|
|
Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false));
|
|
}
|
|
}
|