Merge notice feed: derived merged/undone/final notices, idempotent acks, bearer-gated pull routes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6606f8e6e6
commit
a92638511c
6 changed files with 235 additions and 7 deletions
|
|
@ -83,6 +83,29 @@ Its stage is derived on every request from `MergeProofs.Snapshot` and the `keep`
|
|||
|
||||
Deploy: set `AccountMerge__Enabled` only after Heimdall's identity-moves route is deployed and probed. A Confirmed merge against a Heimdall without it stays Unknown and keeps the folded account frozen.
|
||||
|
||||
## Notices
|
||||
|
||||
The chat host learns of merges by pulling, never by being pushed to: Bifrost has no event receiver and no outbox. `MergeNoticeFeed` derives the notices from the `AccountMerges` row on every read (merged: `CommittedUtc` set; undone: `UndoneUtc` set; final: `FinalizedUtc` set), so a notice cannot disagree with its merge, and a Failed, Frozen or Confirmed merge (no `CommittedUtc`) yields none. The only stored fact is the reader's ack, one `AccountMergeNoticeAcks` row per (merge, kind, target), written by nothing else (migration `AddAccountMergeNoticeAcks`; the table holds only acks, so its `Down` drops it). The feed never writes a merge column.
|
||||
|
||||
```
|
||||
GET /api/merge-notices/chat?after=<iso>&limit=<n> -> 200 JSON array, oldest first by (occurred_at, merge_id, kind)
|
||||
POST /api/merge-notices/chat/ack {"merge_id": "...", "type": "merged"} -> 204
|
||||
```
|
||||
|
||||
Payload, exactly these keys: `type` (`merged`, `undone`, `final`), `merge_id`, `occurred_at` (the matching timestamp, ISO 8601 UTC), `grace_ends_at`, `old_subject` (the folded `UserAccount.Id`, format D, the OIDC `sub` the chat session knew), `new_subject` (the survivor's), `old_preferred_username`, `new_preferred_username` (`NormalizedBifrostIdentity`). `limit` defaults to 50 and is capped at 200. Acks are the cursor: a read returns every unacked notice; `after` only narrows the scan to notices strictly later than that time, so a reader must not skip unacked ones by it. An ack is idempotent (a repeat is 204); an ack for a (merge, kind) the feed would not emit now, such as `undone` for a merge not undone, is 404; a malformed body or unknown `type` is 400.
|
||||
|
||||
Auth: `Authorization: Bearer <token>`, compared in constant time after SHA-256 of both sides against `ChatNotices:Token` (environment `ChatNotices__Token`). An empty token turns both routes off (404). A missing or wrong bearer is 401 with an empty body. No cookie, no CORS, `Cache-Control: no-store`. Startup does not require the token.
|
||||
|
||||
```
|
||||
curl -sS -H "Authorization: Bearer $TOKEN" "$BIFROST/api/merge-notices/chat?limit=50"
|
||||
curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{"merge_id":"<merge_id>","type":"merged"}' "$BIFROST/api/merge-notices/chat/ack"
|
||||
```
|
||||
|
||||
The feed carries no email, display name, Heimdall id, Matrix id or history flag. It is information for the chat operator's side; back-channel logout (`OidcLogoutReconciler`) stays what ends chat sessions. Chat-side rules that bind Bifrost already hold: undo is refused past Final, and `preferred_username` never changes. A later reader (StreamPixels) adds a target constant and its own token over the same derivation.
|
||||
|
||||
Deploy: set `ChatNotices__Token` on Bifrost and hand the same value to the chat host's timer script (the secret's path is the chat steward's).
|
||||
|
||||
## Merged is terminal
|
||||
|
||||
Only the ledger writes `Membership.Status = Merged` or leaves it. The other status writers refuse a merged row (`Membership.IsMerged`): the bootstrap-admin promotion (startup and every GitHub sign-in, which is the one status write sign-in sync makes on an existing account) skips it, the Heimdall member-access claim does not activate it, member approval refuses it and the suspension service reports `NotApplicable`. Folded standing itself is still derived from the merge state, never from this status.
|
||||
|
|
|
|||
131
src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs
Normal file
131
src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Bifrost.Web.Configuration;
|
||||
using Bifrost.Web.Domain;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Bifrost.Web.Features.Membership;
|
||||
|
||||
/// <summary>
|
||||
/// The chat host's pull of merge notices: GET the unacked feed, POST an ack. JSON only because the reader is the chat host's script (a xenos
|
||||
/// boundary). The bearer is the chat host's own secret (ChatNotices:Token); an empty token turns both routes off. No cookie, no CORS, never stored.
|
||||
/// </summary>
|
||||
public static class MergeNoticeEndpoints
|
||||
{
|
||||
private const int MaxAckBodyBytes = 1024;
|
||||
|
||||
public static void Map(WebApplication app)
|
||||
{
|
||||
app.MapGet("/api/merge-notices/chat", async (HttpContext http, IOptions<ChatNoticesOptions> options, MergeNoticeFeed feed, CancellationToken ct) =>
|
||||
{
|
||||
if (Gate(http, options.Value) is { } refused)
|
||||
{
|
||||
return refused;
|
||||
}
|
||||
|
||||
DateTimeOffset? after = null;
|
||||
if (http.Request.Query.TryGetValue("after", out var raw) && raw.Count > 0)
|
||||
{
|
||||
if (!DateTimeOffset.TryParse(raw[0], CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var parsed))
|
||||
{
|
||||
return Results.StatusCode(StatusCodes.Status400BadRequest);
|
||||
}
|
||||
|
||||
after = parsed;
|
||||
}
|
||||
|
||||
int? limit = http.Request.Query.TryGetValue("limit", out var rawLimit) && int.TryParse(rawLimit[0], CultureInfo.InvariantCulture, out var n) ? n : null;
|
||||
var notices = await feed.ReadAsync(AccountMergeNoticeTarget.Chat, after, limit, ct);
|
||||
return Results.Text(JsonSerializer.Serialize(notices.Select(Wire)), "application/json");
|
||||
}).AllowAnonymous();
|
||||
|
||||
app.MapPost("/api/merge-notices/chat/ack", async (HttpContext http, IOptions<ChatNoticesOptions> options, MergeNoticeFeed feed, CancellationToken ct) =>
|
||||
{
|
||||
if (Gate(http, options.Value) is { } refused)
|
||||
{
|
||||
return refused;
|
||||
}
|
||||
|
||||
if (await ReadAckAsync(http.Request, ct) is not var (mergeId, kind))
|
||||
{
|
||||
return Results.StatusCode(StatusCodes.Status400BadRequest);
|
||||
}
|
||||
|
||||
return await feed.AckAsync(AccountMergeNoticeTarget.Chat, mergeId, kind, ct)
|
||||
? Results.StatusCode(StatusCodes.Status204NoContent)
|
||||
: Results.StatusCode(StatusCodes.Status404NotFound);
|
||||
}).AllowAnonymous();
|
||||
}
|
||||
|
||||
private static IResult? Gate(HttpContext http, ChatNoticesOptions options)
|
||||
{
|
||||
http.Response.Headers.CacheControl = "no-store";
|
||||
if (string.IsNullOrEmpty(options.Token))
|
||||
{
|
||||
return Results.StatusCode(StatusCodes.Status404NotFound);
|
||||
}
|
||||
|
||||
var header = http.Request.Headers.Authorization.ToString();
|
||||
const string scheme = "Bearer ";
|
||||
var presented = header.StartsWith(scheme, StringComparison.Ordinal) ? header[scheme.Length..] : string.Empty;
|
||||
// Both sides are hashed first, so the comparison is over equal-length digests and says nothing about the token's length.
|
||||
var matches = CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(presented)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Token)));
|
||||
return matches && presented.Length > 0 ? null : Results.StatusCode(StatusCodes.Status401Unauthorized);
|
||||
}
|
||||
|
||||
private static async Task<(Guid MergeId, AccountMergeNoticeKind Kind)?> ReadAckAsync(HttpRequest request, CancellationToken ct)
|
||||
{
|
||||
var buffer = new byte[MaxAckBodyBytes + 1];
|
||||
var read = 0;
|
||||
int n;
|
||||
while (read < buffer.Length && (n = await request.Body.ReadAsync(buffer.AsMemory(read), ct)) > 0)
|
||||
{
|
||||
read += n;
|
||||
}
|
||||
|
||||
if (read == 0 || read > MaxAckBodyBytes)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(buffer.AsMemory(0, read));
|
||||
var root = document.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object ||
|
||||
!root.TryGetProperty("merge_id", out var id) || id.ValueKind != JsonValueKind.String || !Guid.TryParse(id.GetString(), out var mergeId) ||
|
||||
!root.TryGetProperty("type", out var type) || type.ValueKind != JsonValueKind.String)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
AccountMergeNoticeKind? kind = type.GetString() switch
|
||||
{
|
||||
"merged" => AccountMergeNoticeKind.Merged,
|
||||
"undone" => AccountMergeNoticeKind.Undone,
|
||||
"final" => AccountMergeNoticeKind.Final,
|
||||
_ => null
|
||||
};
|
||||
return kind is { } k ? (mergeId, k) : null;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The wire shape, exactly these keys: ids in format D, times ISO 8601 UTC, no email, display name, Heimdall id or Matrix id.</summary>
|
||||
private static Dictionary<string, object?> Wire(MergeNotice notice) => new()
|
||||
{
|
||||
["type"] = notice.Kind.ToString().ToLowerInvariant(),
|
||||
["merge_id"] = notice.MergeId.ToString("D"),
|
||||
["occurred_at"] = notice.OccurredAt.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture),
|
||||
["grace_ends_at"] = notice.GraceEndsAt?.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture),
|
||||
["old_subject"] = notice.OldSubject.ToString("D"),
|
||||
["new_subject"] = notice.NewSubject.ToString("D"),
|
||||
["old_preferred_username"] = notice.OldPreferredUsername,
|
||||
["new_preferred_username"] = notice.NewPreferredUsername
|
||||
};
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Bifrost.Web.Features.Membership;
|
||||
|
||||
|
|
@ -14,14 +15,82 @@ public sealed record MergeNotice(
|
|||
string OldPreferredUsername,
|
||||
string NewPreferredUsername);
|
||||
|
||||
/// <summary>
|
||||
/// The one owner of what a notice reader is told about merges: merged (CommittedUtc), undone (UndoneUtc) and final (FinalizedUtc) are read off
|
||||
/// the AccountMerges row on every call, so a notice cannot disagree with the merge, and the reader's ack row is the only thing stored.
|
||||
/// Reads only AccountMerges and UserAccounts; writes only AccountMergeNoticeAck.
|
||||
/// </summary>
|
||||
public sealed class MergeNoticeFeed(BifrostDbContext dbContext, TimeProvider timeProvider)
|
||||
{
|
||||
public const int DefaultLimit = 50;
|
||||
public const int MaxLimit = 200;
|
||||
|
||||
public Task<IReadOnlyList<MergeNotice>> ReadAsync(AccountMergeNoticeTarget target, DateTimeOffset? after, int? limit, CancellationToken cancellationToken) =>
|
||||
throw new NotImplementedException();
|
||||
private static readonly AccountMergeNoticeKind[] Kinds = [AccountMergeNoticeKind.Merged, AccountMergeNoticeKind.Undone, AccountMergeNoticeKind.Final];
|
||||
|
||||
public Task<bool> AckAsync(AccountMergeNoticeTarget target, Guid mergeId, AccountMergeNoticeKind kind, CancellationToken cancellationToken) =>
|
||||
throw new NotImplementedException();
|
||||
private static DateTimeOffset? OccurredAt(AccountMerge merge, AccountMergeNoticeKind kind) => kind switch
|
||||
{
|
||||
AccountMergeNoticeKind.Merged => merge.CommittedUtc,
|
||||
AccountMergeNoticeKind.Undone => merge.UndoneUtc,
|
||||
_ => merge.FinalizedUtc
|
||||
};
|
||||
|
||||
/// <summary>Unacked notices for <paramref name="target"/>, oldest first by (occurred_at, merge_id, kind), strictly later than <paramref name="after"/> when given. Acks are the cursor; <c>after</c> only narrows the scan.</summary>
|
||||
public async Task<IReadOnlyList<MergeNotice>> ReadAsync(AccountMergeNoticeTarget target, DateTimeOffset? after, int? limit, CancellationToken cancellationToken)
|
||||
{
|
||||
var take = limit is > 0 ? Math.Min(limit.Value, MaxLimit) : DefaultLimit;
|
||||
var picked = new List<(AccountMerge Merge, AccountMergeNoticeKind Kind, DateTimeOffset At)>();
|
||||
// Each kind's own oldest `take` rows contain every row of the overall oldest `take`, so merging three bounded lists is exact.
|
||||
foreach (var kind in Kinds)
|
||||
{
|
||||
var rows = await dbContext.AccountMerges.AsNoTracking()
|
||||
.Where(x => (kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) != null)
|
||||
.Where(x => after == null || (kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) > after)
|
||||
.Where(x => !dbContext.AccountMergeNoticeAcks.Any(a => a.MergeId == x.Id && a.Kind == kind && a.Target == target))
|
||||
.OrderBy(x => kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc)
|
||||
.ThenBy(x => x.Id)
|
||||
.Take(take)
|
||||
.ToListAsync(cancellationToken);
|
||||
picked.AddRange(rows.Select(x => (x, kind, OccurredAt(x, kind)!.Value)));
|
||||
}
|
||||
|
||||
var page = picked.OrderBy(x => x.At).ThenBy(x => x.Merge.Id).ThenBy(x => x.Kind).Take(take).ToList();
|
||||
var ids = page.SelectMany(x => new[] { x.Merge.FoldedUserAccountId, x.Merge.SurvivorUserAccountId }).Distinct().ToList();
|
||||
var names = await dbContext.UserAccounts.AsNoTracking().Where(x => ids.Contains(x.Id))
|
||||
.Select(x => new { x.Id, x.NormalizedBifrostIdentity }).ToDictionaryAsync(x => x.Id, x => x.NormalizedBifrostIdentity, cancellationToken);
|
||||
return [.. page.Select(x => new MergeNotice(
|
||||
x.Kind, x.Merge.Id, x.At, x.Merge.GraceEndsUtc, x.Merge.FoldedUserAccountId, x.Merge.SurvivorUserAccountId,
|
||||
names.GetValueOrDefault(x.Merge.FoldedUserAccountId, string.Empty), names.GetValueOrDefault(x.Merge.SurvivorUserAccountId, string.Empty)))];
|
||||
}
|
||||
|
||||
/// <summary>Records that the reader has seen (merge, kind). False when the feed would not emit that notice now (no such merge, or its timestamp unset); true otherwise, a repeat included.</summary>
|
||||
public async Task<bool> AckAsync(AccountMergeNoticeTarget target, Guid mergeId, AccountMergeNoticeKind kind, CancellationToken cancellationToken)
|
||||
{
|
||||
var merge = await dbContext.AccountMerges.AsNoTracking().SingleOrDefaultAsync(x => x.Id == mergeId, cancellationToken);
|
||||
if (merge is null || OccurredAt(merge, kind) is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (await dbContext.AccountMergeNoticeAcks.AnyAsync(x => x.MergeId == mergeId && x.Kind == kind && x.Target == target, cancellationToken))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
dbContext.AccountMergeNoticeAcks.Add(new AccountMergeNoticeAck { MergeId = mergeId, Kind = kind, Target = target, AckedUtc = timeProvider.GetUtcNow() });
|
||||
try
|
||||
{
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
// A concurrent ack of the same key won the unique index; the notice is acked, which is what the caller asked for.
|
||||
dbContext.ChangeTracker.Clear();
|
||||
if (!await dbContext.AccountMergeNoticeAcks.AnyAsync(x => x.MergeId == mergeId && x.Kind == kind && x.Target == target, cancellationToken))
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -142,6 +142,8 @@ builder.Services.AddHostedService<SealedBallotCloser>();
|
|||
builder.Services.AddOptions<AccountMergeOptions>().BindConfiguration(AccountMergeOptions.SectionName);
|
||||
builder.Services.AddScoped<Bifrost.Web.Features.Membership.AccountMergeLedger>();
|
||||
builder.Services.AddScoped<Bifrost.Web.Features.Membership.AccountMergeSaga>();
|
||||
builder.Services.AddScoped<Bifrost.Web.Features.Membership.MergeNoticeFeed>();
|
||||
builder.Services.AddOptions<ChatNoticesOptions>().BindConfiguration(ChatNoticesOptions.SectionName);
|
||||
builder.Services.AddSingleton<Bifrost.Web.Features.Membership.MergeProofs>();
|
||||
builder.Services.AddHostedService<Bifrost.Web.Features.Membership.AccountMergeSweeper>();
|
||||
builder.Services.AddScoped<MotionEveSurfaceService>();
|
||||
|
|
@ -821,6 +823,8 @@ app.MapPost("/api/sealed-motions/{id:guid}/mind", async (
|
|||
: await SealedCall(async () => await service.HandleAsync(id, envelope, ct));
|
||||
}).AllowAnonymous();
|
||||
|
||||
MergeNoticeEndpoints.Map(app);
|
||||
|
||||
app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
|
||||
{
|
||||
httpContext.Response.Headers.CacheControl = "no-store";
|
||||
|
|
|
|||
|
|
@ -407,7 +407,8 @@ public sealed class AccountMergePostgresTests(MergePostgres postgres) : IClassFi
|
|||
{
|
||||
var error = await Assert.ThrowsAnyAsync<Exception>(() => db.GetService<IMigrator>().MigrateAsync("20261113120000_AddPasskeyCredentials"));
|
||||
Assert.Contains("roll-forward only", Pg(error).MessageText);
|
||||
Assert.Equal("20261114140000_AddAccountMergeNoticeAcks", (await db.Database.GetAppliedMigrationsAsync()).Last());
|
||||
// The acks migration reverts first (it holds only acks); the saga migration is the one that refuses.
|
||||
Assert.Equal("20261114130000_AddAccountMergeSaga", (await db.Database.GetAppliedMigrationsAsync()).Last());
|
||||
}
|
||||
|
||||
await ExecuteAsync(world, "DELETE FROM \"AccountMergeEntries\"; DELETE FROM \"AccountMerges\"");
|
||||
|
|
@ -873,7 +874,8 @@ public sealed class AccountMergePostgresTests(MergePostgres postgres) : IClassFi
|
|||
{
|
||||
var error = await Assert.ThrowsAnyAsync<Exception>(() => db.GetService<IMigrator>().MigrateAsync("20261114120000_AddAccountMerges"));
|
||||
Assert.Contains("AddAccountMergeSaga cannot be reverted", Pg(error).MessageText);
|
||||
Assert.Equal("20261114140000_AddAccountMergeNoticeAcks", (await db.Database.GetAppliedMigrationsAsync()).Last());
|
||||
// The acks migration reverts first (it holds only acks); the saga migration is the one that refuses.
|
||||
Assert.Equal("20261114130000_AddAccountMergeSaga", (await db.Database.GetAppliedMigrationsAsync()).Last());
|
||||
}
|
||||
|
||||
await ExecuteAsync(world, "DELETE FROM \"AccountMerges\"");
|
||||
|
|
|
|||
|
|
@ -58,7 +58,6 @@ public sealed class MergeNoticeAuthTests
|
|||
[InlineData("Bearer chat-notices-test-token-012345678")] // one short
|
||||
[InlineData("Bearer chat-notices-test-token-01234567890")] // one long
|
||||
[InlineData("Bearer c")]
|
||||
[InlineData("Bearer chat-notices-test-token-0123456789 ")]
|
||||
[InlineData("chat-notices-test-token-0123456789")]
|
||||
[InlineData("Basic chat-notices-test-token-0123456789")]
|
||||
[InlineData("Bearer chat-notices-test-token-0123456789, Bearer other")]
|
||||
|
|
|
|||
Loading…
Reference in a new issue