Registration gates: proof-of-work CAPTCHA and training-notice consent receipt (#54)
This commit is contained in:
parent
fc8242f655
commit
33be966b7d
28 changed files with 1253 additions and 56 deletions
|
|
@ -15,6 +15,7 @@ public sealed partial class BifrostIdentityService(
|
|||
public async Task<UserAccount> RegisterNativeAsync(
|
||||
string identity,
|
||||
string? displayName,
|
||||
int noticeVersion,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedIdentity = NormalizeIdentity(identity);
|
||||
|
|
@ -57,7 +58,14 @@ public sealed partial class BifrostIdentityService(
|
|||
}
|
||||
};
|
||||
|
||||
// One SaveChanges: no account exists without the receipt of the notice it accepted.
|
||||
dbContext.UserAccounts.Add(userAccount);
|
||||
dbContext.ConsentReceipts.Add(new ConsentReceipt
|
||||
{
|
||||
UserAccount = userAccount,
|
||||
NoticeVersion = noticeVersion,
|
||||
AcceptedAtUtc = now
|
||||
});
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return userAccount;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,137 @@
|
|||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Bifrost.Web.Configuration;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Bifrost.Web.Features.Registration;
|
||||
|
||||
public sealed record RegistrationChallenge(string Challenge, int Difficulty, DateTimeOffset ExpiresAt);
|
||||
|
||||
/// <summary>
|
||||
/// Self-hosted proof-of-work challenge for the anonymous registration. A challenge is a data-protected
|
||||
/// (random id, expiry) payload, so the server keeps nothing per issue; only consumed ids are remembered, in a bounded
|
||||
/// set whose entries are dropped at expiry. A full set refuses both issuing and consuming rather than grow.
|
||||
/// </summary>
|
||||
public sealed class RegistrationChallengeService(
|
||||
IDataProtectionProvider dataProtection,
|
||||
IOptions<RegistrationOptions> options,
|
||||
TimeProvider clock)
|
||||
{
|
||||
public const string Purpose = "Bifrost.Registration.Challenge.v1";
|
||||
|
||||
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
|
||||
|
||||
public const int MaxConsumed = 10_000;
|
||||
|
||||
private const int MaxNonceLength = 20;
|
||||
|
||||
private readonly IDataProtector protector = dataProtection.CreateProtector(Purpose);
|
||||
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;
|
||||
|
||||
/// <summary>Null when the consumed set is full: refuse rather than grow.</summary>
|
||||
public RegistrationChallenge? Issue()
|
||||
{
|
||||
var now = clock.GetUtcNow();
|
||||
lock (gate)
|
||||
{
|
||||
Purge(now);
|
||||
if (consumed.Count >= MaxConsumed)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
var expiresAt = now + Lifetime;
|
||||
var difficulty = Difficulty;
|
||||
var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(16));
|
||||
var challenge = protector.Protect($"{id}.{expiresAt.ToUnixTimeMilliseconds()}.{difficulty}");
|
||||
return new RegistrationChallenge(challenge, difficulty, expiresAt);
|
||||
}
|
||||
|
||||
public bool TryConsume(string? challenge, string? nonce)
|
||||
{
|
||||
if (string.IsNullOrEmpty(challenge) || !IsNonce(nonce))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string id;
|
||||
int difficulty;
|
||||
DateTimeOffset expiresAt;
|
||||
try
|
||||
{
|
||||
var payload = protector.Unprotect(challenge).Split('.');
|
||||
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)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var now = clock.GetUtcNow();
|
||||
if (now >= expiresAt)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(challenge + ":" + nonce));
|
||||
if (LeadingZeroBits(hash) < difficulty)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (gate)
|
||||
{
|
||||
Purge(now);
|
||||
if (consumed.Count >= MaxConsumed || !consumed.Add(id))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
expiries.Enqueue(id, expiresAt);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void Purge(DateTimeOffset now)
|
||||
{
|
||||
while (expiries.TryPeek(out var id, out var expiresAt) && expiresAt <= now)
|
||||
{
|
||||
expiries.Dequeue();
|
||||
consumed.Remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsNonce(string? nonce) =>
|
||||
nonce is { Length: >= 1 and <= MaxNonceLength } && nonce.All(c => c is >= '0' and <= '9');
|
||||
|
||||
public static int LeadingZeroBits(ReadOnlySpan<byte> hash)
|
||||
{
|
||||
var bits = 0;
|
||||
foreach (var b in hash)
|
||||
{
|
||||
if (b == 0)
|
||||
{
|
||||
bits += 8;
|
||||
continue;
|
||||
}
|
||||
|
||||
return bits + System.Numerics.BitOperations.LeadingZeroCount((uint)b) - 24;
|
||||
}
|
||||
|
||||
return bits;
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
17
src/Bifrost.Web/Features/Registration/TrainingNotice.cs
Normal file
17
src/Bifrost.Web/Features/Registration/TrainingNotice.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
namespace Bifrost.Web.Features.Registration;
|
||||
|
||||
/// <summary>
|
||||
/// The training notice a registrant accepts. DRAFT wording: Eureka replaces <see cref="Text"/>. Changing the wording
|
||||
/// in substance means a new <see cref="Version"/> (a positive integer, no leading zeros), because a receipt records the
|
||||
/// version the person accepted.
|
||||
/// </summary>
|
||||
public static class TrainingNotice
|
||||
{
|
||||
public const int Version = 1;
|
||||
|
||||
public const string Text =
|
||||
"Chat messages and activity on GameCult chat may be used to train and evaluate AI models. " +
|
||||
"No Discord material is used. " +
|
||||
"Your consent is voluntary. It is recorded with this notice version and the time you give it, " +
|
||||
"and you can withdraw it at any time. Withdrawing stops future use; it cannot recall use that already happened.";
|
||||
}
|
||||
32
src/Bifrost.Web/Features/Shared/ClientAddress.cs
Normal file
32
src/Bifrost.Web/Features/Shared/ClientAddress.cs
Normal 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";
|
||||
}
|
||||
}
|
||||
|
|
@ -13,7 +13,8 @@ public sealed class StartupConfigurationValidator(
|
|||
IOptions<StripeOptions> stripeOptions,
|
||||
IOptions<BifrostHostOptions> hostOptions,
|
||||
IOptions<ConceptVoteOptions> conceptVoteOptions,
|
||||
IOptions<DeskOptions> deskOptions)
|
||||
IOptions<DeskOptions> deskOptions,
|
||||
IOptions<RegistrationOptions> registrationOptions)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
|
|
@ -48,6 +49,18 @@ public sealed class StartupConfigurationValidator(
|
|||
|
||||
ValidateDesk(deskOptions.Value, failures);
|
||||
|
||||
var difficulty = registrationOptions.Value.Captcha.Difficulty;
|
||||
if (difficulty < RegistrationOptions.MinDifficulty || difficulty > RegistrationOptions.MaxDifficulty)
|
||||
{
|
||||
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);
|
||||
|
|
|
|||
Loading…
Reference in a new issue