Account merge ledger: AccountMerge receipt, reductions, alias standing, undo and final sweep

AccountMergeLedger owns what a merge does to Bifrost records: PlanAsync (dry run, block codes),
CommitAsync (one save, total, idempotent), UndoLocalAsync (journal replay), FinalizeDueAsync
(AccountMergeSweeper) and StandingAsync/ResolveAsync. Votes and concept appraisals are voided by a
stamp that a model query filter hides from every tally. The actor accessor no longer ORs several
credentials under SingleOrDefault (a latent crash); a frozen or folded account resolves to no
account on every route, the OIDC authorize and chat refusal deny it, and patron intake follows the
alias. Migration AddAccountMerges is additive. No UI, no Heimdall call, nothing deployed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-14 02:31:51 +00:00
commit 84ff2c4578
20 changed files with 2077 additions and 27 deletions

49
docs/account-merge.md Normal file
View file

@ -0,0 +1,49 @@
# Account merge ledger
What a merge of two Bifrost accounts does to Bifrost records, who owns it, and how an account stands under one. Design: `/opt/commons/handoff/heimdall-account-merge-design-20261113.md` sections 3, 5 and 7. This is the ledger only: no page, no Heimdall call, and nothing calls `CommitAsync` or `UndoLocalAsync` yet (the saga cut does).
## Owner
`Features/Membership/AccountMergeLedger.cs` is the one owner of merge effects. Outside it nothing writes `VoidedByMergeId`, `MembershipStatus.Merged`, `AccountMergeEntry`, or the states Committed, Final and Undone, and nothing but the ledger calls `IgnoreQueryFilters` on `Vote` or `ConceptAppraisal`. The ledger never reads an email, display name or login string; accounts are matched by id.
## States
`AccountMerge.State` (stored as a string) declares the whole lifecycle once: `Proposed`, `Confirmed`, `HeimdallMoved`, `Committed`, `Final`, `UndoRequested`, `HeimdallReversed`, `Undone`, `Failed`. Later cuts add columns, not states.
An account's standing is derived from that state on every request; there is no `MergedInto` column and `Membership.Status = Merged` is never read to decide it.
| State of the merge the account is folded in | `StandingAsync` |
| --- | --- |
| Confirmed, HeimdallMoved | `Frozen(mergeId)` |
| Committed, Final, UndoRequested, HeimdallReversed | `Folded(mergeId, survivorId)` |
| Proposed, Failed, Undone | none |
`ResolveAsync(id)` follows `Folded` links to the end (at most eight hops; each account is folded once). Heimdall patron intake resolves through it, so an event for a folded account's Heimdall id records on the survivor.
`CurrentBifrostActorAccessor` is the one gate for every cookie-authenticated route: a Frozen or Folded account resolves to an authenticated actor with no account (`CurrentBifrostActor.Merge` set), so no route can act as it. The OIDC authorize endpoint denies it with `MergedDescription`, and `ChatRefusalAsync` refuses its token and userinfo, so the logout reconciler ends its chat sessions. The accessor looks an account up by identity, then Heimdall id, then GitHub id; the first hit wins and several matching rows can no longer throw.
## Plan, commit, undo, finalize
`PlanAsync(survivorId, foldedId)` writes nothing and returns the blocks (codes only), the journal entries a commit would write, and counts of rows left untouched. Blocks: `same_account`, `account_missing`, `mind_account`, `native_account` (either side has no Heimdall id: v1 merges Heimdall-backed accounts only), `merge_in_flight`, `survivor_is_folded`, `already_folded`, `folded_survivor_in_grace`, `sealed_ballot_pending`.
`CommitAsync(mergeId)` needs `HeimdallMoved` (Committed and Final return the receipt; any other state throws). It is total: blocks were checked before the move, so it never refuses on them. It applies everything in one `SaveChanges` together with `State = Committed` and `GraceEndsUtc = CommittedUtc + 7 days`; a failed save leaves the merge `HeimdallMoved` and applies nothing, and a retry applies once.
What it reduces:
- **Suspension wins.** A suspended folded account and a survivor that is not suspended: the survivor becomes Suspended with the reason `merged with a suspended account (merge <id>)`. A survivor without a membership row is not given one.
- **Membership.** The folded membership becomes `Merged` (weight 0 by the not-Active rule). Roles and admin flags of the folded membership are never copied.
- **Votes on open standard motions.** Both voted: the folded vote is voided. Only the folded account voted: the vote moves to the survivor if the survivor is Active after the suspension rule, else it is voided. A move keeps the vote's weight and cast time; a later survivor cast updates the moved row (`CastVoteAsync` is per motion and account), never a second row. Closed motions are untouched.
- **Concept appraisals.** The survivor also appraised the subject: the folded one is voided. Otherwise it moves to `account:<survivor>` if the survivor is Active, else it is voided.
- **Patron events** of the folded account move to the survivor, and both tiers are derived again once from the events each account now holds (never tier A plus tier B). This happens only when events moved, so a tier that no event backs is not wiped by a merge with no patron history.
Voiding stamps `VoidedByMergeId` and `VoidedUtc`; the model's query filter on `Vote` and `ConceptAppraisal` then removes the row from every tally, including future ones. Nothing is deleted.
Left untouched (counted by the plan): consent receipts, passkeys, ledger entries, points, work and revenue rows.
`UndoLocalAsync(mergeId)` needs `HeimdallReversed` (Undone is a no-op). In one save it replays the journal backward: it un-voids votes whose motion is still Open and appraisals, moves a moved vote or appraisal back only if the survivor did not re-cast it since, restores the folded status, restores the survivor's status only while it is still Suspended with this merge's reason, moves patron events back and derives both tiers again. What it keeps it records as `KeptAfterUndo`; nothing is updated or deleted in the journal, only appended to.
`FinalizeDueAsync(now)` moves Committed merges whose grace has ended to `Final`; `AccountMergeSweeper` runs it every five minutes. Undo is never allowed past Final (the saga reads `State` and `GraceEndsUtc`).
## Not covered
`MembershipSynchronizationService` still writes the profile of any GitHub-signed-in row it finds, and re-promotes a bootstrap admin; it is not a merge path and was not changed here. Sealed-ballot rows of a folded account on a motion that is already closed stay as they are.

View file

@ -66,3 +66,5 @@ A link refused because the login already belongs to another account (`409 identi
Several exits leave the held attempt cookie (`__Host-bifrost_heimdall_<slot>`, HttpOnly, so script cannot clear it) in the browser until its ten minutes end: the complete page's redirect when Discord or Patreon refuses a link because the login belongs to another account, every other `heimdall_status=error` redirect, and a return with no code or no attempt. The script redirects without posting anything; clearing the cookie would need a server route reached by GET or a post from the failure path, which the hardened script deliberately does not do.
A start takes a free slot, else overwrites the slot that expires first, live or dead (`ChooseSlot`, two slots). So three member starts within ten minutes can cost a still-live older attempt, which then finds no cookie and is refused; the member starts again.
See [account-merge.md](account-merge.md) for what a merge does to Bifrost records, the states it moves through and how a folded account stands.

View file

@ -81,6 +81,10 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
public DbSet<ConceptAppraisal> ConceptAppraisals => Set<ConceptAppraisal>();
public DbSet<AccountMerge> AccountMerges => Set<AccountMerge>();
public DbSet<AccountMergeEntry> AccountMergeEntries => Set<AccountMergeEntry>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserAccount>(entity =>
@ -301,6 +305,8 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
modelBuilder.Entity<Vote>(entity =>
{
entity.HasIndex(x => new { x.MotionId, x.UserAccountId }).IsUnique();
// A merge voids a vote by stamping it; every tally reads through this filter, and only AccountMergeLedger ignores it.
entity.HasQueryFilter(x => x.VoidedByMergeId == null);
entity.Property(x => x.Choice).HasConversion<string>();
entity.Property(x => x.Weight).HasPrecision(18, 2);
entity.HasOne(x => x.Motion)
@ -607,6 +613,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
entity.Property(x => x.NetworkTag).HasMaxLength(64);
entity.Property(x => x.Stance).HasConversion<string>().HasMaxLength(16);
entity.Property(x => x.VoterClass).HasConversion<string>().HasMaxLength(16);
entity.HasQueryFilter(x => x.VoidedByMergeId == null);
entity.HasIndex(x => new { x.SubjectId, x.VoterKey }).IsUnique();
entity.HasIndex(x => new { x.NetworkTag, x.CastAtUtc });
entity.HasOne(x => x.Subject)
@ -618,5 +625,34 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
.HasForeignKey(x => x.UserAccountId)
.OnDelete(DeleteBehavior.SetNull);
});
modelBuilder.Entity<AccountMerge>(entity =>
{
entity.Property(x => x.State).HasConversion<string>().HasMaxLength(24);
entity.Property(x => x.FailureCode).HasMaxLength(64);
entity.HasIndex(x => new { x.FoldedUserAccountId, x.State });
entity.HasIndex(x => new { x.SurvivorUserAccountId, x.State });
entity.HasIndex(x => new { x.State, x.GraceEndsUtc });
entity.HasOne<UserAccount>()
.WithMany()
.HasForeignKey(x => x.SurvivorUserAccountId)
.OnDelete(DeleteBehavior.Restrict);
entity.HasOne<UserAccount>()
.WithMany()
.HasForeignKey(x => x.FoldedUserAccountId)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<AccountMergeEntry>(entity =>
{
entity.Property(x => x.Kind).HasConversion<string>().HasMaxLength(24);
entity.Property(x => x.Action).HasConversion<string>().HasMaxLength(24);
entity.Property(x => x.PriorText).HasMaxLength(120);
entity.HasIndex(x => new { x.MergeId, x.Seq }).IsUnique();
entity.HasOne(x => x.Merge)
.WithMany(x => x.Entries)
.HasForeignKey(x => x.MergeId)
.OnDelete(DeleteBehavior.Restrict);
});
}
}

View file

@ -0,0 +1,150 @@
using System;
using Bifrost.Web.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bifrost.Web.Data.Migrations
{
// Scaffolded by IMigrationsScaffolder against the previous snapshot (no dotnet-ef on the authoring host), the designer file dropped and
// the snapshot edited by hand to match, like AddPasskeyCredentials. Additive only; Down drops what Up adds.
[DbContext(typeof(BifrostDbContext))]
[Migration("20261114120000_AddAccountMerges")]
public partial class AddAccountMerges : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "VoidedByMergeId",
table: "Votes",
type: "uuid",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "VoidedUtc",
table: "Votes",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<Guid>(
name: "VoidedByMergeId",
table: "ConceptAppraisals",
type: "uuid",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "VoidedUtc",
table: "ConceptAppraisals",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.CreateTable(
name: "AccountMerges",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
State = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
SurvivorUserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
FoldedUserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
CommittedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
GraceEndsUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
FinalizedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
UndoneUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
FailedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
FailureCode = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AccountMerges", x => x.Id);
table.ForeignKey(
name: "FK_AccountMerges_UserAccounts_FoldedUserAccountId",
column: x => x.FoldedUserAccountId,
principalTable: "UserAccounts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AccountMerges_UserAccounts_SurvivorUserAccountId",
column: x => x.SurvivorUserAccountId,
principalTable: "UserAccounts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "AccountMergeEntries",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
MergeId = table.Column<Guid>(type: "uuid", nullable: false),
Seq = table.Column<int>(type: "integer", nullable: false),
Kind = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
RecordId = table.Column<Guid>(type: "uuid", nullable: false),
Action = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
PriorUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
PriorText = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: true),
PriorAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
AtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AccountMergeEntries", x => x.Id);
table.ForeignKey(
name: "FK_AccountMergeEntries_AccountMerges_MergeId",
column: x => x.MergeId,
principalTable: "AccountMerges",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_AccountMergeEntries_MergeId_Seq",
table: "AccountMergeEntries",
columns: new[] { "MergeId", "Seq" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AccountMerges_FoldedUserAccountId_State",
table: "AccountMerges",
columns: new[] { "FoldedUserAccountId", "State" });
migrationBuilder.CreateIndex(
name: "IX_AccountMerges_State_GraceEndsUtc",
table: "AccountMerges",
columns: new[] { "State", "GraceEndsUtc" });
migrationBuilder.CreateIndex(
name: "IX_AccountMerges_SurvivorUserAccountId_State",
table: "AccountMerges",
columns: new[] { "SurvivorUserAccountId", "State" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AccountMergeEntries");
migrationBuilder.DropTable(
name: "AccountMerges");
migrationBuilder.DropColumn(
name: "VoidedByMergeId",
table: "Votes");
migrationBuilder.DropColumn(
name: "VoidedUtc",
table: "Votes");
migrationBuilder.DropColumn(
name: "VoidedByMergeId",
table: "ConceptAppraisals");
migrationBuilder.DropColumn(
name: "VoidedUtc",
table: "ConceptAppraisals");
}
}
}

View file

@ -22,6 +22,103 @@ namespace Bifrost.Web.Data.Migrations
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Bifrost.Web.Domain.AccountMerge", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("CommittedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("FailedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("FailureCode")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset?>("FinalizedUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("FoldedUserAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("GraceEndsUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("State")
.IsRequired()
.HasMaxLength(24)
.HasColumnType("character varying(24)");
b.Property<Guid>("SurvivorUserAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("UndoneUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("FoldedUserAccountId", "State");
b.HasIndex("State", "GraceEndsUtc");
b.HasIndex("SurvivorUserAccountId", "State");
b.ToTable("AccountMerges");
});
modelBuilder.Entity("Bifrost.Web.Domain.AccountMergeEntry", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Action")
.IsRequired()
.HasMaxLength(24)
.HasColumnType("character varying(24)");
b.Property<DateTimeOffset>("AtUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(24)
.HasColumnType("character varying(24)");
b.Property<Guid>("MergeId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("PriorAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("PriorText")
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<Guid?>("PriorUserAccountId")
.HasColumnType("uuid");
b.Property<Guid>("RecordId")
.HasColumnType("uuid");
b.Property<int>("Seq")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("MergeId", "Seq")
.IsUnique();
b.ToTable("AccountMergeEntries");
});
modelBuilder.Entity("Bifrost.Web.Domain.AgentDispatchRun", b =>
{
b.Property<Guid>("Id")
@ -437,6 +534,12 @@ namespace Bifrost.Web.Data.Migrations
b.Property<Guid?>("UserAccountId")
.HasColumnType("uuid");
b.Property<Guid?>("VoidedByMergeId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("VoidedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("VoterClass")
.IsRequired()
.HasMaxLength(16)
@ -1676,6 +1779,12 @@ namespace Bifrost.Web.Data.Migrations
b.Property<Guid>("UserAccountId")
.HasColumnType("uuid");
b.Property<Guid?>("VoidedByMergeId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("VoidedUtc")
.HasColumnType("timestamp with time zone");
b.Property<decimal>("Weight")
.HasPrecision(18, 2)
.HasColumnType("numeric(18,2)");
@ -2063,6 +2172,32 @@ namespace Bifrost.Web.Data.Migrations
b.ToTable("OpenIddictTokens", (string)null);
});
modelBuilder.Entity("Bifrost.Web.Domain.AccountMerge", b =>
{
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
.WithMany()
.HasForeignKey("FoldedUserAccountId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
.WithMany()
.HasForeignKey("SurvivorUserAccountId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Bifrost.Web.Domain.AccountMergeEntry", b =>
{
b.HasOne("Bifrost.Web.Domain.AccountMerge", "Merge")
.WithMany("Entries")
.HasForeignKey("MergeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Merge");
});
modelBuilder.Entity("Bifrost.Web.Domain.AgentDispatchRun", b =>
{
b.HasOne("Bifrost.Web.Domain.UserAccount", "StartedByUserAccount")
@ -2602,6 +2737,11 @@ namespace Bifrost.Web.Data.Migrations
b.Navigation("Authorization");
});
modelBuilder.Entity("Bifrost.Web.Domain.AccountMerge", b =>
{
b.Navigation("Entries");
});
modelBuilder.Entity("Bifrost.Web.Domain.Membership", b =>
{
b.Navigation("RoleAssignments");

View file

@ -0,0 +1,93 @@
namespace Bifrost.Web.Domain;
/// <summary>The whole lifecycle of an account merge, declared once; later cuts add columns, not states. Stored as a string.</summary>
public enum AccountMergeState
{
Proposed,
Confirmed,
HeimdallMoved,
Committed,
Final,
UndoRequested,
HeimdallReversed,
Undone,
Failed
}
public enum AccountMergeEntryKind
{
Vote,
ConceptAppraisal,
Membership,
Standing,
PatronSupportEvent
}
public enum AccountMergeEntryAction
{
Voided,
Moved,
Closed,
Suspended,
Restored,
KeptAfterUndo
}
/// <summary>
/// The merge receipt: two Heimdall-backed accounts, one survivor. Whether an account is folded or frozen is derived from this row's
/// State on every request (AccountMergeLedger.StandingAsync); no column on the account says so.
/// </summary>
public sealed class AccountMerge
{
public Guid Id { get; set; } = Guid.NewGuid();
public AccountMergeState State { get; set; } = AccountMergeState.Proposed;
public Guid SurvivorUserAccountId { get; set; }
public Guid FoldedUserAccountId { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public DateTimeOffset? CommittedUtc { get; set; }
public DateTimeOffset? GraceEndsUtc { get; set; }
public DateTimeOffset? FinalizedUtc { get; set; }
public DateTimeOffset? UndoneUtc { get; set; }
public DateTimeOffset? FailedUtc { get; set; }
public string FailureCode { get; set; } = string.Empty;
public ICollection<AccountMergeEntry> Entries { get; set; } = [];
}
/// <summary>Append-only journal of what a merge did to one record; undo and the later preview read it, tallies and gates never do.</summary>
public sealed class AccountMergeEntry
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid MergeId { get; set; }
public int Seq { get; set; }
public AccountMergeEntryKind Kind { get; set; }
public Guid RecordId { get; set; }
public AccountMergeEntryAction Action { get; set; }
public Guid? PriorUserAccountId { get; set; }
/// <summary>The prior status or prior voter key.</summary>
public string? PriorText { get; set; }
/// <summary>The cast time of a moved vote or appraisal, so undo can tell whether the survivor re-cast it.</summary>
public DateTimeOffset? PriorAtUtc { get; set; }
public DateTimeOffset AtUtc { get; set; }
public AccountMerge Merge { get; set; } = null!;
}

View file

@ -7,7 +7,9 @@ public enum MembershipStatus
Authenticated,
PendingApproval,
Active,
Suspended
Suspended,
/// <summary>Terminal status of a folded membership; written only by the account merge ledger, never read to decide standing.</summary>
Merged
}
public enum MemberRole
@ -776,6 +778,11 @@ public sealed class Vote
public DateTimeOffset CastAtUtc { get; set; }
/// <summary>Set by the account merge ledger when a merge removes this vote from every tally; the model's query filter then hides the row.</summary>
public Guid? VoidedByMergeId { get; set; }
public DateTimeOffset? VoidedUtc { get; set; }
public Motion Motion { get; set; } = null!;
public UserAccount UserAccount { get; set; } = null!;

View file

@ -46,5 +46,10 @@ public sealed class ConceptAppraisal
public DateTimeOffset CastAtUtc { get; set; }
/// <summary>Set by the account merge ledger when a merge removes this appraisal from every tally; the model's query filter then hides the row.</summary>
public Guid? VoidedByMergeId { get; set; }
public DateTimeOffset? VoidedUtc { get; set; }
public ConceptSubject? Subject { get; set; }
}

View file

@ -5,6 +5,7 @@ using System.Text.Json.Serialization;
using Bifrost.Web.Configuration;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Patronage;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
@ -14,6 +15,7 @@ namespace Bifrost.Web.Features.Heimdall;
public sealed class HeimdallPatronSupportIntakeService(
BifrostDbContext dbContext,
PatronageService patronageService,
AccountMergeLedger mergeLedger,
IOptions<HeimdallOptions> heimdallOptions)
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
@ -83,7 +85,7 @@ public sealed class HeimdallPatronSupportIntakeService(
var supportEvent = await patronageService.RecordSupportEventAsync(
actorUserAccountId: null,
userAccountId: user.Id,
userAccountId: await mergeLedger.ResolveAsync(user.Id, cancellationToken), // a folded account's events record on the survivor
request.Kind,
request.Amount,
request.CurrencyCode,

View file

@ -0,0 +1,583 @@
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Patronage;
using Microsoft.EntityFrameworkCore;
namespace Bifrost.Web.Features.Membership;
/// <summary>How an account stands under a merge: the folded account of an unfinished merge is Frozen, of a landed one Folded.</summary>
public abstract record MergeStanding(Guid MergeId)
{
public sealed record Frozen(Guid MergeId) : MergeStanding(MergeId);
public sealed record Folded(Guid MergeId, Guid SurvivorId) : MergeStanding(MergeId);
}
public sealed record MergePlanEntry(
AccountMergeEntryKind Kind,
AccountMergeEntryAction Action,
Guid RecordId,
Guid? PriorUserAccountId = null,
string? PriorText = null,
DateTimeOffset? PriorAtUtc = null);
/// <summary>A dry run: the block codes (never account names), the journal entries a commit would write, and the record counts left untouched.</summary>
public sealed record MergePlan(
IReadOnlyList<string> Blocks,
IReadOnlyList<MergePlanEntry> Entries,
IReadOnlyDictionary<string, int> Left);
/// <summary>
/// The one owner of what an account merge does to Bifrost records and of how an account stands under one: the plan, the Committed
/// save, the undo save, the Final transition, StandingAsync and ResolveAsync. A merge only reduces: nothing is deleted, votes and
/// appraisals are stamped void (the model's query filter then removes them from every tally) or re-pointed, and every change is
/// journalled in AccountMergeEntry. Design: /opt/commons/handoff/heimdall-account-merge-design-20261113.md sections 3, 5, 7.
/// </summary>
public sealed class AccountMergeLedger(
BifrostDbContext dbContext,
PatronageService patronageService,
TimeProvider timeProvider)
{
public static readonly TimeSpan Grace = TimeSpan.FromDays(7);
private const int MaxHops = 8;
private static readonly AccountMergeState[] FrozenStates = [AccountMergeState.Confirmed, AccountMergeState.HeimdallMoved];
private static readonly AccountMergeState[] FoldedStates =
[AccountMergeState.Committed, AccountMergeState.Final, AccountMergeState.UndoRequested, AccountMergeState.HeimdallReversed];
private static readonly AccountMergeState[] InFlightStates =
[AccountMergeState.Confirmed, AccountMergeState.HeimdallMoved, AccountMergeState.UndoRequested, AccountMergeState.HeimdallReversed];
public static string SuspensionReason(Guid mergeId) => $"merged with a suspended account (merge {mergeId})";
public Task<MergeStanding?> StandingAsync(Guid userAccountId, CancellationToken cancellationToken) =>
StandingAsync(dbContext, userAccountId, cancellationToken);
/// <summary>The single reading of standing, shared by the actor accessor and the OIDC refusal, which holds only a context. Derived from the merge state on every call.</summary>
public static async Task<MergeStanding?> StandingAsync(BifrostDbContext db, Guid userAccountId, CancellationToken cancellationToken)
{
var merge = await db.AccountMerges.AsNoTracking()
.Where(x => x.FoldedUserAccountId == userAccountId &&
(FrozenStates.Contains(x.State) || FoldedStates.Contains(x.State)))
.OrderByDescending(x => x.CreatedUtc)
.FirstOrDefaultAsync(cancellationToken);
return merge is null
? null
: FrozenStates.Contains(merge.State)
? new MergeStanding.Frozen(merge.Id)
: new MergeStanding.Folded(merge.Id, merge.SurvivorUserAccountId);
}
/// <summary>Follows Folded links to the account that now carries the person. Each account is folded once, so the hop cap is only a guard.</summary>
public async Task<Guid> ResolveAsync(Guid userAccountId, CancellationToken cancellationToken)
{
var current = userAccountId;
for (var hop = 0; hop < MaxHops; hop++)
{
if (await StandingAsync(current, cancellationToken) is not MergeStanding.Folded folded)
{
return current;
}
current = folded.SurvivorId;
}
return current;
}
/// <summary>Writes nothing. <paramref name="exceptMergeId"/> lets the saga re-plan a merge it already holds without it blocking itself.</summary>
public async Task<MergePlan> PlanAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? exceptMergeId = null)
{
var blocks = await BlocksAsync(survivorId, foldedId, exceptMergeId, cancellationToken);
var entries = new List<MergePlanEntry>();
var left = new Dictionary<string, int>();
if (!blocks.Contains("account_missing"))
{
var reduction = await ReduceAsync(survivorId, foldedId, cancellationToken);
entries.AddRange(reduction.Entries);
left["ConsentReceipts"] = await dbContext.ConsentReceipts.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
left["PasskeyCredentials"] = await dbContext.PasskeyCredentials.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
left["LedgerEntries"] = await dbContext.LedgerEntries.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
}
return new MergePlan(blocks, entries, left);
}
private async Task<IReadOnlyList<string>> BlocksAsync(Guid survivorId, Guid foldedId, Guid? exceptMergeId, CancellationToken cancellationToken)
{
var blocks = new List<string>();
if (survivorId == foldedId)
{
blocks.Add("same_account");
}
var accounts = await dbContext.UserAccounts.AsNoTracking()
.Where(x => x.Id == survivorId || x.Id == foldedId)
.Select(x => new { x.Id, x.HeimdallAccountId })
.ToListAsync(cancellationToken);
if (accounts.Count < (survivorId == foldedId ? 1 : 2))
{
blocks.Add("account_missing");
return blocks;
}
if (await dbContext.MindPersonas.AnyAsync(x => x.UserAccountId == survivorId || x.UserAccountId == foldedId, cancellationToken))
{
blocks.Add("mind_account");
}
if (accounts.Any(x => string.IsNullOrWhiteSpace(x.HeimdallAccountId)))
{
blocks.Add("native_account");
}
if (await dbContext.AccountMerges.AnyAsync(
x => x.Id != exceptMergeId &&
InFlightStates.Contains(x.State) &&
(x.SurvivorUserAccountId == survivorId || x.FoldedUserAccountId == survivorId ||
x.SurvivorUserAccountId == foldedId || x.FoldedUserAccountId == foldedId),
cancellationToken))
{
blocks.Add("merge_in_flight");
}
if (await FoldedLinkAsync(survivorId, exceptMergeId, cancellationToken))
{
blocks.Add("survivor_is_folded");
}
if (await FoldedLinkAsync(foldedId, exceptMergeId, cancellationToken))
{
blocks.Add("already_folded");
}
// Heimdall could no longer reverse a merge this account survived once it is folded into another.
if (await dbContext.AccountMerges.AnyAsync(
x => x.Id != exceptMergeId && x.State == AccountMergeState.Committed && x.SurvivorUserAccountId == foldedId,
cancellationToken))
{
blocks.Add("folded_survivor_in_grace");
}
if (await dbContext.SealedBallots.AnyAsync(
x => x.UserAccountId == foldedId && x.Motion.Status == MotionStatus.Open,
cancellationToken))
{
blocks.Add("sealed_ballot_pending");
}
return blocks;
}
private Task<bool> FoldedLinkAsync(Guid accountId, Guid? exceptMergeId, CancellationToken cancellationToken) =>
dbContext.AccountMerges.AnyAsync(
x => x.Id != exceptMergeId && x.FoldedUserAccountId == accountId && FoldedStates.Contains(x.State),
cancellationToken);
/// <summary>
/// Applies the merge to Bifrost records in one save, together with State=Committed. Total: blocks were checked before the move
/// and a refusal now would strand moved logins, so it recomputes the reductions from current rows and applies them. Committed
/// and Final are no-ops returning the receipt; any other state but HeimdallMoved is an error.
/// </summary>
public async Task<AccountMerge> CommitAsync(Guid mergeId, CancellationToken cancellationToken)
{
var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, cancellationToken);
if (merge.State is AccountMergeState.Committed or AccountMergeState.Final)
{
return merge;
}
if (merge.State != AccountMergeState.HeimdallMoved)
{
throw new InvalidOperationException($"Merge {mergeId} is {merge.State}; only a HeimdallMoved merge can be committed.");
}
try
{
var reduction = await ReduceAsync(merge.SurvivorUserAccountId, merge.FoldedUserAccountId, cancellationToken, mergeId);
var now = timeProvider.GetUtcNow();
var seq = 0;
foreach (var entry in reduction.Entries)
{
dbContext.AccountMergeEntries.Add(Journal(merge.Id, ++seq, entry, now));
}
reduction.Apply(now);
if (reduction.MovedPatronEvents)
{
await RestageTiersAsync(reduction.Survivor, reduction.Folded, now, cancellationToken);
}
merge.State = AccountMergeState.Committed;
merge.CommittedUtc = now;
merge.GraceEndsUtc = now + Grace;
await dbContext.SaveChangesAsync(cancellationToken);
return merge;
}
catch
{
// Nothing was saved; drop what was staged so a retry on this context starts from the stored rows.
dbContext.ChangeTracker.Clear();
throw;
}
}
/// <summary>Replays the journal backward in one save with State=Undone. Total, like commit. Undone is a no-op; any other state but HeimdallReversed is an error.</summary>
public async Task<AccountMerge> UndoLocalAsync(Guid mergeId, CancellationToken cancellationToken)
{
var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, cancellationToken);
if (merge.State == AccountMergeState.Undone)
{
return merge;
}
if (merge.State != AccountMergeState.HeimdallReversed)
{
throw new InvalidOperationException($"Merge {mergeId} is {merge.State}; only a HeimdallReversed merge can be undone locally.");
}
try
{
var now = timeProvider.GetUtcNow();
var journal = await dbContext.AccountMergeEntries.Where(x => x.MergeId == mergeId).OrderByDescending(x => x.Seq).ToListAsync(cancellationToken);
var seq = journal.Count == 0 ? 0 : journal.Max(x => x.Seq);
var survivor = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
.SingleAsync(x => x.Id == merge.SurvivorUserAccountId, cancellationToken);
var folded = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
.SingleAsync(x => x.Id == merge.FoldedUserAccountId, cancellationToken);
var survivorKey = AppraisalKey(survivor.Id);
var restagePatron = false;
void Record(AccountMergeEntry original, bool restored) =>
dbContext.AccountMergeEntries.Add(new AccountMergeEntry
{
MergeId = mergeId,
Seq = ++seq,
Kind = original.Kind,
RecordId = original.RecordId,
Action = restored ? AccountMergeEntryAction.Restored : AccountMergeEntryAction.KeptAfterUndo,
PriorUserAccountId = original.PriorUserAccountId,
AtUtc = now
});
foreach (var entry in journal.Where(x => x.Action is AccountMergeEntryAction.Voided or AccountMergeEntryAction.Moved or AccountMergeEntryAction.Closed or AccountMergeEntryAction.Suspended))
{
switch (entry.Kind, entry.Action)
{
case (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided):
{
var vote = await dbContext.Votes.IgnoreQueryFilters().Include(x => x.Motion).SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
var restore = vote?.VoidedByMergeId == mergeId && vote.Motion.Status == MotionStatus.Open;
if (restore)
{
vote!.VoidedByMergeId = null;
vote.VoidedUtc = null;
}
Record(entry, restore);
break;
}
case (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved):
{
var vote = await dbContext.Votes.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
var restore = vote is not null && vote.UserAccountId == survivor.Id && vote.CastAtUtc == entry.PriorAtUtc;
if (restore)
{
vote!.UserAccountId = entry.PriorUserAccountId!.Value;
}
Record(entry, restore);
break;
}
case (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Voided):
{
var row = await dbContext.ConceptAppraisals.IgnoreQueryFilters().SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
var restore = row?.VoidedByMergeId == mergeId;
if (restore)
{
row!.VoidedByMergeId = null;
row.VoidedUtc = null;
}
Record(entry, restore);
break;
}
case (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved):
{
var row = await dbContext.ConceptAppraisals.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
var restore = row is not null && row.UserAccountId == survivor.Id && row.VoterKey == survivorKey && row.CastAtUtc == entry.PriorAtUtc;
if (restore)
{
row!.UserAccountId = entry.PriorUserAccountId!.Value;
row.VoterKey = entry.PriorText ?? row.VoterKey;
}
Record(entry, restore);
break;
}
case (AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed):
{
var restore = folded.Membership is { Status: MembershipStatus.Merged } && Enum.TryParse<MembershipStatus>(entry.PriorText, out _);
if (restore)
{
folded.Membership!.Status = Enum.Parse<MembershipStatus>(entry.PriorText!);
}
Record(entry, restore);
break;
}
case (AccountMergeEntryKind.Standing, AccountMergeEntryAction.Suspended):
{
// Only while the survivor still carries exactly this merge's suspension; an admin who changed it since owns the standing now.
var restore = survivor.Membership is { Status: MembershipStatus.Suspended } member &&
member.SuspensionReason == SuspensionReason(mergeId) &&
Enum.TryParse<MembershipStatus>(entry.PriorText, out _);
if (restore)
{
survivor.Membership!.Status = Enum.Parse<MembershipStatus>(entry.PriorText!);
survivor.Membership.SuspensionReason = null;
}
Record(entry, restore);
break;
}
case (AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved):
{
var row = await dbContext.PatronSupportEvents.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
var restore = row is not null && row.UserAccountId == survivor.Id;
if (restore)
{
row!.UserAccountId = entry.PriorUserAccountId!.Value;
restagePatron = true;
}
Record(entry, restore);
break;
}
}
}
if (restagePatron)
{
await RestageTiersAsync(survivor, folded, now, cancellationToken);
}
merge.State = AccountMergeState.Undone;
merge.UndoneUtc = now;
await dbContext.SaveChangesAsync(cancellationToken);
return merge;
}
catch
{
dbContext.ChangeTracker.Clear();
throw;
}
}
/// <summary>Committed merges whose grace has ended become Final; returns how many. Undo is never allowed past Final.</summary>
public async Task<int> FinalizeDueAsync(DateTimeOffset now, CancellationToken cancellationToken)
{
var due = await dbContext.AccountMerges
.Where(x => x.State == AccountMergeState.Committed && x.GraceEndsUtc <= now)
.ToListAsync(cancellationToken);
foreach (var merge in due)
{
merge.State = AccountMergeState.Final;
merge.FinalizedUtc = now;
}
await dbContext.SaveChangesAsync(cancellationToken);
return due.Count;
}
private sealed class Reduction(
UserAccount survivor,
UserAccount folded,
List<MergePlanEntry> entries,
List<Action<Guid, DateTimeOffset>> effects,
bool movedPatronEvents)
{
public UserAccount Survivor { get; } = survivor;
public UserAccount Folded { get; } = folded;
public IReadOnlyList<MergePlanEntry> Entries => entries;
public bool MovedPatronEvents { get; } = movedPatronEvents;
public Guid MergeId { get; set; }
public void Apply(DateTimeOffset now)
{
foreach (var effect in effects)
{
effect(MergeId, now);
}
}
}
/// <summary>
/// What a merge does to records, computed from current rows without writing: the journal entries and the effects that apply them.
/// Rules (design 5): suspension wins; the folded membership is closed and its roles never copied; open standard motions and
/// concept appraisals keep one voice per person (the survivor's), a lone folded one moving only to an Active survivor; patron
/// events follow the person.
/// </summary>
private async Task<Reduction> ReduceAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? mergeId = null)
{
var survivor = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
.SingleAsync(x => x.Id == survivorId, cancellationToken);
var folded = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
.SingleAsync(x => x.Id == foldedId, cancellationToken);
var entries = new List<MergePlanEntry>();
var effects = new List<Action<Guid, DateTimeOffset>>();
var foldedSuspended = folded.Membership?.Status == MembershipStatus.Suspended;
var survivorSuspendedNow = survivor.Membership?.Status == MembershipStatus.Suspended;
var survivorStanding = survivor.Membership?.Status;
if (foldedSuspended && !survivorSuspendedNow && survivor.Membership is { } survivorMembership)
{
entries.Add(new MergePlanEntry(AccountMergeEntryKind.Standing, AccountMergeEntryAction.Suspended, survivorMembership.Id, null, survivorMembership.Status.ToString()));
effects.Add((id, _) =>
{
survivorMembership.Status = MembershipStatus.Suspended;
survivorMembership.SuspensionReason = SuspensionReason(id);
});
survivorStanding = MembershipStatus.Suspended;
}
var survivorActive = survivorStanding == MembershipStatus.Active;
if (folded.Membership is { } foldedMembership)
{
entries.Add(new MergePlanEntry(AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed, foldedMembership.Id, null, foldedMembership.Status.ToString()));
effects.Add((_, _) => foldedMembership.Status = MembershipStatus.Merged);
}
var foldedVotes = await dbContext.Votes
.Where(x => x.UserAccountId == foldedId && x.Motion.Status == MotionStatus.Open && x.Motion.Kind == MotionKind.Standard)
.ToListAsync(cancellationToken);
var survivorVotedMotions = (await dbContext.Votes
.Where(x => x.UserAccountId == survivorId && x.Motion.Status == MotionStatus.Open && x.Motion.Kind == MotionKind.Standard)
.Select(x => x.MotionId)
.ToListAsync(cancellationToken)).ToHashSet();
foreach (var vote in foldedVotes)
{
if (survivorVotedMotions.Contains(vote.MotionId) || !survivorActive)
{
entries.Add(new MergePlanEntry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided, vote.Id, vote.UserAccountId));
effects.Add((id, now) =>
{
vote.VoidedByMergeId = id;
vote.VoidedUtc = now;
});
}
else
{
entries.Add(new MergePlanEntry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved, vote.Id, vote.UserAccountId, null, vote.CastAtUtc));
effects.Add((_, _) => vote.UserAccountId = survivorId);
}
}
var survivorKey = AppraisalKey(survivorId);
var foldedAppraisals = await dbContext.ConceptAppraisals.Where(x => x.UserAccountId == foldedId).ToListAsync(cancellationToken);
var survivorSubjects = (await dbContext.ConceptAppraisals
.Where(x => x.UserAccountId == survivorId || x.VoterKey == survivorKey)
.Select(x => x.SubjectId)
.ToListAsync(cancellationToken)).ToHashSet();
foreach (var appraisal in foldedAppraisals)
{
if (survivorSubjects.Contains(appraisal.SubjectId) || !survivorActive)
{
entries.Add(new MergePlanEntry(AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Voided, appraisal.Id, appraisal.UserAccountId));
effects.Add((id, now) =>
{
appraisal.VoidedByMergeId = id;
appraisal.VoidedUtc = now;
});
}
else
{
entries.Add(new MergePlanEntry(AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved, appraisal.Id, appraisal.UserAccountId, appraisal.VoterKey, appraisal.CastAtUtc));
effects.Add((_, _) =>
{
appraisal.UserAccountId = survivorId;
appraisal.VoterKey = survivorKey;
});
}
}
var foldedEvents = folded.PatronSupportEvents.ToList();
foreach (var supportEvent in foldedEvents)
{
entries.Add(new MergePlanEntry(AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved, supportEvent.Id, supportEvent.UserAccountId));
effects.Add((_, _) => supportEvent.UserAccountId = survivorId);
}
var reduction = new Reduction(survivor, folded, entries, effects, foldedEvents.Count > 0);
if (mergeId is { } m)
{
reduction.MergeId = m;
}
return reduction;
}
// Tiers derive once from all the events now on each account, never tier A plus tier B. Ownership is read from the
// tracked rows, so it holds before the save as well as after it.
private async Task RestageTiersAsync(UserAccount survivor, UserAccount folded, DateTimeOffset now, CancellationToken cancellationToken)
{
var events = survivor.PatronSupportEvents.Concat(folded.PatronSupportEvents).DistinctBy(x => x.Id).ToList();
await StageIfMembershipAsync(survivor.Membership, events.Where(x => x.UserAccountId == survivor.Id).ToList(), now, cancellationToken);
await StageIfMembershipAsync(folded.Membership, events.Where(x => x.UserAccountId == folded.Id).ToList(), now, cancellationToken);
}
private async Task StageIfMembershipAsync(Bifrost.Web.Domain.Membership? membership, IEnumerable<PatronSupportEvent> events, DateTimeOffset now, CancellationToken cancellationToken)
{
if (membership is not null)
{
await patronageService.StageTierSnapshotAsync(membership, events, now, cancellationToken);
}
}
private static AccountMergeEntry Journal(Guid mergeId, int seq, MergePlanEntry entry, DateTimeOffset now) => new()
{
MergeId = mergeId,
Seq = seq,
Kind = entry.Kind,
RecordId = entry.RecordId,
Action = entry.Action,
PriorUserAccountId = entry.PriorUserAccountId,
PriorText = entry.PriorText,
PriorAtUtc = entry.PriorAtUtc,
AtUtc = now
};
private static string AppraisalKey(Guid accountId) => "account:" + accountId.ToString("N");
}
/// <summary>Finalizes merges past their grace every five minutes. Copies the SealedBallotCloser shape: a new scope per tick, a warning on failure.</summary>
public sealed class AccountMergeSweeper(IServiceScopeFactory scopes, TimeProvider clock, ILogger<AccountMergeSweeper> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
do
{
try
{
using var scope = scopes.CreateScope();
await scope.ServiceProvider.GetRequiredService<AccountMergeLedger>().FinalizeDueAsync(clock.GetUtcNow(), stoppingToken);
}
catch (Exception error) when (error is not OperationCanceledException)
{
logger.LogWarning(error, "Account merge sweep failed; retrying next tick.");
}
}
while (await timer.WaitForNextTickAsync(stoppingToken));
}
}

View file

@ -23,6 +23,7 @@ namespace Bifrost.Web.Features.Oidc;
public static class OidcEndpoints
{
public const string SuspendedDescription = "The account is suspended.";
public const string MergedDescription = "The account is part of an account merge and can no longer sign in.";
public const string NoIdentityDescription = "The account has no Bifrost identity.";
public const string ReservedIdentityDescription = "The account's Bifrost identity is reserved.";
public const string ConsentRequiredDescription = "Agreement to the training notice in force is needed to speak in a recorded room.";
@ -56,7 +57,7 @@ public static class OidcEndpoints
// every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync).
if (actor.UserAccount is null)
{
return Deny(Errors.AccessDenied, NoIdentityDescription);
return Deny(Errors.AccessDenied, actor.Merge is not null ? MergedDescription : NoIdentityDescription);
}
if (actor.Membership?.Status == MembershipStatus.Suspended)
@ -176,6 +177,12 @@ public static class OidcEndpoints
return SuspendedDescription;
}
// A folded or frozen subject's chat sessions end: token, userinfo and the logout reconciler all read this one refusal.
if (await AccountMergeLedger.StandingAsync(db, accountId, cancellationToken) is not null)
{
return MergedDescription;
}
return deskToken || await ConsentEndpoints.HasLiveReceiptAsync(db, accountId, cancellationToken) ? null : ConsentRequiredDescription;
}

View file

@ -146,35 +146,7 @@ public sealed class PatronageService(
throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
}
var summary = CalculatePatronPoints(user.PatronSupportEvents, timeProvider.GetUtcNow());
var tier = PatronTierPolicy.ResolveTier(summary.EffectivePoints);
var now = timeProvider.GetUtcNow();
var currentPatronSnapshots = await dbContext.TierSnapshots
.Where(x => x.MembershipId == user.Membership.Id &&
x.Kind == TierSnapshotKind.Patron &&
x.IsCurrent)
.ToListAsync(cancellationToken);
foreach (var snapshot in currentPatronSnapshots)
{
snapshot.IsCurrent = false;
}
if (tier is not null)
{
dbContext.TierSnapshots.Add(new TierSnapshot
{
MembershipId = user.Membership.Id,
Kind = TierSnapshotKind.Patron,
Label = PatronTierPolicy.SnapshotLabel(tier),
Weight = tier.VotingWeight,
IsCurrent = true,
EffectiveFromUtc = now,
CapturedAtUtc = now,
Notes = PatronTierPolicy.SnapshotNote(summary.EffectivePoints, now)
});
}
var (summary, tier) = await StageTierSnapshotAsync(user.Membership, user.PatronSupportEvents, timeProvider.GetUtcNow(), cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
await auditTrailService.RecordAsync(
@ -190,6 +162,49 @@ public sealed class PatronageService(
return summary with { TierLabel = tier?.Label ?? string.Empty, VotingWeight = tier?.VotingWeight ?? 0m };
}
/// <summary>
/// Derives the membership's patron tier from the events once and stages it on the tracker: demotes the current Patron snapshots
/// and adds the new one. It never saves and never clears the tracker, so a caller can stage it inside a larger single save
/// (the account merge ledger does).
/// </summary>
public async Task<(PatronPointSummary Summary, PatronTierDefinition? Tier)> StageTierSnapshotAsync(
Bifrost.Web.Domain.Membership membership,
IEnumerable<PatronSupportEvent> events,
DateTimeOffset now,
CancellationToken cancellationToken)
{
var summary = CalculatePatronPoints(events, now);
var tier = PatronTierPolicy.ResolveTier(summary.EffectivePoints);
var currentPatronSnapshots = await dbContext.TierSnapshots
.Where(x => x.MembershipId == membership.Id &&
x.Kind == TierSnapshotKind.Patron &&
x.IsCurrent)
.ToListAsync(cancellationToken);
foreach (var snapshot in currentPatronSnapshots)
{
snapshot.IsCurrent = false;
}
if (tier is not null)
{
dbContext.TierSnapshots.Add(new TierSnapshot
{
MembershipId = membership.Id,
Kind = TierSnapshotKind.Patron,
Label = PatronTierPolicy.SnapshotLabel(tier),
Weight = tier.VotingWeight,
IsCurrent = true,
EffectiveFromUtc = now,
CapturedAtUtc = now,
Notes = PatronTierPolicy.SnapshotNote(summary.EffectivePoints, now)
});
}
return (summary, tier);
}
public static PatronPointSummary CalculatePatronPoints(
IEnumerable<PatronSupportEvent> supportEvents,
DateTimeOffset nowUtc)

View file

@ -1,9 +1,13 @@
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Membership;
namespace Bifrost.Web.Features.Shared;
public sealed record CurrentBifrostActor(bool IsAuthenticated, UserAccount? UserAccount)
{
/// <summary>Set when the account behind this sign-in is frozen or folded by an account merge; the actor then has no account.</summary>
public MergeStanding? Merge { get; init; }
public static readonly CurrentBifrostActor Anonymous = new(false, null);
public Bifrost.Web.Domain.Membership? Membership => UserAccount?.Membership;

View file

@ -12,7 +12,8 @@ public interface ICurrentBifrostActorAccessor
public sealed class CurrentBifrostActorAccessor(
IHttpContextAccessor httpContextAccessor,
BifrostDbContext dbContext) : ICurrentBifrostActorAccessor
BifrostDbContext dbContext,
AccountMergeLedger ledger) : ICurrentBifrostActorAccessor
{
private const string CacheKey = "Bifrost.CurrentActor";
@ -45,18 +46,41 @@ public sealed class CurrentBifrostActorAccessor(
return Cache(httpContext, CurrentBifrostActor.Anonymous);
}
var userAccount = await dbContext.UserAccounts
// One credential names one row: identity first, then Heimdall id, then GitHub id; the first hit wins. Two rows matching
// one principal (a merge can leave a login on either side) must never throw or pick by luck.
var accounts = dbContext.UserAccounts
.AsNoTracking()
.Include(x => x.MemberProfile)
.Include(x => x.Membership!)
.ThenInclude(x => x.RoleAssignments)
.Include(x => x.Membership!)
.ThenInclude(x => x.TierSnapshots)
.SingleOrDefaultAsync(
x => (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity) && x.NormalizedBifrostIdentity == normalizedBifrostIdentity) ||
(!string.IsNullOrWhiteSpace(heimdallAccountId) && x.HeimdallAccountId == heimdallAccountId) ||
(hasGitHubUserId && x.GitHubUserId == gitHubUserId),
cancellationToken);
.ThenInclude(x => x.TierSnapshots);
Bifrost.Web.Domain.UserAccount? userAccount = null;
if (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity))
{
userAccount = await accounts.SingleOrDefaultAsync(x => x.NormalizedBifrostIdentity == normalizedBifrostIdentity, cancellationToken);
}
if (userAccount is null && !string.IsNullOrWhiteSpace(heimdallAccountId))
{
userAccount = await accounts.SingleOrDefaultAsync(x => x.HeimdallAccountId == heimdallAccountId, cancellationToken);
}
if (userAccount is null && hasGitHubUserId)
{
userAccount = await accounts.SingleOrDefaultAsync(x => x.GitHubUserId == gitHubUserId, cancellationToken);
}
// A folded or frozen account acts as nobody on every route: this is the one gate (merge ledger standing, derived per request).
if (userAccount is not null)
{
var standing = await ledger.StandingAsync(userAccount.Id, cancellationToken);
if (standing is not null)
{
return Cache(httpContext, new CurrentBifrostActor(true, null) { Merge = standing });
}
}
return Cache(httpContext, new CurrentBifrostActor(true, userAccount));
}

View file

@ -139,6 +139,8 @@ builder.Services.AddSingleton<RegistrationChallengeService>();
builder.Services.AddSingleton<RegistrationRateLimit>();
builder.Services.AddScoped<NativeRegistration>();
builder.Services.AddHostedService<SealedBallotCloser>();
builder.Services.AddScoped<Bifrost.Web.Features.Membership.AccountMergeLedger>();
builder.Services.AddHostedService<Bifrost.Web.Features.Membership.AccountMergeSweeper>();
builder.Services.AddScoped<MotionEveSurfaceService>();
builder.Services.AddScoped<PatronageService>();
builder.Services.AddScoped<StripeWebhookService>();

View file

@ -0,0 +1,150 @@
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
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>A folded member's browser and Heimdall's patron intake, over HTTP: the merge ledger is the single gate behind both.</summary>
public sealed class AccountMergeHttpTests(TestWebApplicationFactory factory) : IClassFixture<TestWebApplicationFactory>
{
private sealed record Seeded(Guid Survivor, Guid Folded, Guid Motion, string FoldedHeimdallId, long SurvivorGitHubId, long FoldedGitHubId);
private async Task<Seeded> SeedAsync()
{
using var scope = factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
var seed = Random.Shared.NextInt64(1_000_000, 900_000_000);
UserAccount Make(string name, long gitHubId) => new()
{
DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = name, GitHubUserId = gitHubId, GitHubLogin = name, NormalizedGitHubLogin = name,
HeimdallAccountId = "hd-" + name,
MemberProfile = new MemberProfile { Nickname = name, Headline = "seed", UpdatedAtUtc = DateTimeOffset.UtcNow },
Membership = new Bifrost.Web.Domain.Membership { Status = MembershipStatus.Active, ApprovedAtUtc = DateTimeOffset.UtcNow }
};
var survivor = Make($"surv-{seed}", seed);
var folded = Make($"fold-{seed}", seed + 1);
db.UserAccounts.AddRange(survivor, folded);
var motion = new Motion
{
CreatedByUserAccountId = survivor.Id, Title = "Open motion", Status = MotionStatus.Open, OpensAtUtc = DateTimeOffset.UtcNow.AddHours(-1),
ClosesAtUtc = DateTimeOffset.UtcNow.AddDays(2), CreatedAtUtc = DateTimeOffset.UtcNow
};
db.Motions.Add(motion);
await db.SaveChangesAsync();
return new Seeded(survivor.Id, folded.Id, motion.Id, folded.HeimdallAccountId, seed, seed + 1);
}
private HttpClient ClientFor(long gitHubId, string login)
{
var client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, BaseAddress = new Uri("https://localhost"), HandleCookies = true });
client.DefaultRequestHeaders.Add("X-Test-GitHub-Id", gitHubId.ToString());
client.DefaultRequestHeaders.Add("X-Test-GitHub-Login", login);
return client;
}
private static async Task<string> TokenAsync(HttpClient client)
{
using var page = await client.GetAsync("/App/Motions");
var html = await page.Content.ReadAsStringAsync();
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
Assert.NotEmpty(token);
return token;
}
private static Task<HttpResponseMessage> VoteAsync(HttpClient client, Guid motion, string token) =>
client.PostAsync("/App/Motions?handler=Vote", new FormUrlEncodedContent(new Dictionary<string, string>
{
["motionId"] = motion.ToString(), ["choice"] = "For", ["comment"] = "yes", ["__RequestVerificationToken"] = token
}));
private async Task<T> WithDb<T>(Func<BifrostDbContext, Task<T>> read)
{
using var scope = factory.Services.CreateScope();
return await read(scope.ServiceProvider.GetRequiredService<BifrostDbContext>());
}
private Task<int> VoteRowsAsync(Guid motion) => WithDb(db => db.Votes.IgnoreQueryFilters().CountAsync(x => x.MotionId == motion));
private async Task<Guid> MergeAsync(Seeded s, AccountMergeState state)
{
using var scope = factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
var merge = new AccountMerge { SurvivorUserAccountId = s.Survivor, FoldedUserAccountId = s.Folded, State = state, CreatedUtc = DateTimeOffset.UtcNow };
db.AccountMerges.Add(merge);
await db.SaveChangesAsync();
return merge.Id;
}
private async Task SetStateAsync(Guid mergeId, AccountMergeState state) =>
await WithDb(async db =>
{
(await db.AccountMerges.SingleAsync(x => x.Id == mergeId)).State = state;
await db.SaveChangesAsync();
return 0;
});
[Fact]
public async Task A_folded_session_cookie_acts_as_nobody_while_Frozen_and_after_Committed_and_the_survivor_still_votes()
{
var s = await SeedAsync();
using var folded = ClientFor(s.FoldedGitHubId, $"fold-{s.SurvivorGitHubId}");
var token = await TokenAsync(folded); // a live, valid form from before the merge: the cookie outlives the merge
var merge = await MergeAsync(s, AccountMergeState.Confirmed);
using (var whileFrozen = await VoteAsync(folded, s.Motion, token))
{
Assert.NotEqual(HttpStatusCode.OK, whileFrozen.StatusCode);
}
Assert.Equal(0, await VoteRowsAsync(s.Motion));
using (var page = await folded.GetAsync("/App/Motions"))
{
Assert.NotEqual(HttpStatusCode.OK, page.StatusCode);
}
await SetStateAsync(merge, AccountMergeState.HeimdallMoved);
await SetStateAsync(merge, AccountMergeState.Committed);
using (var afterCommit = await VoteAsync(folded, s.Motion, token))
{
Assert.NotEqual(HttpStatusCode.OK, afterCommit.StatusCode);
}
Assert.Equal(0, await VoteRowsAsync(s.Motion));
using var survivor = ClientFor(s.SurvivorGitHubId, $"surv-{s.SurvivorGitHubId}");
using var control = await VoteAsync(survivor, s.Motion, await TokenAsync(survivor));
Assert.Equal(HttpStatusCode.Redirect, control.StatusCode);
Assert.Equal(1, await VoteRowsAsync(s.Motion));
}
[Fact]
public async Task Patron_intake_for_a_folded_heimdall_id_records_on_the_survivor()
{
var s = await SeedAsync();
await MergeAsync(s, AccountMergeState.Final);
var payload = JsonSerializer.Serialize(new
{
heimdallAccountId = s.FoldedHeimdallId, provider = "PayPal", providerEventId = $"WH-{Guid.NewGuid():N}", kind = "OneTimeDonation",
amount = 25m, currencyCode = "USD", externalSupportId = "CAPTURE-1", supportedAtUtc = DateTimeOffset.UtcNow, isCurrentRecurringSupport = false
});
using var hasher = new HMACSHA256(Encoding.UTF8.GetBytes("test-heimdall-intake-secret"));
using var request = new HttpRequestMessage(HttpMethod.Post, "/heimdall/patron-support/events");
request.Headers.Add("X-Heimdall-Signature-256", "sha256=" + Convert.ToHexString(hasher.ComputeHash(Encoding.UTF8.GetBytes(payload))).ToLowerInvariant());
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
using var client = factory.CreateClient();
using var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
var owners = await WithDb(db => db.PatronSupportEvents.Where(x => x.UserAccountId == s.Survivor || x.UserAccountId == s.Folded).Select(x => x.UserAccountId).ToListAsync());
Assert.Equal([s.Survivor], owners);
}
}

View file

@ -0,0 +1,725 @@
using Bifrost.Web.Configuration;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.ConceptVotes;
using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Motions;
using Bifrost.Web.Features.Patronage;
using Bifrost.Web.Features.Shared;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Options;
namespace Bifrost.Web.Tests;
/// <summary>
/// The merge ledger from its consumers' side: the motion state and close a member sees, the concept tallies a visitor sees, the actor
/// a sign-in resolves to, the patron weight, and the undo. Each operation opens its own context, as a request scope would.
/// </summary>
public sealed class AccountMergeLedgerTests
{
private static readonly DateTimeOffset T0 = new(2026, 11, 14, 12, 0, 0, TimeSpan.Zero);
private sealed class Clock(DateTimeOffset start) : TimeProvider
{
public DateTimeOffset Now { get; set; } = start;
public override DateTimeOffset GetUtcNow() => Now;
}
private sealed class World
{
private readonly string _name = $"merge-{Guid.NewGuid():N}";
private readonly SaveChangesInterceptor[] _interceptors;
public World(params SaveChangesInterceptor[] interceptors) => _interceptors = interceptors;
public Clock Clock { get; } = new(T0);
public BifrostDbContext Db() => new(new DbContextOptionsBuilder<BifrostDbContext>()
.UseInMemoryDatabase(_name)
.AddInterceptors(_interceptors)
.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning))
.Options);
public AccountMergeLedger Ledger(BifrostDbContext db) => new(db, new PatronageService(db, new AuditTrailService(db, Clock), Clock), Clock);
public MotionGovernanceService Motions(BifrostDbContext db) => new(db, new AuditTrailService(db, Clock), Clock);
public ConceptAppraisalService Concepts(BifrostDbContext db) =>
new(db, new AuditTrailService(db, Clock), Clock, Options.Create(new ConceptVoteOptions()));
public async Task<UserAccount> AccountAsync(string name, MembershipStatus status = MembershipStatus.Active, bool heimdall = true, bool moderator = false, params MemberRole[] roles)
{
await using var db = Db();
var account = new UserAccount
{
DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = BifrostIdentityService.NormalizeIdentity(name),
HeimdallAccountId = heimdall ? $"hd-{name}-{Guid.NewGuid():N}" : string.Empty,
CreatedAtUtc = T0, LastSeenAtUtc = T0
};
account.Membership = new Membership { UserAccountId = account.Id, Status = status, CanModerateMotions = moderator };
foreach (var role in roles)
{
account.Membership.RoleAssignments.Add(new RoleAssignment { Role = role });
}
db.UserAccounts.Add(account);
await db.SaveChangesAsync();
return account;
}
public async Task<Motion> MotionAsync(string title = "m", MotionStatus status = MotionStatus.Open, MotionKind kind = MotionKind.Standard)
{
await using var db = Db();
var author = await AccountAsync("author-" + Guid.NewGuid().ToString("N")[..6]);
var motion = new Motion
{
CreatedByUserAccountId = author.Id, Title = title, Status = status, Kind = kind, OpensAtUtc = T0,
ClosesAtUtc = T0.AddDays(3), CreatedAtUtc = T0, ApprovalThreshold = 0.5m
};
db.Motions.Add(motion);
await db.SaveChangesAsync();
return motion;
}
public async Task VoteAsync(Motion motion, UserAccount who, VoteChoice choice, decimal weight = 1m, DateTimeOffset? at = null)
{
await using var db = Db();
db.Votes.Add(new Vote { MotionId = motion.Id, UserAccountId = who.Id, Choice = choice, Weight = weight, CastAtUtc = at ?? T0.AddHours(1) });
await db.SaveChangesAsync();
}
public async Task<AccountMerge> MergeAsync(UserAccount survivor, UserAccount folded, AccountMergeState state = AccountMergeState.HeimdallMoved)
{
await using var db = Db();
var merge = new AccountMerge { SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = folded.Id, State = state, CreatedUtc = T0 };
db.AccountMerges.Add(merge);
await db.SaveChangesAsync();
return merge;
}
public async Task<AccountMerge> CommitAsync(AccountMerge merge)
{
await using var db = Db();
return await Ledger(db).CommitAsync(merge.Id, default);
}
public async Task SetStateAsync(AccountMerge merge, AccountMergeState state)
{
await using var db = Db();
(await db.AccountMerges.SingleAsync(x => x.Id == merge.Id)).State = state;
await db.SaveChangesAsync();
}
public async Task<MotionListItem> StateOfAsync(Motion motion, UserAccount viewer)
{
await using var db = Db();
var actorAccount = await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments)
.SingleAsync(x => x.Id == viewer.Id);
var state = await Motions(db).GetStateAsync(new CurrentBifrostActor(true, actorAccount), default);
return state.Motions.Single(x => x.Id == motion.Id);
}
public async Task<CurrentBifrostActor> ActorAsync(Guid accountId)
{
await using var db = Db();
var account = await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments)
.SingleAsync(x => x.Id == accountId);
return new CurrentBifrostActor(true, account);
}
public async Task<MotionStatus> CloseAsync(Motion motion, UserAccount moderator)
{
await using var db = Db();
await Motions(db).CloseMotionAsync(await ActorAsync(moderator.Id), motion.Id, default);
await using var check = Db();
return (await check.Motions.SingleAsync(x => x.Id == motion.Id)).Status;
}
public async Task<List<Vote>> AllVotesAsync(Motion motion)
{
await using var db = Db();
return await db.Votes.IgnoreQueryFilters().AsNoTracking().Where(x => x.MotionId == motion.Id).ToListAsync();
}
public async Task<List<AccountMergeEntry>> JournalAsync(AccountMerge merge)
{
await using var db = Db();
return await db.AccountMergeEntries.AsNoTracking().Where(x => x.MergeId == merge.Id).OrderBy(x => x.Seq).ToListAsync();
}
public async Task<Membership> MembershipOfAsync(UserAccount account)
{
await using var db = Db();
return await db.Memberships.AsNoTracking().Include(x => x.TierSnapshots).Include(x => x.RoleAssignments).SingleAsync(x => x.UserAccountId == account.Id);
}
}
// ---- votes ----
[Fact]
public async Task Both_voted_on_an_open_motion_only_the_survivors_weight_counts_in_state_and_close()
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
var moderator = await world.AccountAsync("mod", moderator: true);
var motion = await world.MotionAsync();
await world.VoteAsync(motion, survivor, VoteChoice.Against, 1m);
await world.VoteAsync(motion, folded, VoteChoice.For, 3m);
var before = await world.StateOfAsync(motion, moderator);
Assert.Equal((3m, 1m), (before.VotesFor, before.VotesAgainst));
await world.CommitAsync(await world.MergeAsync(survivor, folded));
var after = await world.StateOfAsync(motion, moderator);
Assert.Equal((0m, 1m), (after.VotesFor, after.VotesAgainst));
Assert.Equal(MotionStatus.Failed, await world.CloseAsync(motion, moderator));
Assert.Equal(2, (await world.AllVotesAsync(motion)).Count); // nothing is deleted
}
[Fact]
public async Task A_vote_only_the_folded_account_cast_moves_and_a_later_survivor_cast_replaces_it_never_doubling()
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
var moderator = await world.AccountAsync("mod", moderator: true);
var motion = await world.MotionAsync();
await world.VoteAsync(motion, folded, VoteChoice.For, 1m);
await world.CommitAsync(await world.MergeAsync(survivor, folded));
Assert.Equal(1m, (await world.StateOfAsync(motion, moderator)).VotesFor);
await using (var db = world.Db())
{
await world.Motions(db).CastVoteAsync(await world.ActorAsync(survivor.Id), motion.Id, VoteChoice.Against, "changed my mind", default);
}
var item = await world.StateOfAsync(motion, moderator);
Assert.Equal((0m, 1m), (item.VotesFor, item.VotesAgainst));
var row = Assert.Single(await world.AllVotesAsync(motion));
Assert.Equal(survivor.Id, row.UserAccountId);
Assert.Null(row.VoidedByMergeId);
}
[Fact]
public async Task A_vote_only_the_folded_account_cast_is_voided_when_the_survivor_is_not_active()
{
var world = new World();
var survivor = await world.AccountAsync("survivor", MembershipStatus.PendingApproval);
var folded = await world.AccountAsync("folded");
var moderator = await world.AccountAsync("mod", moderator: true);
var motion = await world.MotionAsync();
await world.VoteAsync(motion, folded, VoteChoice.For, 1m);
var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
Assert.Equal(0m, (await world.StateOfAsync(motion, moderator)).VotesFor);
var row = Assert.Single(await world.AllVotesAsync(motion));
Assert.Equal(merge.Id, row.VoidedByMergeId);
Assert.Equal(folded.Id, row.UserAccountId);
}
[Fact]
public async Task Closed_motions_keep_every_vote_and_tally()
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
var moderator = await world.AccountAsync("mod", moderator: true);
var motion = await world.MotionAsync(status: MotionStatus.Passed);
await world.VoteAsync(motion, survivor, VoteChoice.For, 1m);
await world.VoteAsync(motion, folded, VoteChoice.For, 2m);
await world.CommitAsync(await world.MergeAsync(survivor, folded));
Assert.Equal(3m, (await world.StateOfAsync(motion, moderator)).VotesFor);
Assert.All(await world.AllVotesAsync(motion), v => Assert.Null(v.VoidedByMergeId));
}
// ---- concept appraisals ----
[Fact]
public async Task Appraisals_reduce_to_one_voice_per_person_and_the_tallies_count_the_person_once()
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
Guid both, onlyFolded;
await using (var db = world.Db())
{
var s1 = new ConceptSubject { Collection = "c", Key = "both", Title = "Both", RegisteredAtUtc = T0 };
var s2 = new ConceptSubject { Collection = "c", Key = "only-folded", Title = "Only folded", RegisteredAtUtc = T0 };
db.ConceptSubjects.AddRange(s1, s2);
ConceptAppraisal Row(ConceptSubject s, UserAccount who, ConceptStance stance) => new()
{
SubjectId = s.Id, UserAccountId = who.Id, VoterKey = "account:" + who.Id.ToString("N"), Stance = stance,
VoterClass = VoterClass.Member, CastAtUtc = T0
};
db.ConceptAppraisals.AddRange(Row(s1, survivor, ConceptStance.Up), Row(s1, folded, ConceptStance.Down), Row(s2, folded, ConceptStance.Down));
await db.SaveChangesAsync();
(both, onlyFolded) = (s1.Id, s2.Id);
}
await world.CommitAsync(await world.MergeAsync(survivor, folded));
await using var read = world.Db();
var tallies = await world.Concepts(read).GetTalliesAsync("c", default);
Assert.Equal((1, 0), (tallies["both"].Up, tallies["both"].Down));
Assert.Equal((0, 1), (tallies["only-folded"].Up, tallies["only-folded"].Down));
var moved = await read.ConceptAppraisals.SingleAsync(x => x.SubjectId == onlyFolded);
Assert.Equal(survivor.Id, moved.UserAccountId);
Assert.Equal("account:" + survivor.Id.ToString("N"), moved.VoterKey);
Assert.Equal(1, await read.ConceptAppraisals.IgnoreQueryFilters().CountAsync(x => x.SubjectId == both && x.VoidedByMergeId != null));
}
// ---- membership, standing, patronage ----
[Fact]
public async Task The_folded_membership_becomes_Merged_with_weight_zero_and_no_role_or_admin_flag_is_carried()
{
var world = new World();
var survivor = await world.AccountAsync("survivor", roles: MemberRole.StandardMember);
var folded = await world.AccountAsync("folded", roles: [MemberRole.PlatformAdmin, MemberRole.Producer]);
await using (var db = world.Db())
{
(await db.Memberships.SingleAsync(x => x.UserAccountId == folded.Id)).IsPlatformAdmin = true;
await db.SaveChangesAsync();
}
await world.CommitAsync(await world.MergeAsync(survivor, folded));
var foldedMembership = await world.MembershipOfAsync(folded);
Assert.Equal(MembershipStatus.Merged, foldedMembership.Status);
Assert.Equal(0m, foldedMembership.EffectiveVotingWeight);
var survivorMembership = await world.MembershipOfAsync(survivor);
Assert.Equal([MemberRole.StandardMember], survivorMembership.RoleAssignments.Select(x => x.Role));
Assert.False(survivorMembership.IsPlatformAdmin);
Assert.Equal(MembershipStatus.Active, survivorMembership.Status);
}
[Fact]
public async Task A_suspended_folded_account_suspends_the_survivor_and_undo_restores_it_only_if_unchanged()
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded", MembershipStatus.Suspended);
var untouched = await world.MergeAsync(survivor, folded);
await world.CommitAsync(untouched);
var suspended = await world.MembershipOfAsync(survivor);
Assert.Equal(MembershipStatus.Suspended, suspended.Status);
Assert.Equal(AccountMergeLedger.SuspensionReason(untouched.Id), suspended.SuspensionReason);
await world.SetStateAsync(untouched, AccountMergeState.HeimdallReversed);
await using (var db = world.Db())
{
await world.Ledger(db).UndoLocalAsync(untouched.Id, default);
}
Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(survivor)).Status);
Assert.Equal(MembershipStatus.Suspended, (await world.MembershipOfAsync(folded)).Status);
// The same again, but a steward re-suspends the survivor for their own reason before the undo: that standing is theirs now.
var folded2 = await world.AccountAsync("folded2", MembershipStatus.Suspended);
var second = await world.MergeAsync(survivor, folded2);
await world.CommitAsync(second);
await using (var db = world.Db())
{
(await db.Memberships.SingleAsync(x => x.UserAccountId == survivor.Id)).SuspensionReason = "steward decision";
await db.SaveChangesAsync();
}
await world.SetStateAsync(second, AccountMergeState.HeimdallReversed);
await using (var db = world.Db())
{
await world.Ledger(db).UndoLocalAsync(second.Id, default);
}
Assert.Equal(MembershipStatus.Suspended, (await world.MembershipOfAsync(survivor)).Status);
Assert.Contains(await world.JournalAsync(second), e => e.Kind == AccountMergeEntryKind.Standing && e.Action == AccountMergeEntryAction.KeptAfterUndo);
}
[Fact]
public async Task Patron_events_follow_the_person_and_the_survivors_tier_derives_once_from_all_events_not_tier_plus_tier()
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
await using (var db = world.Db())
{
PatronSupportEvent Event(UserAccount who, decimal amount) => new()
{
UserAccountId = who.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = amount,
ProviderEventId = Guid.NewGuid().ToString("N"), SupportedAtUtc = T0, RecordedAtUtc = T0
};
db.PatronSupportEvents.AddRange(Event(survivor, 90m), Event(folded, 1000m));
var memberships = await db.Memberships.ToListAsync();
foreach (var (who, weight) in new[] { (survivor, 1m), (folded, 3m) })
{
db.TierSnapshots.Add(new TierSnapshot { MembershipId = memberships.Single(m => m.UserAccountId == who.Id).Id, Kind = TierSnapshotKind.Patron, Label = "t", Weight = weight, IsCurrent = true, EffectiveFromUtc = T0, CapturedAtUtc = T0 });
}
await db.SaveChangesAsync();
}
await world.CommitAsync(await world.MergeAsync(survivor, folded));
var survivorMembership = await world.MembershipOfAsync(survivor);
Assert.Equal(3m, survivorMembership.EffectiveVotingWeight); // 1090 points: Gold, not Bronze 1 + Gold 3
Assert.Single(survivorMembership.TierSnapshots, x => x.Kind == TierSnapshotKind.Patron && x.IsCurrent);
Assert.DoesNotContain(( await world.MembershipOfAsync(folded)).TierSnapshots, x => x.IsCurrent);
await using var db2 = world.Db();
Assert.All(await db2.PatronSupportEvents.ToListAsync(), e => Assert.Equal(survivor.Id, e.UserAccountId));
}
// ---- who the actor is ----
[Fact]
public async Task A_principal_whose_identity_names_one_row_and_whose_heimdall_id_names_another_resolves_the_first_and_does_not_throw()
{
var world = new World();
var byIdentity = await world.AccountAsync("by-identity");
var byHeimdall = await world.AccountAsync("by-heimdall");
var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
http.User = new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity(
[
new System.Security.Claims.Claim(BifrostClaimTypes.BifrostIdentity, byIdentity.BifrostIdentity),
new System.Security.Claims.Claim(BifrostClaimTypes.HeimdallAccountId, byHeimdall.HeimdallAccountId)
], "test"));
await using var db = world.Db();
var accessor = new CurrentBifrostActorAccessor(new Microsoft.AspNetCore.Http.HttpContextAccessor { HttpContext = http }, db, world.Ledger(db));
var actor = await accessor.GetAsync(default);
Assert.Equal(byIdentity.Id, actor.UserAccount!.Id);
}
[Theory]
[InlineData(AccountMergeState.Confirmed, true)]
[InlineData(AccountMergeState.HeimdallMoved, true)]
[InlineData(AccountMergeState.Committed, false)]
[InlineData(AccountMergeState.Final, false)]
[InlineData(AccountMergeState.UndoRequested, false)]
[InlineData(AccountMergeState.HeimdallReversed, false)]
public async Task A_folded_account_is_frozen_then_folded_and_acts_as_nobody_while_the_survivor_acts_normally(AccountMergeState state, bool frozen)
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded", roles: MemberRole.PlatformAdmin);
var merge = await world.MergeAsync(survivor, folded, state);
foreach (var (account, isFolded) in new[] { (folded, true), (survivor, false) })
{
var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
http.User = new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity(
[new System.Security.Claims.Claim(BifrostClaimTypes.HeimdallAccountId, account.HeimdallAccountId)], "test"));
await using var db = world.Db();
var actor = await new CurrentBifrostActorAccessor(new Microsoft.AspNetCore.Http.HttpContextAccessor { HttpContext = http }, db, world.Ledger(db)).GetAsync(default);
if (!isFolded)
{
Assert.Equal(survivor.Id, actor.UserAccount!.Id);
Assert.Null(actor.Merge);
continue;
}
Assert.True(actor.IsAuthenticated);
Assert.Null(actor.UserAccount);
Assert.False(actor.IsPlatformAdmin);
Assert.False(actor.IsActiveMember);
Assert.Equal(merge.Id, actor.Merge!.MergeId);
Assert.Equal(frozen, actor.Merge is MergeStanding.Frozen);
Assert.Equal(!frozen, actor.Merge is MergeStanding.Folded f && f.SurvivorId == survivor.Id);
}
}
[Theory]
[InlineData(AccountMergeState.Proposed)]
[InlineData(AccountMergeState.Failed)]
[InlineData(AccountMergeState.Undone)]
public async Task A_merge_that_never_reached_or_has_left_the_move_leaves_the_folded_account_standing_alone(AccountMergeState state)
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
await world.MergeAsync(survivor, folded, state);
await using var db = world.Db();
Assert.Null(await world.Ledger(db).StandingAsync(folded.Id, default));
Assert.Equal(folded.Id, await world.Ledger(db).ResolveAsync(folded.Id, default));
}
[Fact]
public async Task Resolve_follows_folded_links_to_the_end()
{
var world = new World();
var a = await world.AccountAsync("acct-a");
var b = await world.AccountAsync("acct-b");
var c = await world.AccountAsync("acct-c");
await world.MergeAsync(b, a, AccountMergeState.Final);
await world.MergeAsync(c, b, AccountMergeState.Committed);
await using var db = world.Db();
Assert.Equal(c.Id, await world.Ledger(db).ResolveAsync(a.Id, default));
Assert.Equal(c.Id, await world.Ledger(db).ResolveAsync(c.Id, default));
}
// ---- plan ----
[Fact]
public async Task Plan_writes_nothing_and_says_what_a_commit_would_do()
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
var motion = await world.MotionAsync();
await world.VoteAsync(motion, folded, VoteChoice.For);
await using (var db = world.Db())
{
var plan = await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default);
Assert.Empty(plan.Blocks);
Assert.Contains(plan.Entries, e => e.Kind == AccountMergeEntryKind.Vote && e.Action == AccountMergeEntryAction.Moved);
Assert.Contains(plan.Entries, e => e.Kind == AccountMergeEntryKind.Membership && e.Action == AccountMergeEntryAction.Closed);
}
await using var check = world.Db();
Assert.Empty(check.AccountMerges);
Assert.Empty(check.AccountMergeEntries);
Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(folded)).Status);
Assert.Equal(folded.Id, Assert.Single(await world.AllVotesAsync(motion)).UserAccountId);
}
public static IEnumerable<object[]> BlockCases() =>
new[] { "same_account", "mind_account", "native_account", "merge_in_flight", "survivor_is_folded", "already_folded", "folded_survivor_in_grace", "sealed_ballot_pending" }
.Select(x => new object[] { x });
[Theory]
[MemberData(nameof(BlockCases))]
public async Task Plan_reports_each_block_by_code(string code)
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded", heimdall: code != "native_account");
var other = await world.AccountAsync("other");
var (planSurvivor, planFolded) = (survivor.Id, folded.Id);
switch (code)
{
case "same_account":
planFolded = survivor.Id;
break;
case "mind_account":
await using (var db = world.Db())
{
db.MindPersonas.Add(new MindPersona { PersonaId = "p", UserAccountId = folded.Id });
await db.SaveChangesAsync();
}
break;
case "merge_in_flight":
await world.MergeAsync(other, folded, AccountMergeState.Confirmed);
break;
case "survivor_is_folded":
await world.MergeAsync(other, survivor, AccountMergeState.Final);
break;
case "already_folded":
await world.MergeAsync(other, folded, AccountMergeState.Committed);
break;
case "folded_survivor_in_grace":
await world.MergeAsync(folded, other, AccountMergeState.Committed);
break;
case "sealed_ballot_pending":
var motion = await world.MotionAsync(kind: MotionKind.SealedBallot);
await using (var db = world.Db())
{
db.SealedBallots.Add(new SealedBallot { MotionId = motion.Id, UserAccountId = folded.Id, Commitment = "c", CommittedAtUtc = T0 });
await db.SaveChangesAsync();
}
break;
}
await using var read = world.Db();
var plan = await world.Ledger(read).PlanAsync(planSurvivor, planFolded, default);
Assert.Contains(code, plan.Blocks);
}
// ---- commit, undo, finalize ----
[Fact]
public async Task Commit_twice_is_a_no_op_the_second_time_and_the_journal_is_unchanged()
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
var motion = await world.MotionAsync();
await world.VoteAsync(motion, folded, VoteChoice.For);
var merge = await world.MergeAsync(survivor, folded);
var first = await world.CommitAsync(merge);
var journal = await world.JournalAsync(merge);
world.Clock.Now = T0.AddDays(1);
var second = await world.CommitAsync(merge);
Assert.Equal(AccountMergeState.Committed, second.State);
Assert.Equal(first.CommittedUtc, second.CommittedUtc);
Assert.Equal(first.GraceEndsUtc, T0 + TimeSpan.FromDays(7));
Assert.Equal(journal.Count, (await world.JournalAsync(merge)).Count);
Assert.NotEmpty(journal);
}
private sealed class FailOnce : SaveChangesInterceptor
{
public bool Armed { get; set; }
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
if (Armed)
{
Armed = false;
throw new DbUpdateException("simulated store failure");
}
return base.SavingChangesAsync(eventData, result, cancellationToken);
}
}
[Fact]
public async Task A_commit_whose_save_fails_applies_nothing_and_a_retry_applies_exactly_once()
{
var failure = new FailOnce();
var world = new World(failure);
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
var motion = await world.MotionAsync();
await world.VoteAsync(motion, folded, VoteChoice.For);
var merge = await world.MergeAsync(survivor, folded);
failure.Armed = true;
await using (var db = world.Db())
{
var ledger = world.Ledger(db);
await Assert.ThrowsAsync<DbUpdateException>(() => ledger.CommitAsync(merge.Id, default));
await using var check = world.Db();
Assert.Equal(AccountMergeState.HeimdallMoved, (await check.AccountMerges.SingleAsync()).State);
Assert.Empty(check.AccountMergeEntries);
Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(folded)).Status);
await ledger.CommitAsync(merge.Id, default); // the same context, retried
}
var journal = await world.JournalAsync(merge);
Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count());
Assert.Equal(1, journal.Count(x => x.Kind == AccountMergeEntryKind.Vote));
Assert.Equal(AccountMergeState.Committed, (await world.CommitAsync(merge)).State);
}
[Theory]
[InlineData(AccountMergeState.Proposed)]
[InlineData(AccountMergeState.Confirmed)]
[InlineData(AccountMergeState.Failed)]
public async Task Commit_from_any_state_but_HeimdallMoved_throws_and_undo_from_Committed_throws(AccountMergeState state)
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
var merge = await world.MergeAsync(survivor, folded, state);
await using var db = world.Db();
await Assert.ThrowsAsync<InvalidOperationException>(() => world.Ledger(db).CommitAsync(merge.Id, default));
await world.SetStateAsync(merge, AccountMergeState.Committed);
await using var db2 = world.Db();
await Assert.ThrowsAsync<InvalidOperationException>(() => world.Ledger(db2).UndoLocalAsync(merge.Id, default));
}
[Fact]
public async Task Undo_restores_open_motion_votes_keeps_voided_ones_on_since_closed_motions_and_a_survivor_recast_and_restores_membership_and_patron_events()
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var folded = await world.AccountAsync("folded");
var moderator = await world.AccountAsync("mod", moderator: true);
var bothOpen = await world.MotionAsync("both-open");
var bothClosing = await world.MotionAsync("both-closing");
var movedKept = await world.MotionAsync("moved-recast");
var movedBack = await world.MotionAsync("moved-back");
foreach (var motion in new[] { bothOpen, bothClosing })
{
await world.VoteAsync(motion, survivor, VoteChoice.For);
await world.VoteAsync(motion, folded, VoteChoice.Against);
}
await world.VoteAsync(movedKept, folded, VoteChoice.For, at: T0.AddHours(2));
await world.VoteAsync(movedBack, folded, VoteChoice.For, at: T0.AddHours(3));
await using (var db = world.Db())
{
db.PatronSupportEvents.Add(new PatronSupportEvent
{
UserAccountId = folded.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = 100m,
ProviderEventId = "e1", SupportedAtUtc = T0, RecordedAtUtc = T0
});
await db.SaveChangesAsync();
}
var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
Assert.Equal(2m, (await world.MembershipOfAsync(survivor)).EffectiveVotingWeight);
// After the merge: one motion closes, and the survivor re-casts on a moved vote.
await world.CloseAsync(bothClosing, moderator);
world.Clock.Now = T0.AddDays(1);
await using (var db = world.Db())
{
await world.Motions(db).CastVoteAsync(await world.ActorAsync(survivor.Id), movedKept.Id, VoteChoice.Against, null, default);
}
await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed);
await using (var db = world.Db())
{
Assert.Equal(AccountMergeState.Undone, (await world.Ledger(db).UndoLocalAsync(merge.Id, default)).State);
}
var open = (await world.AllVotesAsync(bothOpen)).Single(v => v.UserAccountId == folded.Id);
Assert.Null(open.VoidedByMergeId);
var closed = (await world.AllVotesAsync(bothClosing)).Single(v => v.UserAccountId == folded.Id);
Assert.Equal(merge.Id, closed.VoidedByMergeId);
var recast = Assert.Single(await world.AllVotesAsync(movedKept));
Assert.Equal((survivor.Id, VoteChoice.Against), (recast.UserAccountId, recast.Choice));
Assert.Equal(folded.Id, Assert.Single(await world.AllVotesAsync(movedBack)).UserAccountId);
Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(folded)).Status);
Assert.Equal(2m, (await world.MembershipOfAsync(folded)).EffectiveVotingWeight);
Assert.Equal(1m, (await world.MembershipOfAsync(survivor)).EffectiveVotingWeight);
await using var read = world.Db();
Assert.Equal(folded.Id, (await read.PatronSupportEvents.SingleAsync()).UserAccountId);
var journal = await world.JournalAsync(merge);
Assert.Contains(journal, e => e.Action == AccountMergeEntryAction.KeptAfterUndo && e.Kind == AccountMergeEntryKind.Vote);
Assert.Contains(journal, e => e.Action == AccountMergeEntryAction.Restored && e.Kind == AccountMergeEntryKind.Membership);
Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count());
Assert.Equal(AccountMergeState.Undone, (await world.Ledger(read).UndoLocalAsync(merge.Id, default)).State); // a second undo is a no-op
}
[Fact]
public async Task Finalize_moves_Committed_merges_past_their_grace_to_Final_and_leaves_the_rest()
{
var world = new World();
var survivor = await world.AccountAsync("survivor");
var due = await world.AccountAsync("due");
var young = await world.AccountAsync("young");
var dueMerge = await world.CommitAsync(await world.MergeAsync(survivor, due));
world.Clock.Now = T0.AddDays(5);
var youngMerge = await world.CommitAsync(await world.MergeAsync(survivor, young));
world.Clock.Now = T0.AddDays(7);
await using var db = world.Db();
Assert.Equal(1, await world.Ledger(db).FinalizeDueAsync(world.Clock.Now, default));
await using var read = world.Db();
var final = await read.AccountMerges.SingleAsync(x => x.Id == dueMerge.Id);
Assert.Equal((AccountMergeState.Final, T0.AddDays(7)), (final.State, final.FinalizedUtc));
Assert.Equal(AccountMergeState.Committed, (await read.AccountMerges.SingleAsync(x => x.Id == youngMerge.Id)).State);
}
}

View file

@ -29,6 +29,7 @@ public sealed class MigrationDiscoveryTests
"20261111110000_AddMembershipSuspensionReason",
"20261111120000_ClearLegacyConsentReceipts",
"20261113120000_AddPasskeyCredentials",
"20261114120000_AddAccountMerges",
];
// Database.GetMigrations() reads assembly metadata only; no connection is opened.

View file

@ -121,6 +121,33 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
Assert.False(redirect.ContainsKey("code"));
}
[Theory]
[InlineData(AccountMergeState.Confirmed)]
[InlineData(AccountMergeState.HeimdallMoved)]
[InlineData(AccountMergeState.Committed)]
[InlineData(AccountMergeState.Final)]
public async Task A_folded_or_frozen_account_is_refused_with_access_denied_and_no_code(AccountMergeState state)
{
var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Folded One");
using (var scope = _factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<Bifrost.Web.Data.BifrostDbContext>();
db.AccountMerges.Add(new AccountMerge
{
SurvivorUserAccountId = Guid.NewGuid(), FoldedUserAccountId = _factory.AccountId(identity), State = state, CreatedUtc = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync();
}
var request = NewRequest();
var final = await DriveAsync(client, request);
var redirect = AssertRedirectToClient(final, request.State);
Assert.Equal("access_denied", redirect["error"]);
Assert.Equal(Bifrost.Web.Features.Oidc.OidcEndpoints.MergedDescription, redirect["error_description"]);
Assert.False(redirect.ContainsKey("code"));
}
[Theory]
[InlineData(MembershipStatus.Authenticated)]
[InlineData(MembershipStatus.PendingApproval)]

View file

@ -95,6 +95,34 @@ public sealed class OidcLogoutTests
Assert.True(factory.ValidAuthorizations(factory.AccountId(agreed).ToString("D")) > 0);
}
[Fact]
public async Task A_folded_subject_gets_one_signed_logout_and_loses_the_authorizations_while_the_survivor_keeps_them()
{
using var factory = new OidcLogoutFactory();
var (folded, _) = await factory.GrantAsync(MembershipStatus.Active);
var (survivor, _) = await factory.GrantAsync(MembershipStatus.Active);
var foldedSubject = factory.AccountId(folded).ToString("D");
var survivorSubject = factory.AccountId(survivor).ToString("D");
Assert.True(factory.ValidAuthorizations(foldedSubject) > 0);
using (var scope = factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<Bifrost.Web.Data.BifrostDbContext>();
db.AccountMerges.Add(new AccountMerge
{
SurvivorUserAccountId = factory.AccountId(survivor), FoldedUserAccountId = factory.AccountId(folded),
State = AccountMergeState.Committed, CreatedUtc = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync();
}
await factory.Reconciler.ReconcileOnceAsync(CancellationToken.None);
var token = new JsonWebToken(Assert.Single(factory.Mas.LogoutTokens()));
Assert.Equal(foldedSubject, token.Subject);
Assert.Equal(0, factory.ValidAuthorizations(foldedSubject));
Assert.True(factory.ValidAuthorizations(survivorSubject) > 0);
}
[Fact]
public async Task Two_logouts_for_one_subject_carry_different_jti()
{