A position left out together with its stop kept the account prudent for good: the stop was still asked for shares that no longer exist. The cover required now stops at what the account holds, the stops are compared again after the choice, and where one is still missing Align takes the excluded position up again. After the choice the account waits for the stop with its own reason, so it returns to normal by itself also past the 15 minutes; a new difference still gets its own 15 minutes. A right password alone no longer clears the wrong second-factor codes: it takes back only its own attempt. Capital and shares are planned and written in one transaction, so overlapping changes cannot apply twice and an interruption leaves nothing halfway; sending the same figures again completes what an old one left. The cash that purchases under way still hold is no longer given away, counted as the risk engine counts it. /health said healthy when the trading engine had failed to start. It now says so at once, or after ten minutes of a stalled start, and the host tries the start again every minute; the guard still sees a start that does not move. The image of the manual publication says its version and its commit, marked when the tree is dirty, and publish.sh refuses before any login an image that does not come from the commit of the tag. refs #75 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
439 lines
27 KiB
C#
439 lines
27 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);
|
|
|
|
// The file of the data folder is lost: nobody can tell this database from an old copy, so the engine does not start.
|
|
var before = Installation.ReadFile(data)!;
|
|
File.Delete(data.InstallationFile);
|
|
var missing = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false);
|
|
Assert.AreEqual(IdentityVerdict.MissingFile, missing.Verdict);
|
|
Assert.IsFalse(missing.CanStart);
|
|
Assert.IsFalse(File.Exists(data.InstallationFile));
|
|
|
|
// A stale copy of the database: same installation, older fingerprint.
|
|
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, "prova").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: whoever asks goes on without it, and the status says it must be entered again.
|
|
var otherKey = new SecretStore(test.Db, clock, Enumerable.Repeat((byte)7, 32).ToArray());
|
|
Assert.IsNull(await otherKey.RevealAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false));
|
|
Assert.IsTrue((await otherKey.StatusAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)).Unreadable);
|
|
Assert.IsFalse((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)).Unreadable);
|
|
|
|
// 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);
|
|
var stolen = token;
|
|
(var changed, token) = await access.ChangePasswordAsync(session.User.Id, "initial-pass-1", "una password nuova", session.Id).ConfigureAwait(false);
|
|
Assert.AreEqual(AccessChange.Done, changed);
|
|
Assert.IsNull(await access.ValidateAsync(stolen).ConfigureAwait(false), "A copy of the cookie stops working too.");
|
|
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();
|
|
var (_, elsewhere) = await access.SignInAsync("una password nuova", null, null, null).ConfigureAwait(false);
|
|
Task<AccessChange> EnableAsync(byte[] with, string password, string number) => access.EnableSecondFactorAsync(session.User.Id, with, password, number, session.Id);
|
|
Assert.AreEqual(AccessChange.Wrong, await EnableAsync(secret, "una password nuova", Totp.Compute(secret, clock.UtcNow.AddMinutes(10))).ConfigureAwait(false));
|
|
Assert.AreEqual(AccessChange.Wrong, await EnableAsync(secret, "not the password", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false), "A session alone is not enough.");
|
|
Assert.IsNotNull(await access.ValidateAsync(elsewhere).ConfigureAwait(false));
|
|
Assert.AreEqual(AccessChange.Done, await EnableAsync(secret, "una password nuova", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false));
|
|
Assert.IsNull(await access.ValidateAsync(elsewhere).ConfigureAwait(false), "The other sessions signed in without the factor: they end.");
|
|
Assert.IsNotNull(await access.ValidateAsync(token).ConfigureAwait(false));
|
|
var draft = Totp.NewSecret();
|
|
Assert.AreEqual(AccessChange.AlreadyOn, await EnableAsync(draft, "una password nuova", Totp.Compute(draft, clock.UtcNow)).ConfigureAwait(false), "Never over an active one.");
|
|
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.AreEqual(AccessChange.Wrong, await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", null, session.Id).ConfigureAwait(false));
|
|
Assert.AreEqual(AccessChange.Done, await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", Totp.Compute(secret, clock.UtcNow), session.Id).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));
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task EveryCheckOfThePasswordSharesOneLimitThatTheServicesCannotClear()
|
|
{
|
|
var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 9, 0, 0, TimeSpan.Zero));
|
|
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
|
var guards = new AccessGuards(clock);
|
|
AccessStore Started() => new(test.Db, clock, new SecretStore(test.Db, clock, new byte[32]), iterations: 1000, guards);
|
|
var access = Started();
|
|
Assert.IsTrue(await access.EnsureUserAsync("password-giusta", mustChange: false).ConfigureAwait(false));
|
|
var user = (await access.GetUserAsync().ConfigureAwait(false))!.Id;
|
|
var secret = Totp.NewSecret();
|
|
|
|
Assert.AreEqual(AccessChange.Wrong, (await access.ChangePasswordAsync(user, "sbagliata-1", "una password nuova", Guid.Empty).ConfigureAwait(false)).Outcome);
|
|
Assert.AreEqual(AccessChange.Wrong, await access.DisableSecondFactorAsync(user, "sbagliata-2", null, Guid.Empty).ConfigureAwait(false));
|
|
Assert.AreEqual(AccessChange.Wrong, await access.EnableSecondFactorAsync(user, secret, "sbagliata-3", Totp.Compute(secret, clock.UtcNow), Guid.Empty).ConfigureAwait(false));
|
|
Assert.IsFalse(await Started().ReauthenticateAsync("sbagliata-4", null).ConfigureAwait(false), "The services start again, the count goes on.");
|
|
Assert.IsFalse(await Started().ReauthenticateAsync("sbagliata-5", null).ConfigureAwait(false));
|
|
|
|
access = Started();
|
|
Assert.AreEqual(AccessChange.Locked, (await access.ChangePasswordAsync(user, "password-giusta", "una password nuova", Guid.Empty).ConfigureAwait(false)).Outcome);
|
|
Assert.AreEqual(AccessChange.Locked, await access.DisableSecondFactorAsync(user, "password-giusta", null, Guid.Empty).ConfigureAwait(false));
|
|
Assert.AreEqual(AccessChange.Locked, await access.EnableSecondFactorAsync(user, secret, "password-giusta", Totp.Compute(secret, clock.UtcNow), Guid.Empty).ConfigureAwait(false));
|
|
clock.Advance(LoginLimiter.Window);
|
|
var code = Totp.Compute(secret, clock.UtcNow);
|
|
Assert.AreEqual(AccessChange.Done, await access.EnableSecondFactorAsync(user, secret, "password-giusta", code, Guid.Empty).ConfigureAwait(false));
|
|
Assert.IsFalse(await Started().ReauthenticateAsync("password-giusta", code).ConfigureAwait(false), "A code used once stays used after the services start again.");
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task ThePasswordAloneDoesNotClearTheWrongCodes()
|
|
{
|
|
var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 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));
|
|
var user = (await access.GetUserAsync().ConfigureAwait(false))!.Id;
|
|
var secret = Totp.NewSecret();
|
|
Assert.AreEqual(AccessChange.Done, await access.EnableSecondFactorAsync(user, secret, "password-giusta", Totp.Compute(secret, clock.UtcNow), Guid.Empty).ConfigureAwait(false));
|
|
clock.Advance(TimeSpan.FromMinutes(1));
|
|
var wrong = Totp.Compute(secret, clock.UtcNow.AddHours(1));
|
|
|
|
// Whoever knows the password and not the code: neither form gives back the attempts.
|
|
for (var i = 0; i < LoginLimiter.PerAddress - 1; i++)
|
|
{
|
|
Assert.IsFalse(await access.ReauthenticateAsync("password-giusta", wrong).ConfigureAwait(false));
|
|
}
|
|
|
|
Assert.AreEqual(AccessChange.Done, (await access.ChangePasswordAsync(user, "password-giusta", "una password nuova", Guid.Empty).ConfigureAwait(false)).Outcome, "It takes back its own attempt only.");
|
|
Assert.AreEqual(AccessChange.AlreadyOn, await access.EnableSecondFactorAsync(user, Totp.NewSecret(), "una password nuova", "000000", Guid.Empty).ConfigureAwait(false));
|
|
Assert.IsFalse(await access.ReauthenticateAsync("una password nuova", wrong).ConfigureAwait(false));
|
|
Assert.IsFalse(await access.ReauthenticateAsync("una password nuova", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false), "Locked: even the right code waits.");
|
|
clock.Advance(LoginLimiter.Window);
|
|
|
|
// Both right: the count starts over.
|
|
Assert.IsFalse(await access.ReauthenticateAsync("una password nuova", wrong).ConfigureAwait(false));
|
|
Assert.IsTrue(await access.ReauthenticateAsync("una password nuova", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false));
|
|
for (var i = 0; i < LoginLimiter.PerAddress; i++)
|
|
{
|
|
Assert.AreEqual(AccessChange.Wrong, (await access.ChangePasswordAsync(user, "sbagliata", "una password nuova", Guid.Empty).ConfigureAwait(false)).Outcome);
|
|
}
|
|
|
|
Assert.AreEqual(AccessChange.Locked, (await access.ChangePasswordAsync(user, "una password nuova", "un'altra ancora", Guid.Empty).ConfigureAwait(false)).Outcome);
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task EndedSessionsAreRemovedAtTheNextSignIn()
|
|
{
|
|
var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 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));
|
|
var (_, listening) = await access.SignInAsync("password-giusta", null, "browser", "10.0.0.1").ConfigureAwait(false);
|
|
for (var i = 0; i < 12; i++)
|
|
{
|
|
Assert.IsNotNull(await access.ValidateAsync(listening, refresh: false).ConfigureAwait(false));
|
|
clock.Advance(TimeSpan.FromHours(1));
|
|
}
|
|
|
|
Assert.IsNull(await access.ValidateAsync(listening).ConfigureAwait(false), "Listening does not keep a session alive.");
|
|
await access.SignInAsync("password-giusta", null, null, null).ConfigureAwait(false);
|
|
Assert.AreEqual(1L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions")).ConfigureAwait(false));
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void SuccessfulSignInsDoNotFillTheOverallCount()
|
|
{
|
|
var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 9, 0, 0, TimeSpan.Zero));
|
|
var limiter = new LoginLimiter(clock);
|
|
for (var i = 0; i < 3 * LoginLimiter.Overall; i++)
|
|
{
|
|
Assert.AreEqual(TimeSpan.Zero, limiter.Begin("10.0.0.1"));
|
|
limiter.Succeeded("10.0.0.1");
|
|
}
|
|
|
|
for (var i = 0; i < LoginLimiter.Overall; i++)
|
|
{
|
|
Assert.AreEqual(TimeSpan.Zero, limiter.Begin("10.0.1." + i));
|
|
}
|
|
|
|
Assert.IsGreaterThan(TimeSpan.Zero, limiter.Begin("10.0.0.9"), "Twenty failures, from anywhere, still stop everyone.");
|
|
}
|
|
}
|