Account merge ledger: fix the first Soul pass (suspension carried into a memberless survivor, merged status terminal, standing at the desk door, linked accounts and write time, journalled grace intake, survivor weight on moved votes, one-hop alias, State token and database guards for overlapping merges, live-Postgres tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
84ff2c4578
commit
f402eb13cc
23 changed files with 1273 additions and 97 deletions
|
|
@ -628,9 +628,16 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
|||
|
||||
modelBuilder.Entity<AccountMerge>(entity =>
|
||||
{
|
||||
entity.Property(x => x.State).HasConversion<string>().HasMaxLength(24);
|
||||
// State is the token: a transition computed from a stale read (the sweeper's Final over a saga's UndoRequested) fails its save.
|
||||
entity.Property(x => x.State).HasConversion<string>().HasMaxLength(24).IsConcurrencyToken();
|
||||
entity.Property(x => x.FailureCode).HasMaxLength(64);
|
||||
entity.HasIndex(x => new { x.FoldedUserAccountId, x.State });
|
||||
// An account is folded once: the DB refuses a second live merge folding it. The cross-role case (a survivor that is also
|
||||
// folded) cannot be one unique index; the migration's trigger refuses it.
|
||||
entity.HasIndex(x => x.FoldedUserAccountId)
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UX_AccountMerges_FoldedUserAccountId_Live")
|
||||
.HasFilter("\"State\" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed')");
|
||||
entity.HasIndex(x => new { x.SurvivorUserAccountId, x.State });
|
||||
entity.HasIndex(x => new { x.State, x.GraceEndsUtc });
|
||||
entity.HasOne<UserAccount>()
|
||||
|
|
|
|||
|
|
@ -105,6 +105,13 @@ namespace Bifrost.Web.Data.Migrations
|
|||
columns: new[] { "MergeId", "Seq" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "UX_AccountMerges_FoldedUserAccountId_Live",
|
||||
table: "AccountMerges",
|
||||
column: "FoldedUserAccountId",
|
||||
unique: true,
|
||||
filter: "\"State\" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed')");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_AccountMerges_FoldedUserAccountId_State",
|
||||
table: "AccountMerges",
|
||||
|
|
@ -119,11 +126,50 @@ namespace Bifrost.Web.Data.Migrations
|
|||
name: "IX_AccountMerges_SurvivorUserAccountId_State",
|
||||
table: "AccountMerges",
|
||||
columns: new[] { "SurvivorUserAccountId", "State" });
|
||||
|
||||
// The cross-role guard no single unique index can express: a live merge's survivor is never another live merge's folded
|
||||
// account (no chains), whichever order they arrive in. Advisory locks on both accounts, taken in a fixed order, serialise two
|
||||
// transactions racing over the same account, so the second one's check sees the first's committed row.
|
||||
migrationBuilder.Sql(@"
|
||||
CREATE FUNCTION ""AccountMerges_refuse_chain""() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.""State"" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed') THEN
|
||||
PERFORM pg_advisory_xact_lock(hashtextextended(LEAST(NEW.""SurvivorUserAccountId""::text, NEW.""FoldedUserAccountId""::text), 0));
|
||||
PERFORM pg_advisory_xact_lock(hashtextextended(GREATEST(NEW.""SurvivorUserAccountId""::text, NEW.""FoldedUserAccountId""::text), 0));
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM ""AccountMerges"" m
|
||||
WHERE m.""Id"" <> NEW.""Id""
|
||||
AND m.""State"" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed')
|
||||
AND (m.""SurvivorUserAccountId"" = NEW.""FoldedUserAccountId"" OR m.""FoldedUserAccountId"" = NEW.""SurvivorUserAccountId""))
|
||||
THEN
|
||||
RAISE EXCEPTION 'account merge chain refused' USING ERRCODE = '23P01';
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END
|
||||
$$;
|
||||
CREATE TRIGGER ""AccountMerges_refuse_chain"" BEFORE INSERT OR UPDATE OF ""State"", ""SurvivorUserAccountId"", ""FoldedUserAccountId"" ON ""AccountMerges""
|
||||
FOR EACH ROW EXECUTE FUNCTION ""AccountMerges_refuse_chain""();");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
// Voiding lives only in the new build's query filter and these columns: dropping them (or running an older build over them)
|
||||
// counts every voided vote again, and a close in that window records a wrong result for good. Refuse while any is voided;
|
||||
// see docs/account-merge.md (Rollback).
|
||||
migrationBuilder.Sql(@"
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM ""Votes"" WHERE ""VoidedByMergeId"" IS NOT NULL)
|
||||
OR EXISTS (SELECT 1 FROM ""ConceptAppraisals"" WHERE ""VoidedByMergeId"" IS NOT NULL) THEN
|
||||
RAISE EXCEPTION 'AddAccountMerges cannot be reverted while merged votes or appraisals are voided';
|
||||
END IF;
|
||||
END
|
||||
$$;");
|
||||
|
||||
migrationBuilder.Sql(@"DROP TRIGGER ""AccountMerges_refuse_chain"" ON ""AccountMerges""; DROP FUNCTION ""AccountMerges_refuse_chain""();");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "AccountMergeEntries");
|
||||
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ namespace Bifrost.Web.Data.Migrations
|
|||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("State")
|
||||
.IsConcurrencyToken()
|
||||
.IsRequired()
|
||||
.HasMaxLength(24)
|
||||
.HasColumnType("character varying(24)");
|
||||
|
|
@ -64,6 +65,11 @@ namespace Bifrost.Web.Data.Migrations
|
|||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("FoldedUserAccountId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UX_AccountMerges_FoldedUserAccountId_Live")
|
||||
.HasFilter("\"State\" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed')");
|
||||
|
||||
b.HasIndex("FoldedUserAccountId", "State");
|
||||
|
||||
b.HasIndex("State", "GraceEndsUtc");
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ public enum AccountMergeEntryAction
|
|||
Moved,
|
||||
Closed,
|
||||
Suspended,
|
||||
Created,
|
||||
Restored,
|
||||
KeptAfterUndo
|
||||
}
|
||||
|
|
@ -81,7 +82,7 @@ public sealed class AccountMergeEntry
|
|||
|
||||
public Guid? PriorUserAccountId { get; set; }
|
||||
|
||||
/// <summary>The prior status or prior voter key.</summary>
|
||||
/// <summary>What the record held before: the prior status; for a moved vote its weight; for a moved appraisal its voter class and key (class|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>
|
||||
|
|
|
|||
|
|
@ -359,6 +359,10 @@ public sealed class Membership
|
|||
|
||||
public ICollection<TierSnapshot> TierSnapshots { get; set; } = [];
|
||||
|
||||
/// <summary>The folded membership of a landed merge. Terminal: only AccountMergeLedger writes it or leaves it, so every other status writer (sign-in sync, bootstrap, claim, approval, suspension) refuses a merged row.</summary>
|
||||
[NotMapped]
|
||||
public bool IsMerged => Status == MembershipStatus.Merged;
|
||||
|
||||
[NotMapped]
|
||||
public decimal EffectiveVotingWeight =>
|
||||
Status != MembershipStatus.Active
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ using System.Net;
|
|||
using Bifrost.Web.Configuration;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Membership;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
|
@ -64,6 +65,13 @@ public sealed class ConceptAppraisalService(
|
|||
return CastResult.NoVoter;
|
||||
}
|
||||
|
||||
// A voter resolved before a merge froze the account must not write an appraisal after it: standing is read again at the write.
|
||||
if (voter.UserAccountId is { } voterAccountId &&
|
||||
await AccountMergeLedger.StandingAsync(dbContext, voterAccountId, cancellationToken) is not null)
|
||||
{
|
||||
return CastResult.NoVoter;
|
||||
}
|
||||
|
||||
var subject = await FindSubjectAsync(collection, key, cancellationToken);
|
||||
if (subject is null)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -845,8 +845,8 @@ public sealed class HeimdallAuthService(
|
|||
UserAccountId = userAccount.Id,
|
||||
CreatedAtUtc = now
|
||||
};
|
||||
// A suspension is an admin's decision: the claim neither lifts it nor, absent, imposes it.
|
||||
if (grantMemberAccess && userAccount.Membership.Status != MembershipStatus.Suspended)
|
||||
// A suspension is an admin's decision: the claim neither lifts it nor, absent, imposes it. A merged row is terminal: the claim never reactivates it.
|
||||
if (grantMemberAccess && userAccount.Membership.Status != MembershipStatus.Suspended && !userAccount.Membership.IsMerged)
|
||||
{
|
||||
userAccount.Membership.Status = MembershipStatus.Active;
|
||||
userAccount.Membership.ApprovedAtUtc ??= now;
|
||||
|
|
|
|||
|
|
@ -66,17 +66,25 @@ public sealed class HeimdallPatronSupportIntakeService(
|
|||
x.ProviderEventId == request.ProviderEventId.Trim(),
|
||||
cancellationToken);
|
||||
|
||||
var user = await dbContext.UserAccounts
|
||||
.AsNoTracking()
|
||||
.SingleOrDefaultAsync(x => x.HeimdallAccountId == request.HeimdallAccountId.Trim(), cancellationToken);
|
||||
|
||||
// A folded account's events record on the survivor and are journalled on the merge, so an undo moves them back.
|
||||
var folded = user is null ? null : await mergeLedger.StandingAsync(user.Id, cancellationToken) as MergeStanding.Folded;
|
||||
|
||||
if (existingEvent is not null)
|
||||
{
|
||||
if (folded is not null && user is not null)
|
||||
{
|
||||
await mergeLedger.JournalIntakeAsync(folded.MergeId, user.Id, existingEvent.Id, cancellationToken);
|
||||
}
|
||||
|
||||
return HeimdallPatronSupportIntakeResult.Processed(
|
||||
$"Already processed {request.Provider} patron support event {request.ProviderEventId}.",
|
||||
existingEvent.Id);
|
||||
}
|
||||
|
||||
var user = await dbContext.UserAccounts
|
||||
.AsNoTracking()
|
||||
.SingleOrDefaultAsync(x => x.HeimdallAccountId == request.HeimdallAccountId.Trim(), cancellationToken);
|
||||
|
||||
if (user is null)
|
||||
{
|
||||
return HeimdallPatronSupportIntakeResult.BadRequest(
|
||||
|
|
@ -85,7 +93,7 @@ public sealed class HeimdallPatronSupportIntakeService(
|
|||
|
||||
var supportEvent = await patronageService.RecordSupportEventAsync(
|
||||
actorUserAccountId: null,
|
||||
userAccountId: await mergeLedger.ResolveAsync(user.Id, cancellationToken), // a folded account's events record on the survivor
|
||||
userAccountId: folded?.SurvivorId ?? user.Id,
|
||||
request.Kind,
|
||||
request.Amount,
|
||||
request.CurrencyCode,
|
||||
|
|
@ -99,6 +107,11 @@ public sealed class HeimdallPatronSupportIntakeService(
|
|||
request.Notes,
|
||||
cancellationToken);
|
||||
|
||||
if (folded is not null)
|
||||
{
|
||||
await mergeLedger.JournalIntakeAsync(folded.MergeId, user.Id, supportEvent.Id, cancellationToken);
|
||||
}
|
||||
|
||||
return HeimdallPatronSupportIntakeResult.Processed(
|
||||
$"Processed {request.Provider} patron support event {request.ProviderEventId}.",
|
||||
supportEvent.Id);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
using System.Globalization;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Patronage;
|
||||
|
|
@ -29,7 +30,7 @@ public sealed record MergePlan(
|
|||
|
||||
/// <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
|
||||
/// save, the undo save, the Final transition and StandingAsync. 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>
|
||||
|
|
@ -40,8 +41,6 @@ public sealed class AccountMergeLedger(
|
|||
{
|
||||
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 =
|
||||
|
|
@ -71,23 +70,6 @@ public sealed class AccountMergeLedger(
|
|||
: 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)
|
||||
{
|
||||
|
|
@ -155,12 +137,12 @@ public sealed class AccountMergeLedger(
|
|||
blocks.Add("already_folded");
|
||||
}
|
||||
|
||||
// Heimdall could no longer reverse a merge this account survived once it is folded into another.
|
||||
// One hop only: a landed merge's survivor never folds into a third account, so an alias is never a chain.
|
||||
if (await dbContext.AccountMerges.AnyAsync(
|
||||
x => x.Id != exceptMergeId && x.State == AccountMergeState.Committed && x.SurvivorUserAccountId == foldedId,
|
||||
x => x.Id != exceptMergeId && FoldedStates.Contains(x.State) && x.SurvivorUserAccountId == foldedId,
|
||||
cancellationToken))
|
||||
{
|
||||
blocks.Add("folded_survivor_in_grace");
|
||||
blocks.Add("folded_is_survivor");
|
||||
}
|
||||
|
||||
if (await dbContext.SealedBallots.AnyAsync(
|
||||
|
|
@ -212,6 +194,7 @@ public sealed class AccountMergeLedger(
|
|||
await RestageTiersAsync(reduction.Survivor, reduction.Folded, now, cancellationToken);
|
||||
}
|
||||
|
||||
reduction.ReweighMovedVotes();
|
||||
merge.State = AccountMergeState.Committed;
|
||||
merge.CommittedUtc = now;
|
||||
merge.GraceEndsUtc = now + Grace;
|
||||
|
|
@ -240,6 +223,11 @@ public sealed class AccountMergeLedger(
|
|||
throw new InvalidOperationException($"Merge {mergeId} is {merge.State}; only a HeimdallReversed merge can be undone locally.");
|
||||
}
|
||||
|
||||
if (merge.FinalizedUtc is not null)
|
||||
{
|
||||
throw new InvalidOperationException($"Merge {mergeId} is Final; a merge is never undone past Final.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var now = timeProvider.GetUtcNow();
|
||||
|
|
@ -264,7 +252,7 @@ public sealed class AccountMergeLedger(
|
|||
AtUtc = now
|
||||
});
|
||||
|
||||
foreach (var entry in journal.Where(x => x.Action is AccountMergeEntryAction.Voided or AccountMergeEntryAction.Moved or AccountMergeEntryAction.Closed or AccountMergeEntryAction.Suspended))
|
||||
foreach (var entry in journal.Where(x => x.Action is AccountMergeEntryAction.Voided or AccountMergeEntryAction.Moved or AccountMergeEntryAction.Closed or AccountMergeEntryAction.Suspended or AccountMergeEntryAction.Created))
|
||||
{
|
||||
switch (entry.Kind, entry.Action)
|
||||
{
|
||||
|
|
@ -288,6 +276,10 @@ public sealed class AccountMergeLedger(
|
|||
if (restore)
|
||||
{
|
||||
vote!.UserAccountId = entry.PriorUserAccountId!.Value;
|
||||
if (decimal.TryParse(entry.PriorText, NumberStyles.Number, CultureInfo.InvariantCulture, out var priorWeight))
|
||||
{
|
||||
vote.Weight = priorWeight;
|
||||
}
|
||||
}
|
||||
|
||||
Record(entry, restore);
|
||||
|
|
@ -313,7 +305,9 @@ public sealed class AccountMergeLedger(
|
|||
if (restore)
|
||||
{
|
||||
row!.UserAccountId = entry.PriorUserAccountId!.Value;
|
||||
row.VoterKey = entry.PriorText ?? row.VoterKey;
|
||||
var (priorClass, priorKey) = ParseAppraisalPrior(entry.PriorText);
|
||||
row.VoterKey = priorKey ?? row.VoterKey;
|
||||
row.VoterClass = priorClass ?? row.VoterClass;
|
||||
}
|
||||
|
||||
Record(entry, restore);
|
||||
|
|
@ -345,6 +339,19 @@ public sealed class AccountMergeLedger(
|
|||
Record(entry, restore);
|
||||
break;
|
||||
}
|
||||
case (AccountMergeEntryKind.Standing, AccountMergeEntryAction.Created):
|
||||
{
|
||||
// The membership this merge made to carry a suspension goes with the merge, unless an admin has taken it over since.
|
||||
var created = await dbContext.Memberships.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
|
||||
var restore = created is { Status: MembershipStatus.Suspended } && created.SuspensionReason == SuspensionReason(mergeId);
|
||||
if (restore)
|
||||
{
|
||||
dbContext.Memberships.Remove(created!);
|
||||
}
|
||||
|
||||
Record(entry, restore);
|
||||
break;
|
||||
}
|
||||
case (AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved):
|
||||
{
|
||||
var row = await dbContext.PatronSupportEvents.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
|
||||
|
|
@ -378,20 +385,62 @@ public sealed class AccountMergeLedger(
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Committed merges whose grace has ended become Final; returns how many. Undo is never allowed past Final.</summary>
|
||||
/// <summary>
|
||||
/// Committed merges whose grace has ended become Final; returns how many this call finalized. Undo is never allowed past Final.
|
||||
/// State is the merge's concurrency token, so a merge another writer moved first (UndoRequested) fails its save and is left to that
|
||||
/// transition: a stale Committed read can never overwrite it.
|
||||
/// </summary>
|
||||
public async Task<int> FinalizeDueAsync(DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var due = await dbContext.AccountMerges
|
||||
var dueIds = await dbContext.AccountMerges.AsNoTracking()
|
||||
.Where(x => x.State == AccountMergeState.Committed && x.GraceEndsUtc <= now)
|
||||
.Select(x => x.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
foreach (var merge in due)
|
||||
var finalized = 0;
|
||||
foreach (var id in dueIds)
|
||||
{
|
||||
var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == id, cancellationToken);
|
||||
if (merge.State != AccountMergeState.Committed)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
merge.State = AccountMergeState.Final;
|
||||
merge.FinalizedUtc = now;
|
||||
try
|
||||
{
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
finalized++;
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
dbContext.ChangeTracker.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
return finalized;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Journals a patron event that landed on a folded account's survivor during grace, so undo moves it back with the rest. Idempotent:
|
||||
/// the intake calls it again when the provider retries an event it already processed.
|
||||
/// </summary>
|
||||
public async Task JournalIntakeAsync(Guid mergeId, Guid foldedUserAccountId, Guid supportEventId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await dbContext.AccountMergeEntries.AnyAsync(
|
||||
x => x.MergeId == mergeId && x.Kind == AccountMergeEntryKind.PatronSupportEvent && x.RecordId == supportEventId,
|
||||
cancellationToken))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var seq = await dbContext.AccountMergeEntries.Where(x => x.MergeId == mergeId).MaxAsync(x => (int?)x.Seq, cancellationToken) ?? 0;
|
||||
dbContext.AccountMergeEntries.Add(Journal(
|
||||
mergeId,
|
||||
seq + 1,
|
||||
new MergePlanEntry(AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved, supportEventId, foldedUserAccountId),
|
||||
timeProvider.GetUtcNow()));
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return due.Count;
|
||||
}
|
||||
|
||||
private sealed class Reduction(
|
||||
|
|
@ -399,6 +448,7 @@ public sealed class AccountMergeLedger(
|
|||
UserAccount folded,
|
||||
List<MergePlanEntry> entries,
|
||||
List<Action<Guid, DateTimeOffset>> effects,
|
||||
List<Vote> movedVotes,
|
||||
bool movedPatronEvents)
|
||||
{
|
||||
public UserAccount Survivor { get; } = survivor;
|
||||
|
|
@ -411,6 +461,15 @@ public sealed class AccountMergeLedger(
|
|||
|
||||
public Guid MergeId { get; set; }
|
||||
|
||||
/// <summary>A moved vote carries the survivor's weight, derived once from the survivor's tiers as they stand after the restage, never the folded account's.</summary>
|
||||
public void ReweighMovedVotes()
|
||||
{
|
||||
foreach (var vote in movedVotes)
|
||||
{
|
||||
vote.Weight = Survivor.Membership!.EffectiveVotingWeight;
|
||||
}
|
||||
}
|
||||
|
||||
public void Apply(DateTimeOffset now)
|
||||
{
|
||||
foreach (var effect in effects)
|
||||
|
|
@ -428,25 +487,43 @@ public sealed class AccountMergeLedger(
|
|||
/// </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)
|
||||
var survivor = await dbContext.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.PatronSupportEvents)
|
||||
.SingleAsync(x => x.Id == survivorId, cancellationToken);
|
||||
var folded = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
|
||||
var folded = await dbContext.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.PatronSupportEvents)
|
||||
.SingleAsync(x => x.Id == foldedId, cancellationToken);
|
||||
|
||||
var entries = new List<MergePlanEntry>();
|
||||
var effects = new List<Action<Guid, DateTimeOffset>>();
|
||||
var movedVotes = new List<Vote>();
|
||||
|
||||
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)
|
||||
if (foldedSuspended && !survivorSuspendedNow)
|
||||
{
|
||||
entries.Add(new MergePlanEntry(AccountMergeEntryKind.Standing, AccountMergeEntryAction.Suspended, survivorMembership.Id, null, survivorMembership.Status.ToString()));
|
||||
effects.Add((id, _) =>
|
||||
if (survivor.Membership is { } survivorMembership)
|
||||
{
|
||||
survivorMembership.Status = MembershipStatus.Suspended;
|
||||
survivorMembership.SuspensionReason = SuspensionReason(id);
|
||||
});
|
||||
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);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
// The chat tier holds no membership, and an absent one chats: without a row the suspension would be gone. The row is journalled so undo removes it.
|
||||
var created = new Bifrost.Web.Domain.Membership { UserAccountId = survivor.Id, Status = MembershipStatus.Suspended };
|
||||
entries.Add(new MergePlanEntry(AccountMergeEntryKind.Standing, AccountMergeEntryAction.Created, created.Id));
|
||||
effects.Add((id, now) =>
|
||||
{
|
||||
created.SuspensionReason = SuspensionReason(id);
|
||||
created.CreatedAtUtc = now;
|
||||
created.Notes = "Created by an account merge to carry the folded account's suspension.";
|
||||
dbContext.Memberships.Add(created);
|
||||
});
|
||||
}
|
||||
|
||||
survivorStanding = MembershipStatus.Suspended;
|
||||
}
|
||||
|
||||
|
|
@ -478,7 +555,8 @@ public sealed class AccountMergeLedger(
|
|||
}
|
||||
else
|
||||
{
|
||||
entries.Add(new MergePlanEntry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved, vote.Id, vote.UserAccountId, null, vote.CastAtUtc));
|
||||
entries.Add(new MergePlanEntry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved, vote.Id, vote.UserAccountId, vote.Weight.ToString(CultureInfo.InvariantCulture), vote.CastAtUtc));
|
||||
movedVotes.Add(vote);
|
||||
effects.Add((_, _) => vote.UserAccountId = survivorId);
|
||||
}
|
||||
}
|
||||
|
|
@ -502,11 +580,12 @@ public sealed class AccountMergeLedger(
|
|||
}
|
||||
else
|
||||
{
|
||||
entries.Add(new MergePlanEntry(AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved, appraisal.Id, appraisal.UserAccountId, appraisal.VoterKey, appraisal.CastAtUtc));
|
||||
entries.Add(new MergePlanEntry(AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved, appraisal.Id, appraisal.UserAccountId, $"{appraisal.VoterClass}|{appraisal.VoterKey}", appraisal.CastAtUtc));
|
||||
effects.Add((_, _) =>
|
||||
{
|
||||
appraisal.UserAccountId = survivorId;
|
||||
appraisal.VoterKey = survivorKey;
|
||||
appraisal.VoterClass = VoterClass.Member; // the survivor is Active here, which is what makes an account a Member voter
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -518,7 +597,7 @@ public sealed class AccountMergeLedger(
|
|||
effects.Add((_, _) => supportEvent.UserAccountId = survivorId);
|
||||
}
|
||||
|
||||
var reduction = new Reduction(survivor, folded, entries, effects, foldedEvents.Count > 0);
|
||||
var reduction = new Reduction(survivor, folded, entries, effects, movedVotes, foldedEvents.Count > 0);
|
||||
if (mergeId is { } m)
|
||||
{
|
||||
reduction.MergeId = m;
|
||||
|
|
@ -538,7 +617,7 @@ public sealed class AccountMergeLedger(
|
|||
|
||||
private async Task StageIfMembershipAsync(Bifrost.Web.Domain.Membership? membership, IEnumerable<PatronSupportEvent> events, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
if (membership is not null)
|
||||
if (membership is not null && dbContext.Entry(membership).State != EntityState.Deleted)
|
||||
{
|
||||
await patronageService.StageTierSnapshotAsync(membership, events, now, cancellationToken);
|
||||
}
|
||||
|
|
@ -558,6 +637,12 @@ public sealed class AccountMergeLedger(
|
|||
};
|
||||
|
||||
private static string AppraisalKey(Guid accountId) => "account:" + accountId.ToString("N");
|
||||
|
||||
private static (VoterClass? Class, string? Key) ParseAppraisalPrior(string? prior)
|
||||
{
|
||||
var split = prior?.IndexOf('|') ?? -1;
|
||||
return split > 0 && Enum.TryParse<VoterClass>(prior![..split], out var voterClass) ? (voterClass, prior[(split + 1)..]) : (null, null);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Finalizes merges past their grace every five minutes. Copies the SealedBallotCloser shape: a new scope per tick, a warning on failure.</summary>
|
||||
|
|
|
|||
|
|
@ -49,6 +49,12 @@ public sealed class MembershipSuspensionService(BifrostDbContext dbContext, Audi
|
|||
return SuspensionOutcome.NoSuchAccount;
|
||||
}
|
||||
|
||||
// A merged account is terminal: only the merge ledger leaves that status, so neither suspending nor lifting applies.
|
||||
if (membership.IsMerged)
|
||||
{
|
||||
return SuspensionOutcome.NotApplicable;
|
||||
}
|
||||
|
||||
// An admin cannot suspend themselves or another platform admin here (the same derivation that makes an actor an admin):
|
||||
// bootstrap admins are re-promoted to Active at sign-in by configuration, so the suspension would be undone without a receipt.
|
||||
if (suspend && (user.Id == actor.UserAccount.Id || new CurrentBifrostActor(true, user).IsPlatformAdmin))
|
||||
|
|
|
|||
|
|
@ -67,6 +67,11 @@ public sealed class MembershipSynchronizationService(
|
|||
|
||||
dbContext.UserAccounts.Add(userAccount);
|
||||
}
|
||||
else if (userAccount.Membership is { IsMerged: true })
|
||||
{
|
||||
// A folded account is terminal: sign-in rewrites nothing on it (the actor gate already makes it act as nobody).
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
userAccount.GitHubLogin = gitHubLogin;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Membership;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
|
|
@ -52,6 +53,13 @@ public sealed class MotionGovernanceService(
|
|||
CancellationToken cancellationToken)
|
||||
{
|
||||
var actorUser = actor.UserAccount ?? throw new UnauthorizedAccessException("A linked Bifrost actor is required.");
|
||||
|
||||
// An actor resolved before a merge froze this account must not write a vote after it: standing is read again at the write.
|
||||
if (await AccountMergeLedger.StandingAsync(dbContext, actorUser.Id, cancellationToken) is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var motion = await dbContext.Motions
|
||||
.Include(x => x.Votes)
|
||||
.SingleAsync(x => x.Id == motionId, cancellationToken);
|
||||
|
|
|
|||
|
|
@ -194,6 +194,12 @@ public static class OidcEndpoints
|
|||
return null;
|
||||
}
|
||||
|
||||
// A folded or frozen subject's live token acts as nobody on the desk too: the same standing the cookie gate and ChatRefusalAsync read.
|
||||
if (await AccountMergeLedger.StandingAsync(db, accountId, cancellationToken) is not null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var account = await db.UserAccounts.AsNoTracking()
|
||||
.Include(x => x.Membership)
|
||||
.SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken);
|
||||
|
|
|
|||
|
|
@ -55,12 +55,18 @@ public sealed class ApplicationBootstrapper(
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// The one bootstrap-admin promotion, used at startup and at sign-in. A Suspended account is left exactly as it is (an admin's
|
||||
/// The one bootstrap-admin promotion, used at startup and at sign-in. A Merged or Suspended account is left exactly as it is (an admin's
|
||||
/// decision; only the suspension service lifts it) and the refusal is logged by account id. Returns whether it promoted.
|
||||
/// </summary>
|
||||
public static bool TryPromoteBootstrapAdmin(UserAccount account, DateTimeOffset now, ILogger logger)
|
||||
{
|
||||
var membership = account.Membership!;
|
||||
if (membership.IsMerged)
|
||||
{
|
||||
logger.LogWarning("Bootstrap admin promotion skipped for merged account {UserAccountId}.", account.Id);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (membership.Status == MembershipStatus.Suspended)
|
||||
{
|
||||
logger.LogWarning("Bootstrap admin promotion skipped for suspended account {UserAccountId}.", account.Id);
|
||||
|
|
|
|||
|
|
@ -37,6 +37,8 @@ public sealed class IndexModel(
|
|||
internal const string ApproveSuspendedNotice = "Nothing changed: a suspended account can only be lifted with Unsuspend.";
|
||||
/// <summary>Admin-only text for a Suspended row whose reason predates the SuspensionReason column; the old text is never read back from the audit trail.</summary>
|
||||
internal const string LegacySuspensionText = "Suspended before reasons were recorded";
|
||||
internal const string ApproveMergedNotice = "Nothing changed: that account was merged into another and cannot be approved.";
|
||||
|
||||
internal const string NoMembershipNotice = "Nothing changed: that account has no membership yet.";
|
||||
internal const string OwnAdminRoleNotice = "Nothing changed: you cannot remove or change your own platform admin role.";
|
||||
internal const string RoleOnSuspendedNotice = "Nothing changed: a suspended account's roles cannot be changed until it is unsuspended.";
|
||||
|
|
@ -136,6 +138,12 @@ public sealed class IndexModel(
|
|||
return RedirectToPage();
|
||||
}
|
||||
|
||||
if (user.Membership.IsMerged)
|
||||
{
|
||||
Notice = ApproveMergedNotice; // only the merge ledger leaves Merged
|
||||
return RedirectToPage();
|
||||
}
|
||||
|
||||
user.Membership.Status = MembershipStatus.Active;
|
||||
user.Membership.ApprovedAtUtc = timeProvider.GetUtcNow();
|
||||
ApplicationBootstrapper.EnsureRole(
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ using Bifrost.Web.Features.Passkeys;
|
|||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
|
|
@ -23,6 +24,7 @@ public sealed class LinkedAccountsModel(
|
|||
HeimdallAuthService heimdallAuthService,
|
||||
LinkedAccountsSnapshots snapshots,
|
||||
PasskeyService passkeys,
|
||||
ICurrentBifrostActorAccessor actors,
|
||||
IOptions<BifrostHostOptions> hostOptions,
|
||||
ILogger<LinkedAccountsModel> logger) : PageModel
|
||||
{
|
||||
|
|
@ -33,6 +35,21 @@ public sealed class LinkedAccountsModel(
|
|||
["google"] = "Google"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// A folded or frozen account manages no logins and enrols no passkey: the page's handlers all begin a Heimdall flow on the
|
||||
/// account's raw claim, so the one gate is here, on the actor accessor's standing, before any handler runs.
|
||||
/// </summary>
|
||||
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
|
||||
{
|
||||
if ((await actors.GetAsync(context.HttpContext.RequestAborted)).Merge is not null)
|
||||
{
|
||||
context.Result = Forbid();
|
||||
return;
|
||||
}
|
||||
|
||||
await base.OnPageHandlerExecutionAsync(context, next);
|
||||
}
|
||||
|
||||
private string? AccountId => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 } id ? id : null;
|
||||
|
||||
/// <summary>The wording of the outcome the page was sent back with: a closed set, null for anything else.</summary>
|
||||
|
|
|
|||
|
|
@ -856,7 +856,10 @@ app.MapPost("/auth/heimdall/complete", async (
|
|||
held.Value.Value,
|
||||
form?["code"].ToString(),
|
||||
form?["pendingLinkId"].ToString(),
|
||||
httpContext.User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId),
|
||||
// A folded or frozen account links nothing: the actor accessor's standing decides, not the raw claim.
|
||||
(await httpContext.RequestServices.GetRequiredService<ICurrentBifrostActorAccessor>().GetAsync(cancellationToken)).Merge is null
|
||||
? httpContext.User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId)
|
||||
: null,
|
||||
cancellationToken);
|
||||
if (step.Next is not null)
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue