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
31
src/Bifrost.Web/Configuration/RegistrationOptions.cs
Normal file
31
src/Bifrost.Web/Configuration/RegistrationOptions.cs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
namespace Bifrost.Web.Configuration;
|
||||
|
||||
/// <summary>Gates on the anonymous native registration (section <c>Bifrost:Registration</c>).</summary>
|
||||
public sealed class RegistrationOptions
|
||||
{
|
||||
public const string SectionName = "Bifrost:Registration";
|
||||
|
||||
public const int MinDifficulty = 1;
|
||||
|
||||
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
|
||||
{
|
||||
/// <summary>Leading zero bits the SHA-256 of <c>challenge:nonce</c> must have. 18 is about 262k hashes, a second or two in a browser.</summary>
|
||||
public int Difficulty { get; init; } = 18;
|
||||
}
|
||||
|
|
@ -43,6 +43,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
|||
|
||||
public DbSet<SealedBallot> SealedBallots => Set<SealedBallot>();
|
||||
|
||||
public DbSet<ConsentReceipt> ConsentReceipts => Set<ConsentReceipt>();
|
||||
public DbSet<MindKey> MindKeys => Set<MindKey>();
|
||||
|
||||
public DbSet<MindNonce> MindNonces => Set<MindNonce>();
|
||||
|
|
@ -322,6 +323,15 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
|||
.OnDelete(DeleteBehavior.Restrict);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ConsentReceipt>(entity =>
|
||||
{
|
||||
entity.HasIndex(x => new { x.UserAccountId, x.NoticeVersion }).IsUnique();
|
||||
entity.HasOne(x => x.UserAccount)
|
||||
.WithMany()
|
||||
.HasForeignKey(x => x.UserAccountId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<MindKey>(entity =>
|
||||
{
|
||||
entity.HasIndex(x => new { x.PersonaId, x.PublicKey }).IsUnique();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,40 @@
|
|||
using System;
|
||||
using Bifrost.Web.Data;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Bifrost.Web.Data.Migrations
|
||||
{
|
||||
// Hand-written like AddMindKeys: no dotnet-ef on the authoring host; the snapshot was edited to match.
|
||||
[DbContext(typeof(BifrostDbContext))]
|
||||
[Migration("20261111090000_AddConsentReceipts")]
|
||||
public partial class AddConsentReceipts : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ConsentReceipts",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
UserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
NoticeVersion = table.Column<int>(type: "integer", nullable: false),
|
||||
AcceptedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
WithdrawnAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ConsentReceipts", x => x.Id);
|
||||
table.ForeignKey("FK_ConsentReceipts_UserAccounts_UserAccountId", x => x.UserAccountId, "UserAccounts", "Id", onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
migrationBuilder.CreateIndex(name: "IX_ConsentReceipts_UserAccountId_NoticeVersion", table: "ConsentReceipts", columns: new[] { "UserAccountId", "NoticeVersion" }, unique: true);
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(name: "ConsentReceipts");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1440,6 +1440,32 @@ namespace Bifrost.Web.Data.Migrations
|
|||
b.ToTable("VolunteerClaims");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.ConsentReceipt", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("AcceptedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int>("NoticeVersion")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<Guid>("UserAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset?>("WithdrawnAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserAccountId", "NoticeVersion")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("ConsentReceipts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.MindKey", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
|
|
@ -2142,6 +2168,17 @@ namespace Bifrost.Web.Data.Migrations
|
|||
b.Navigation("WorkItem");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.ConsentReceipt", b =>
|
||||
{
|
||||
b.HasOne("Bifrost.Web.Domain.UserAccount", "UserAccount")
|
||||
.WithMany()
|
||||
.HasForeignKey("UserAccountId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("UserAccount");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.MemberProfile", b =>
|
||||
{
|
||||
b.HasOne("Bifrost.Web.Domain.UserAccount", "UserAccount")
|
||||
|
|
|
|||
|
|
@ -1155,6 +1155,25 @@ public sealed class AuditEvent
|
|||
public UserAccount? ActorUserAccount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An account's consent to the training notice, recorded with the notice version it accepted. Withdrawal sets
|
||||
/// <see cref="WithdrawnAtUtc"/>; the row is never deleted, so what was agreed and when stays answerable.
|
||||
/// </summary>
|
||||
public sealed class ConsentReceipt
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
public Guid UserAccountId { get; set; }
|
||||
|
||||
public int NoticeVersion { get; set; }
|
||||
|
||||
public DateTimeOffset AcceptedAtUtc { get; set; }
|
||||
|
||||
public DateTimeOffset? WithdrawnAtUtc { get; set; }
|
||||
|
||||
public UserAccount? UserAccount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A Mind's registered Ed25519 public key. Bifrost never holds a private key.</summary>
|
||||
public sealed class MindKey
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ using Bifrost.Web.Features.Membership;
|
|||
using Bifrost.Web.Features.Motions;
|
||||
using Bifrost.Web.Features.Oidc;
|
||||
using Bifrost.Web.Features.Patronage;
|
||||
using Bifrost.Web.Features.Registration;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
|
|
@ -131,6 +132,9 @@ builder.Services.AddScoped<SealedBallotService>();
|
|||
builder.Services.AddScoped<MindIntakeService>();
|
||||
builder.Services.AddOptions<MindIntakeOptions>().BindConfiguration(MindIntakeOptions.SectionName);
|
||||
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>();
|
||||
|
|
@ -386,13 +390,34 @@ app.MapPost("/auth/bifrost/register", async (
|
|||
NativeBifrostRegistrationRequest request,
|
||||
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)
|
||||
{
|
||||
return Results.Text(
|
||||
$"Registration requires accepting the training notice, current version {TrainingNotice.Version}.",
|
||||
statusCode: StatusCodes.Status400BadRequest);
|
||||
}
|
||||
|
||||
if (!challenges.TryConsume(request.Challenge, request.Nonce))
|
||||
{
|
||||
return Results.Text("Registration challenge failed.", statusCode: StatusCodes.Status400BadRequest);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var userAccount = await bifrostIdentityService.RegisterNativeAsync(
|
||||
request.Identity,
|
||||
request.DisplayName,
|
||||
TrainingNotice.Version,
|
||||
cancellationToken);
|
||||
await httpContext.SignInAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
|
|
@ -414,6 +439,56 @@ app.MapPost("/auth/bifrost/register", async (
|
|||
}
|
||||
}).AllowAnonymous();
|
||||
|
||||
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
|
||||
? Results.Text("Registration is busy; try again shortly.", statusCode: StatusCodes.Status503ServiceUnavailable)
|
||||
: JsonResult(challenge, appJsonSerializerOptions);
|
||||
}).AllowAnonymous();
|
||||
|
||||
app.MapGet("/auth/bifrost/notice", () =>
|
||||
JsonResult(new { version = TrainingNotice.Version, text = TrainingNotice.Text }, appJsonSerializerOptions)).AllowAnonymous();
|
||||
|
||||
// Withdrawal stops future use; the receipt row stays. Idempotent: an already-withdrawn receipt keeps its first timestamp.
|
||||
app.MapPost("/auth/bifrost/consent/withdraw", async (
|
||||
ICurrentBifrostActorAccessor actors,
|
||||
BifrostDbContext dbContext,
|
||||
TimeProvider clock,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var actor = await actors.GetAsync(cancellationToken);
|
||||
if (!actor.IsAuthenticated || actor.UserAccount is null)
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
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))
|
||||
{
|
||||
receipt.WithdrawnAtUtc = now;
|
||||
}
|
||||
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return JsonResult(
|
||||
new { withdrawnAtUtc = receipts.Min(x => x.WithdrawnAtUtc) },
|
||||
appJsonSerializerOptions);
|
||||
});
|
||||
|
||||
app.MapGet("/auth/heimdall/{provider}", async (
|
||||
string provider,
|
||||
HttpContext httpContext,
|
||||
|
|
@ -792,7 +867,10 @@ public partial class Program;
|
|||
public sealed record NativeBifrostRegistrationRequest(
|
||||
string Identity,
|
||||
string? DisplayName,
|
||||
string? ReturnUrl);
|
||||
string? ReturnUrl,
|
||||
string? Challenge,
|
||||
string? Nonce,
|
||||
int? AcceptedNoticeVersion);
|
||||
|
||||
public sealed record NativeBifrostRegistrationResponse(
|
||||
Guid UserAccountId,
|
||||
|
|
|
|||
Loading…
Reference in a new issue