From 71ba999f9db8a9e68976e196cabaf3965e3da3e3 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 12:22:20 +0000 Subject: [PATCH] Suspension reason moves to an admin-read column on the membership; the receipt holds no reason Co-Authored-By: Claude Sonnet 5.5 --- docs/registration-gates.md | 2 +- ...111110000_AddMembershipSuspensionReason.cs | 25 ++++++ .../BifrostDbContextModelSnapshot.cs | 3 + src/Bifrost.Web/Domain/BifrostModels.cs | 3 + .../Membership/MembershipSuspensionService.cs | 8 +- .../Pages/App/Members/Index.cshtml | 4 + .../Pages/App/Members/Index.cshtml.cs | 2 + .../MembershipSuspensionTests.cs | 25 +++++- .../MigrationDiscoveryTests.cs | 3 +- .../Support/OidcLogoutKit.cs | 20 ++++- .../SuspensionReasonExposureTests.cs | 84 +++++++++++++++++++ 11 files changed, 168 insertions(+), 11 deletions(-) create mode 100644 src/Bifrost.Web/Data/Migrations/20261111110000_AddMembershipSuspensionReason.cs create mode 100644 tests/Bifrost.Web.Tests/SuspensionReasonExposureTests.cs diff --git a/docs/registration-gates.md b/docs/registration-gates.md index fd039be..5564b17 100644 --- a/docs/registration-gates.md +++ b/docs/registration-gates.md @@ -11,7 +11,7 @@ This page scopes the three that did not exist, says where each lives, and record | Rate limits and brake | `OidcGuardMiddleware` (`docs/oidc-issuer.md`) | Merged. Covers `/connect/*` only, not the register endpoint. | | Reserved names | `BifrostIdentityService.IsReserved`, 28 names | Merged, at creation and at authorize. | | Chat tier, no vote | `Authenticated` / `PendingApproval` accounts chat and open no member or governance surface | Merged. | -| Suspension | `MembershipSuspensionService` | Merged. | +| Suspension | `MembershipSuspensionService` | Merged. The reason is `Membership.SuspensionReason`, written with the status change and its receipt, cleared on unsuspend, projected only to admins on the members page; the receipt (`AuditEvent.Detail`) holds no reason text. Receipts written before the column existed still hold their reasons as history; the member dashboard keeps filtering suspension receipts out. An unsuspend still requires a reason, but nothing stores it. | | CAPTCHA | `Features/Registration/RegistrationChallengeService` | Built here. | | Consent receipt | `ConsentReceipt`, `TrainingNotice` | Built here. | | Email verification | nowhere | Scoped below, not built. | diff --git a/src/Bifrost.Web/Data/Migrations/20261111110000_AddMembershipSuspensionReason.cs b/src/Bifrost.Web/Data/Migrations/20261111110000_AddMembershipSuspensionReason.cs new file mode 100644 index 0000000..4dc7719 --- /dev/null +++ b/src/Bifrost.Web/Data/Migrations/20261111110000_AddMembershipSuspensionReason.cs @@ -0,0 +1,25 @@ +using Bifrost.Web.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Bifrost.Web.Data.Migrations +{ + // Hand-written like ConsentReceiptsOneLivePerVersion: no dotnet-ef on the authoring host; the snapshot was edited to match. + // Reasons already written to AuditEvent.Detail stay there as history; new ones live only in this admin-read column. + [DbContext(typeof(BifrostDbContext))] + [Migration("20261111110000_AddMembershipSuspensionReason")] + public partial class AddMembershipSuspensionReason : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn(name: "SuspensionReason", table: "Memberships", type: "text", nullable: true); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn(name: "SuspensionReason", table: "Memberships"); + } + } +} diff --git a/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs b/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs index 851318c..042e2f0 100644 --- a/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs +++ b/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs @@ -821,6 +821,9 @@ namespace Bifrost.Web.Data.Migrations .IsRequired() .HasColumnType("text"); + b.Property("SuspensionReason") + .HasColumnType("text"); + b.Property("UserAccountId") .HasColumnType("uuid"); diff --git a/src/Bifrost.Web/Domain/BifrostModels.cs b/src/Bifrost.Web/Domain/BifrostModels.cs index 2e5d680..00e3f9c 100644 --- a/src/Bifrost.Web/Domain/BifrostModels.cs +++ b/src/Bifrost.Web/Domain/BifrostModels.cs @@ -334,6 +334,9 @@ public sealed class Membership public MembershipStatus Status { get; set; } = MembershipStatus.Authenticated; + /// Why an admin suspended the account; set and cleared only by MembershipSuspensionService and projected only to admins. + public string? SuspensionReason { get; set; } + public bool IsPlatformAdmin { get; set; } public bool CanManageProjects { get; set; } diff --git a/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs b/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs index cb5626c..870ca4f 100644 --- a/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs +++ b/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs @@ -17,7 +17,7 @@ public enum SuspensionOutcome /// /// The one place a membership becomes Suspended or stops being. Only a platform admin may call it, every use leaves an audit -/// receipt naming the admin, the account and the reason, and no sign-in path writes or lifts a suspension (Heimdall and GitHub +/// receipt naming the admin and the account (the reason is kept on the membership row, readable by admins only), and no sign-in path writes or lifts a suspension (Heimdall and GitHub /// sign-in leave a Suspended membership as it is). Unsuspending restores Active for an account that was once approved, /// Authenticated for one that never was; a pending request is not remembered. /// @@ -65,14 +65,16 @@ public sealed class MembershipSuspensionService(BifrostDbContext dbContext, Audi membership.Status = suspend ? MembershipStatus.Suspended : membership.ApprovedAtUtc is null ? MembershipStatus.Authenticated : MembershipStatus.Active; + // The reason is a column on the membership, for admins; the receipt names who and what changed, never why. var clipped = reason.Trim().Length > MaxReasonLength ? reason.Trim()[..MaxReasonLength] : reason.Trim(); - // One save: the status change and its receipt stand or fall together (RecordAsync saves the shared context). + membership.SuspensionReason = suspend ? clipped : null; + // One save: the status change, the reason and the receipt stand or fall together (RecordAsync saves the shared context). await auditTrailService.RecordAsync( actor.UserAccount.Id, nameof(Membership), membership.Id, suspend ? "membership.suspended" : "membership.unsuspended", - $"{(suspend ? "Suspended" : "Unsuspended")} {user.DisplayName} ({before} -> {membership.Status}): {clipped}", + $"{(suspend ? "Suspended" : "Unsuspended")} {user.DisplayName} ({before} -> {membership.Status}).", cancellationToken); return SuspensionOutcome.Done; } diff --git a/src/Bifrost.Web/Pages/App/Members/Index.cshtml b/src/Bifrost.Web/Pages/App/Members/Index.cshtml index 91f04c4..94e791d 100644 --- a/src/Bifrost.Web/Pages/App/Members/Index.cshtml +++ b/src/Bifrost.Web/Pages/App/Members/Index.cshtml @@ -191,6 +191,10 @@ @if (Model.Actor.CanManageMembership) { + @if (user.Status == MembershipStatus.Suspended && !string.IsNullOrEmpty(user.SuspensionReason)) + { +
Suspended: @user.SuspensionReason
+ }
diff --git a/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs b/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs index ba0715c..9a0a57a 100644 --- a/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs +++ b/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs @@ -359,6 +359,7 @@ public sealed class IndexModel( user.MemberProfile?.Skills ?? string.Empty, user.MemberProfile?.Availability ?? string.Empty, user.Membership?.Status ?? MembershipStatus.Authenticated, + Actor.CanManageMembership ? user.Membership?.SuspensionReason ?? string.Empty : string.Empty, user.Membership?.RoleAssignments.Select(x => x.Role).OrderBy(x => x.ToString()).ToArray() ?? [], patronTier?.Label ?? string.Empty, patronTier?.Weight ?? 0m, @@ -446,6 +447,7 @@ public sealed class IndexModel( string Skills, string Availability, MembershipStatus Status, + string SuspensionReason, IReadOnlyList Roles, string PatronTierLabel, decimal PatronTierWeight, diff --git a/tests/Bifrost.Web.Tests/MembershipSuspensionTests.cs b/tests/Bifrost.Web.Tests/MembershipSuspensionTests.cs index 85e12ca..97f0c99 100644 --- a/tests/Bifrost.Web.Tests/MembershipSuspensionTests.cs +++ b/tests/Bifrost.Web.Tests/MembershipSuspensionTests.cs @@ -57,6 +57,12 @@ public sealed class MembershipSuspensionTests : IClassFixture StatusAsync(Guid id) => InScopeAsync(async (_, db) => (await db.Memberships.AsNoTracking().SingleAsync(x => x.UserAccountId == id)).Status); + private Task ReasonAsync(Guid id) => InScopeAsync(async (_, db) => + (await db.Memberships.AsNoTracking().SingleAsync(x => x.UserAccountId == id)).SuspensionReason); + + private Task MembershipIdAsync(Guid id) => InScopeAsync(async (_, db) => + (await db.Memberships.AsNoTracking().SingleAsync(x => x.UserAccountId == id)).Id); + private Task> AuditAsync(string action) => InScopeAsync((_, db) => db.AuditEvents.AsNoTracking().Where(x => x.Action == action).ToListAsync()); @@ -78,9 +84,12 @@ public sealed class MembershipSuspensionTests : IClassFixture x.Detail.Contains("spam in chat")); + var membershipId = (await MembershipIdAsync(seed.MemberId)).ToString(); + var receipt = Assert.Single(await AuditAsync("membership.suspended"), x => x.EntityId == membershipId); Assert.Equal(seed.AdminId, receipt.ActorUserAccountId); Assert.Contains("Active -> Suspended", receipt.Detail); + Assert.DoesNotContain("spam in chat", receipt.Detail); + Assert.Equal("spam in chat", await ReasonAsync(seed.MemberId)); } [Fact] @@ -95,7 +104,7 @@ public sealed class MembershipSuspensionTests : IClassFixture await sp.GetRequiredService().GetAsync(seed.OrdinaryId, CancellationToken.None)); Assert.DoesNotContain(snapshot.RecentActivity, x => x.Detail.Contains("private-reason-canary")); - Assert.Contains(await AuditAsync("membership.suspended"), x => x.Detail.Contains("private-reason-canary")); + Assert.DoesNotContain(await AuditAsync("membership.suspended"), x => x.Detail.Contains("private-reason-canary")); + Assert.Equal("private-reason-canary", await ReasonAsync(seed.MemberId)); } [Fact] @@ -132,9 +142,16 @@ public sealed class MembershipSuspensionTests : IClassFixture + { + (await db.Memberships.SingleAsync(x => x.UserAccountId == seed.MemberId)).SuspensionReason = "old reason"; + await db.SaveChangesAsync(); + return 0; + }); Assert.Equal(SuspensionOutcome.Done, await UnsuspendAsync(seed.AdminId, seed.MemberId, "appeal upheld")); Assert.Equal(restored, await StatusAsync(seed.MemberId)); - Assert.Contains(await AuditAsync("membership.unsuspended"), x => x.Detail.Contains("appeal upheld") && x.ActorUserAccountId == seed.AdminId); + Assert.Contains(await AuditAsync("membership.unsuspended"), x => x.ActorUserAccountId == seed.AdminId && !x.Detail.Contains("appeal upheld")); + Assert.Null(await ReasonAsync(seed.MemberId)); Assert.Equal(SuspensionOutcome.NotApplicable, await UnsuspendAsync(seed.AdminId, seed.MemberId, "again")); } diff --git a/tests/Bifrost.Web.Tests/MigrationDiscoveryTests.cs b/tests/Bifrost.Web.Tests/MigrationDiscoveryTests.cs index 1fc57d2..012b061 100644 --- a/tests/Bifrost.Web.Tests/MigrationDiscoveryTests.cs +++ b/tests/Bifrost.Web.Tests/MigrationDiscoveryTests.cs @@ -26,6 +26,7 @@ public sealed class MigrationDiscoveryTests "20261109210000_AddMindKeys", "20261111090000_AddConsentReceipts", "20261111100000_ConsentReceiptsOneLivePerVersion", + "20261111110000_AddMembershipSuspensionReason", ]; // Database.GetMigrations() reads assembly metadata only; no connection is opened. @@ -55,7 +56,7 @@ public sealed class MigrationDiscoveryTests } [Fact] - public void All_sixteen_migrations_are_listed_in_order() + public void All_migrations_are_listed_in_order() { Assert.Equal(ExpectedMigrations, Discovered()); } diff --git a/tests/Bifrost.Web.Tests/Support/OidcLogoutKit.cs b/tests/Bifrost.Web.Tests/Support/OidcLogoutKit.cs index 582fa04..1ef58c0 100644 --- a/tests/Bifrost.Web.Tests/Support/OidcLogoutKit.cs +++ b/tests/Bifrost.Web.Tests/Support/OidcLogoutKit.cs @@ -359,6 +359,11 @@ public sealed class OidcLogoutFactory : OidcWebApplicationFactory public FakeMasHandler Mas { get; } = new(); + /// The raw token response and access token of the last . + public string LastTokenResponse { get; private set; } = string.Empty; + + public string LastAccessToken { get; private set; } = string.Empty; + public ManualClock Time { get; } = new(); public OidcLogoutReconciler Reconciler => Services.GetServices().OfType().Single(); @@ -399,7 +404,7 @@ public sealed class OidcLogoutFactory : OidcWebApplicationFactory }; /// Registers a member, sets , and completes one authorization-code flow for them. - public async Task<(string Identity, string IdToken)> GrantAsync(MembershipStatus status = MembershipStatus.Active) + public async Task<(string Identity, string IdToken)> GrantAsync(MembershipStatus status = MembershipStatus.Active, string? suspensionReason = null) { using var client = CreateClient(HostClientOptions()); var identity = $"member-{Guid.NewGuid():N}"; @@ -409,6 +414,14 @@ public sealed class OidcLogoutFactory : OidcWebApplicationFactory } await SetMembershipAsync(identity, MembershipStatus.Active); + if (suspensionReason is not null) + { + using var scope = Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var account = db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity); + db.Memberships.Single(x => x.UserAccountId == account.Id).SuspensionReason = suspensionReason; + await db.SaveChangesAsync(); + } var verifier = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(48)); var state = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(24)); @@ -444,7 +457,10 @@ public sealed class OidcLogoutFactory : OidcWebApplicationFactory "Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{OidcTestKit.ClientId}:{Kit.ClientSecret}"))); using var tokens = await bare.SendAsync(exchange); Assert.Equal(HttpStatusCode.OK, tokens.StatusCode); - var idToken = (await tokens.Content.ReadFromJsonAsync()).GetProperty("id_token").GetString()!; + var body = await tokens.Content.ReadFromJsonAsync(); + var idToken = body.GetProperty("id_token").GetString()!; + LastTokenResponse = body.GetRawText(); + LastAccessToken = body.GetProperty("access_token").GetString()!; if (status != MembershipStatus.Active) { diff --git a/tests/Bifrost.Web.Tests/SuspensionReasonExposureTests.cs b/tests/Bifrost.Web.Tests/SuspensionReasonExposureTests.cs new file mode 100644 index 0000000..f4f5d30 --- /dev/null +++ b/tests/Bifrost.Web.Tests/SuspensionReasonExposureTests.cs @@ -0,0 +1,84 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; +using Bifrost.Web.Data; +using Bifrost.Web.Domain; +using Bifrost.Web.Tests.Support; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Bifrost.Web.Tests; + +/// The suspension reason is for admins: no member-facing page or the OIDC token and userinfo output carries it. +public sealed class SuspensionReasonExposureTests +{ + private const string Canary = "REASON-CANARY-9d2f-do-not-leak"; + + private static async Task SeedAsync(IServiceProvider services, string identity, MembershipStatus status, string? reason) + { + using var scope = services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.UserAccounts.Add(new UserAccount + { + DisplayName = identity, BifrostIdentity = identity, NormalizedBifrostIdentity = identity, + Membership = new Bifrost.Web.Domain.Membership { Status = status, ApprovedAtUtc = DateTimeOffset.UtcNow, SuspensionReason = reason } + }); + await db.SaveChangesAsync(); + } + + private static async Task GetAsync(HttpClient client, string path, string? identity) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + request.Headers.Add("X-Test-Bifrost-Identity", identity); + using var response = await client.SendAsync(request); + Assert.True(response.StatusCode == HttpStatusCode.OK, path); + return await response.Content.ReadAsStringAsync(); + } + + [Fact] + public async Task Member_facing_pages_never_carry_the_reason_and_the_admin_members_page_does() + { + using var factory = new TestWebApplicationFactory(); + using var client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, BaseAddress = new Uri("https://localhost") }); + await SeedAsync(factory.Services, "suspendedone", MembershipStatus.Suspended, Canary); + await SeedAsync(factory.Services, "ordinaryone", MembershipStatus.Active, null); + + foreach (var path in new[] { "/App", "/App/Members", "/Membership/Status" }) + { + Assert.DoesNotContain(Canary, await GetAsync(client, path, "ordinaryone")); + } + + Assert.DoesNotContain(Canary, await GetAsync(client, "/Membership/Status", "suspendedone")); + + using var admin = factory.CreateClient(new WebApplicationFactoryClientOptions { BaseAddress = new Uri("https://localhost") }); + Assert.Contains(Canary, await admin.GetStringAsync("/App/Members")); // the default test sign-in is a bootstrap admin + } + + [Fact] + public async Task The_OIDC_token_response_and_id_token_never_carry_the_reason() + { + using var factory = new OidcLogoutFactory(); + var (_, idToken) = await factory.GrantAsync(suspensionReason: Canary); + + Assert.DoesNotContain(Canary, factory.LastTokenResponse); + var payload = new JsonWebToken(idToken).EncodedPayload; + Assert.DoesNotContain(Canary, Encoding.UTF8.GetString(Base64UrlEncoder.DecodeBytes(payload))); + } + + // Userinfo is broken in some environments before this change (OidcIssuerTests' userinfo cases fail identically there). + [Fact] + public async Task OIDC_userinfo_never_carries_the_reason() + { + using var factory = new OidcLogoutFactory(); + _ = await factory.GrantAsync(suspensionReason: Canary); + + using var client = factory.CreateClient(factory.HostClientOptions()); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", factory.LastAccessToken); + using var userinfo = await client.GetAsync("/connect/userinfo"); + Assert.Equal(HttpStatusCode.OK, userinfo.StatusCode); + Assert.DoesNotContain(Canary, await userinfo.Content.ReadAsStringAsync()); + } +}