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 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-11 09:00:23 +02:00
commit fbf6e43955
13 changed files with 794 additions and 69 deletions

View file

@ -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.

View file

@ -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<ConceptVoteOptions> 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));
}

View file

@ -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<string, Entry> 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;
}
}

View file

@ -16,12 +16,35 @@ public sealed class StartupConfigurationValidator(
{
public void Validate()
{
if (hostEnvironment.IsDevelopment() || hostEnvironment.IsEnvironment("Testing"))
var failures = new List<string>();
// 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<string>();
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<string> failures)
{
if (failures.Count > 0)
{
throw new InvalidOperationException(

View file

@ -17,6 +17,7 @@ public sealed class VoteModel(
ICurrentBifrostActorAccessor actorAccessor,
ConceptAppraisalService appraisals,
VoterKeyResolver deviceCookie,
ConceptVoteRateLimits limits,
IOptions<ConceptVoteOptions> options,
IOptions<BifrostHostOptions> host) : PageModel
{
@ -61,7 +62,7 @@ public sealed class VoteModel(
public async Task<IActionResult> 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<IActionResult> 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<bool> LoadAsync(string collection, string key, VoterIdentity? voter, CancellationToken cancellationToken)

View file

@ -119,6 +119,7 @@ builder.Services.AddScoped<StripeWebhookService>();
builder.Services.AddScoped<HeimdallPatronSupportIntakeService>();
builder.Services.AddScoped<ConceptAppraisalService>();
builder.Services.AddScoped<VoterKeyResolver>();
builder.Services.AddSingleton<ConceptVoteRateLimits>();
builder.Services.AddScoped<ConceptSubjectRegistry>();
builder.Services.AddScoped<ReadinessService>();
builder.Services.AddScoped<ApplicationBootstrapper>();