diff --git a/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs b/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs index a5e0781..0e60f7d 100644 --- a/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs +++ b/src/Bifrost.Web/Configuration/ConceptVoteOptions.cs @@ -20,6 +20,28 @@ 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. 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 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 // 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..fcfe361 --- /dev/null +++ b/src/Bifrost.Web/Features/ConceptVotes/ConceptVoteRateLimits.cs @@ -0,0 +1,29 @@ +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 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 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 BudgetDenial? DenyCast(IPAddress? client, VoterIdentity? known) => + known?.UserAccountId is { } account + ? castAccounts.Spend(account.ToString("N")) + : castNetworks.Spend(NetKey(client)); + + public BudgetDenial? DenyMint(IPAddress? client) => mint.Spend(NetKey(client)); + + private string NetKey(IPAddress? client) => + 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..b6c9083 --- /dev/null +++ b/src/Bifrost.Web/Features/Shared/FixedWindowBudget.cs @@ -0,0 +1,131 @@ +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 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 +{ + 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 LinkedList byStart = new(); + private readonly LinkedList byUse = new(); + private readonly object gate = new(); + + 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: the keys whose window is still open, never more than maxKeys. + public int TrackedKeys + { + get + { + lock (gate) + { + return entries.Count; + } + } + } + + // 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.First is { Value: var oldest } && oldest.Start + window <= now) + { + Remove(oldest); + } + + if (entries.TryGetValue(key, out var entry)) + { + if (entry.Count >= permits) + { + return new BudgetDenial(entry.Start + window - now, false); + } + + entry.Count++; + 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) + { + if (byUse.First is not { Value: var forgotten }) + { + return new BudgetDenial(byStart.First!.Value.Start + window - now, true); + } + + Remove(forgotten); + } + + 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 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/Features/Shared/StartupConfigurationValidator.cs b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs index c511413..98b8dc7 100644 --- a/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs +++ b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs @@ -16,12 +16,40 @@ 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 (conceptVotes.MaxTrackedKeys < 1) + { + failures.Add("ConceptVotes:MaxTrackedKeys must be at least 1."); + } + + if (hostEnvironment.IsDevelopment() || hostEnvironment.IsEnvironment("Testing")) + { + Refuse(failures); + return; + } if (!gitHubOAuthOptions.Value.IsConfigured) { @@ -73,7 +101,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 +108,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..dd87f6d 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 (await appraisals.GetSubjectAsync(collection, key, null, cancellationToken) is null) { return NotFound(); } - var voter = ResolveVoter(actor, mint: false); + if (Throttled(limits.DenyCast(HttpContext.Connection.RemoteIpAddress, voter), CastRefusal, voter) is { } throttled) + { + return throttled; + } + 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 (await appraisals.GetSubjectAsync(collection, key, null, cancellationToken) is null) { return NotFound(); } - var voter = ResolveVoter(actor, mint: true); + if (Throttled(limits.DenyCast(client, voter), CastRefusal, voter) is { } throttled) + { + return throttled; + } + + if (voter is null) + { + if (Throttled(limits.DenyMint(client), MintRefusal, voter) 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,41 @@ 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, in words a voter can read; it writes no row, sets no cookie and + // 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 const string BusyRefusal = "Voting is very busy right now. Please try again in a little while."; + + // 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) { - var voter = VoterIdentity.For(actor, null) ?? VoterIdentity.For(actor, deviceCookie.TryRead(HttpContext)); - if (voter is null && mint) + if (denial is not { } refused) { - voter = VoterIdentity.For(actor, deviceCookie.Mint(HttpContext)); + return null; } - return voter; + 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 + { + 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/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..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; @@ -183,6 +184,37 @@ 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(StatusCodes.Status403Forbidden, context.Response.StatusCode); + Assert.False(context.Response.Headers.ContainsKey("Set-Cookie")); + Assert.Empty(await Rows(collection, "alpha")); + } + [Theory] [InlineData("same-origin", true)] [InlineData("same-site", false)] @@ -638,46 +670,4 @@ 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..04cdff4 --- /dev/null +++ b/tests/Bifrost.Web.Tests/ConceptVoteRateLimitTests.cs @@ -0,0 +1,621 @@ +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; +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)); + } + + // 499.5 s remain: Retry-After rounds up, so a client told to wait never retries early. + _factory.Clock.Advance(TimeSpan.FromMilliseconds(100_500)); + using (var later = await device.Post(collection, "Up")) + { + Assert.Equal(HttpStatusCode.TooManyRequests, later.StatusCode); + Assert.Equal("500", RetryAfter(later)); + } + + _factory.Clock.Advance(TimeSpan.FromMilliseconds(498_500)); + 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 Retract_by_a_signed_in_account_spends_the_account_budget_from_any_prefix() + { + var collection = await NewSubject(); + var home = new Client(_factory, "203.0.113.60") { Account = ("7003", "carol-limits") }; + var away = new Client(_factory, "203.0.113.61") { Account = ("7003", "carol-limits") }; + var elsewhere = new Client(_factory, "203.0.113.62") { Account = ("7003", "carol-limits") }; + await home.Post(collection, "Up"); + await home.Post(collection, "Down"); + using var third = await away.Post(collection, "Retract"); + Assert.Equal(HttpStatusCode.Redirect, third.StatusCode); + + using var denied = await elsewhere.Post(collection, "Retract"); + + Assert.Equal(HttpStatusCode.TooManyRequests, denied.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); + Assert.StartsWith("text/plain", denied.Content.Headers.ContentType?.MediaType); + var refusal = await denied.Content.ReadAsStringAsync(); + Assert.Contains("sign in", refusal, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("203.0.113", refusal); + + // 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 body = await denied.Content.ReadAsStringAsync(); + Assert.Contains("too fast", body); + var seen = body + + 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 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 Every_table_holds_at_most_the_configured_keys_and_accounts_have_a_table_of_their_own() + { + var limits = new Bifrost.Web.Features.ConceptVotes.ConceptVoteRateLimits( + Microsoft.Extensions.Options.Options.Create( + new Bifrost.Web.Configuration.ConceptVoteOptions { MaxTrackedKeys = 1, CastPermits = 1, MintPermits = 1 }), + new TestClock()); + var account = new VoterIdentity("account:test", VoterClass.Account, Guid.NewGuid()); + + Assert.Null(limits.DenyCast(IPAddress.Parse("198.51.100.1"), null)); + Assert.True(limits.DenyCast(IPAddress.Parse("198.51.100.2"), null)!.Value.TableFull); + Assert.Null(limits.DenyCast(IPAddress.Parse("198.51.100.2"), account)); + var otherAccount = new VoterIdentity("account:other", VoterClass.Account, Guid.NewGuid()); + Assert.True(limits.DenyCast(IPAddress.Parse("198.51.100.2"), otherAccount)!.Value.TableFull); + Assert.Null(limits.DenyMint(IPAddress.Parse("198.51.100.1"))); + Assert.True(limits.DenyMint(IPAddress.Parse("198.51.100.2"))!.Value.TableFull); + } + + [Fact] + public async Task Filling_the_table_with_unspent_keys_locks_out_neither_a_fresh_visitor_nor_a_fresh_account() + { + var factory = Capped(4); + var collection = await NewSubject(); + for (var i = 0; i < 4; i++) + { + using var filler = await new Client(factory, $"203.0.113.{80 + i}").Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, filler.StatusCode); + } + + using var visitor = await new Client(factory, "203.0.113.90").Post(collection, "Up"); + using var account = await new Client(factory, "203.0.113.91") { Account = ("7101", "fresh-account") } + .Post(collection, "Up"); + + Assert.Equal(HttpStatusCode.Redirect, visitor.StatusCode); + Assert.NotNull(SetCookie(visitor)); + Assert.Equal(HttpStatusCode.Redirect, account.StatusCode); + } + + [Fact] + public async Task A_spent_key_survives_eviction_pressure_and_stays_refused_while_rotating_callers_succeed() + { + var factory = Capped(4); + var collection = await NewSubject(); + var spender = new Client(factory, "203.0.113.100"); + for (var i = 0; i < 3; i++) + { + using var ok = await spender.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, ok.StatusCode); + } + + for (var i = 0; i < 12; i++) + { + using var rotating = await new Client(factory, $"203.0.114.{i + 1}").Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, rotating.StatusCode); + } + + using var denied = await spender.Post(collection, "Up"); + + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); + Assert.Contains("too fast", await denied.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task A_rotating_caller_wins_back_only_a_forgotten_keys_unspent_budget() + { + var factory = Capped(2); + var collection = await NewSubject(); + var forgotten = new Client(factory, "203.0.113.110"); + await forgotten.Post(collection, "Up"); + await forgotten.Post(collection, "Up"); + var recent = new Client(factory, "203.0.113.111"); + await recent.Post(collection, "Up"); + await new Client(factory, "203.0.113.112").Post(collection, "Up"); + + // forgotten was least recently used and had one permit left: it was evicted, so it has all three again, no more. + for (var i = 0; i < 3; i++) + { + using var ok = await forgotten.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, ok.StatusCode); + } + + using var denied = await forgotten.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); + } + + [Fact] + public async Task A_table_full_of_spent_keys_refuses_a_new_visitor_with_its_true_reason_and_leaves_accounts_alone() + { + var factory = Capped(4); + var collection = await NewSubject(); + for (var i = 0; i < 4; i++) + { + var spender = new Client(factory, $"203.0.113.{120 + i}"); + for (var cast = 0; cast < 3; cast++) + { + using var ok = await spender.Post(collection, "Up"); + Assert.Equal(HttpStatusCode.Redirect, ok.StatusCode); + } + } + + var rowsBefore = (await Rows(collection)).Count; + using var visitor = await new Client(factory, "203.0.113.130").Post(collection, "Up"); + using var account = await new Client(factory, "203.0.113.131") { Account = ("7102", "spared-account") } + .Post(collection, "Up"); + + Assert.Equal(HttpStatusCode.TooManyRequests, visitor.StatusCode); + Assert.NotNull(RetryAfter(visitor)); + Assert.Null(SetCookie(visitor)); + var body = await visitor.Content.ReadAsStringAsync(); + Assert.Contains("busy", body); + Assert.DoesNotContain("too fast", body); + Assert.Contains("sign in", body, StringComparison.OrdinalIgnoreCase); + 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); + } + + [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() + { + 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] + public void A_request_with_no_client_address_shares_one_bucket_apart_from_every_address() + { + var limits = new Bifrost.Web.Features.ConceptVotes.ConceptVoteRateLimits( + Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.ConceptVoteOptions { CastPermits = 1 }), + new TestClock()); + + Assert.Null(limits.DenyCast(null, null)); + Assert.NotNull(limits.DenyCast(null, null)); + Assert.Null(limits.DenyCast(IPAddress.Parse("198.51.100.1"), null)); + } + + [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 WebApplicationFactory 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; + + 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; + private long _ticks = 5_000_000; + + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + + public override DateTimeOffset GetUtcNow() => _now; + + 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. + 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..e2fedb2 --- /dev/null +++ b/tests/Bifrost.Web.Tests/FixedWindowBudgetTests.cs @@ -0,0 +1,299 @@ +using Bifrost.Web.Features.Shared; + +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, Cap, clock); + + Assert.True(Try(budget, "a", out _)); + clock.Advance(TimeSpan.FromSeconds(10)); + Assert.True(Try(budget, "a", out _)); + Assert.False(Try(budget, "a", out var wait)); + + Assert.Equal(TimeSpan.FromSeconds(50), wait); + Assert.True(Try(budget, "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, Cap, clock); + Assert.True(Try(budget, "a", out _)); + + clock.Advance(Window - TimeSpan.FromTicks(1)); + Assert.False(Try(budget, "a", out var wait)); + Assert.Equal(TimeSpan.FromTicks(1), wait); + + clock.Advance(TimeSpan.FromTicks(1)); + Assert.True(Try(budget, "a", out _)); + Assert.False(Try(budget, "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, Cap, clock); + Try(budget, "a", out _); + for (var i = 0; i < 5; i++) + { + clock.Advance(TimeSpan.FromSeconds(10)); + Assert.False(Try(budget, "a", out _)); + } + + clock.Advance(TimeSpan.FromSeconds(10)); + Assert.True(Try(budget, "a", out _)); + } + + [Fact] + 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, Cap, clock); + Try(budget, "a", out _); + clock.Advance(TimeSpan.FromSeconds(30)); + Try(budget, "b", out _); + clock.Advance(TimeSpan.FromSeconds(30)); + + // At 60 s a has ended and b has 30 s left. + Try(budget, "c", out _); + Assert.Equal(2, budget.TrackedKeys); + Assert.False(Try(budget, "b", out var wait)); + Assert.Equal(TimeSpan.FromSeconds(30), wait); + + clock.Advance(TimeSpan.FromSeconds(30) - TimeSpan.FromTicks(1)); + Assert.False(Try(budget, "b", out _)); + clock.Advance(TimeSpan.FromTicks(1)); + Assert.True(Try(budget, "b", out _)); + } + + [Fact] + 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, Cap, clock); + Try(budget, "a", out _); + clock.Advance(TimeSpan.FromSeconds(10)); + clock.StepWall(-TimeSpan.FromHours(1)); + + Assert.False(Try(budget, "a", out var wait)); + Assert.Equal(TimeSpan.FromSeconds(50), wait); + clock.Advance(TimeSpan.FromSeconds(50)); + Assert.True(Try(budget, "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); + Try(budget, "a", out _); + clock.StepWall(TimeSpan.FromHours(1)); + + Assert.False(Try(budget, "a", out var wait)); + Assert.Equal(Window, wait); + } + + [Fact] + 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); + Assert.True(Try(budget, "a", out _)); + clock.Advance(TimeSpan.FromSeconds(20)); + Assert.True(Try(budget, "b", out _)); + clock.Advance(TimeSpan.FromSeconds(10)); + + 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); + + clock.Advance(TimeSpan.FromSeconds(30)); + Assert.True(Try(budget, "c", out _)); + Assert.Equal(2, budget.TrackedKeys); + 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(Try(budget, "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] + 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, Cap, clock); + for (var i = 0; i < 100; i++) + { + Try(budget, "k" + i, out _); + } + + Assert.Equal(100, budget.TrackedKeys); + clock.Advance(Window); + Try(budget, "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), Cap, new Clock())); + } + + [Fact] + public void A_cap_below_one_is_refused() + { + 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 + { + private DateTimeOffset _wall = new(2026, 10, 11, 12, 0, 0, TimeSpan.Zero); + private long _ticks = 5_000_000; + + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + + 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 7d55439..54c0128 100644 --- a/tests/Bifrost.Web.Tests/HostTrustTests.cs +++ b/tests/Bifrost.Web.Tests/HostTrustTests.cs @@ -185,6 +185,62 @@ 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("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("")] @@ -267,7 +323,12 @@ 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, + int maxTrackedKeys = 100_000) { var values = new Dictionary { @@ -295,7 +356,12 @@ 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), + MaxTrackedKeys = maxTrackedKeys })).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",