Suspension reason moves to an admin-read column on the membership; the receipt holds no reason

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-11 12:22:20 +00:00
commit 71ba999f9d
11 changed files with 168 additions and 11 deletions

View file

@ -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. |

View file

@ -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<string>(name: "SuspensionReason", table: "Memberships", type: "text", nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(name: "SuspensionReason", table: "Memberships");
}
}
}

View file

@ -821,6 +821,9 @@ namespace Bifrost.Web.Data.Migrations
.IsRequired()
.HasColumnType("text");
b.Property<string>("SuspensionReason")
.HasColumnType("text");
b.Property<Guid>("UserAccountId")
.HasColumnType("uuid");

View file

@ -334,6 +334,9 @@ public sealed class Membership
public MembershipStatus Status { get; set; } = MembershipStatus.Authenticated;
/// <summary>Why an admin suspended the account; set and cleared only by <c>MembershipSuspensionService</c> and projected only to admins.</summary>
public string? SuspensionReason { get; set; }
public bool IsPlatformAdmin { get; set; }
public bool CanManageProjects { get; set; }

View file

@ -17,7 +17,7 @@ public enum SuspensionOutcome
/// <summary>
/// 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.
/// </summary>
@ -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;
}

View file

@ -191,6 +191,10 @@
@if (Model.Actor.CanManageMembership)
{
@if (user.Status == MembershipStatus.Suspended && !string.IsNullOrEmpty(user.SuspensionReason))
{
<div class="muted" style="margin-top: 0.8rem;">Suspended: @user.SuspensionReason</div>
}
<form method="post" asp-page-handler="@(user.Status == MembershipStatus.Suspended ? "Unsuspend" : "Suspend")" style="margin-top: 0.8rem;">
<input type="hidden" name="userAccountId" value="@user.UserAccountId" />
<input type="text" name="reason" maxlength="500" required placeholder="Reason" />

View file

@ -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<MemberRole> Roles,
string PatronTierLabel,
decimal PatronTierWeight,

View file

@ -57,6 +57,12 @@ public sealed class MembershipSuspensionTests : IClassFixture<TestWebApplication
private Task<MembershipStatus> StatusAsync(Guid id) => InScopeAsync(async (_, db) =>
(await db.Memberships.AsNoTracking().SingleAsync(x => x.UserAccountId == id)).Status);
private Task<string?> ReasonAsync(Guid id) => InScopeAsync(async (_, db) =>
(await db.Memberships.AsNoTracking().SingleAsync(x => x.UserAccountId == id)).SuspensionReason);
private Task<Guid> MembershipIdAsync(Guid id) => InScopeAsync(async (_, db) =>
(await db.Memberships.AsNoTracking().SingleAsync(x => x.UserAccountId == id)).Id);
private Task<List<AuditEvent>> AuditAsync(string action) => InScopeAsync((_, db) =>
db.AuditEvents.AsNoTracking().Where(x => x.Action == action).ToListAsync());
@ -78,9 +84,12 @@ public sealed class MembershipSuspensionTests : IClassFixture<TestWebApplication
Assert.Equal(SuspensionOutcome.Done, await SuspendAsync(seed.AdminId, seed.MemberId, "spam in chat"));
Assert.Equal(MembershipStatus.Suspended, await StatusAsync(seed.MemberId));
var receipt = Assert.Single(await AuditAsync("membership.suspended"), x => 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<TestWebApplication
}
[Fact]
public async Task A_suspension_reason_does_not_reach_the_member_dashboard_snapshot()
public async Task A_suspension_reason_is_on_the_membership_row_not_the_audit_trail_or_the_member_dashboard_snapshot()
{
var seed = await SeedAsync();
await SuspendAsync(seed.AdminId, seed.MemberId, "private-reason-canary");
@ -103,7 +112,8 @@ public sealed class MembershipSuspensionTests : IClassFixture<TestWebApplication
var snapshot = await InScopeAsync(async (sp, _) => await sp.GetRequiredService<DashboardSnapshotService>().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<TestWebApplication
Assert.Equal(SuspensionOutcome.NoReason, await UnsuspendAsync(seed.AdminId, seed.MemberId, null));
Assert.Equal(MembershipStatus.Suspended, await StatusAsync(seed.MemberId));
await InScopeAsync(async (_, db) =>
{
(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"));
}

View file

@ -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());
}

View file

@ -359,6 +359,11 @@ public sealed class OidcLogoutFactory : OidcWebApplicationFactory
public FakeMasHandler Mas { get; } = new();
/// <summary>The raw token response and access token of the last <see cref="GrantAsync"/>.</summary>
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<IHostedService>().OfType<OidcLogoutReconciler>().Single();
@ -399,7 +404,7 @@ public sealed class OidcLogoutFactory : OidcWebApplicationFactory
};
/// <summary>Registers a member, sets <paramref name="status"/>, and completes one authorization-code flow for them.</summary>
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<BifrostDbContext>();
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<JsonElement>()).GetProperty("id_token").GetString()!;
var body = await tokens.Content.ReadFromJsonAsync<JsonElement>();
var idToken = body.GetProperty("id_token").GetString()!;
LastTokenResponse = body.GetRawText();
LastAccessToken = body.GetProperty("access_token").GetString()!;
if (status != MembershipStatus.Active)
{

View file

@ -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;
/// <summary>The suspension reason is for admins: no member-facing page or the OIDC token and userinfo output carries it.</summary>
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<BifrostDbContext>();
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<string> 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());
}
}