From fbf6e43955dbd1efaa1fe0b7c162a1ab6c68e53f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 11 Oct 2026 09:00:23 +0200 Subject: [PATCH 01/10] Concept vote rate limits: cast and mint budgets per account or network prefix One FixedWindowBudget (injectable clock) owned by ConceptVoteRateLimits; the vote page 429s with Retry-After before any row or cookie. Prefix lengths and budgets are validated in every environment. Pins the empty Origin branch of CastRequestGuard. Unverified; not yet built. Co-Authored-By: Claude Opus 5.5 --- .../Configuration/ConceptVoteOptions.cs | 14 + .../ConceptVotes/ConceptVoteRateLimits.cs | 28 ++ .../Features/Shared/FixedWindowBudget.cs | 78 ++++ .../Shared/StartupConfigurationValidator.cs | 45 +- src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs | 44 +- src/Bifrost.Web/Program.cs | 1 + .../Bifrost.Web.Tests/ConceptVotePageTests.cs | 58 +-- .../ConceptVoteRateLimitTests.cs | 392 ++++++++++++++++++ .../FixedWindowBudgetTests.cs | 93 +++++ tests/Bifrost.Web.Tests/HostTrustTests.cs | 56 ++- .../Support/CapturingLoggerProvider.cs | 45 ++ .../Support/TestAuthHandler.cs | 9 +- .../Support/TestWebApplicationFactory.cs | 2 + 13 files changed, 795 insertions(+), 70 deletions(-) create mode 100644 src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs create mode 100644 src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs create mode 100644 tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs create mode 100644 tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs create mode 100644 tests/Bifrost.Web.Tests/Support/CapturingLoggerProvider.cs diff --git a/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs b/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs index a5e0781..41a866e 100644 --- a/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs +++ b/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs @@ -20,6 +20,20 @@ public sealed class ConceptVoteOptions // default weighed in the note, not a standard. Tune on observed abuse. public int IPv6PrefixLength { get; init; } = 56; + // Vote budgets (Features/ConceptVotes/ConceptVoteRateLimits). The research note + // (docs/research/anonymous-vote-stuffing-prior-art.md section 3) gives no numbers, so these are first values to tune on + // observed abuse. Cast: one visitor reading through the Mill can vote on a few dozen concepts in a sitting, so 30 per + // 10 minutes per account or network prefix does not trouble a person and caps a script at 180 an hour. + public int CastPermits { get; init; } = 30; + + public TimeSpan CastWindow { get; init; } = TimeSpan.FromMinutes(10); + + // Mint: a new device cookie is a new voter identity, the cheapest stuffing lever, and a household has few devices, + // so 5 new devices per hour per network prefix. + public int MintPermits { get; init; } = 5; + + public TimeSpan MintWindow { get; init; } = TimeSpan.FromHours(1); + // The origins whose pages may read the public tally export from a browser (CORS). Each entry is exactly // https://host[:non-default-port], lower case, no path; empty allows none. StartupConfigurationValidator // refuses anything else outside Development and Testing, because "*" would allow every origin. diff --git a/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs b/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs new file mode 100644 index 0000000..aac9802 --- /dev/null +++ b/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs @@ -0,0 +1,28 @@ +using System.Net; +using Bifrost.Web.Configuration; +using Bifrost.Web.Features.Shared; +using Microsoft.Extensions.Options; + +namespace Bifrost.Web.Features.ConceptVotes; + +// The one owner of the vote budgets. Cast is spent by every cast and retract; mint is spent additionally by a cast that +// is about to mint a device cookie. A denial returns how long to wait and writes nothing. The partition is the account +// when the voter is signed in, otherwise the network prefix (NetworkPrefix.Of) of the address the forwarded-headers +// middleware left on the connection. No header and no client input ever becomes a key. +public sealed class ConceptVoteRateLimits(IOptions options, TimeProvider clock) +{ + private readonly ConceptVoteOptions opts = options.Value; + private readonly FixedWindowBudget cast = new(options.Value.CastPermits, options.Value.CastWindow, clock); + private readonly FixedWindowBudget mint = new(options.Value.MintPermits, options.Value.MintWindow, clock); + + public TimeSpan? DenyCast(IPAddress? client, VoterIdentity? known) => + cast.TryAcquire(known?.UserAccountId is { } account ? "account:" + account.ToString("N") : NetKey(client), out var wait) + ? null + : wait; + + public TimeSpan? DenyMint(IPAddress? client) => + mint.TryAcquire(NetKey(client), out var wait) ? null : wait; + + private string NetKey(IPAddress? client) => + "net:" + (client is null ? "unknown" : NetworkPrefix.Of(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength)); +} diff --git a/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs b/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs new file mode 100644 index 0000000..abcaa0f --- /dev/null +++ b/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs @@ -0,0 +1,78 @@ +namespace Bifrost.Web.Features.Shared; + +// The one rate-limit mechanism: a fixed-window permit budget per caller-chosen partition key, read against an injected +// clock. Keys are opaque and are never stored beyond their window: an entry whose window has ended is dropped by the +// next sweep, so the table is bounded by the distinct keys seen in one window. System.Threading.RateLimiting is not +// used because its limiters time themselves on Stopwatch and timers, which a test cannot move. +public sealed class FixedWindowBudget +{ + private readonly int permits; + private readonly TimeSpan window; + private readonly TimeProvider clock; + private readonly Dictionary entries = new(StringComparer.Ordinal); + private readonly object gate = new(); + private DateTimeOffset nextSweep = DateTimeOffset.MinValue; + + public FixedWindowBudget(int permits, TimeSpan window, TimeProvider clock) + { + ArgumentOutOfRangeException.ThrowIfLessThan(permits, 1); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(window, TimeSpan.Zero); + this.permits = permits; + this.window = window; + this.clock = clock; + } + + // How many keys are held now: bounded by the distinct keys seen in one window, not by every key ever seen. + public int TrackedKeys + { + get + { + lock (gate) + { + return entries.Count; + } + } + } + + // Takes one permit for the key. When none is left, returns false and how long until its window ends. + public bool TryAcquire(string key, out TimeSpan retryAfter) + { + var now = clock.GetUtcNow(); + lock (gate) + { + if (now >= nextSweep) + { + foreach (var expired in entries.Where(x => x.Value.Start + window <= now).Select(x => x.Key).ToList()) + { + entries.Remove(expired); + } + + nextSweep = now + window; + } + + if (!entries.TryGetValue(key, out var entry) || entry.Start + window <= now) + { + entries[key] = new Entry(now); + retryAfter = TimeSpan.Zero; + return true; + } + + if (entry.Count < permits) + { + entry.Count++; + retryAfter = TimeSpan.Zero; + return true; + } + + retryAfter = entry.Start + window - now; + return false; + } + } + + private sealed class Entry(DateTimeOffset start) + { + public DateTimeOffset Start { get; } = start; + + public int Count { get; set; } = 1; + } +} diff --git a/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs index c511413..676e628 100644 --- a/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs +++ b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs @@ -16,12 +16,35 @@ public sealed class StartupConfigurationValidator( { public void Validate() { - if (hostEnvironment.IsDevelopment() || hostEnvironment.IsEnvironment("Testing")) + var failures = new List(); + + // Checked in every environment: a bad value here would otherwise pass startup and throw on every cast. + var conceptVotes = conceptVoteOptions.Value; + if (!NetworkPrefix.IsValidLength(conceptVotes.IPv4PrefixLength, NetworkPrefix.IPv4Bits)) { - return; + failures.Add($"ConceptVotes:IPv4PrefixLength must be between 0 and {NetworkPrefix.IPv4Bits}."); } - var failures = new List(); + if (!NetworkPrefix.IsValidLength(conceptVotes.IPv6PrefixLength, NetworkPrefix.IPv6Bits)) + { + failures.Add($"ConceptVotes:IPv6PrefixLength must be between 0 and {NetworkPrefix.IPv6Bits}."); + } + + if (conceptVotes.CastPermits < 1 || conceptVotes.CastWindow <= TimeSpan.Zero) + { + failures.Add("ConceptVotes:CastPermits must be at least 1 and ConceptVotes:CastWindow must be positive."); + } + + if (conceptVotes.MintPermits < 1 || conceptVotes.MintWindow <= TimeSpan.Zero) + { + failures.Add("ConceptVotes:MintPermits must be at least 1 and ConceptVotes:MintWindow must be positive."); + } + + if (hostEnvironment.IsDevelopment() || hostEnvironment.IsEnvironment("Testing")) + { + Refuse(failures); + return; + } if (!gitHubOAuthOptions.Value.IsConfigured) { @@ -73,7 +96,6 @@ public sealed class StartupConfigurationValidator( failures.Add("DataProtection:KeysPath must be configured for production."); } - var conceptVotes = conceptVoteOptions.Value; if (string.IsNullOrWhiteSpace(conceptVotes.NetworkTagSecret) || conceptVotes.NetworkTagSecret.Length < ConceptVoteOptions.MinNetworkTagSecretLength) { @@ -81,21 +103,16 @@ public sealed class StartupConfigurationValidator( $"ConceptVotes:NetworkTagSecret must be configured with at least {ConceptVoteOptions.MinNetworkTagSecretLength} characters for production."); } - if (!NetworkPrefix.IsValidLength(conceptVotes.IPv4PrefixLength, NetworkPrefix.IPv4Bits)) - { - failures.Add($"ConceptVotes:IPv4PrefixLength must be between 0 and {NetworkPrefix.IPv4Bits}."); - } - - if (!NetworkPrefix.IsValidLength(conceptVotes.IPv6PrefixLength, NetworkPrefix.IPv6Bits)) - { - failures.Add($"ConceptVotes:IPv6PrefixLength must be between 0 and {NetworkPrefix.IPv6Bits}."); - } - if (!conceptVotes.AllowedOrigins.All(IsExactHttpsOrigin)) { failures.Add("ConceptVotes:AllowedOrigins entries must each be exactly https://host with no path, wildcard or trailing slash."); } + Refuse(failures); + } + + private static void Refuse(List failures) + { if (failures.Count > 0) { throw new InvalidOperationException( diff --git a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs index 525811d..5e46e1d 100644 --- a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs +++ b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs @@ -17,6 +17,7 @@ public sealed class VoteModel( ICurrentBifrostActorAccessor actorAccessor, ConceptAppraisalService appraisals, VoterKeyResolver deviceCookie, + ConceptVoteRateLimits limits, IOptions options, IOptions host) : PageModel { @@ -61,7 +62,7 @@ public sealed class VoteModel( public async Task OnGetAsync(string collection, string key, CancellationToken cancellationToken) { var actor = await actorAccessor.GetAsync(cancellationToken); - var voter = ResolveVoter(actor, mint: false); + var voter = ResolveVoter(actor); SignedIn = voter?.UserAccountId is not null; return await LoadAsync(collection, key, voter, cancellationToken) ? Page() : NotFound(); } @@ -75,12 +76,17 @@ public sealed class VoteModel( public async Task OnPostRetractAsync(string collection, string key, CancellationToken cancellationToken) { var actor = await actorAccessor.GetAsync(cancellationToken); + var voter = ResolveVoter(actor); + if (Throttled(limits.DenyCast(HttpContext.Connection.RemoteIpAddress, voter)) is { } throttled) + { + return throttled; + } + if (await appraisals.GetSubjectAsync(collection, key, null, cancellationToken) is null) { return NotFound(); } - var voter = ResolveVoter(actor, mint: false); await appraisals.RetractAsync(collection, key, voter, cancellationToken); return RedirectToPage(new { collection, key }); } @@ -92,12 +98,28 @@ public sealed class VoteModel( CancellationToken cancellationToken) { var actor = await actorAccessor.GetAsync(cancellationToken); + var client = HttpContext.Connection.RemoteIpAddress; + var voter = ResolveVoter(actor); + if (Throttled(limits.DenyCast(client, voter)) is { } throttled) + { + return throttled; + } + if (await appraisals.GetSubjectAsync(collection, key, null, cancellationToken) is null) { return NotFound(); } - var voter = ResolveVoter(actor, mint: true); + if (voter is null) + { + if (Throttled(limits.DenyMint(client)) is { } mintThrottled) + { + return mintThrottled; + } + + voter = VoterIdentity.For(actor, deviceCookie.Mint(HttpContext)); + } + var result = await appraisals.CastAsync( collection, key, voter, stance, HttpContext.Connection.RemoteIpAddress, cancellationToken); return result is CastResult.UnknownSubject or CastResult.RetiredSubject @@ -106,16 +128,20 @@ public sealed class VoteModel( } // Accounts key to the account and never touch the cookie. An anonymous visitor keys to a device cookie that - // unprotects to a well-formed id; a cast without one mints it, and no other path does. - private VoterIdentity? ResolveVoter(CurrentBifrostActor actor, bool mint) + // unprotects to a well-formed id; a cast without one mints it (CastAsync, after the mint budget), and no other path does. + private VoterIdentity? ResolveVoter(CurrentBifrostActor actor) => + VoterIdentity.For(actor, null) ?? VoterIdentity.For(actor, deviceCookie.TryRead(HttpContext)); + + // A denied budget is a 429 that says when to retry; it writes no row and sets no cookie. + private IActionResult? Throttled(TimeSpan? retryAfter) { - var voter = VoterIdentity.For(actor, null) ?? VoterIdentity.For(actor, deviceCookie.TryRead(HttpContext)); - if (voter is null && mint) + if (retryAfter is not { } wait) { - voter = VoterIdentity.For(actor, deviceCookie.Mint(HttpContext)); + return null; } - return voter; + Response.Headers.RetryAfter = Math.Max(1, (int)Math.Ceiling(wait.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture); + return new StatusCodeResult(StatusCodes.Status429TooManyRequests); } private async Task LoadAsync(string collection, string key, VoterIdentity? voter, CancellationToken cancellationToken) diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index 94276e1..99ecd84 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -119,6 +119,7 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs b/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs index 1870b6f..b31c1c0 100644 --- a/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs @@ -183,6 +183,22 @@ public sealed partial class ConceptVotePageTests : IClassFixture _lines = []; - - public IReadOnlyList Lines - { - get - { - lock (_lines) - { - return _lines.ToArray(); - } - } - } - - public ILogger CreateLogger(string categoryName) => new Capture(this); - - public void Dispose() - { - } - - private sealed class Capture(CapturingLoggerProvider owner) : ILogger - { - public IDisposable? BeginScope(TState state) where TState : notnull => null; - - public bool IsEnabled(LogLevel logLevel) => true; - - public void Log( - LogLevel logLevel, - EventId eventId, - TState state, - Exception? exception, - Func formatter) - { - lock (owner._lines) - { - owner._lines.Add(formatter(state, exception) + (exception is null ? string.Empty : "\n" + exception)); - } - } - } - } } diff --git a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs new file mode 100644 index 0000000..7165973 --- /dev/null +++ b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs @@ -0,0 +1,392 @@ +using System.Net; +using Bifrost.Web.Data; +using Bifrost.Web.Domain; +using Bifrost.Web.Tests.Support; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; + +namespace Bifrost.Web.Tests; + +// The vote budgets through the full pipeline: a loopback peer (the proxy) forwards the client address in +// X-Forwarded-For, the clock is the test's own, and Cast is 3 per 10 minutes, Mint 2 per hour. +public sealed class ConceptVoteRateLimitTests : IClassFixture +{ + private const string Site = "https://localhost"; + private const string CookieName = "bifrost_voter"; + + private readonly LimitedFactory _factory; + + public ConceptVoteRateLimitTests(LimitedFactory factory) => _factory = factory; + + [Fact] + public async Task Burst_from_one_prefix_gets_429_while_another_prefix_is_unaffected() + { + var collection = await NewSubject(); + var device = new Client(_factory, "203.0.113.10"); + foreach (var handler in new[] { "Up", "Down", "Up" }) + { + using var ok = await device.Post(collection, handler); + Assert.Equal(HttpStatusCode.Redirect, ok.StatusCode); + } + + using var denied = await device.Post(collection, "Down"); + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); + + var other = new Client(_factory, "203.0.113.11"); + using var unaffected = await other.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, unaffected.StatusCode); + } + + [Fact] + public async Task Retract_spends_the_cast_budget() + { + var collection = await NewSubject(); + var device = new Client(_factory, "203.0.113.12"); + await device.Post(collection, "Up"); + await device.Post(collection, "Retract"); + await device.Post(collection, "Retract"); + + using var denied = await device.Post(collection, "Retract"); + + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); + } + + [Fact] + public async Task Addresses_in_one_ipv6_prefix_share_a_bucket_and_another_prefix_does_not() + { + var collection = await NewSubject(); + var first = new Client(_factory, "2001:db8:1:100::1"); + var sameBlock = new Client(_factory, "2001:db8:1:1ff::2"); + await first.Post(collection, "Up"); + await first.Post(collection, "Down"); + using var third = await sameBlock.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, third.StatusCode); + + using var denied = await sameBlock.Post(collection, "Down"); + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); + + var elsewhere = new Client(_factory, "2001:db8:1:200::1"); + using var unaffected = await elsewhere.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, unaffected.StatusCode); + } + + [Fact] + public async Task The_window_ends_exactly_at_its_length_and_retry_after_counts_down_to_it() + { + var collection = await NewSubject(); + var device = new Client(_factory, "203.0.113.13"); + for (var i = 0; i < 3; i++) + { + await device.Post(collection, "Up"); + } + + using (var first = await device.Post(collection, "Up")) + { + Assert.Equal(HttpStatusCode.TooManyRequests, first.StatusCode); + Assert.Equal("600", RetryAfter(first)); + } + + _factory.Clock.Advance(TimeSpan.FromSeconds(100)); + using (var later = await device.Post(collection, "Up")) + { + Assert.Equal(HttpStatusCode.TooManyRequests, later.StatusCode); + Assert.Equal("500", RetryAfter(later)); + } + + _factory.Clock.Advance(TimeSpan.FromSeconds(499)); + using (var last = await device.Post(collection, "Up")) + { + Assert.Equal(HttpStatusCode.TooManyRequests, last.StatusCode); + Assert.Equal("1", RetryAfter(last)); + } + + _factory.Clock.Advance(TimeSpan.FromSeconds(1)); + using var reopened = await device.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, reopened.StatusCode); + } + + [Fact] + public async Task Forged_forwarded_header_from_non_loopback_peer_does_not_move_the_bucket() + { + var collection = await NewSubject(); + var device = new Client(_factory, "198.51.100.9") { Peer = "198.51.100.9" }; + for (var i = 0; i < 3; i++) + { + using var ok = await device.Post(collection, "Up", forwardedFor: $"192.0.2.{i + 1}"); + Assert.Equal(HttpStatusCode.Redirect, ok.StatusCode); + } + + using var denied = await device.Post(collection, "Up", forwardedFor: "192.0.2.200"); + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); + } + + [Fact] + public async Task Signed_in_accounts_are_limited_per_account() + { + var collection = await NewSubject(); + var alice = new Client(_factory, "203.0.113.20") { Account = ("7001", "alice-limits") }; + var aliceElsewhere = new Client(_factory, "203.0.113.21") { Account = ("7001", "alice-limits") }; + var bob = new Client(_factory, "203.0.113.20") { Account = ("7002", "bob-limits") }; + var visitor = new Client(_factory, "203.0.113.20"); + + await alice.Post(collection, "Up"); + await alice.Post(collection, "Down"); + await aliceElsewhere.Post(collection, "Up"); + using var denied = await aliceElsewhere.Post(collection, "Down"); + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); + + var aliceAgain = new Client(_factory, "203.0.113.22") { Account = ("7001", "alice-limits") }; + using var sameAccountNewPrefix = await aliceAgain.Post(collection, "Down"); + Assert.Equal(HttpStatusCode.TooManyRequests, sameAccountNewPrefix.StatusCode); + + using var bobOk = await bob.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, bobOk.StatusCode); + using var visitorOk = await visitor.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, visitorOk.StatusCode); + } + + [Fact] + public async Task Mint_budget_is_spent_only_by_minting_casts() + { + var collection = await NewSubject(); + const string prefix = "203.0.113.30"; + var first = new Client(_factory, prefix); + using (var mint = await first.Post(collection, "Up")) + { + Assert.NotNull(SetCookie(mint)); + } + + // Recasts by the existing device spend cast permits only; they would exhaust a budget of 2 if they spent mint. + using (var recast = await first.Post(collection, "Down")) + { + Assert.Equal(HttpStatusCode.Redirect, recast.StatusCode); + Assert.Null(SetCookie(recast)); + } + + using (var recastAgain = await first.Post(collection, "Up")) + { + Assert.Equal(HttpStatusCode.Redirect, recastAgain.StatusCode); + } + + _factory.Clock.Advance(TimeSpan.FromMinutes(10)); + var second = new Client(_factory, prefix); + using (var secondMint = await second.Post(collection, "Up")) + { + Assert.Equal(HttpStatusCode.Redirect, secondMint.StatusCode); + Assert.NotNull(SetCookie(secondMint)); + } + + var rowsBefore = (await Rows(collection)).Count; + var third = new Client(_factory, prefix); + using var denied = await third.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); + Assert.Null(SetCookie(denied)); + Assert.Equal(rowsBefore, (await Rows(collection)).Count); + + // An hour after the first mint the budget is whole again. + _factory.Clock.Advance(TimeSpan.FromMinutes(50)); + using var reopened = await third.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, reopened.StatusCode); + } + + [Fact] + public async Task Anonymous_cast_under_the_limit_succeeds() + { + var collection = await NewSubject(); + var visitor = new Client(_factory, "203.0.113.40"); + + using var response = await visitor.Post(collection, "Up"); + + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + var row = Assert.Single(await Rows(collection)); + Assert.Equal(VoterClass.Anonymous, row.VoterClass); + Assert.Equal(ConceptStance.Up, row.Stance); + } + + [Fact] + public async Task Rejection_writes_nothing_says_when_to_retry_and_echoes_no_address() + { + var logs = new CapturingLoggerProvider(); + var factory = _factory.WithWebHostBuilder(b => b.ConfigureServices(s => s.AddLogging(l => l.AddProvider(logs)))); + var collection = await NewSubject(); + var visitor = new Client(factory, "203.0.113.77"); + for (var i = 0; i < 3; i++) + { + await visitor.Post(collection, i == 1 ? "Down" : "Up"); + } + + var before = Assert.Single(await Rows(collection)); + using var denied = await visitor.Post(collection, "Down"); + + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); + Assert.NotNull(RetryAfter(denied)); + Assert.Null(SetCookie(denied)); + var after = Assert.Single(await Rows(collection)); + Assert.Equal(before.Stance, after.Stance); + var seen = await denied.Content.ReadAsStringAsync() + + string.Join("\n", denied.Headers.Select(h => h.Key + ":" + string.Join(",", h.Value))); + Assert.DoesNotContain("203.0.113", seen); + Assert.DoesNotContain(logs.Lines, line => line.Contains("203.0.113", StringComparison.Ordinal)); + } + + [Fact] + public async Task Reads_are_not_under_the_vote_budgets() + { + var collection = await NewSubject(); + var visitor = new Client(_factory, "203.0.113.50"); + for (var i = 0; i < 4; i++) + { + await visitor.Post(collection, "Up"); + } + + using var page = await visitor.Get($"/mill/{collection}/alpha"); + using var export = await visitor.Get($"/public/concepts/{collection}/tallies"); + + Assert.Equal(HttpStatusCode.OK, page.StatusCode); + Assert.Equal(HttpStatusCode.OK, export.StatusCode); + } + + private static string? RetryAfter(HttpResponseMessage response) => + response.Headers.TryGetValues("Retry-After", out var values) ? values.Single() : null; + + private static string? SetCookie(HttpResponseMessage response) => + response.Headers.TryGetValues("Set-Cookie", out var values) + ? values.FirstOrDefault(x => x.StartsWith(CookieName + "=", StringComparison.Ordinal)) + : null; + + private async Task NewSubject() + { + var collection = "c" + Guid.NewGuid().ToString("N"); + using var scope = _factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.ConceptSubjects.Add(new ConceptSubject + { + Collection = collection, + Key = "alpha", + Title = "alpha", + RegisteredAtUtc = DateTimeOffset.UtcNow + }); + await db.SaveChangesAsync(); + return collection; + } + + private async Task> Rows(string collection) + { + using var scope = _factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.ConceptAppraisals.AsNoTracking() + .Where(x => x.Subject!.Collection == collection) + .ToListAsync(); + } + + // One browser: a client address that reaches the app through the proxy, a cookie jar, optionally an account. + private sealed class Client(WebApplicationFactory factory, string address) + { + private readonly HttpClient _http = factory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + HandleCookies = false, + BaseAddress = new Uri(Site) + }); + + private string? _cookie; + + public string Peer { get; init; } = "127.0.0.1"; + + public (string Id, string Login)? Account { get; init; } + + public Task Post(string collection, string handler, string? forwardedFor = null) => + Send( + new HttpRequestMessage(HttpMethod.Post, $"/mill/{collection}/alpha?handler={handler}") + { + Content = new FormUrlEncodedContent([]) + }, + forwardedFor); + + public Task Get(string path) => Send(new HttpRequestMessage(HttpMethod.Get, path), null); + + private async Task Send(HttpRequestMessage request, string? forwardedFor) + { + request.Headers.TryAddWithoutValidation("Origin", Site); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", forwardedFor ?? address); + request.Headers.TryAddWithoutValidation("X-Test-Peer", Peer); + if (Account is { } account) + { + request.Headers.TryAddWithoutValidation("X-Test-GitHub-Id", account.Id); + request.Headers.TryAddWithoutValidation("X-Test-GitHub-Login", account.Login); + } + else + { + request.Headers.TryAddWithoutValidation("X-Test-Anonymous", "true"); + } + + if (_cookie is not null) + { + request.Headers.TryAddWithoutValidation("Cookie", _cookie); + } + + var response = await _http.SendAsync(request); + if (SetCookie(response) is { } set) + { + _cookie = set.Split(';')[0]; + } + + return response; + } + } + + public sealed class LimitedFactory : TestWebApplicationFactory + { + public TestClock Clock { get; } = new(); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + builder.ConfigureAppConfiguration((_, configuration) => + configuration.AddInMemoryCollection(new Dictionary + { + ["ConceptVotes:CastPermits"] = "3", + ["ConceptVotes:CastWindow"] = "00:10:00", + ["ConceptVotes:MintPermits"] = "2", + ["ConceptVotes:MintWindow"] = "01:00:00", + ["ConceptVotes:NetworkTagSecret"] = "rate-limit-test-tag-secret-0123456789" + })); + builder.ConfigureServices(services => + { + services.RemoveAll(); + services.AddSingleton(Clock); + services.AddTransient(); + }); + } + } + + public sealed class TestClock : TimeProvider + { + private DateTimeOffset _now = DateTimeOffset.UtcNow; + + public override DateTimeOffset GetUtcNow() => _now; + + public void Advance(TimeSpan by) => _now += by; + } + + // The proxy's connection: TestServer has no socket, so the peer address is set ahead of the app pipeline. + private sealed class PeerFilter : IStartupFilter + { + public Action Configure(Action next) => app => + { + app.Use((context, nextMiddleware) => + { + context.Connection.RemoteIpAddress = + IPAddress.Parse(context.Request.Headers["X-Test-Peer"].FirstOrDefault() ?? "127.0.0.1"); + return nextMiddleware(context); + }); + next(app); + }; + } +} diff --git a/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs b/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs new file mode 100644 index 0000000..0343c7f --- /dev/null +++ b/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs @@ -0,0 +1,93 @@ +using Bifrost.Web.Features.Shared; + +namespace Bifrost.Web.Tests; + +public sealed class FixedWindowBudgetTests +{ + private static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + + [Fact] + public void Permits_are_spent_per_key_and_the_next_is_denied_with_the_time_left() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(2, Window, clock); + + Assert.True(budget.TryAcquire("a", out _)); + clock.Advance(TimeSpan.FromSeconds(10)); + Assert.True(budget.TryAcquire("a", out _)); + Assert.False(budget.TryAcquire("a", out var wait)); + + Assert.Equal(TimeSpan.FromSeconds(50), wait); + Assert.True(budget.TryAcquire("b", out _)); + } + + [Fact] + public void A_window_opens_at_its_first_permit_and_closes_exactly_one_window_later() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(1, Window, clock); + Assert.True(budget.TryAcquire("a", out _)); + + clock.Advance(Window - TimeSpan.FromTicks(1)); + Assert.False(budget.TryAcquire("a", out var wait)); + Assert.Equal(TimeSpan.FromTicks(1), wait); + + clock.Advance(TimeSpan.FromTicks(1)); + Assert.True(budget.TryAcquire("a", out _)); + Assert.False(budget.TryAcquire("a", out wait)); + Assert.Equal(Window, wait); + } + + [Fact] + public void A_denied_attempt_does_not_extend_the_window() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(1, Window, clock); + budget.TryAcquire("a", out _); + for (var i = 0; i < 5; i++) + { + clock.Advance(TimeSpan.FromSeconds(10)); + Assert.False(budget.TryAcquire("a", out _)); + } + + clock.Advance(TimeSpan.FromSeconds(10)); + Assert.True(budget.TryAcquire("a", out _)); + } + + [Fact] + public void Expired_windows_are_dropped_so_the_table_does_not_grow_with_every_key_ever_seen() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(1, Window, clock); + for (var i = 0; i < 100; i++) + { + budget.TryAcquire("k" + i, out _); + } + + Assert.Equal(100, budget.TrackedKeys); + clock.Advance(Window); + budget.TryAcquire("fresh", out _); + + Assert.Equal(1, budget.TrackedKeys); + } + + [Theory] + [InlineData(0, 60)] + [InlineData(-1, 60)] + [InlineData(1, 0)] + [InlineData(1, -5)] + public void A_budget_that_cannot_be_enforced_is_refused(int permits, int seconds) + { + Assert.ThrowsAny( + () => new FixedWindowBudget(permits, TimeSpan.FromSeconds(seconds), new Clock())); + } + + private sealed class Clock : TimeProvider + { + private DateTimeOffset _now = new(2026, 10, 11, 12, 0, 0, TimeSpan.Zero); + + public override DateTimeOffset GetUtcNow() => _now; + + public void Advance(TimeSpan by) => _now += by; + } +} diff --git a/tests/Bifrost.Web.Tests/HostTrustTests.cs b/tests/Bifrost.Web.Tests/HostTrustTests.cs index 7d55439..959c883 100644 --- a/tests/Bifrost.Web.Tests/HostTrustTests.cs +++ b/tests/Bifrost.Web.Tests/HostTrustTests.cs @@ -185,6 +185,50 @@ public sealed class HostTrustTests : IClassFixture Validate(keysPath: "/keys", ipv4Length: 0, ipv6Length: 0); } + [Theory] + [InlineData("Development")] + [InlineData("Testing")] + [InlineData("Production")] + public void Every_environment_refuses_prefix_lengths_outside_the_address_family(string environment) + { + var v4 = Assert.Throws( + () => Validate(keysPath: "/keys", environment: environment, ipv4Length: 33)); + Assert.Contains("ConceptVotes:IPv4PrefixLength", v4.Message); + Assert.DoesNotContain("IPv6PrefixLength", v4.Message); + + var v6 = Assert.Throws( + () => Validate(keysPath: "/keys", environment: environment, ipv6Length: 129)); + Assert.Contains("ConceptVotes:IPv6PrefixLength", v6.Message); + Assert.DoesNotContain("IPv4PrefixLength", v6.Message); + + Validate(keysPath: "/keys", environment: environment, ipv4Length: 0, ipv6Length: 0); + } + + [Theory] + [InlineData("Development", 0, 1, 5, 1, "ConceptVotes:CastPermits")] + [InlineData("Testing", 30, 0, 5, 1, "ConceptVotes:CastPermits")] + [InlineData("Production", 30, 1, 0, 1, "ConceptVotes:MintPermits")] + [InlineData("Production", 30, 1, 5, 0, "ConceptVotes:MintPermits")] + public void Every_environment_refuses_a_vote_budget_that_cannot_be_enforced( + string environment, + int castPermits, + int castMinutes, + int mintPermits, + int mintMinutes, + string key) + { + var refusal = Assert.Throws(() => Validate( + keysPath: "/keys", + environment: environment, + castPermits: castPermits, + castWindow: TimeSpan.FromMinutes(castMinutes), + mintPermits: mintPermits, + mintWindow: TimeSpan.FromMinutes(mintMinutes))); + + Assert.Contains(key, refusal.Message); + Validate(keysPath: "/keys", environment: environment); + } + [Theory] [InlineData("*")] [InlineData("")] @@ -267,7 +311,11 @@ public sealed class HostTrustTests : IClassFixture string? tagSecret = ValidTagSecret, int ipv4Length = 32, int ipv6Length = 56, - string[]? allowedOrigins = null) + string[]? allowedOrigins = null, + int castPermits = 30, + TimeSpan? castWindow = null, + int mintPermits = 5, + TimeSpan? mintWindow = null) { var values = new Dictionary { @@ -295,7 +343,11 @@ public sealed class HostTrustTests : IClassFixture NetworkTagSecret = tagSecret ?? string.Empty, IPv4PrefixLength = ipv4Length, IPv6PrefixLength = ipv6Length, - AllowedOrigins = allowedOrigins ?? [] + AllowedOrigins = allowedOrigins ?? [], + CastPermits = castPermits, + CastWindow = castWindow ?? TimeSpan.FromMinutes(10), + MintPermits = mintPermits, + MintWindow = mintWindow ?? TimeSpan.FromHours(1) })).Validate(); } diff --git a/tests/Bifrost.Web.Tests/Support/CapturingLoggerProvider.cs b/tests/Bifrost.Web.Tests/Support/CapturingLoggerProvider.cs new file mode 100644 index 0000000..ea7558b --- /dev/null +++ b/tests/Bifrost.Web.Tests/Support/CapturingLoggerProvider.cs @@ -0,0 +1,45 @@ +using Microsoft.Extensions.Logging; + +namespace Bifrost.Web.Tests.Support; + +public sealed class CapturingLoggerProvider : ILoggerProvider +{ + private readonly List _lines = []; + + public IReadOnlyList Lines + { + get + { + lock (_lines) + { + return _lines.ToArray(); + } + } + } + + public ILogger CreateLogger(string categoryName) => new Capture(this); + + public void Dispose() + { + } + + private sealed class Capture(CapturingLoggerProvider owner) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) + { + lock (owner._lines) + { + owner._lines.Add(formatter(state, exception) + (exception is null ? string.Empty : "\n" + exception)); + } + } + } +} diff --git a/tests/Bifrost.Web.Tests/Support/TestAuthHandler.cs b/tests/Bifrost.Web.Tests/Support/TestAuthHandler.cs index f63fc13..298642e 100644 --- a/tests/Bifrost.Web.Tests/Support/TestAuthHandler.cs +++ b/tests/Bifrost.Web.Tests/Support/TestAuthHandler.cs @@ -21,11 +21,14 @@ public sealed class TestAuthHandler( return Task.FromResult(AuthenticateResult.NoResult()); } + // A test may sign in as another account by naming its GitHub id and login. + var gitHubId = Request.Headers["X-Test-GitHub-Id"].FirstOrDefault() ?? "12345"; + var login = Request.Headers["X-Test-GitHub-Login"].FirstOrDefault() ?? "test-admin"; var claims = new[] { - new Claim(ClaimTypes.NameIdentifier, "12345"), - new Claim(ClaimTypes.Name, "test-admin"), - new Claim(BifrostClaimTypes.GitHubLogin, "test-admin"), + new Claim(ClaimTypes.NameIdentifier, gitHubId), + new Claim(ClaimTypes.Name, login), + new Claim(BifrostClaimTypes.GitHubLogin, login), new Claim(BifrostClaimTypes.DisplayName, "Test Admin") }; diff --git a/tests/Bifrost.Web.Tests/Support/TestWebApplicationFactory.cs b/tests/Bifrost.Web.Tests/Support/TestWebApplicationFactory.cs index ed3c4ed..7672a76 100644 --- a/tests/Bifrost.Web.Tests/Support/TestWebApplicationFactory.cs +++ b/tests/Bifrost.Web.Tests/Support/TestWebApplicationFactory.cs @@ -34,6 +34,8 @@ public class TestWebApplicationFactory : WebApplicationFactory ["GitHubApp:PrivateKeyPem"] = "test-private-key", ["GitHubApp:AppId"] = "1", ["Bridge:LocalBridgeToken"] = "test-bridge-token", + ["ConceptVotes:CastPermits"] = "100000", + ["ConceptVotes:MintPermits"] = "100000", ["Host:PublicBaseUrl"] = "https://localhost", ["Host:ExpectedHost"] = "localhost", ["Host:RequireStrictHostValidation"] = "false", From 7f375ecf8f39169fb8e27d8cdb075c28fa20ef01 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 11 Oct 2026 09:02:01 +0200 Subject: [PATCH 02/10] Pin the empty Origin branch with a server-built request HttpClient drops an empty header value, so the first version of the test never sent the header; the request is now built on the TestServer. Co-Authored-By: Claude Opus 5.5 --- .../Bifrost.Web.Tests/ConceptVotePageTests.cs | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs b/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs index b31c1c0..5434e8d 100644 --- a/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs @@ -4,6 +4,7 @@ using Bifrost.Web.Data; using Bifrost.Web.Domain; using Bifrost.Web.Tests.Support; using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; @@ -190,12 +191,27 @@ public sealed partial class ConceptVotePageTests : IClassFixture + { + http.Request.Method = HttpMethods.Post; + http.Request.Scheme = "https"; + http.Request.Host = new HostString("localhost"); + http.Request.Path = $"/mill/{collection}/alpha"; + http.Request.QueryString = new QueryString("?handler=Up"); + http.Request.ContentType = "application/x-www-form-urlencoded"; + http.Request.Headers["X-Test-Anonymous"] = "true"; + http.Request.Headers["Origin"] = string.Empty; + if (fetchSite is not null) + { + http.Request.Headers["Sec-Fetch-Site"] = fetchSite; + } + }); - Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); - Assert.False(response.Headers.Contains("Set-Cookie")); + Assert.Equal(StatusCodes.Status403Forbidden, context.Response.StatusCode); + Assert.False(context.Response.Headers.ContainsKey("Set-Cookie")); Assert.Empty(await Rows(collection, "alpha")); } From 9fcef927fd4086e05c6b505275329de61b49c50a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 11 Oct 2026 09:35:50 +0200 Subject: [PATCH 03/10] Pin the budget sweep and Retry-After rounding; drop a redundant Math.Max Survivors of the first Stryker pass on FixedWindowBudget: the sweep dropping live windows, sweeping every call, and the exact window boundary (masked by the sweep in the first test). Co-Authored-By: Claude Opus 5.5 --- src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs | 2 +- .../ConceptVoteRateLimitTests.cs | 5 ++- .../FixedWindowBudgetTests.cs | 41 +++++++++++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs index 5e46e1d..a06c3b3 100644 --- a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs +++ b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs @@ -140,7 +140,7 @@ public sealed class VoteModel( return null; } - Response.Headers.RetryAfter = Math.Max(1, (int)Math.Ceiling(wait.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture); + Response.Headers.RetryAfter = ((int)Math.Ceiling(wait.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture); return new StatusCodeResult(StatusCodes.Status429TooManyRequests); } diff --git a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs index 7165973..5049071 100644 --- a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs @@ -92,14 +92,15 @@ public sealed class ConceptVoteRateLimitTests : IClassFixture Date: Sun, 11 Oct 2026 09:46:45 +0200 Subject: [PATCH 04/10] Pin that a signed-in retract spends the account budget Hand mutant retract-key-ignores-signed-in-voter survived the first table. Co-Authored-By: Claude Opus 5.5 --- .../ConceptVoteRateLimitTests.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs index 5049071..b2beb0b 100644 --- a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs @@ -152,6 +152,23 @@ public sealed class ConceptVoteRateLimitTests : IClassFixture Date: Sun, 11 Oct 2026 17:32:01 +0200 Subject: [PATCH 05/10] Vote budgets: monotonic windows, a key cap, 30 mints an hour and a readable 429 FixedWindowBudget times windows on the clock's monotonic timestamps so a wall-clock step cannot stretch or reset one, expires windows from a start-ordered queue instead of a periodic sweep, and holds at most MaxTrackedKeys keys: a new key at the cap is denied with the true wait and a held key is never evicted. MintPermits is 30 per hour per the operator ruling, and a 429 now carries a plain-text reason; a refused new device is told it can sign in. Not yet built or tested at this commit. Co-Authored-By: Claude Sonnet 5.5 --- .../Configuration/ConceptVoteOptions.cs | 13 ++- .../ConceptVotes/ConceptVoteRateLimits.cs | 4 +- .../Features/Shared/FixedWindowBudget.cs | 68 ++++++----- .../Shared/StartupConfigurationValidator.cs | 5 + src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs | 23 +++- .../ConceptVoteRateLimitTests.cs | 44 ++++++- .../FixedWindowBudgetTests.cs | 109 ++++++++++++++---- tests/Bifrost.Web.Tests/HostTrustTests.cs | 18 ++- 8 files changed, 221 insertions(+), 63 deletions(-) diff --git a/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs b/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs index 41a866e..c5e5701 100644 --- a/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs +++ b/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs @@ -28,12 +28,19 @@ public sealed class ConceptVoteOptions public TimeSpan CastWindow { get; init; } = TimeSpan.FromMinutes(10); - // Mint: a new device cookie is a new voter identity, the cheapest stuffing lever, and a household has few devices, - // so 5 new devices per hour per network prefix. - public int MintPermits { get; init; } = 5; + // Mint: a new device cookie is a new voter identity, the cheapest stuffing lever. Anonymous visitors share an + // address behind carrier, school and office NAT (the research note records it), so 30 new devices per hour per + // address (operator ruling concept-mill-votes:ruling:mint-budget-30-per-hour); per-device and per-prefix cast + // limits still bound stuffing. + public int MintPermits { get; init; } = 30; public TimeSpan MintWindow { get; init; } = TimeSpan.FromHours(1); + // The most partitions each budget holds at once. At the cap a partition not yet held is refused with a 429 until + // the oldest window ends; held partitions are never evicted, so a rotating caller cannot escape a spent budget. + // 100000 partitions is a few tens of MB; a real audience is far below it. + public int MaxTrackedKeys { get; init; } = 100_000; + // The origins whose pages may read the public tally export from a browser (CORS). Each entry is exactly // https://host[:non-default-port], lower case, no path; empty allows none. StartupConfigurationValidator // refuses anything else outside Development and Testing, because "*" would allow every origin. diff --git a/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs b/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs index aac9802..d662b8a 100644 --- a/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs +++ b/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs @@ -12,8 +12,8 @@ namespace Bifrost.Web.Features.ConceptVotes; public sealed class ConceptVoteRateLimits(IOptions options, TimeProvider clock) { private readonly ConceptVoteOptions opts = options.Value; - private readonly FixedWindowBudget cast = new(options.Value.CastPermits, options.Value.CastWindow, clock); - private readonly FixedWindowBudget mint = new(options.Value.MintPermits, options.Value.MintWindow, clock); + private readonly FixedWindowBudget cast = new(options.Value.CastPermits, options.Value.CastWindow, options.Value.MaxTrackedKeys, clock); + private readonly FixedWindowBudget mint = new(options.Value.MintPermits, options.Value.MintWindow, options.Value.MaxTrackedKeys, clock); public TimeSpan? DenyCast(IPAddress? client, VoterIdentity? known) => cast.TryAcquire(known?.UserAccountId is { } account ? "account:" + account.ToString("N") : NetKey(client), out var wait) diff --git a/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs b/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs index abcaa0f..c002f03 100644 --- a/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs +++ b/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs @@ -1,28 +1,37 @@ namespace Bifrost.Web.Features.Shared; -// The one rate-limit mechanism: a fixed-window permit budget per caller-chosen partition key, read against an injected -// clock. Keys are opaque and are never stored beyond their window: an entry whose window has ended is dropped by the -// next sweep, so the table is bounded by the distinct keys seen in one window. System.Threading.RateLimiting is not -// used because its limiters time themselves on Stopwatch and timers, which a test cannot move. +// The one rate-limit mechanism: a fixed-window permit budget per caller-chosen partition key, timed on the injected +// clock's monotonic timestamps (never its wall time, which can step), so a clock adjustment cannot stretch or reset a +// window. Windows all have one length, so they end in the order they began: a queue of window starts expires them from +// the front and the table never holds a key past its window. The table holds at most maxKeys keys; a new key arriving +// at the cap is denied until the oldest window ends, with the true wait, so a rotating caller cannot evict a spent key +// to escape its budget and the refusal is a 429 that says when to retry, never a silent drop. +// System.Threading.RateLimiting is not used because its limiters time themselves on Stopwatch and timers, which a +// test cannot move. public sealed class FixedWindowBudget { private readonly int permits; private readonly TimeSpan window; + private readonly int maxKeys; private readonly TimeProvider clock; + private readonly long origin; private readonly Dictionary entries = new(StringComparer.Ordinal); + private readonly Queue byStart = new(); private readonly object gate = new(); - private DateTimeOffset nextSweep = DateTimeOffset.MinValue; - public FixedWindowBudget(int permits, TimeSpan window, TimeProvider clock) + public FixedWindowBudget(int permits, TimeSpan window, int maxKeys, TimeProvider clock) { ArgumentOutOfRangeException.ThrowIfLessThan(permits, 1); ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(window, TimeSpan.Zero); + ArgumentOutOfRangeException.ThrowIfLessThan(maxKeys, 1); this.permits = permits; this.window = window; + this.maxKeys = maxKeys; this.clock = clock; + origin = clock.GetTimestamp(); } - // How many keys are held now: bounded by the distinct keys seen in one window, not by every key ever seen. + // How many keys are held now: the keys whose window is still open, never more than maxKeys. public int TrackedKeys { get @@ -34,44 +43,47 @@ public sealed class FixedWindowBudget } } - // Takes one permit for the key. When none is left, returns false and how long until its window ends. + // Takes one permit for the key. When none is left, or the table is full and the key is new, returns false and how + // long until a window ends and the answer can change. public bool TryAcquire(string key, out TimeSpan retryAfter) { - var now = clock.GetUtcNow(); lock (gate) { - if (now >= nextSweep) + var now = clock.GetElapsedTime(origin); + while (byStart.TryPeek(out var oldest) && entries[oldest].Start + window <= now) { - foreach (var expired in entries.Where(x => x.Value.Start + window <= now).Select(x => x.Key).ToList()) + entries.Remove(byStart.Dequeue()); + } + + if (entries.TryGetValue(key, out var entry)) + { + if (entry.Count >= permits) { - entries.Remove(expired); + retryAfter = entry.Start + window - now; + return false; } - nextSweep = now + window; - } - - if (!entries.TryGetValue(key, out var entry) || entry.Start + window <= now) - { - entries[key] = new Entry(now); - retryAfter = TimeSpan.Zero; - return true; - } - - if (entry.Count < permits) - { entry.Count++; retryAfter = TimeSpan.Zero; return true; } - retryAfter = entry.Start + window - now; - return false; + if (entries.Count >= maxKeys) + { + retryAfter = entries[byStart.Peek()].Start + window - now; + return false; + } + + entries[key] = new Entry(now); + byStart.Enqueue(key); + retryAfter = TimeSpan.Zero; + return true; } } - private sealed class Entry(DateTimeOffset start) + private sealed class Entry(TimeSpan start) { - public DateTimeOffset Start { get; } = start; + public TimeSpan Start { get; } = start; public int Count { get; set; } = 1; } diff --git a/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs index 676e628..98b8dc7 100644 --- a/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs +++ b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs @@ -40,6 +40,11 @@ public sealed class StartupConfigurationValidator( failures.Add("ConceptVotes:MintPermits must be at least 1 and ConceptVotes:MintWindow must be positive."); } + if (conceptVotes.MaxTrackedKeys < 1) + { + failures.Add("ConceptVotes:MaxTrackedKeys must be at least 1."); + } + if (hostEnvironment.IsDevelopment() || hostEnvironment.IsEnvironment("Testing")) { Refuse(failures); diff --git a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs index a06c3b3..2e11b1f 100644 --- a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs +++ b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs @@ -77,7 +77,7 @@ public sealed class VoteModel( { var actor = await actorAccessor.GetAsync(cancellationToken); var voter = ResolveVoter(actor); - if (Throttled(limits.DenyCast(HttpContext.Connection.RemoteIpAddress, voter)) is { } throttled) + if (Throttled(limits.DenyCast(HttpContext.Connection.RemoteIpAddress, voter), CastRefusal) is { } throttled) { return throttled; } @@ -100,7 +100,7 @@ public sealed class VoteModel( var actor = await actorAccessor.GetAsync(cancellationToken); var client = HttpContext.Connection.RemoteIpAddress; var voter = ResolveVoter(actor); - if (Throttled(limits.DenyCast(client, voter)) is { } throttled) + if (Throttled(limits.DenyCast(client, voter), CastRefusal) is { } throttled) { return throttled; } @@ -112,7 +112,7 @@ public sealed class VoteModel( if (voter is null) { - if (Throttled(limits.DenyMint(client)) is { } mintThrottled) + if (Throttled(limits.DenyMint(client), MintRefusal) is { } mintThrottled) { return mintThrottled; } @@ -132,8 +132,14 @@ public sealed class VoteModel( private VoterIdentity? ResolveVoter(CurrentBifrostActor actor) => VoterIdentity.For(actor, null) ?? VoterIdentity.For(actor, deviceCookie.TryRead(HttpContext)); - // A denied budget is a 429 that says when to retry; it writes no row and sets no cookie. - private IActionResult? Throttled(TimeSpan? retryAfter) + // A denied budget is a 429 that says when to retry, in words a voter can read; it writes no row, sets no cookie and + // repeats nothing of the request. A refused new device is told it can sign in, which has a budget of its own. + private const string CastRefusal = "You are voting too fast. Please wait a little before voting again."; + + private const string MintRefusal = + "Too many new voters have voted from your network recently. You can sign in to vote now, or try again later."; + + private IActionResult? Throttled(TimeSpan? retryAfter, string refusal) { if (retryAfter is not { } wait) { @@ -141,7 +147,12 @@ public sealed class VoteModel( } Response.Headers.RetryAfter = ((int)Math.Ceiling(wait.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture); - return new StatusCodeResult(StatusCodes.Status429TooManyRequests); + return new ContentResult + { + StatusCode = StatusCodes.Status429TooManyRequests, + ContentType = "text/plain; charset=utf-8", + Content = refusal + }; } private async Task LoadAsync(string collection, string key, VoterIdentity? voter, CancellationToken cancellationToken) diff --git a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs index b2beb0b..8e533f4 100644 --- a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs @@ -206,6 +206,10 @@ public sealed class ConceptVoteRateLimitTests : IClassFixture h.Key + ":" + string.Join(",", h.Value))); Assert.DoesNotContain("203.0.113", seen); Assert.DoesNotContain(logs.Lines, line => line.Contains("203.0.113", StringComparison.Ordinal)); } + [Fact] + public void Defaults_allow_thirty_new_devices_an_hour_per_address() + { + var defaults = new Bifrost.Web.Configuration.ConceptVoteOptions(); + + Assert.Equal(30, defaults.MintPermits); + Assert.Equal(TimeSpan.FromHours(1), defaults.MintWindow); + Assert.Equal(100_000, defaults.MaxTrackedKeys); + } + + [Fact] + public void Both_budgets_hold_at_most_the_configured_number_of_partitions_and_refuse_a_new_one_at_the_cap() + { + var clock = new TestClock(); + var limits = new Bifrost.Web.Features.ConceptVotes.ConceptVoteRateLimits( + Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.ConceptVoteOptions { MaxTrackedKeys = 1 }), + clock); + + Assert.Null(limits.DenyCast(IPAddress.Parse("198.51.100.1"), null)); + Assert.NotNull(limits.DenyCast(IPAddress.Parse("198.51.100.2"), null)); + Assert.Null(limits.DenyMint(IPAddress.Parse("198.51.100.1"))); + Assert.NotNull(limits.DenyMint(IPAddress.Parse("198.51.100.2"))); + Assert.Null(limits.DenyCast(IPAddress.Parse("198.51.100.1"), null)); + } + [Fact] public async Task Reads_are_not_under_the_vote_budgets() { @@ -387,10 +418,19 @@ public sealed class ConceptVoteRateLimitTests : IClassFixture TimeSpan.TicksPerSecond; public override DateTimeOffset GetUtcNow() => _now; - public void Advance(TimeSpan by) => _now += by; + public override long GetTimestamp() => _ticks; + + public void Advance(TimeSpan by) + { + _now += by; + _ticks += by.Ticks; + } } // The proxy's connection: TestServer has no socket, so the peer address is set ahead of the app pipeline. diff --git a/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs b/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs index 0493a03..5d1c3b7 100644 --- a/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs +++ b/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs @@ -5,12 +5,13 @@ namespace Bifrost.Web.Tests; public sealed class FixedWindowBudgetTests { private static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + private const int Cap = 1000; [Fact] public void Permits_are_spent_per_key_and_the_next_is_denied_with_the_time_left() { var clock = new Clock(); - var budget = new FixedWindowBudget(2, Window, clock); + var budget = new FixedWindowBudget(2, Window, Cap, clock); Assert.True(budget.TryAcquire("a", out _)); clock.Advance(TimeSpan.FromSeconds(10)); @@ -25,7 +26,7 @@ public sealed class FixedWindowBudgetTests public void A_window_opens_at_its_first_permit_and_closes_exactly_one_window_later() { var clock = new Clock(); - var budget = new FixedWindowBudget(1, Window, clock); + var budget = new FixedWindowBudget(1, Window, Cap, clock); Assert.True(budget.TryAcquire("a", out _)); clock.Advance(Window - TimeSpan.FromTicks(1)); @@ -42,7 +43,7 @@ public sealed class FixedWindowBudgetTests public void A_denied_attempt_does_not_extend_the_window() { var clock = new Clock(); - var budget = new FixedWindowBudget(1, Window, clock); + var budget = new FixedWindowBudget(1, Window, Cap, clock); budget.TryAcquire("a", out _); for (var i = 0; i < 5; i++) { @@ -55,16 +56,16 @@ public sealed class FixedWindowBudgetTests } [Fact] - public void A_sweep_drops_only_expired_windows_and_a_live_one_keeps_counting_to_its_exact_end() + public void An_expired_window_is_dropped_and_a_live_one_keeps_counting_to_its_exact_end() { var clock = new Clock(); - var budget = new FixedWindowBudget(1, Window, clock); + var budget = new FixedWindowBudget(1, Window, Cap, clock); budget.TryAcquire("a", out _); clock.Advance(TimeSpan.FromSeconds(30)); budget.TryAcquire("b", out _); clock.Advance(TimeSpan.FromSeconds(30)); - // The sweep due at 60 s drops a, which ended, and keeps b, which has 30 s left. + // At 60 s a has ended and b has 30 s left. budget.TryAcquire("c", out _); Assert.Equal(2, budget.TrackedKeys); Assert.False(budget.TryAcquire("b", out var wait)); @@ -77,29 +78,79 @@ public sealed class FixedWindowBudgetTests } [Fact] - public void Sweeping_is_at_most_once_per_window_so_a_flood_of_keys_costs_one_pass_not_one_per_request() + public void A_wall_clock_step_back_does_not_extend_a_window_or_its_retry_after() { var clock = new Clock(); - var budget = new FixedWindowBudget(1, Window, clock); + var budget = new FixedWindowBudget(1, Window, Cap, clock); budget.TryAcquire("a", out _); - clock.Advance(TimeSpan.FromSeconds(30)); + clock.Advance(TimeSpan.FromSeconds(10)); + clock.StepWall(-TimeSpan.FromHours(1)); + + Assert.False(budget.TryAcquire("a", out var wait)); + Assert.Equal(TimeSpan.FromSeconds(50), wait); + clock.Advance(TimeSpan.FromSeconds(50)); + Assert.True(budget.TryAcquire("a", out _)); + Assert.Equal(1, budget.TrackedKeys); + } + + [Fact] + public void A_wall_clock_step_forward_does_not_reset_a_window() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(1, Window, Cap, clock); + budget.TryAcquire("a", out _); + clock.StepWall(TimeSpan.FromHours(1)); + + Assert.False(budget.TryAcquire("a", out var wait)); + Assert.Equal(Window, wait); + } + + [Fact] + public void A_new_key_at_the_cap_is_denied_until_the_oldest_window_ends_and_a_held_key_is_never_evicted() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(1, Window, 2, clock); + budget.TryAcquire("a", out _); + clock.Advance(TimeSpan.FromSeconds(20)); budget.TryAcquire("b", out _); - clock.Advance(TimeSpan.FromSeconds(31)); - budget.TryAcquire("c", out _); + clock.Advance(TimeSpan.FromSeconds(10)); + + Assert.False(budget.TryAcquire("c", out var wait)); + Assert.Equal(TimeSpan.FromSeconds(30), wait); Assert.Equal(2, budget.TrackedKeys); - // b ended at 90 s but the next sweep is not due until 121 s. - clock.Advance(TimeSpan.FromSeconds(39)); - budget.TryAcquire("d", out _); + // Rotating new keys cannot push a spent key out to get its budget back. + for (var i = 0; i < 10; i++) + { + Assert.False(budget.TryAcquire("rot" + i, out _)); + } - Assert.Equal(3, budget.TrackedKeys); + Assert.False(budget.TryAcquire("a", out wait)); + Assert.Equal(TimeSpan.FromSeconds(30), wait); + + clock.Advance(TimeSpan.FromSeconds(30)); + Assert.True(budget.TryAcquire("c", out _)); + Assert.Equal(2, budget.TrackedKeys); + Assert.False(budget.TryAcquire("b", out wait)); + Assert.Equal(TimeSpan.FromSeconds(20), wait); + } + + [Fact] + public void A_held_key_under_its_permits_is_served_even_when_the_table_is_full() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(2, Window, 1, clock); + Assert.True(budget.TryAcquire("a", out _)); + + Assert.True(budget.TryAcquire("a", out _)); + Assert.False(budget.TryAcquire("a", out _)); } [Fact] public void Expired_windows_are_dropped_so_the_table_does_not_grow_with_every_key_ever_seen() { var clock = new Clock(); - var budget = new FixedWindowBudget(1, Window, clock); + var budget = new FixedWindowBudget(1, Window, Cap, clock); for (var i = 0; i < 100; i++) { budget.TryAcquire("k" + i, out _); @@ -120,15 +171,33 @@ public sealed class FixedWindowBudgetTests public void A_budget_that_cannot_be_enforced_is_refused(int permits, int seconds) { Assert.ThrowsAny( - () => new FixedWindowBudget(permits, TimeSpan.FromSeconds(seconds), new Clock())); + () => new FixedWindowBudget(permits, TimeSpan.FromSeconds(seconds), Cap, new Clock())); } + [Fact] + public void A_cap_below_one_is_refused() + { + Assert.Throws(() => new FixedWindowBudget(1, Window, 0, new Clock())); + } + + // Time advances monotonic and wall together; StepWall moves only the wall clock, as an NTP step would. private sealed class Clock : TimeProvider { - private DateTimeOffset _now = new(2026, 10, 11, 12, 0, 0, TimeSpan.Zero); + private DateTimeOffset _wall = new(2026, 10, 11, 12, 0, 0, TimeSpan.Zero); + private long _ticks = 5_000_000; - public override DateTimeOffset GetUtcNow() => _now; + public override long TimestampFrequency => TimeSpan.TicksPerSecond; - public void Advance(TimeSpan by) => _now += by; + public override DateTimeOffset GetUtcNow() => _wall; + + public override long GetTimestamp() => _ticks; + + public void Advance(TimeSpan by) + { + _wall += by; + _ticks += by.Ticks; + } + + public void StepWall(TimeSpan by) => _wall += by; } } diff --git a/tests/Bifrost.Web.Tests/HostTrustTests.cs b/tests/Bifrost.Web.Tests/HostTrustTests.cs index 959c883..54c0128 100644 --- a/tests/Bifrost.Web.Tests/HostTrustTests.cs +++ b/tests/Bifrost.Web.Tests/HostTrustTests.cs @@ -229,6 +229,18 @@ public sealed class HostTrustTests : IClassFixture Validate(keysPath: "/keys", environment: environment); } + [Theory] + [InlineData("Development")] + [InlineData("Testing")] + [InlineData("Production")] + public void Every_environment_refuses_a_vote_table_cap_below_one(string environment) + { + var refusal = Assert.Throws( + () => Validate(keysPath: "/keys", environment: environment, maxTrackedKeys: 0)); + + Assert.Contains("ConceptVotes:MaxTrackedKeys", refusal.Message); + } + [Theory] [InlineData("*")] [InlineData("")] @@ -315,7 +327,8 @@ public sealed class HostTrustTests : IClassFixture int castPermits = 30, TimeSpan? castWindow = null, int mintPermits = 5, - TimeSpan? mintWindow = null) + TimeSpan? mintWindow = null, + int maxTrackedKeys = 100_000) { var values = new Dictionary { @@ -347,7 +360,8 @@ public sealed class HostTrustTests : IClassFixture CastPermits = castPermits, CastWindow = castWindow ?? TimeSpan.FromMinutes(10), MintPermits = mintPermits, - MintWindow = mintWindow ?? TimeSpan.FromHours(1) + MintWindow = mintWindow ?? TimeSpan.FromHours(1), + MaxTrackedKeys = maxTrackedKeys })).Validate(); } From 8f57dc89f0f9f6c249f991e3c90b6a46388608b4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 11 Oct 2026 17:38:56 +0200 Subject: [PATCH 06/10] Pin the no-client-address bucket of the vote budgets Kills the Stryker survivor on the null-client key: a request with no address shares one bucket and does not throw. Builds with a8c3ecf; test added after the main verify job. Co-Authored-By: Claude Sonnet 5.5 --- tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs index 8e533f4..4feac7c 100644 --- a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs @@ -284,6 +284,18 @@ public sealed class ConceptVoteRateLimitTests : IClassFixture Date: Sun, 11 Oct 2026 19:16:30 +0200 Subject: [PATCH 07/10] Vote budgets: at the cap a new key evicts the least recently used key with permits left Ruling budget-table-evict-oldest. FixedWindowBudget keeps two linked lists (window start, last use among keys with permits left) so eviction and expiry are O(1); a spent key is never evicted, and a table full of spent keys refuses a new key as TableFull with the true wait. Accounts get their own cast table. The vote page checks the subject before spending any key, and the refusal names its reason: cast budget, mint budget, or a busy table. Not verified by a build yet at this commit. Co-Authored-By: Claude Sonnet 5.5 --- .../Configuration/ConceptVoteOptions.cs | 7 +- .../ConceptVotes/ConceptVoteRateLimits.cs | 23 +-- .../Features/Shared/FixedWindowBudget.cs | 83 ++++++-- src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs | 33 ++-- .../ConceptVoteRateLimitTests.cs | 148 +++++++++++++- .../FixedWindowBudgetTests.cs | 182 +++++++++++++----- 6 files changed, 377 insertions(+), 99 deletions(-) diff --git a/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs b/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs index c5e5701..0e60f7d 100644 --- a/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs +++ b/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs @@ -36,9 +36,10 @@ public sealed class ConceptVoteOptions public TimeSpan MintWindow { get; init; } = TimeSpan.FromHours(1); - // The most partitions each budget holds at once. At the cap a partition not yet held is refused with a 429 until - // the oldest window ends; held partitions are never evicted, so a rotating caller cannot escape a spent budget. - // 100000 partitions is a few tens of MB; a real audience is far below it. + // The most partitions each budget table holds at once (cast by account, cast by network prefix, mint). At the cap a + // partition not yet held evicts the least recently used one that still has permits left; a partition that has + // spent its permits is never evicted, so rotating sources can at most win back a forgotten partition's partial + // budget. 100000 partitions is a few tens of MB; a real audience is far below it. public int MaxTrackedKeys { get; init; } = 100_000; // The origins whose pages may read the public tally export from a browser (CORS). Each entry is exactly diff --git a/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs b/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs index d662b8a..fcfe361 100644 --- a/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs +++ b/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs @@ -6,23 +6,24 @@ using Microsoft.Extensions.Options; namespace Bifrost.Web.Features.ConceptVotes; // The one owner of the vote budgets. Cast is spent by every cast and retract; mint is spent additionally by a cast that -// is about to mint a device cookie. A denial returns how long to wait and writes nothing. The partition is the account -// when the voter is signed in, otherwise the network prefix (NetworkPrefix.Of) of the address the forwarded-headers -// middleware left on the connection. No header and no client input ever becomes a key. +// is about to mint a device cookie. A denial says why and how long to wait, and writes nothing. The partition is the +// account when the voter is signed in, otherwise the network prefix (NetworkPrefix.Of) of the address the +// forwarded-headers middleware left on the connection. No header and no client input ever becomes a key. Accounts +// have a table of their own, so a flood of anonymous sources cannot crowd a signed-in voter out of it. public sealed class ConceptVoteRateLimits(IOptions options, TimeProvider clock) { private readonly ConceptVoteOptions opts = options.Value; - private readonly FixedWindowBudget cast = new(options.Value.CastPermits, options.Value.CastWindow, options.Value.MaxTrackedKeys, clock); + private readonly FixedWindowBudget castAccounts = new(options.Value.CastPermits, options.Value.CastWindow, options.Value.MaxTrackedKeys, clock); + private readonly FixedWindowBudget castNetworks = new(options.Value.CastPermits, options.Value.CastWindow, options.Value.MaxTrackedKeys, clock); private readonly FixedWindowBudget mint = new(options.Value.MintPermits, options.Value.MintWindow, options.Value.MaxTrackedKeys, clock); - public TimeSpan? DenyCast(IPAddress? client, VoterIdentity? known) => - cast.TryAcquire(known?.UserAccountId is { } account ? "account:" + account.ToString("N") : NetKey(client), out var wait) - ? null - : wait; + public BudgetDenial? DenyCast(IPAddress? client, VoterIdentity? known) => + known?.UserAccountId is { } account + ? castAccounts.Spend(account.ToString("N")) + : castNetworks.Spend(NetKey(client)); - public TimeSpan? DenyMint(IPAddress? client) => - mint.TryAcquire(NetKey(client), out var wait) ? null : wait; + public BudgetDenial? DenyMint(IPAddress? client) => mint.Spend(NetKey(client)); private string NetKey(IPAddress? client) => - "net:" + (client is null ? "unknown" : NetworkPrefix.Of(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength)); + client is null ? "unknown" : NetworkPrefix.Of(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength); } diff --git a/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs b/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs index c002f03..b6c9083 100644 --- a/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs +++ b/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs @@ -1,11 +1,18 @@ namespace Bifrost.Web.Features.Shared; +// Why a permit was refused and how long until the answer can change. TableFull is not the caller's own spending: the +// table holds only spent windows and has no room for a key it does not know. +public readonly record struct BudgetDenial(TimeSpan RetryAfter, bool TableFull); + // The one rate-limit mechanism: a fixed-window permit budget per caller-chosen partition key, timed on the injected // clock's monotonic timestamps (never its wall time, which can step), so a clock adjustment cannot stretch or reset a -// window. Windows all have one length, so they end in the order they began: a queue of window starts expires them from -// the front and the table never holds a key past its window. The table holds at most maxKeys keys; a new key arriving -// at the cap is denied until the oldest window ends, with the true wait, so a rotating caller cannot evict a spent key -// to escape its budget and the refusal is a 429 that says when to retry, never a silent drop. +// window. Windows all have one length, so they end in the order they began: a list of entries in start order expires +// them from the front and the table never holds a key past its window. +// The table holds at most maxKeys keys. A new key arriving at the cap evicts the least recently used key that still +// has permits left (nginx limit_req_zone does the same); a key that has spent all its permits is never evicted, so a +// rotating caller can at most win back a forgotten key's partial budget and never a spent one, and nobody fresh is +// refused because the table is full. Only when every held key is spent is a new key refused, with the true wait. +// Every step is O(1): two linked lists, one by window start and one by last use among keys with permits left. // System.Threading.RateLimiting is not used because its limiters time themselves on Stopwatch and timers, which a // test cannot move. public sealed class FixedWindowBudget @@ -16,7 +23,8 @@ public sealed class FixedWindowBudget private readonly TimeProvider clock; private readonly long origin; private readonly Dictionary entries = new(StringComparer.Ordinal); - private readonly Queue byStart = new(); + private readonly LinkedList byStart = new(); + private readonly LinkedList byUse = new(); private readonly object gate = new(); public FixedWindowBudget(int permits, TimeSpan window, int maxKeys, TimeProvider clock) @@ -43,48 +51,81 @@ public sealed class FixedWindowBudget } } - // Takes one permit for the key. When none is left, or the table is full and the key is new, returns false and how - // long until a window ends and the answer can change. - public bool TryAcquire(string key, out TimeSpan retryAfter) + // Takes one permit for the key and returns null, or returns why it could not. + public BudgetDenial? Spend(string key) { lock (gate) { var now = clock.GetElapsedTime(origin); - while (byStart.TryPeek(out var oldest) && entries[oldest].Start + window <= now) + while (byStart.First is { Value: var oldest } && oldest.Start + window <= now) { - entries.Remove(byStart.Dequeue()); + Remove(oldest); } if (entries.TryGetValue(key, out var entry)) { if (entry.Count >= permits) { - retryAfter = entry.Start + window - now; - return false; + return new BudgetDenial(entry.Start + window - now, false); } entry.Count++; - retryAfter = TimeSpan.Zero; - return true; + if (entry.Count >= permits) + { + byUse.Remove(entry.UseNode!); + entry.UseNode = null; + } + else + { + byUse.Remove(entry.UseNode!); + byUse.AddLast(entry.UseNode!); + } + + return null; } if (entries.Count >= maxKeys) { - retryAfter = entries[byStart.Peek()].Start + window - now; - return false; + if (byUse.First is not { Value: var forgotten }) + { + return new BudgetDenial(byStart.First!.Value.Start + window - now, true); + } + + Remove(forgotten); } - entries[key] = new Entry(now); - byStart.Enqueue(key); - retryAfter = TimeSpan.Zero; - return true; + var added = new Entry(key, now); + entries[key] = added; + added.StartNode = byStart.AddLast(added); + if (added.Count < permits) + { + added.UseNode = byUse.AddLast(added); + } + + return null; } } - private sealed class Entry(TimeSpan start) + private void Remove(Entry entry) { + entries.Remove(entry.Key); + byStart.Remove(entry.StartNode!); + if (entry.UseNode is not null) + { + byUse.Remove(entry.UseNode); + } + } + + private sealed class Entry(string key, TimeSpan start) + { + public string Key { get; } = key; + public TimeSpan Start { get; } = start; public int Count { get; set; } = 1; + + public LinkedListNode? StartNode { get; set; } + + public LinkedListNode? UseNode { get; set; } } } diff --git a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs index 2e11b1f..f843f0a 100644 --- a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs +++ b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs @@ -77,16 +77,16 @@ public sealed class VoteModel( { var actor = await actorAccessor.GetAsync(cancellationToken); var voter = ResolveVoter(actor); - if (Throttled(limits.DenyCast(HttpContext.Connection.RemoteIpAddress, voter), CastRefusal) is { } throttled) - { - return throttled; - } - if (await appraisals.GetSubjectAsync(collection, key, null, cancellationToken) is null) { return NotFound(); } + if (Throttled(limits.DenyCast(HttpContext.Connection.RemoteIpAddress, voter), CastRefusal) is { } throttled) + { + return throttled; + } + await appraisals.RetractAsync(collection, key, voter, cancellationToken); return RedirectToPage(new { collection, key }); } @@ -100,16 +100,16 @@ public sealed class VoteModel( var actor = await actorAccessor.GetAsync(cancellationToken); var client = HttpContext.Connection.RemoteIpAddress; var voter = ResolveVoter(actor); - if (Throttled(limits.DenyCast(client, voter), CastRefusal) is { } throttled) - { - return throttled; - } - if (await appraisals.GetSubjectAsync(collection, key, null, cancellationToken) is null) { return NotFound(); } + if (Throttled(limits.DenyCast(client, voter), CastRefusal) is { } throttled) + { + return throttled; + } + if (voter is null) { if (Throttled(limits.DenyMint(client), MintRefusal) is { } mintThrottled) @@ -133,20 +133,25 @@ public sealed class VoteModel( VoterIdentity.For(actor, null) ?? VoterIdentity.For(actor, deviceCookie.TryRead(HttpContext)); // A denied budget is a 429 that says when to retry, in words a voter can read; it writes no row, sets no cookie and - // repeats nothing of the request. A refused new device is told it can sign in, which has a budget of its own. + // repeats nothing of the request. The subject is checked before any budget is spent, so a request for a concept that + // does not exist costs the sender nothing and the table nothing. A refused new device is told it can sign in, which + // has a budget of its own. A table full of spent windows is not the visitor's doing and says so. private const string CastRefusal = "You are voting too fast. Please wait a little before voting again."; private const string MintRefusal = "Too many new voters have voted from your network recently. You can sign in to vote now, or try again later."; - private IActionResult? Throttled(TimeSpan? retryAfter, string refusal) + private const string BusyRefusal = "Voting is very busy right now. Please try again in a little while."; + + private IActionResult? Throttled(BudgetDenial? denial, string spentRefusal) { - if (retryAfter is not { } wait) + if (denial is not { } refused) { return null; } - Response.Headers.RetryAfter = ((int)Math.Ceiling(wait.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture); + var refusal = refused.TableFull ? BusyRefusal : spentRefusal; + Response.Headers.RetryAfter = ((int)Math.Ceiling(refused.RetryAfter.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture); return new ContentResult { StatusCode = StatusCodes.Status429TooManyRequests, diff --git a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs index 4feac7c..30ab093 100644 --- a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs @@ -1,6 +1,7 @@ using System.Net; using Bifrost.Web.Data; using Bifrost.Web.Domain; +using Bifrost.Web.Features.ConceptVotes; using Bifrost.Web.Tests.Support; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -270,18 +271,144 @@ public sealed class ConceptVoteRateLimitTests : IClassFixture string.Join(",", h.Value)))); + Assert.Equal(HttpStatusCode.Redirect, account.StatusCode); + Assert.Equal(rowsBefore + 1, (await Rows(collection)).Count); + } + + [Fact] + public async Task Posts_to_a_missing_subject_spend_no_budget_and_mint_no_device() + { + var collection = await NewSubject(); + var sender = new Client(_factory, "203.0.113.140"); + foreach (var handler in new[] { "Up", "Down", "Retract" }) + { + for (var i = 0; i < 4; i++) + { + using var missing = await sender.Post("c" + Guid.NewGuid().ToString("N"), handler); + Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode); + Assert.Null(SetCookie(missing)); + } + } + + for (var i = 0; i < 3; i++) + { + using var ok = await sender.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, ok.StatusCode); + } + + using var denied = await sender.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); } [Fact] @@ -313,6 +440,13 @@ public sealed class ConceptVoteRateLimitTests : IClassFixture Capped(int maxTrackedKeys) => + _factory.WithWebHostBuilder(b => b.ConfigureAppConfiguration((_, configuration) => + configuration.AddInMemoryCollection(new Dictionary + { + ["ConceptVotes:MaxTrackedKeys"] = maxTrackedKeys.ToString(System.Globalization.CultureInfo.InvariantCulture) + }))); + private static string? RetryAfter(HttpResponseMessage response) => response.Headers.TryGetValues("Retry-After", out var values) ? values.Single() : null; diff --git a/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs b/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs index 5d1c3b7..e2fedb2 100644 --- a/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs +++ b/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs @@ -13,13 +13,13 @@ public sealed class FixedWindowBudgetTests var clock = new Clock(); var budget = new FixedWindowBudget(2, Window, Cap, clock); - Assert.True(budget.TryAcquire("a", out _)); + Assert.True(Try(budget, "a", out _)); clock.Advance(TimeSpan.FromSeconds(10)); - Assert.True(budget.TryAcquire("a", out _)); - Assert.False(budget.TryAcquire("a", out var wait)); + Assert.True(Try(budget, "a", out _)); + Assert.False(Try(budget, "a", out var wait)); Assert.Equal(TimeSpan.FromSeconds(50), wait); - Assert.True(budget.TryAcquire("b", out _)); + Assert.True(Try(budget, "b", out _)); } [Fact] @@ -27,15 +27,15 @@ public sealed class FixedWindowBudgetTests { var clock = new Clock(); var budget = new FixedWindowBudget(1, Window, Cap, clock); - Assert.True(budget.TryAcquire("a", out _)); + Assert.True(Try(budget, "a", out _)); clock.Advance(Window - TimeSpan.FromTicks(1)); - Assert.False(budget.TryAcquire("a", out var wait)); + Assert.False(Try(budget, "a", out var wait)); Assert.Equal(TimeSpan.FromTicks(1), wait); clock.Advance(TimeSpan.FromTicks(1)); - Assert.True(budget.TryAcquire("a", out _)); - Assert.False(budget.TryAcquire("a", out wait)); + Assert.True(Try(budget, "a", out _)); + Assert.False(Try(budget, "a", out wait)); Assert.Equal(Window, wait); } @@ -44,15 +44,15 @@ public sealed class FixedWindowBudgetTests { var clock = new Clock(); var budget = new FixedWindowBudget(1, Window, Cap, clock); - budget.TryAcquire("a", out _); + Try(budget, "a", out _); for (var i = 0; i < 5; i++) { clock.Advance(TimeSpan.FromSeconds(10)); - Assert.False(budget.TryAcquire("a", out _)); + Assert.False(Try(budget, "a", out _)); } clock.Advance(TimeSpan.FromSeconds(10)); - Assert.True(budget.TryAcquire("a", out _)); + Assert.True(Try(budget, "a", out _)); } [Fact] @@ -60,21 +60,21 @@ public sealed class FixedWindowBudgetTests { var clock = new Clock(); var budget = new FixedWindowBudget(1, Window, Cap, clock); - budget.TryAcquire("a", out _); + Try(budget, "a", out _); clock.Advance(TimeSpan.FromSeconds(30)); - budget.TryAcquire("b", out _); + Try(budget, "b", out _); clock.Advance(TimeSpan.FromSeconds(30)); // At 60 s a has ended and b has 30 s left. - budget.TryAcquire("c", out _); + Try(budget, "c", out _); Assert.Equal(2, budget.TrackedKeys); - Assert.False(budget.TryAcquire("b", out var wait)); + Assert.False(Try(budget, "b", out var wait)); Assert.Equal(TimeSpan.FromSeconds(30), wait); clock.Advance(TimeSpan.FromSeconds(30) - TimeSpan.FromTicks(1)); - Assert.False(budget.TryAcquire("b", out _)); + Assert.False(Try(budget, "b", out _)); clock.Advance(TimeSpan.FromTicks(1)); - Assert.True(budget.TryAcquire("b", out _)); + Assert.True(Try(budget, "b", out _)); } [Fact] @@ -82,14 +82,14 @@ public sealed class FixedWindowBudgetTests { var clock = new Clock(); var budget = new FixedWindowBudget(1, Window, Cap, clock); - budget.TryAcquire("a", out _); + Try(budget, "a", out _); clock.Advance(TimeSpan.FromSeconds(10)); clock.StepWall(-TimeSpan.FromHours(1)); - Assert.False(budget.TryAcquire("a", out var wait)); + Assert.False(Try(budget, "a", out var wait)); Assert.Equal(TimeSpan.FromSeconds(50), wait); clock.Advance(TimeSpan.FromSeconds(50)); - Assert.True(budget.TryAcquire("a", out _)); + Assert.True(Try(budget, "a", out _)); Assert.Equal(1, budget.TrackedKeys); } @@ -98,52 +98,141 @@ public sealed class FixedWindowBudgetTests { var clock = new Clock(); var budget = new FixedWindowBudget(1, Window, Cap, clock); - budget.TryAcquire("a", out _); + Try(budget, "a", out _); clock.StepWall(TimeSpan.FromHours(1)); - Assert.False(budget.TryAcquire("a", out var wait)); + Assert.False(Try(budget, "a", out var wait)); Assert.Equal(Window, wait); } [Fact] - public void A_new_key_at_the_cap_is_denied_until_the_oldest_window_ends_and_a_held_key_is_never_evicted() + public void A_new_key_at_the_cap_evicts_the_least_recently_used_key_with_permits_left() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(3, Window, 2, clock); + Assert.True(Try(budget, "a", out _)); + clock.Advance(TimeSpan.FromSeconds(1)); + Assert.True(Try(budget, "b", out _)); + clock.Advance(TimeSpan.FromSeconds(1)); + Assert.True(Try(budget, "a", out _)); + + // b was used least recently, though a began first: c takes b's place and a keeps its count. + Assert.True(Try(budget, "c", out _)); + Assert.Equal(2, budget.TrackedKeys); + Assert.True(Try(budget, "a", out _)); + Assert.False(Try(budget, "a", out _)); + } + + [Fact] + public void A_forgotten_key_regains_only_what_it_had_not_spent_and_a_spent_key_regains_nothing() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(2, Window, 2, clock); + Assert.True(Try(budget, "spent", out _)); + Assert.True(Try(budget, "spent", out _)); + Assert.True(Try(budget, "partial", out _)); + clock.Advance(TimeSpan.FromSeconds(10)); + + // Rotating callers evict partial, never spent. + for (var i = 0; i < 10; i++) + { + Assert.True(Try(budget, "rot" + i, out _)); + } + + Assert.False(Try(budget, "spent", out var wait)); + Assert.Equal(TimeSpan.FromSeconds(50), wait); + Assert.Equal(2, budget.TrackedKeys); + + // partial came back whole (2 permits), which is all a rotating caller can win: its own forgotten budget. + Assert.True(Try(budget, "partial", out _)); + } + + [Fact] + public void A_key_that_spends_its_last_permit_leaves_the_evictable_set() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(2, Window, 2, clock); + Assert.True(Try(budget, "a", out _)); + Assert.True(Try(budget, "a", out _)); + Assert.True(Try(budget, "b", out _)); + + // a is spent and b is not: the newcomer evicts b although a was used less recently. + Assert.True(Try(budget, "c", out _)); + Assert.False(Try(budget, "a", out _)); + Assert.True(Try(budget, "b", out _)); + } + + [Fact] + public void A_table_full_of_spent_keys_refuses_a_new_key_as_table_full_with_the_wait_for_the_oldest_window() { var clock = new Clock(); var budget = new FixedWindowBudget(1, Window, 2, clock); - budget.TryAcquire("a", out _); + Assert.True(Try(budget, "a", out _)); clock.Advance(TimeSpan.FromSeconds(20)); - budget.TryAcquire("b", out _); + Assert.True(Try(budget, "b", out _)); clock.Advance(TimeSpan.FromSeconds(10)); - Assert.False(budget.TryAcquire("c", out var wait)); - Assert.Equal(TimeSpan.FromSeconds(30), wait); + var denial = budget.Spend("c"); + Assert.Equal(new BudgetDenial(TimeSpan.FromSeconds(30), true), denial); + Assert.Equal(new BudgetDenial(TimeSpan.FromSeconds(30), false), budget.Spend("a")); Assert.Equal(2, budget.TrackedKeys); - // Rotating new keys cannot push a spent key out to get its budget back. - for (var i = 0; i < 10; i++) - { - Assert.False(budget.TryAcquire("rot" + i, out _)); - } - - Assert.False(budget.TryAcquire("a", out wait)); - Assert.Equal(TimeSpan.FromSeconds(30), wait); - clock.Advance(TimeSpan.FromSeconds(30)); - Assert.True(budget.TryAcquire("c", out _)); + Assert.True(Try(budget, "c", out _)); Assert.Equal(2, budget.TrackedKeys); - Assert.False(budget.TryAcquire("b", out wait)); + Assert.False(Try(budget, "b", out var wait)); Assert.Equal(TimeSpan.FromSeconds(20), wait); } + [Fact] + public void An_evicted_key_leaves_the_expiry_list_so_its_old_window_end_cannot_remove_the_key_that_took_its_name() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(2, Window, 2, clock); + Try(budget, "a", out _); + clock.Advance(TimeSpan.FromSeconds(1)); + Try(budget, "b", out _); + clock.Advance(TimeSpan.FromSeconds(1)); + Try(budget, "c", out _); + clock.Advance(TimeSpan.FromSeconds(1)); + Try(budget, "a", out _); + + // The first a began at 0 and ended at 60; the a that returned at 3 is still inside its window. + clock.Advance(TimeSpan.FromSeconds(57)); + Try(budget, "c", out _); + + Assert.Equal(2, budget.TrackedKeys); + } + [Fact] public void A_held_key_under_its_permits_is_served_even_when_the_table_is_full() { var clock = new Clock(); var budget = new FixedWindowBudget(2, Window, 1, clock); - Assert.True(budget.TryAcquire("a", out _)); + Assert.True(Try(budget, "a", out _)); - Assert.True(budget.TryAcquire("a", out _)); - Assert.False(budget.TryAcquire("a", out _)); + Assert.True(Try(budget, "a", out _)); + Assert.False(Try(budget, "a", out _)); + } + + [Fact] + public void Eviction_work_does_not_scan_the_table() + { + var clock = new Clock(); + var budget = new FixedWindowBudget(2, Window, 50_000, clock); + for (var i = 0; i < 50_000; i++) + { + budget.Spend("k" + i); + } + + var started = System.Diagnostics.Stopwatch.StartNew(); + for (var i = 0; i < 200_000; i++) + { + budget.Spend("n" + i); + } + + Assert.Equal(50_000, budget.TrackedKeys); + Assert.True(started.Elapsed < TimeSpan.FromSeconds(10), $"200000 evicting inserts took {started.Elapsed}"); } [Fact] @@ -153,12 +242,12 @@ public sealed class FixedWindowBudgetTests var budget = new FixedWindowBudget(1, Window, Cap, clock); for (var i = 0; i < 100; i++) { - budget.TryAcquire("k" + i, out _); + Try(budget, "k" + i, out _); } Assert.Equal(100, budget.TrackedKeys); clock.Advance(Window); - budget.TryAcquire("fresh", out _); + Try(budget, "fresh", out _); Assert.Equal(1, budget.TrackedKeys); } @@ -180,6 +269,13 @@ public sealed class FixedWindowBudgetTests Assert.Throws(() => new FixedWindowBudget(1, Window, 0, new Clock())); } + private static bool Try(FixedWindowBudget budget, string key, out TimeSpan wait) + { + var denial = budget.Spend(key); + wait = denial?.RetryAfter ?? TimeSpan.Zero; + return denial is null; + } + // Time advances monotonic and wall together; StepWall moves only the wall clock, as an NTP step would. private sealed class Clock : TimeProvider { From 912d0838941406d6949c792bd1847f8d5c358973 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 11 Oct 2026 19:17:27 +0200 Subject: [PATCH 08/10] Fix a string literal broken across lines in the table-full test Co-Authored-By: Claude Sonnet 5.5 --- tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs index 30ab093..46dff22 100644 --- a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs @@ -380,8 +380,7 @@ public sealed class ConceptVoteRateLimitTests : IClassFixture string.Join(",", h.Value)))); + Assert.DoesNotContain("203.0.113", body + string.Join(";", visitor.Headers.Select(h => string.Join(",", h.Value)))); Assert.Equal(HttpStatusCode.Redirect, account.StatusCode); Assert.Equal(rowsBefore + 1, (await Rows(collection)).Count); } From a9b9b29bf906e24d539c0f679edf617f9f46b3cc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 11 Oct 2026 19:58:09 +0200 Subject: [PATCH 09/10] Pin the account table's own cap The cap-not-wired-accounts hand mutant survived: no test filled the account table. Co-Authored-By: Claude Sonnet 5.5 --- tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs index 46dff22..1cedf97 100644 --- a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs @@ -282,6 +282,8 @@ public sealed class ConceptVoteRateLimitTests : IClassFixture Date: Sun, 11 Oct 2026 20:23:59 +0200 Subject: [PATCH 10/10] Mill votes: the very-busy refusal offers sign-in to a voter who is not signed in Accounts have their own table, so signing in works while the cast or mint table is full. A signed-in voter is not told to sign in. Pinned through the full pipeline at a small cap, for both audiences. Co-Authored-By: Claude Sonnet 5.5 --- src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs | 15 +++++++---- .../ConceptVoteRateLimitTests.cs | 26 ++++++++++++++++++- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs index f843f0a..dd87f6d 100644 --- a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs +++ b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs @@ -82,7 +82,7 @@ public sealed class VoteModel( return NotFound(); } - if (Throttled(limits.DenyCast(HttpContext.Connection.RemoteIpAddress, voter), CastRefusal) is { } throttled) + if (Throttled(limits.DenyCast(HttpContext.Connection.RemoteIpAddress, voter), CastRefusal, voter) is { } throttled) { return throttled; } @@ -105,14 +105,14 @@ public sealed class VoteModel( return NotFound(); } - if (Throttled(limits.DenyCast(client, voter), CastRefusal) is { } throttled) + if (Throttled(limits.DenyCast(client, voter), CastRefusal, voter) is { } throttled) { return throttled; } if (voter is null) { - if (Throttled(limits.DenyMint(client), MintRefusal) is { } mintThrottled) + if (Throttled(limits.DenyMint(client), MintRefusal, voter) is { } mintThrottled) { return mintThrottled; } @@ -143,14 +143,19 @@ public sealed class VoteModel( private const string BusyRefusal = "Voting is very busy right now. Please try again in a little while."; - private IActionResult? Throttled(BudgetDenial? denial, string spentRefusal) + // Accounts have their own table, so a visitor who is not signed in can still vote by signing in while a table is full. + private const string BusyRefusalSignIn = + "Voting is very busy right now. You can sign in to vote now, or try again in a little while."; + + private IActionResult? Throttled(BudgetDenial? denial, string spentRefusal, VoterIdentity? voter) { if (denial is not { } refused) { return null; } - var refusal = refused.TableFull ? BusyRefusal : spentRefusal; + var busy = voter?.UserAccountId is null ? BusyRefusalSignIn : BusyRefusal; + var refusal = refused.TableFull ? busy : spentRefusal; Response.Headers.RetryAfter = ((int)Math.Ceiling(refused.RetryAfter.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture); return new ContentResult { diff --git a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs index 1cedf97..04cdff4 100644 --- a/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs @@ -381,12 +381,36 @@ public sealed class ConceptVoteRateLimitTests : IClassFixture string.Join(",", h.Value)))); Assert.Equal(HttpStatusCode.Redirect, account.StatusCode); Assert.Equal(rowsBefore + 1, (await Rows(collection)).Count); } + [Fact] + public async Task A_full_account_table_refuses_a_new_account_as_busy_without_offering_sign_in() + { + var factory = Capped(4); + var collection = await NewSubject(); + for (var i = 0; i < 4; i++) + { + var spender = new Client(factory, $"203.0.113.{150 + i}") { Account = ($"72{i:00}", $"spent-account-{i}") }; + for (var cast = 0; cast < 3; cast++) + { + using var ok = await spender.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, ok.StatusCode); + } + } + + using var fresh = await new Client(factory, "203.0.113.160") { Account = ("7299", "fresh-signed-in") } + .Post(collection, "Up"); + + Assert.Equal(HttpStatusCode.TooManyRequests, fresh.StatusCode); + var body = await fresh.Content.ReadAsStringAsync(); + Assert.Contains("busy", body); + Assert.DoesNotContain("sign in", body, StringComparison.OrdinalIgnoreCase); + } + [Fact] public async Task Posts_to_a_missing_subject_spend_no_budget_and_mint_no_device() {