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 <noreply@anthropic.com>
This commit is contained in:
parent
2c8384e44a
commit
a8c3ecf495
8 changed files with 219 additions and 61 deletions
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@ namespace Bifrost.Web.Features.ConceptVotes;
|
|||
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);
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -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<string, Entry> entries = new(StringComparer.Ordinal);
|
||||
private readonly Queue<string> 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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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<bool> LoadAsync(string collection, string key, VoterIdentity? voter, CancellationToken cancellationToken)
|
||||
|
|
|
|||
Loading…
Reference in a new issue