From 8c3827b36d7464ff9af95bb4435c20c2e44861bc Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 11:22:22 +0000 Subject: [PATCH] Consent: optional at registration, a consent page with accept and withdraw, notice version 2 Registration without acceptedNoticeVersion (JSON) or with the box unticked (form) creates the account with no receipt; a version sent must still equal the one in force. GET /auth/bifrost/consent shows the notice and the account's state with the one applicable button. POST accept and withdraw are forms behind the strict RequestOriginGuard.Allows (403 before any read or write), idempotent, and withdraw is no longer JSON. The ConsentReceipt unique index becomes filtered to live rows so a person can agree again after withdrawing. TrainingNotice.Version = 2 with the ruled text. Co-Authored-By: Claude Sonnet 5.5 --- src/Bifrost.Web/Data/BifrostDbContext.cs | 3 +- ...100000_ConsentReceiptsOneLivePerVersion.cs | 36 ++ .../BifrostDbContextModelSnapshot.cs | 3 +- .../Membership/BifrostIdentityService.cs | 17 +- .../Features/Registration/ConsentEndpoints.cs | 180 ++++++++ .../Features/Registration/ConsentPage.cs | 99 +++++ .../Registration/NativeRegistration.cs | 12 +- .../Features/Registration/RegistrationPage.cs | 9 +- .../Features/Registration/TrainingNotice.cs | 34 +- src/Bifrost.Web/Program.cs | 42 +- tests/Bifrost.Web.Tests/ConsentTests.cs | 407 ++++++++++++++++++ .../MigrationDiscoveryTests.cs | 1 + .../RegistrationFormTests.cs | 52 ++- .../RegistrationGateTests.cs | 102 +---- 14 files changed, 844 insertions(+), 153 deletions(-) create mode 100644 src/Bifrost.Web/Data/Migrations/20261111100000_ConsentReceiptsOneLivePerVersion.cs create mode 100644 src/Bifrost.Web/Features/Registration/ConsentEndpoints.cs create mode 100644 src/Bifrost.Web/Features/Registration/ConsentPage.cs create mode 100644 tests/Bifrost.Web.Tests/ConsentTests.cs diff --git a/src/Bifrost.Web/Data/BifrostDbContext.cs b/src/Bifrost.Web/Data/BifrostDbContext.cs index 57f5788..d227c42 100644 --- a/src/Bifrost.Web/Data/BifrostDbContext.cs +++ b/src/Bifrost.Web/Data/BifrostDbContext.cs @@ -325,7 +325,8 @@ public sealed class BifrostDbContext(DbContextOptions options) modelBuilder.Entity(entity => { - entity.HasIndex(x => new { x.UserAccountId, x.NoticeVersion }).IsUnique(); + // One live receipt per account and version; a withdrawn row stays as history and a later agreement is a new row. + entity.HasIndex(x => new { x.UserAccountId, x.NoticeVersion }).IsUnique().HasFilter("\"WithdrawnAtUtc\" IS NULL"); entity.HasOne(x => x.UserAccount) .WithMany() .HasForeignKey(x => x.UserAccountId) diff --git a/src/Bifrost.Web/Data/Migrations/20261111100000_ConsentReceiptsOneLivePerVersion.cs b/src/Bifrost.Web/Data/Migrations/20261111100000_ConsentReceiptsOneLivePerVersion.cs new file mode 100644 index 0000000..a1176b5 --- /dev/null +++ b/src/Bifrost.Web/Data/Migrations/20261111100000_ConsentReceiptsOneLivePerVersion.cs @@ -0,0 +1,36 @@ +using Bifrost.Web.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Bifrost.Web.Data.Migrations +{ + // Hand-written like AddConsentReceipts: no dotnet-ef on the authoring host; the snapshot was edited to match. + // A person may withdraw and agree again to the same version, so uniqueness narrows to the live receipt. + [DbContext(typeof(BifrostDbContext))] + [Migration("20261111100000_ConsentReceiptsOneLivePerVersion")] + public partial class ConsentReceiptsOneLivePerVersion : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex(name: "IX_ConsentReceipts_UserAccountId_NoticeVersion", table: "ConsentReceipts"); + migrationBuilder.CreateIndex( + name: "IX_ConsentReceipts_UserAccountId_NoticeVersion", + table: "ConsentReceipts", + columns: new[] { "UserAccountId", "NoticeVersion" }, + unique: true, + filter: "\"WithdrawnAtUtc\" IS NULL"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex(name: "IX_ConsentReceipts_UserAccountId_NoticeVersion", table: "ConsentReceipts"); + migrationBuilder.CreateIndex( + name: "IX_ConsentReceipts_UserAccountId_NoticeVersion", + table: "ConsentReceipts", + columns: new[] { "UserAccountId", "NoticeVersion" }, + unique: true); + } + } +} diff --git a/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs b/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs index 63f6a40..851318c 100644 --- a/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs +++ b/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs @@ -1461,7 +1461,8 @@ namespace Bifrost.Web.Data.Migrations b.HasKey("Id"); b.HasIndex("UserAccountId", "NoticeVersion") - .IsUnique(); + .IsUnique() + .HasFilter("\"WithdrawnAtUtc\" IS NULL"); b.ToTable("ConsentReceipts"); }); diff --git a/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs b/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs index 4a70995..aa1bf8a 100644 --- a/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs +++ b/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs @@ -35,7 +35,7 @@ public sealed partial class BifrostIdentityService( public async Task RegisterNativeAsync( string identity, string? displayName, - int noticeVersion, + int? noticeVersion, CancellationToken cancellationToken) { var normalizedIdentity = await CheckAvailableAsync(identity, cancellationToken); @@ -66,14 +66,17 @@ public sealed partial class BifrostIdentityService( } }; - // One SaveChanges: no account exists without the receipt of the notice it accepted. + // One SaveChanges: an account that agreed never exists without its receipt. No version, no receipt. dbContext.UserAccounts.Add(userAccount); - dbContext.ConsentReceipts.Add(new ConsentReceipt + if (noticeVersion is { } agreed) { - UserAccount = userAccount, - NoticeVersion = noticeVersion, - AcceptedAtUtc = now - }); + dbContext.ConsentReceipts.Add(new ConsentReceipt + { + UserAccount = userAccount, + NoticeVersion = agreed, + AcceptedAtUtc = now + }); + } try { await dbContext.SaveChangesAsync(cancellationToken); diff --git a/src/Bifrost.Web/Features/Registration/ConsentEndpoints.cs b/src/Bifrost.Web/Features/Registration/ConsentEndpoints.cs new file mode 100644 index 0000000..da300e3 --- /dev/null +++ b/src/Bifrost.Web/Features/Registration/ConsentEndpoints.cs @@ -0,0 +1,180 @@ +using Bifrost.Web.Configuration; +using Bifrost.Web.Data; +using Bifrost.Web.Domain; +using Bifrost.Web.Features.Membership; +using Bifrost.Web.Features.Shared; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; + +namespace Bifrost.Web.Features.Registration; + +/// +/// The consent page and its two form posts, for any signed-in account. The receipt rows are the only state: a receipt is +/// live while is null, and an account's messages count only while a live +/// receipt for the version in force exists. Both posts are refused by before +/// anything is read or written, since a signed-in session is a cookie and these carry no antiforgery token. +/// +public static class ConsentEndpoints +{ + public const string Path = "/auth/bifrost/consent"; + + public static void MapConsent(this IEndpointRouteBuilder app) + { + app.MapGet(Path, async (ICurrentBifrostActorAccessor actors, BifrostDbContext db, CancellationToken ct) => + { + var actor = await actors.GetAsync(ct); + if (!actor.IsAuthenticated || actor.UserAccount is null) + { + return Results.Redirect($"/auth/sign-in?returnUrl={Uri.EscapeDataString(LocalReturnPath.Parse(Path).Value)}"); + } + + return await PageAsync(db, actor.UserAccount.Id, null, StatusCodes.Status200OK, ct); + }).AllowAnonymous(); + + app.MapPost(Path + "/accept", async ( + HttpContext http, + ICurrentBifrostActorAccessor actors, + BifrostDbContext db, + TimeProvider clock, + IOptions host, + CancellationToken ct) => + { + if (!RequestOriginGuard.Allows(http.Request, host.Value)) + { + return Refused(); + } + + var actor = await actors.GetAsync(ct); + if (!actor.IsAuthenticated || actor.UserAccount is null) + { + return Results.Unauthorized(); + } + + var form = await ReadFormAsync(http.Request, ct); + if (form is null || form["version"].ToString() != TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture)) + { + return await PageAsync(db, actor.UserAccount.Id, $"Send the version in force, {TrainingNotice.Version}, to agree.", StatusCodes.Status400BadRequest, ct); + } + + var accountId = actor.UserAccount.Id; + if (!await HasLiveReceiptAsync(db, accountId, ct)) + { + db.ConsentReceipts.Add(new ConsentReceipt + { + UserAccountId = accountId, + NoticeVersion = TrainingNotice.Version, + AcceptedAtUtc = clock.GetUtcNow() + }); + try + { + await db.SaveChangesAsync(ct); + } + catch (DbUpdateException) + { + // A concurrent accept won the filtered unique index; only that race is the same outcome, anything else is a fault. + db.ChangeTracker.Clear(); + if (!await HasLiveReceiptAsync(db, accountId, ct)) + { + throw; + } + } + } + + return Back(); + }).AllowAnonymous(); + + app.MapPost(Path + "/withdraw", async ( + HttpContext http, + ICurrentBifrostActorAccessor actors, + BifrostDbContext db, + TimeProvider clock, + IOptions host, + CancellationToken ct) => + { + if (!RequestOriginGuard.Allows(http.Request, host.Value)) + { + return Refused(); + } + + var actor = await actors.GetAsync(ct); + if (!actor.IsAuthenticated || actor.UserAccount is null) + { + return Results.Unauthorized(); + } + + var live = await db.ConsentReceipts + .Where(x => x.UserAccountId == actor.UserAccount.Id && x.WithdrawnAtUtc == null) + .ToListAsync(ct); + if (live.Count > 0) + { + var now = clock.GetUtcNow(); + foreach (var receipt in live) + { + receipt.WithdrawnAtUtc = now; + } + + await db.SaveChangesAsync(ct); + } + + return Back(); + }).AllowAnonymous(); + } + + private static IResult Refused() => Results.Text("Cross-site consent changes are refused.", statusCode: StatusCodes.Status403Forbidden); + + private static IResult Back() => new SeeOther(Path); + + private static Task HasLiveReceiptAsync(BifrostDbContext db, Guid accountId, CancellationToken ct) => + db.ConsentReceipts.AnyAsync(x => x.UserAccountId == accountId && x.NoticeVersion == TrainingNotice.Version && x.WithdrawnAtUtc == null, ct); + + private static async Task ReadFormAsync(HttpRequest request, CancellationToken ct) + { + const int MaxFormBytes = 1024; + if (!request.HasFormContentType || request.ContentLength > MaxFormBytes) + { + return null; + } + + if (request.HttpContext.Features.Get() is { IsReadOnly: false } limit) + { + limit.MaxRequestBodySize = MaxFormBytes; + } + + try + { + return await request.ReadFormAsync(ct); + } + catch (Exception error) when (error is InvalidDataException or BadHttpRequestException) + { + return null; + } + } + + private sealed class SeeOther(string location) : IResult + { + public Task ExecuteAsync(HttpContext httpContext) + { + httpContext.Response.StatusCode = StatusCodes.Status303SeeOther; + httpContext.Response.Headers.Location = location; + httpContext.Response.Headers.CacheControl = "no-store"; + return Task.CompletedTask; + } + } + + private static async Task PageAsync(BifrostDbContext db, Guid accountId, string? error, int status, CancellationToken ct) + { + var receipts = await db.ConsentReceipts.AsNoTracking().Where(x => x.UserAccountId == accountId).ToListAsync(ct); + return new HtmlPage(ConsentPage.Render(ConsentPage.StateOf(receipts), error), status); + } + + private sealed class HtmlPage(string html, int status) : IResult + { + public async Task ExecuteAsync(HttpContext httpContext) + { + httpContext.Response.StatusCode = status; + httpContext.Response.ContentType = "text/html; charset=utf-8"; + httpContext.Response.Headers.CacheControl = "no-store"; + await httpContext.Response.WriteAsync(html); + } + } +} diff --git a/src/Bifrost.Web/Features/Registration/ConsentPage.cs b/src/Bifrost.Web/Features/Registration/ConsentPage.cs new file mode 100644 index 0000000..306b014 --- /dev/null +++ b/src/Bifrost.Web/Features/Registration/ConsentPage.cs @@ -0,0 +1,99 @@ +using System.Net; +using Bifrost.Web.Domain; + +namespace Bifrost.Web.Features.Registration; + +/// Where an account stands against the notice in force. Exactly one holds. +public abstract record ConsentState +{ + public sealed record None : ConsentState; + + public sealed record Current(DateTimeOffset AgreedAtUtc) : ConsentState; + + public sealed record Older(int Version, DateTimeOffset AgreedAtUtc) : ConsentState; + + public sealed record Withdrawn(DateTimeOffset WithdrawnAtUtc) : ConsentState; +} + +/// +/// The server-rendered consent page: the notice in force, the account's state and the one button that applies. No script, +/// no external asset, no cookie of its own. +/// +public static class ConsentPage +{ + /// A live receipt for the version in force wins, then a live older one, then the latest withdrawal, else none. + public static ConsentState StateOf(IReadOnlyCollection receipts) + { + var live = receipts.Where(x => x.WithdrawnAtUtc is null).ToList(); + if (live.FirstOrDefault(x => x.NoticeVersion == TrainingNotice.Version) is { } current) + { + return new ConsentState.Current(current.AcceptedAtUtc); + } + + if (live.OrderByDescending(x => x.NoticeVersion).FirstOrDefault() is { } older) + { + return new ConsentState.Older(older.NoticeVersion, older.AcceptedAtUtc); + } + + return receipts.Count > 0 + ? new ConsentState.Withdrawn(receipts.Max(x => x.WithdrawnAtUtc!.Value)) + : new ConsentState.None(); + } + + private static string Iso(DateTimeOffset time) => time.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", System.Globalization.CultureInfo.InvariantCulture); + + public static string Render(ConsentState state, string? error) + { + static string E(string? text) => WebUtility.HtmlEncode(text ?? ""); + var version = TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture); + var (message, withdraw) = state switch + { + ConsentState.Current current => ($"You agreed to version {version} on {Iso(current.AgreedAtUtc)}. Your messages may be used as the notice says.", true), + ConsentState.Older older => ($"You agreed to version {older.Version} on {Iso(older.AgreedAtUtc)}; version {version} is in force and your messages are not used until you agree to it.", false), + ConsentState.Withdrawn withdrawn => ($"You withdrew on {Iso(withdrawn.WithdrawnAtUtc)}. Your messages are not used.", false), + _ => ("You have not agreed. Your messages are not used.", false) + }; + var summary = error is null ? "" : $""""""; + var button = withdraw + ? """
""" + : $"""
"""; + + return $$""" + + + + + + Training consent - Bifrost + + + +
+ Your account +

Training consent

+ {{summary}} +

{{E(message)}}

+ {{button}} +
+ Training notice, version {{version}} + {{TrainingNotice.Html("notice")}} +
+
+ + + """; + } +} diff --git a/src/Bifrost.Web/Features/Registration/NativeRegistration.cs b/src/Bifrost.Web/Features/Registration/NativeRegistration.cs index a4e61b5..042b615 100644 --- a/src/Bifrost.Web/Features/Registration/NativeRegistration.cs +++ b/src/Bifrost.Web/Features/Registration/NativeRegistration.cs @@ -35,8 +35,8 @@ public sealed record RegistrationOutcome( /// /// The one registration gate, run by the JSON endpoint and the form alike after each has spent the general address budget. -/// Order: consent, one proof only, the identity rules (which spend nothing), the challenge (proof of work, or the -/// time-lock plus its tighter budget), then the account and receipt in one save, then the cookie. A refusal at any step +/// Order: consent version (when sent), one proof only, the identity rules (which spend nothing), the challenge (proof of work, or the +/// time-lock plus its tighter budget), then the account (and its receipt when consent was sent) in one save, then the cookie. A refusal at any step /// creates nothing, and a refusal before the challenge step spends neither the challenge nor a fallback permit. /// public sealed class NativeRegistration( @@ -46,12 +46,12 @@ public sealed class NativeRegistration( { public async Task RunAsync(HttpContext http, RegistrationAttempt attempt, CancellationToken cancellationToken) { - // Consent first, then the proof; a refusal here creates nothing. - if (attempt.AcceptedNoticeVersion != TrainingNotice.Version) + // Consent is optional: none sends no receipt. A version that is sent must be the one in force; a refusal here creates nothing. + if (attempt.AcceptedNoticeVersion is { } sent && sent != TrainingNotice.Version) { return RegistrationOutcome.Reject( StatusCodes.Status400BadRequest, - $"Registration requires accepting the training notice, current version {TrainingNotice.Version}.", + $"The training notice in force is version {TrainingNotice.Version}; send that version to agree, or send none to register without agreeing.", RegistrationField.Consent); } @@ -111,7 +111,7 @@ public sealed class NativeRegistration( try { - var account = await identities.RegisterNativeAsync(attempt.Identity ?? "", attempt.DisplayName, TrainingNotice.Version, cancellationToken); + var account = await identities.RegisterNativeAsync(attempt.Identity ?? "", attempt.DisplayName, attempt.AcceptedNoticeVersion, cancellationToken); await http.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identities.BuildPrincipal(account)); return new(account, null, StatusCodes.Status200OK, null, RegistrationField.None, false); } diff --git a/src/Bifrost.Web/Features/Registration/RegistrationPage.cs b/src/Bifrost.Web/Features/Registration/RegistrationPage.cs index 4483f89..5fcb252 100644 --- a/src/Bifrost.Web/Features/Registration/RegistrationPage.cs +++ b/src/Bifrost.Web/Features/Registration/RegistrationPage.cs @@ -99,7 +99,7 @@ public static class RegistrationPage var link = model.ErrorField switch { RegistrationField.Identity => """""", - RegistrationField.Consent => """""", + RegistrationField.Consent => """""", _ => "" }; summary.Append($""""""); @@ -153,8 +153,9 @@ public static class RegistrationPage
Training notice, version {{notice}} -

{{E(TrainingNotice.Text)}}

- + {{TrainingNotice.Html("notice")}} + +

Optional. You can create an account without agreeing; then none of your messages are used. You can agree later on your consent page.

@@ -165,7 +166,7 @@ public static class RegistrationPage -

Without a script, or if the automatic check is slow, wait {{wait}} seconds after the page opened and press the button to skip it (or Create account when there is no script). Pressed sooner, the page comes back saying how many seconds remain and keeps your names; the consent box comes back unchecked, so tick the box again before you submit. Without the automatic check only a few registrations per hour are accepted from one address.

+

Without a script, or if the automatic check is slow, wait {{wait}} seconds after the page opened and press the button to skip it (or Create account when there is no script). Pressed sooner, the page comes back saying how many seconds remain and keeps your names; the consent box comes back unchecked, so tick it again if you want to agree. Without the automatic check only a few registrations per hour are accepted from one address.

After registering, Bifrost returns you to {{E(model.ReturnPath)}}.

diff --git a/src/Bifrost.Web/Features/Registration/TrainingNotice.cs b/src/Bifrost.Web/Features/Registration/TrainingNotice.cs index 7aaa679..770919f 100644 --- a/src/Bifrost.Web/Features/Registration/TrainingNotice.cs +++ b/src/Bifrost.Web/Features/Registration/TrainingNotice.cs @@ -1,17 +1,35 @@ +using System.Net; +using System.Text; + namespace Bifrost.Web.Features.Registration; /// -/// The training notice a registrant accepts. DRAFT wording: Eureka replaces . Changing the wording -/// in substance means a new (a positive integer, no leading zeros), because a receipt records the -/// version the person accepted. +/// The training notice a person may agree to. Changing the wording in substance means a new (a +/// positive integer, no leading zeros), because a receipt records the version the person agreed to; a receipt for an +/// older version no longer counts and the person is asked again on the consent page. /// public static class TrainingNotice { - public const int Version = 1; + public const int Version = 2; 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."; + "GameCult chat training notice, version 2\n\n" + + "GameCult may use messages you post in GameCult chat to train and evaluate AI models that GameCult builds and runs.\n\n" + + "What counts. The text of your messages, with their time and room, tied to your account name. Not your email address, your sign-in details or anything you did not post. Nothing that came from Discord is used, in any form.\n\n" + + "It is your choice. You can use GameCult chat without agreeing. If you do not agree, none of your messages are used.\n\n" + + "If you agree, we record your account, this notice's version number and the time. Nothing else is stored with it.\n\n" + + "If you withdraw, we leave all your messages out of every training set made after that moment. Withdrawing deletes nothing: your messages stay in chat and on our servers, anything already used to train a model stays used, and a dataset already built is not recalled. We keep the record that you agreed and when you withdrew.\n\n" + + "You can agree or withdraw at any time on your consent page while signed in. If the notice changes, its version changes and we ask again; until you agree to the new version, your messages are not used."; + + /// The text as HTML-encoded paragraphs inside a div with the given id. + public static string Html(string id) + { + var html = new StringBuilder($"
"); + foreach (var paragraph in Text.Split("\n\n")) + { + html.Append("

").Append(WebUtility.HtmlEncode(paragraph)).Append("

"); + } + + return html.Append("
").ToString(); + } } diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index eea7e7b..9facd1a 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -497,10 +497,11 @@ app.MapPost("/auth/bifrost/register/form", async ( string Field(string name) => form[name].FirstOrDefault() ?? ""; var returnPath = LocalReturnPath.Parse(Field("returnUrl")); - // The checkbox is the consent act: without it the posted notice version is not taken as accepted. - int? accepted = Field("consent") == "yes" && int.TryParse(Field("acceptedNoticeVersion"), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var version) - ? version - : null; + // The checkbox is the consent act and is optional: unticked, the posted notice version is ignored and no receipt is made. + // An unparsable version with the box ticked is sent as -1 and refused, never read as "did not agree". + int? accepted = Field("consent") != "yes" + ? null + : int.TryParse(Field("acceptedNoticeVersion"), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var version) ? version : -1; var identity = Field("identity"); var displayName = Field("displayName"); var challenge = Field("challenge"); @@ -554,38 +555,7 @@ app.MapGet("/auth/bifrost/challenge", (HttpContext httpContext, RegistrationChal 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.MapConsent(); app.MapGet("/auth/heimdall/{provider}", async ( string provider, diff --git a/tests/Bifrost.Web.Tests/ConsentTests.cs b/tests/Bifrost.Web.Tests/ConsentTests.cs new file mode 100644 index 0000000..b17a6e8 --- /dev/null +++ b/tests/Bifrost.Web.Tests/ConsentTests.cs @@ -0,0 +1,407 @@ +using System.Net; +using Bifrost.Web.Data; +using Bifrost.Web.Domain; +using Bifrost.Web.Features.Registration; +using Bifrost.Web.Tests.Support; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Bifrost.Web.Tests; + +// The consent page and its posts, through HTTP, against receipt rows in the database. +public sealed class ConsentTests(RegistrationGateFactory factory) : IClassFixture +{ + private const string Origin = "https://localhost"; + private static readonly DateTimeOffset Agreed = new(2026, 11, 1, 12, 30, 5, TimeSpan.Zero); + private static readonly DateTimeOffset Withdrew = new(2026, 11, 2, 8, 0, 9, TimeSpan.Zero); + + private static string NewIdentity() => $"consent-{Guid.NewGuid():N}"; + + private HttpClient Client() => factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + + private void Seed(string identity, params (int Version, DateTimeOffset Accepted, DateTimeOffset? Withdrawn)[] receipts) + { + using var scope = factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var account = new UserAccount { BifrostIdentity = identity, NormalizedBifrostIdentity = identity, DisplayName = identity }; + db.UserAccounts.Add(account); + foreach (var (version, accepted, withdrawn) in receipts) + { + db.ConsentReceipts.Add(new ConsentReceipt { UserAccount = account, NoticeVersion = version, AcceptedAtUtc = accepted, WithdrawnAtUtc = withdrawn }); + } + + db.SaveChanges(); + } + + private List Receipts(string identity) + { + using var scope = factory.Services.CreateScope(); + return scope.ServiceProvider.GetRequiredService().ConsentReceipts.AsNoTracking() + .Where(x => x.UserAccount!.NormalizedBifrostIdentity == identity).OrderBy(x => x.AcceptedAtUtc).ToList(); + } + + private async Task GetPageAsync(HttpClient client, string? identity) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/auth/bifrost/consent"); + Sign(request, identity); + return await client.SendAsync(request); + } + + private static void Sign(HttpRequestMessage request, string? identity) + { + if (identity is null) + { + request.Headers.Add("X-Test-Anonymous", "true"); + } + else + { + request.Headers.Add("X-Test-Bifrost-Identity", identity); + } + } + + private static async Task PostAsync( + HttpClient client, string action, string? identity, Dictionary? fields = null, string? origin = Origin, string? fetchSite = null) + { + using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/consent/" + action) + { + Content = new FormUrlEncodedContent(fields ?? new Dictionary { ["version"] = TrainingNotice.Version.ToString() }) + }; + Sign(request, identity); + if (origin is not null) + { + request.Headers.Add("Origin", origin); + } + + if (fetchSite is not null) + { + request.Headers.Add("Sec-Fetch-Site", fetchSite); + } + + return await client.SendAsync(request); + } + + private async Task PageHtmlAsync(string identity) + { + using var client = Client(); + using var response = await GetPageAsync(client, identity); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return await response.Content.ReadAsStringAsync(); + } + + [Fact] + public async Task Anonymous_is_sent_to_the_sign_in_chooser_with_the_page_as_return_target() + { + using var client = Client(); + using var response = await GetPageAsync(client, null); + + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/auth/sign-in?returnUrl=%2Fauth%2Fbifrost%2Fconsent", response.Headers.Location!.OriginalString); + } + + [Fact] + public async Task The_page_shows_the_notice_in_force_and_is_plain_server_html() + { + var identity = NewIdentity(); + Seed(identity); + using var client = Client(); + using var response = await GetPageAsync(client, identity); + var html = await response.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.False(response.Headers.Contains("Set-Cookie")); + Assert.Contains("no-store", response.Headers.CacheControl!.ToString()); + foreach (var paragraph in TrainingNotice.Text.Split("\n\n")) + { + Assert.Contains(WebUtility.HtmlEncode(paragraph), html); + } + + Assert.Contains("", html); + Assert.Contains("aria-live=\"polite\"", html); + Assert.DoesNotContain(" Assert.NotNull(x.WithdrawnAtUtc)); + } + + [Fact] + public async Task Withdraw_with_no_receipt_changes_nothing() + { + var identity = NewIdentity(); + Seed(identity); + using var client = Client(); + + using var response = await PostAsync(client, "withdraw", identity); + + Assert.Equal(HttpStatusCode.SeeOther, response.StatusCode); + Assert.Empty(Receipts(identity)); + } + + [Fact] + public async Task Accept_after_withdraw_makes_a_new_live_receipt_and_the_old_one_stays_withdrawn() + { + var identity = NewIdentity(); + Seed(identity, (TrainingNotice.Version, Agreed, Withdrew)); + using var client = Client(); + + using var response = await PostAsync(client, "accept", identity); + + Assert.Equal(HttpStatusCode.SeeOther, response.StatusCode); + var receipts = Receipts(identity); + Assert.Equal(2, receipts.Count); + Assert.Single(receipts, x => x.WithdrawnAtUtc == Withdrew && x.AcceptedAtUtc == Agreed); + Assert.Single(receipts, x => x.WithdrawnAtUtc is null && x.NoticeVersion == TrainingNotice.Version); + } + + [Fact] + public async Task Accept_next_to_an_older_live_receipt_adds_one_for_the_version_in_force() + { + var identity = NewIdentity(); + Seed(identity, (1, Agreed, null)); + using var client = Client(); + + using var response = await PostAsync(client, "accept", identity); + + Assert.Equal(HttpStatusCode.SeeOther, response.StatusCode); + Assert.Equal([1, TrainingNotice.Version], Receipts(identity).Select(x => x.NoticeVersion).Order().ToArray()); + } + + [Theory] + [InlineData("1")] + [InlineData("3")] + [InlineData("abc")] + [InlineData("")] + public async Task Accept_with_the_wrong_version_is_refused_and_creates_nothing(string version) + { + var identity = NewIdentity(); + Seed(identity); + using var client = Client(); + + using var response = await PostAsync(client, "accept", identity, new Dictionary { ["version"] = version }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Contains("role=\"alert\"", await response.Content.ReadAsStringAsync()); + Assert.Empty(Receipts(identity)); + } + + [Fact] + public async Task Accept_with_no_version_field_is_refused_and_creates_nothing() + { + var identity = NewIdentity(); + Seed(identity); + using var client = Client(); + + using var response = await PostAsync(client, "accept", identity, new Dictionary { ["other"] = "x" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(Receipts(identity)); + } + + [Theory] + [InlineData("https://evil.example", null)] + [InlineData(null, "cross-site")] + [InlineData(null, "same-site")] + [InlineData(null, null)] + public async Task Accept_from_another_origin_or_with_no_fetch_metadata_is_forbidden_and_changes_nothing(string? origin, string? fetchSite) + { + var identity = NewIdentity(); + Seed(identity); + using var client = Client(); + + using var response = await PostAsync(client, "accept", identity, origin: origin, fetchSite: fetchSite); + + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Empty(Receipts(identity)); + } + + [Theory] + [InlineData("https://evil.example", null)] + [InlineData(null, "cross-site")] + [InlineData(null, "same-site")] + [InlineData(null, null)] + public async Task Withdraw_from_another_origin_or_with_no_fetch_metadata_is_forbidden_and_changes_nothing(string? origin, string? fetchSite) + { + var identity = NewIdentity(); + Seed(identity, (TrainingNotice.Version, Agreed, null)); + using var client = Client(); + + using var response = await PostAsync(client, "withdraw", identity, origin: origin, fetchSite: fetchSite); + + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Null(Assert.Single(Receipts(identity)).WithdrawnAtUtc); + } + + [Fact] + public async Task Same_origin_by_fetch_metadata_alone_is_allowed() + { + var identity = NewIdentity(); + Seed(identity); + using var client = Client(); + + using var response = await PostAsync(client, "accept", identity, origin: null, fetchSite: "same-origin"); + + Assert.Equal(HttpStatusCode.SeeOther, response.StatusCode); + Assert.Single(Receipts(identity)); + } + + [Theory] + [InlineData("accept")] + [InlineData("withdraw")] + public async Task Anonymous_posts_are_unauthorized(string action) + { + using var client = Client(); + + using var response = await PostAsync(client, action, null); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task One_account_changing_its_consent_leaves_every_other_account_untouched() + { + var mine = NewIdentity(); + var theirs = NewIdentity(); + Seed(mine, (TrainingNotice.Version, Agreed, null)); + Seed(theirs, (TrainingNotice.Version, Agreed, null)); + using var client = Client(); + + (await PostAsync(client, "withdraw", mine)).Dispose(); + (await PostAsync(client, "accept", mine)).Dispose(); + + Assert.Null(Assert.Single(Receipts(theirs)).WithdrawnAtUtc); + Assert.Equal(2, Receipts(mine).Count); + } + + [Fact] + public async Task A_hostile_identity_is_not_echoed_unescaped_on_the_page() + { + // The page shows no account name at all, so a hostile display name cannot reach it. + var identity = NewIdentity(); + using (var scope = factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.UserAccounts.Add(new UserAccount { BifrostIdentity = identity, NormalizedBifrostIdentity = identity, DisplayName = "" }); + db.SaveChanges(); + } + + var html = await PageHtmlAsync(identity); + + Assert.DoesNotContain(" x.WithdrawnAtUtc is null); + } +} diff --git a/tests/Bifrost.Web.Tests/MigrationDiscoveryTests.cs b/tests/Bifrost.Web.Tests/MigrationDiscoveryTests.cs index cd46628..1fc57d2 100644 --- a/tests/Bifrost.Web.Tests/MigrationDiscoveryTests.cs +++ b/tests/Bifrost.Web.Tests/MigrationDiscoveryTests.cs @@ -25,6 +25,7 @@ public sealed class MigrationDiscoveryTests "20261109200000_AddSealedBallotMotions", "20261109210000_AddMindKeys", "20261111090000_AddConsentReceipts", + "20261111100000_ConsentReceiptsOneLivePerVersion", ]; // Database.GetMigrations() reads assembly metadata only; no connection is opened. diff --git a/tests/Bifrost.Web.Tests/RegistrationFormTests.cs b/tests/Bifrost.Web.Tests/RegistrationFormTests.cs index 83e0d13..753df95 100644 --- a/tests/Bifrost.Web.Tests/RegistrationFormTests.cs +++ b/tests/Bifrost.Web.Tests/RegistrationFormTests.cs @@ -149,12 +149,17 @@ public sealed class RegistrationFormTests(RegistrationFormFactory factory) : ICl Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(response.Headers.Contains("Set-Cookie")); - Assert.Contains(WebUtility.HtmlEncode(TrainingNotice.Text), html); + foreach (var paragraph in TrainingNotice.Text.Split("\n\n")) + { + Assert.Contains(WebUtility.HtmlEncode(paragraph), html); + } + Assert.Contains($"version {TrainingNotice.Version}", html); Assert.Contains("", html); - Assert.Matches("]*/>", html); + Assert.Matches("]*/>", html); Assert.DoesNotMatch("]*\\bchecked\\b", html); - Assert.Contains("I have read this notice and consent", html); + Assert.Contains("I agree to this notice (optional)", html); + Assert.DoesNotMatch("]*\\brequired\\b", html); foreach (var id in new[] { "identity", "displayName", "consent" }) { Assert.Matches($"]*for=\"{id}\"", html); @@ -169,7 +174,7 @@ public sealed class RegistrationFormTests(RegistrationFormFactory factory) : ICl Assert.Matches("", html); Assert.DoesNotContain("a few seconds", html); Assert.DoesNotContain("nothing is lost", html); - Assert.Contains("tick the box again", html); + Assert.Contains("tick it again if you want to agree", html); Assert.DoesNotContain("().ConsentReceipts.Where(x => x.UserAccount!.NormalizedBifrostIdentity == identity)); + } + + [Fact] + public async Task The_consent_box_with_a_stale_version_returns_the_page_with_an_error_and_nothing_created() { using var client = Client(); var html = await FormKit.PageAsync(client); var challenge = FormKit.Hidden(html, "challenge"); var identity = NewIdentity(); var before = Counts(); + var fields = FormKit.Fields(html, identity, nonce: FormKit.Solved(html)); + fields["acceptedNoticeVersion"] = "1"; - using var response = await FormKit.PostAsync(client, FormKit.Fields(html, identity, consent: false, nonce: FormKit.Solved(html))); + using var response = await FormKit.PostAsync(client, fields); var again = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Matches("role=\"alert\"", again); - Assert.Contains("requires accepting the training notice", again); Assert.Matches("id=\"consent\"[^>]*aria-invalid=\"true\" aria-describedby=\"errors\"", again); Assert.Contains("", again); Assert.DoesNotMatch("]*\\bchecked\\b", again); Assert.Contains($"value=\"{identity}\"", again); Assert.NotEqual(challenge, FormKit.Hidden(again, "challenge")); - Assert.DoesNotContain(challenge, again); Assert.Equal(before, Counts()); } + [Fact] + public async Task The_consent_box_with_an_unreadable_version_is_refused_not_read_as_no_consent() + { + using var client = Client(); + var html = await FormKit.PageAsync(client); + var identity = NewIdentity(); + var fields = FormKit.Fields(html, identity, nonce: FormKit.Solved(html)); + fields["acceptedNoticeVersion"] = "abc"; + + using var response = await FormKit.PostAsync(client, fields); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.False(Exists(identity)); + } + [Fact] public async Task A_wrong_nonce_fails_the_challenge_and_the_error_never_echoes_the_challenge_or_nonce() { diff --git a/tests/Bifrost.Web.Tests/RegistrationGateTests.cs b/tests/Bifrost.Web.Tests/RegistrationGateTests.cs index 53b2b5b..49d2e78 100644 --- a/tests/Bifrost.Web.Tests/RegistrationGateTests.cs +++ b/tests/Bifrost.Web.Tests/RegistrationGateTests.cs @@ -60,22 +60,32 @@ public sealed class RegistrationGateTests(RegistrationGateFactory factory) : ICl Assert.Equal(before, Counts()); } - [Fact] - public async Task No_consent_is_refused_and_creates_nothing() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task No_consent_registers_the_account_with_no_receipt(bool explicitNull) { using var client = Client(); var (challenge, nonce) = await SolvedAsync(client); + var identity = NewIdentity(); + object body = explicitNull + ? new { identity, challenge, nonce, acceptedNoticeVersion = (int?)null } + : new { identity, challenge, nonce }; - await AssertRefusedCreatesNothingAsync( - client, - new { identity = NewIdentity(), challenge, nonce }, - $"current version {TrainingNotice.Version}"); + using var response = await RegistrationKit.PostAsync(client, body, anonymous: true); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using var scope = factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var account = db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity); + Assert.Empty(db.ConsentReceipts.Where(x => x.UserAccountId == account.Id)); } [Theory] [InlineData(0)] [InlineData(-1)] - [InlineData(2)] + [InlineData(1)] + [InlineData(3)] public async Task A_wrong_notice_version_is_refused_and_creates_nothing(int version) { using var client = Client(); @@ -224,84 +234,12 @@ public sealed class RegistrationGateTests(RegistrationGateFactory factory) : ICl var db = scope.ServiceProvider.GetRequiredService(); var account = db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity); var receipt = db.ConsentReceipts.Single(x => x.UserAccountId == account.Id); - Assert.Equal(1, receipt.NoticeVersion); + Assert.Equal(2, receipt.NoticeVersion); + Assert.Equal(TrainingNotice.Version, receipt.NoticeVersion); Assert.Null(receipt.WithdrawnAtUtc); Assert.InRange((factory.Time.GetUtcNow() - receipt.AcceptedAtUtc).Duration(), TimeSpan.Zero, TimeSpan.FromSeconds(5)); } - [Fact] - public async Task Withdraw_stamps_once_and_touches_only_the_caller() - { - using var client = Client(); - var mine = NewIdentity(); - var theirs = NewIdentity(); - (await RegistrationKit.RegisterAsync(client, mine, anonymous: true)).Dispose(); - (await RegistrationKit.RegisterAsync(client, theirs, anonymous: true)).Dispose(); - - async Task WithdrawAsync() - { - using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/consent/withdraw"); - request.Headers.Add("X-Test-Bifrost-Identity", mine); - using var response = await client.SendAsync(request); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - return await response.Content.ReadFromJsonAsync(); - } - - var first = await WithdrawAsync(); - factory.Time.Advance(TimeSpan.FromHours(1)); - var second = await WithdrawAsync(); - - using var scope = factory.Services.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - var myReceipt = db.ConsentReceipts.Single(x => x.UserAccount!.NormalizedBifrostIdentity == mine); - var theirReceipt = db.ConsentReceipts.Single(x => x.UserAccount!.NormalizedBifrostIdentity == theirs); - Assert.NotNull(myReceipt.WithdrawnAtUtc); - Assert.Equal(myReceipt.WithdrawnAtUtc, first.GetProperty("withdrawnAtUtc").GetDateTimeOffset()); - Assert.Equal(first.GetProperty("withdrawnAtUtc").GetDateTimeOffset(), second.GetProperty("withdrawnAtUtc").GetDateTimeOffset()); - Assert.Null(theirReceipt.WithdrawnAtUtc); - } - - [Fact] - public async Task Anonymous_withdraw_is_refused_and_changes_nothing() - { - using var client = Client(); - var identity = NewIdentity(); - (await RegistrationKit.RegisterAsync(client, identity, anonymous: true)).Dispose(); - - using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/consent/withdraw"); - request.Headers.Add("X-Test-Anonymous", "true"); - using var response = await client.SendAsync(request); - - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - using var scope = factory.Services.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - Assert.DoesNotContain(db.ConsentReceipts, x => x.WithdrawnAtUtc != null && x.UserAccount!.NormalizedBifrostIdentity == identity); - } - - [Fact] - public async Task Withdraw_for_an_account_with_no_receipt_is_404() - { - using var client = Client(); - var identity = NewIdentity(); - using (var scope = factory.Services.CreateScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - db.UserAccounts.Add(new Bifrost.Web.Domain.UserAccount - { - BifrostIdentity = identity, - NormalizedBifrostIdentity = identity, - DisplayName = identity - }); - await db.SaveChangesAsync(); - } - - using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/consent/withdraw"); - request.Headers.Add("X-Test-Bifrost-Identity", identity); - using var response = await client.SendAsync(request); - - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } - [Fact] public async Task The_notice_endpoint_names_the_version_and_the_discord_exclusion() { @@ -309,7 +247,7 @@ public sealed class RegistrationGateTests(RegistrationGateFactory factory) : ICl var notice = await client.GetFromJsonAsync("/auth/bifrost/notice"); - Assert.Equal(1, notice.GetProperty("version").GetInt32()); + Assert.Equal(2, notice.GetProperty("version").GetInt32()); Assert.Contains("Discord", notice.GetProperty("text").GetString()); }