Budget registration per address; embed difficulty; expiry queue; 404 on empty withdraw

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-11 09:34:44 +00:00
commit e67257c750
11 changed files with 368 additions and 36 deletions

View file

@ -10,6 +10,18 @@ public sealed class RegistrationOptions
public const int MaxDifficulty = 30;
public RegistrationCaptchaOptions Captcha { get; init; } = new();
public RegistrationLimitsOptions Limits { get; init; } = new();
}
/// <summary>One budget on GET /auth/bifrost/challenge and POST /auth/bifrost/register together, per source address in one fixed window.</summary>
public sealed class RegistrationLimitsOptions
{
public int PerAddressPermits { get; init; } = 10;
public TimeSpan Window { get; init; } = TimeSpan.FromMinutes(1);
public int MaxTrackedKeys { get; init; } = 10_000;
}
public sealed class RegistrationCaptchaOptions

View file

@ -35,7 +35,7 @@ public sealed class OidcGuardMiddleware(RequestDelegate next, OidcIssuerOptions
return;
}
if (limit.Spend(AddressKey(http.Connection.RemoteIpAddress)) is { } byAddress)
if (limit.Spend(ClientAddress.BudgetKey(http.Connection.RemoteIpAddress)) is { } byAddress)
{
await RefuseAsync(http, StatusCodes.Status429TooManyRequests, "too_many_requests", byAddress.RetryAfter);
return;
@ -86,29 +86,6 @@ public sealed class OidcGuardMiddleware(RequestDelegate next, OidcIssuerOptions
}
}
// An IPv6 caller owns its /64, so rotating the low bits buys nothing.
private static string AddressKey(IPAddress? address)
{
if (address is null)
{
return "unknown";
}
if (address.IsIPv4MappedToIPv6)
{
address = address.MapToIPv4();
}
if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
{
return address.ToString();
}
var bytes = address.GetAddressBytes();
Array.Clear(bytes, 8, 8);
return new IPAddress(bytes).ToString() + "/64";
}
private static Task RefuseAsync(HttpContext http, int status, string error, TimeSpan retryAfter)
{
http.Response.StatusCode = status;

View file

@ -27,7 +27,9 @@ public sealed class RegistrationChallengeService(
private const int MaxNonceLength = 20;
private readonly IDataProtector protector = dataProtection.CreateProtector(Purpose);
private readonly Dictionary<string, DateTimeOffset> consumed = new(StringComparer.Ordinal);
private readonly HashSet<string> consumed = new(StringComparer.Ordinal);
// Ordered by expiry: a challenge consumed late has an earlier expiry than one consumed before it, so a plain FIFO would strand it.
private readonly PriorityQueue<string, DateTimeOffset> expiries = new();
private readonly object gate = new();
private int Difficulty => options.Value.Captcha.Difficulty;
@ -46,9 +48,10 @@ public sealed class RegistrationChallengeService(
}
var expiresAt = now + Lifetime;
var difficulty = Difficulty;
var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(16));
var challenge = protector.Protect($"{id}.{expiresAt.ToUnixTimeMilliseconds()}");
return new RegistrationChallenge(challenge, Difficulty, expiresAt);
var challenge = protector.Protect($"{id}.{expiresAt.ToUnixTimeMilliseconds()}.{difficulty}");
return new RegistrationChallenge(challenge, difficulty, expiresAt);
}
public bool TryConsume(string? challenge, string? nonce)
@ -59,16 +62,18 @@ public sealed class RegistrationChallengeService(
}
string id;
int difficulty;
DateTimeOffset expiresAt;
try
{
var payload = protector.Unprotect(challenge).Split('.');
if (payload.Length != 2)
if (payload.Length != 3)
{
return false;
}
id = payload[0];
difficulty = int.Parse(payload[2], System.Globalization.CultureInfo.InvariantCulture);
expiresAt = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(payload[1], System.Globalization.CultureInfo.InvariantCulture));
}
catch (Exception)
@ -83,7 +88,7 @@ public sealed class RegistrationChallengeService(
}
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(challenge + ":" + nonce));
if (LeadingZeroBits(hash) < Difficulty)
if (LeadingZeroBits(hash) < difficulty)
{
return false;
}
@ -91,20 +96,21 @@ public sealed class RegistrationChallengeService(
lock (gate)
{
Purge(now);
if (consumed.Count >= MaxConsumed || consumed.ContainsKey(id))
if (consumed.Count >= MaxConsumed || !consumed.Add(id))
{
return false;
}
consumed[id] = expiresAt;
expiries.Enqueue(id, expiresAt);
return true;
}
}
private void Purge(DateTimeOffset now)
{
foreach (var id in consumed.Where(x => x.Value <= now).Select(x => x.Key).ToList())
while (expiries.TryPeek(out var id, out var expiresAt) && expiresAt <= now)
{
expiries.Dequeue();
consumed.Remove(id);
}
}

View file

@ -0,0 +1,43 @@
using Bifrost.Web.Configuration;
using Bifrost.Web.Features.Shared;
using Microsoft.Extensions.Options;
namespace Bifrost.Web.Features.Registration;
/// <summary>
/// The per-address permits on the registration endpoints (challenge and register share one budget), on the shared
/// fixed-window budget. It exists so one address cannot fill the consumed-challenge set alone. It fails closed:
/// anything it cannot decide is a 503, never a pass.
/// </summary>
public sealed class RegistrationRateLimit(IOptions<RegistrationOptions> options, TimeProvider clock, ILogger<RegistrationRateLimit> logger)
{
private readonly FixedWindowBudget addresses = new(
options.Value.Limits.PerAddressPermits,
options.Value.Limits.Window,
options.Value.Limits.MaxTrackedKeys,
clock);
/// <summary>Null when the request may proceed; otherwise the refusal to return.</summary>
public IResult? Refuse(HttpContext http)
{
try
{
if (addresses.Spend(ClientAddress.BudgetKey(http.Connection.RemoteIpAddress)) is not { } denial)
{
return null;
}
http.Response.Headers.RetryAfter = RetryAfter(denial.RetryAfter);
return Results.Text("Too many registration requests from this address.", statusCode: StatusCodes.Status429TooManyRequests);
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
logger.LogError("Registration rate limit could not decide ({ExceptionType}); the request is refused.", exception.GetType().Name);
http.Response.Headers.RetryAfter = "60";
return Results.Text("Registration is unavailable; try again shortly.", statusCode: StatusCodes.Status503ServiceUnavailable);
}
}
private static string RetryAfter(TimeSpan wait) =>
Math.Max(1, (int)Math.Ceiling(wait.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture);
}

View file

@ -0,0 +1,32 @@
using System.Net;
namespace Bifrost.Web.Features.Shared;
public static class ClientAddress
{
/// <summary>
/// The partition key for a per-address budget: the connection's address, already corrected by the forwarded-headers
/// handling that trusts only the local proxy. An IPv6 caller owns its /64, so rotating the low bits buys nothing.
/// </summary>
public static string BudgetKey(IPAddress? address)
{
if (address is null)
{
return "unknown";
}
if (address.IsIPv4MappedToIPv6)
{
address = address.MapToIPv4();
}
if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
{
return address.ToString();
}
var bytes = address.GetAddressBytes();
Array.Clear(bytes, 8, 8);
return new IPAddress(bytes).ToString() + "/64";
}
}

View file

@ -55,6 +55,12 @@ public sealed class StartupConfigurationValidator(
failures.Add($"Bifrost:Registration:Captcha:Difficulty must be between {RegistrationOptions.MinDifficulty} and {RegistrationOptions.MaxDifficulty}.");
}
var limits = registrationOptions.Value.Limits;
if (limits.PerAddressPermits < 1 || limits.Window <= TimeSpan.Zero || limits.MaxTrackedKeys < 1)
{
failures.Add("Bifrost:Registration:Limits:PerAddressPermits and MaxTrackedKeys must be at least 1 and Window must be positive.");
}
if (hostEnvironment.IsDevelopment() || hostEnvironment.IsEnvironment("Testing"))
{
Refuse(failures);

View file

@ -134,6 +134,7 @@ builder.Services.AddOptions<MindIntakeOptions>().BindConfiguration(MindIntakeOpt
builder.Services.AddSingleton<MindIntakeRateLimit>(); // TimeProvider and options resolve from the container
builder.Services.AddOptions<RegistrationOptions>().BindConfiguration(RegistrationOptions.SectionName);
builder.Services.AddSingleton<RegistrationChallengeService>();
builder.Services.AddSingleton<RegistrationRateLimit>();
builder.Services.AddHostedService<SealedBallotCloser>();
builder.Services.AddScoped<MotionEveSurfaceService>();
builder.Services.AddScoped<PatronageService>();
@ -390,8 +391,14 @@ app.MapPost("/auth/bifrost/register", async (
HttpContext httpContext,
BifrostIdentityService bifrostIdentityService,
RegistrationChallengeService challenges,
RegistrationRateLimit rateLimit,
CancellationToken cancellationToken) =>
{
if (rateLimit.Refuse(httpContext) is { } refused)
{
return refused;
}
// Consent first, then the proof of work; a refusal here creates nothing.
if (request.AcceptedNoticeVersion != TrainingNotice.Version)
{
@ -432,8 +439,13 @@ app.MapPost("/auth/bifrost/register", async (
}
}).AllowAnonymous();
app.MapGet("/auth/bifrost/challenge", (HttpContext httpContext, RegistrationChallengeService challenges) =>
app.MapGet("/auth/bifrost/challenge", (HttpContext httpContext, RegistrationChallengeService challenges, RegistrationRateLimit rateLimit) =>
{
if (rateLimit.Refuse(httpContext) is { } refused)
{
return refused;
}
httpContext.Response.Headers.CacheControl = "no-store";
var challenge = challenges.Issue();
return challenge is null
@ -460,6 +472,11 @@ app.MapPost("/auth/bifrost/consent/withdraw", async (
var receipts = await dbContext.ConsentReceipts
.Where(x => x.UserAccountId == actor.UserAccount.Id)
.ToListAsync(cancellationToken);
if (receipts.Count == 0)
{
return Results.Text("No consent receipt is recorded for this account.", statusCode: StatusCodes.Status404NotFound);
}
var now = clock.GetUtcNow();
foreach (var receipt in receipts.Where(x => x.WithdrawnAtUtc is null))
{