Update surviving tests and docs for AccountMerge teardown

This commit is contained in:
Meta Vens 2026-12-03 21:36:21 +01:00
commit 425ceb75b9
14 changed files with 7 additions and 429 deletions

View file

@ -57,15 +57,3 @@
- If a question is about trust, accountability, or payout fairness, prefer auditability over automation.
- If a question is about public work crossing GitHub, Discord, Reddit, CultNet/CultCache intake, or future collaboration surfaces, prefer Bifrost-owned requests, receipts, and routing over local helper sprawl.
- Before debugging UI/layout, inspect the live DOM and computed styles instead of guessing from templates or CSS intent.
## Live Postgres tests
Most tests run on the in-memory EF provider, which enforces no unique index, transaction, concurrency token or trigger. The tests that need a real server (`tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs`: commit atomicity, the `(MergeId, Seq)` unique index, the sweeper racing the saga, overlapping merges refused by the database, the one-current-Patron-snapshot index under racing restages, the intake journal `Seq`, the write gate's shared lock racing a merge's freeze and commit, the migration's roll-forward-only guard) run only when `BIFROST_TEST_PG` holds a connection string with no `Database=`, for a role that may create databases; otherwise they are skipped with that reason. Each test creates its own database, builds it through the real migrations and the class drops it, so point the variable at a disposable server:
```bash
BIFROST_TEST_PG='Host=127.0.0.1;Port=54329;Username=postgres' dotnet test tests/Bifrost.Web.Tests --filter FullyQualifiedName~AccountMergePostgresTests
```
## Account merges are roll-forward only
Once any `AccountMerges` row exists, do not deploy a build older than the `AddAccountMerges` migration, and do not revert that migration: an older build cannot read the `Merged` membership status and counts voided votes again. `Down` refuses while any merge row exists. Fix forward (`heimdall-body:ruling:merge-roll-forward-only`, `docs/account-merge.md` Rollback). Any deploy list that names a rollback must say so.

View file

@ -277,8 +277,7 @@ COMMIT;
Then point `/srv/bifrost/app/current` at the previous release and start it, as in Rollback. Go **only this far**: the same release
also brings `AddAccountMergeSaga`, whose `Down` refuses while any merge row exists, so never roll
the schema back past `20261114140000_AddAccountMergeNoticeAcks` once a merge has been made. The live-PG test
`Reverting_the_migration_is_refused_while_any_merge_exists` pins that refusal and the `Down` through `AddChatInvites`.
the schema back past `20261114140000_AddAccountMergeNoticeAcks` once a merge has been made.
## What this plan does not do

View file

@ -47,7 +47,7 @@ A link refused because the login already belongs to another account (`409 identi
## Not here
- Merging two accounts. A refused link ends there; nothing is moved or merged. Merging is the separate Merge accounts page, behind the `AccountMerge:Enabled` flag (`docs/account-merge.md`, Pages and flags).
- Merging two accounts. A refused link ends there; nothing is moved or merged.
- Step-up through Discord, Patreon or Twitch. Heimdall does not offer it to the `bifrost` profile.
- Linking Twitch or GitHub: not admitted by the `bifrost` profile, and Heimdall's GitHub runtime is not implemented.
- A list of other apps' logins, grants or consent receipts (Heimdall's grants page).
@ -66,5 +66,3 @@ 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

@ -118,7 +118,7 @@ reach chat on their own.
- Redemption has one owner, `ChatInviteService.RedeemCarriedAsync`, called after the Heimdall completion signs in and after native
registration signs in. A request carrying the cookie spends the invite onto the signed-in account (`ChatInvitedAtUtc`, `RedeemedByUserAccountId`)
in one save conditioned on the invite still being unredeemed and unrevoked, so of two accounts racing for one link one loses. The cookie
is cleared either way. An account that is already invited, or `Active`, keeps the invite unspent. GitHub OAuth sign-in redeems nothing, so `/auth/sign-in?provider=github` answers 409 with the sign-ins that do while the cookie is carried. A merge carries no copy of the fact: an account counts as invited while any merge standing into it folded an invited account (`AccountMergeLedger.CarriedInviteAsync`), so undoing merges in any order leaves what the standing merges give.
is cleared either way. An account that is already invited, or `Active`, keeps the invite unspent. GitHub OAuth sign-in redeems nothing, so `/auth/sign-in?provider=github` answers 409 with the sign-ins that do while the cookie is carried.
- Sessions that were open for an uninvited, non-`Active` account end at the logout reconciler's next pass, as for any refusal read by `ChatRefusalAsync`.
## Chat needs a receipt

View file

@ -256,184 +256,6 @@ public sealed class ChatInviteHeimdallTests
}
}
/// <summary>The single-use fact rests on a concurrency token and the migration, which the in-memory provider does not enforce: proven on a real server (skipped without BIFROST_TEST_PG).</summary>
public sealed class ChatInvitePostgresTests(MergePostgres postgres) : IClassFixture<MergePostgres>
{
[PostgresFact]
public async Task Two_accounts_racing_for_one_link_leave_it_with_exactly_one_and_the_token_is_stored_only_hashed()
{
var world = await postgres.NewWorldAsync();
var time = TimeProvider.System;
const string token = "race-token-0123456789";
Guid first, second;
await using (var seed = world.Db())
{
var a = new UserAccount { BifrostIdentity = "racer-a", NormalizedBifrostIdentity = "racer-a", DisplayName = "A" };
var b = new UserAccount { BifrostIdentity = "racer-b", NormalizedBifrostIdentity = "racer-b", DisplayName = "B" };
seed.UserAccounts.AddRange(a, b);
seed.ChatInvites.Add(new ChatInvite { TokenHash = ChatInviteService.Hash(token), Note = "race", IssuedAtUtc = time.GetUtcNow(), ExpiresAtUtc = time.GetUtcNow().AddDays(1) });
await seed.SaveChangesAsync();
(first, second) = (a.Id, b.Id);
}
async Task Redeem(Guid account)
{
await using var db = world.Db();
var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
http.Request.Headers.Cookie = ChatInviteService.CookieName + "=" + token;
var options = Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions());
await new ChatInviteService(db, new Bifrost.Web.Features.Shared.AuditTrailService(db, time), time, options).RedeemCarriedAsync(http, account, CancellationToken.None);
}
await Task.WhenAll(Task.Run(() => Redeem(first)), Task.Run(() => Redeem(second)));
await using var read = world.Db();
var invite = await read.ChatInvites.AsNoTracking().SingleAsync();
Assert.NotNull(invite.RedeemedByUserAccountId);
Assert.Equal(1, await read.UserAccounts.CountAsync(x => x.ChatInvitedAtUtc != null));
Assert.Equal(invite.RedeemedByUserAccountId, (await read.UserAccounts.SingleAsync(x => x.ChatInvitedAtUtc != null)).Id);
Assert.Equal(1, await read.AuditEvents.CountAsync(x => x.Action == "chat.invite.redeemed"));
}
/// <summary>Holds each redemption's save until both have loaded the invite, so the interleave the concurrency token exists for is forced, not left to timing.</summary>
private sealed class BothLoadedBeforeEitherSaves : Microsoft.EntityFrameworkCore.Diagnostics.SaveChangesInterceptor
{
private int _arrived;
private readonly TaskCompletionSource _both = new(TaskCreationOptions.RunContinuationsAsynchronously);
public override async ValueTask<Microsoft.EntityFrameworkCore.Diagnostics.InterceptionResult<int>> SavingChangesAsync(
Microsoft.EntityFrameworkCore.Diagnostics.DbContextEventData eventData,
Microsoft.EntityFrameworkCore.Diagnostics.InterceptionResult<int> result,
CancellationToken cancellationToken = default)
{
if (eventData.Context!.ChangeTracker.Entries<ChatInvite>().Any(x => x.State == EntityState.Modified))
{
if (Interlocked.Increment(ref _arrived) == 2)
{
_both.TrySetResult();
}
await _both.Task.WaitAsync(TimeSpan.FromSeconds(20), cancellationToken);
}
return result;
}
}
[PostgresFact]
public async Task Two_redemptions_that_both_loaded_the_invite_before_either_saved_still_leave_it_with_one()
{
var world = await postgres.NewWorldAsync(new BothLoadedBeforeEitherSaves());
var time = TimeProvider.System;
const string token = "interleave-token-0123456789";
Guid first, second;
await using (var seed = world.Db())
{
var a = new UserAccount { BifrostIdentity = "inter-a", NormalizedBifrostIdentity = "inter-a", DisplayName = "A" };
var b = new UserAccount { BifrostIdentity = "inter-b", NormalizedBifrostIdentity = "inter-b", DisplayName = "B" };
seed.UserAccounts.AddRange(a, b);
seed.ChatInvites.Add(new ChatInvite { TokenHash = ChatInviteService.Hash(token), Note = "interleave", IssuedAtUtc = time.GetUtcNow(), ExpiresAtUtc = time.GetUtcNow().AddDays(1) });
await seed.SaveChangesAsync();
(first, second) = (a.Id, b.Id);
}
async Task Redeem(Guid account)
{
await using var db = world.Db();
var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
http.Request.Headers.Cookie = ChatInviteService.CookieName + "=" + token;
var options = Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions());
await new ChatInviteService(db, new Bifrost.Web.Features.Shared.AuditTrailService(db, time), time, options).RedeemCarriedAsync(http, account, CancellationToken.None);
}
await Task.WhenAll(Task.Run(() => Redeem(first)), Task.Run(() => Redeem(second)));
await using var read = world.Db();
var invite = await read.ChatInvites.AsNoTracking().SingleAsync();
var invited = await read.UserAccounts.Where(x => x.ChatInvitedAtUtc != null).Select(x => x.Id).ToListAsync();
Assert.Single(invited);
Assert.Equal(invite.RedeemedByUserAccountId, invited[0]);
Assert.Equal(1, await read.AuditEvents.CountAsync(x => x.Action == "chat.invite.redeemed"));
}
}
/// <summary>An account merge leaves the person invited while the merge stands: the fact is read from the merges that stand, never copied, so undo in any order leaves what the surviving merges give.</summary>
public sealed class ChatInviteMergeTests
{
private static readonly DateTimeOffset Early = new(2026, 11, 1, 9, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset Late = new(2026, 11, 10, 9, 0, 0, TimeSpan.Zero);
private static async Task<UserAccount> AccountAsync(AccountMergeLedgerTests.World world, string name, DateTimeOffset? invitedAt = null)
{
var account = await world.AccountAsync(name, MembershipStatus.Authenticated);
if (invitedAt is { } at)
{
await using var db = world.Db();
(await db.UserAccounts.SingleAsync(x => x.Id == account.Id)).ChatInvitedAtUtc = at;
await db.SaveChangesAsync();
}
return account;
}
private static async Task<bool> RefusedAsNotInvitedAsync(AccountMergeLedgerTests.World world, UserAccount account)
{
await using var db = world.Db();
return await Bifrost.Web.Features.Oidc.OidcEndpoints.ChatRefusalAsync(db, account.Id.ToString(), default) == Bifrost.Web.Features.Oidc.OidcEndpoints.NotInvitedDescription;
}
private static async Task UndoAsync(AccountMergeLedgerTests.World world, AccountMerge merge)
{
await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed);
await using var db = world.Db();
await world.Ledger(db).UndoLocalAsync(merge.Id, default);
}
[Fact]
public async Task An_invited_account_folded_into_an_uninvited_survivor_leaves_the_person_invited_until_the_merge_is_undone()
{
var world = new AccountMergeLedgerTests.World();
var survivor = await AccountAsync(world, "survivor");
var folded = await AccountAsync(world, "folded", Early);
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
Assert.False(await RefusedAsNotInvitedAsync(world, survivor));
await UndoAsync(world, merge);
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
}
[Fact]
public async Task A_folded_account_that_was_never_invited_gives_the_survivor_nothing()
{
var world = new AccountMergeLedgerTests.World();
var survivor = await AccountAsync(world, "survivor");
var folded = await AccountAsync(world, "folded");
await world.CommitAsync(await world.MergeAsync(survivor, folded));
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Two_invited_accounts_merged_into_one_survivor_undone_in_either_order_leave_the_survivor_uninvited(bool earlierMergeFirst)
{
var world = new AccountMergeLedgerTests.World();
var survivor = await AccountAsync(world, "survivor");
var late = await AccountAsync(world, "late", Late);
var early = await AccountAsync(world, "early", Early);
var first = await world.CommitAsync(await world.MergeAsync(survivor, late));
var second = await world.CommitAsync(await world.MergeAsync(survivor, early));
await UndoAsync(world, earlierMergeFirst ? first : second);
Assert.False(await RefusedAsNotInvitedAsync(world, survivor)); // the other merge still stands
await UndoAsync(world, earlierMergeFirst ? second : first);
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
}
}
public static class InviteRequests
{
/// <summary>What a browser sends from the landing page's form under its Referrer-Policy: same-origin: the site's Origin and Sec-Fetch-Site: same-origin.</summary>

View file

@ -889,33 +889,6 @@ public sealed class HeimdallCompletionTests
Assert.Equal(rolesBefore, after.RoleAssignments.Count);
}
[Fact]
public async Task A_merged_account_stays_merged_through_a_sign_in_with_the_member_claim()
{
using var host = new HeimdallHost();
var foldedId = HeimdallShapes.NewAccountId();
var survivorId = HeimdallShapes.NewAccountId();
Assert.True((await Genuine(host, await host.StartAsync(member: true), foldedId, ["member_access"])).SignedIn);
Assert.True((await Genuine(host, await host.StartAsync(member: true), survivorId, ["member_access"])).SignedIn);
await host.Db(async db =>
{
var folded = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == foldedId);
var survivor = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == survivorId);
var merge = new AccountMerge { SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = folded.Id, State = AccountMergeState.HeimdallMoved, CreatedUtc = DateTimeOffset.UtcNow };
db.AccountMerges.Add(merge);
await db.SaveChangesAsync();
var clock = TimeProvider.System;
await new AccountMergeLedger(db, new PatronageService(db, new AuditTrailService(db, clock), clock), clock).CommitAsync(merge.Id, default);
return 0;
});
Assert.Equal(MembershipStatus.Merged, (await host.Account(foldedId))!.Membership!.Status);
var again = await Genuine(host, await host.StartAsync(member: true), foldedId, ["member_access"]);
Assert.True(again.SignedIn); // the login still completes; it is the actor gate that makes it act as nobody
Assert.Equal(MembershipStatus.Merged, (await host.Account(foldedId))!.Membership!.Status);
}
[Fact]
public async Task A_legacy_account_without_a_membership_row_signs_in_and_gets_one()
{
@ -936,54 +909,6 @@ public sealed class HeimdallCompletionTests
Assert.Equal(MembershipStatus.Active, (await host.Account(accountId))!.Membership!.Status);
}
[Theory]
[InlineData(AccountMergeState.Confirmed)]
[InlineData(AccountMergeState.Committed)]
public async Task A_chat_tier_account_without_a_membership_that_a_merge_froze_or_folded_signs_in_without_getting_one(AccountMergeState state)
{
using var host = new HeimdallHost();
var foldedId = HeimdallShapes.NewAccountId();
var survivorId = HeimdallShapes.NewAccountId();
Assert.True((await Genuine(host, await host.StartAsync(member: false), foldedId)).SignedIn);
Assert.True((await Genuine(host, await host.StartAsync(member: false), survivorId)).SignedIn);
await MergeAsync(host, survivorId, foldedId, state, dropFoldedMembership: true); // a chat-tier account holds none
await Genuine(host, await host.StartAsync(member: true), foldedId, ["member_access"]);
Assert.Null((await host.Account(foldedId))!.Membership);
Assert.Equal(0, await host.Db(db => db.Memberships.CountAsync(x => x.UserAccount.HeimdallAccountId == foldedId)));
}
[Fact]
public async Task A_frozen_accounts_sign_in_with_member_access_does_not_activate_its_membership()
{
using var host = new HeimdallHost();
var foldedId = HeimdallShapes.NewAccountId();
var survivorId = HeimdallShapes.NewAccountId();
Assert.True((await Genuine(host, await host.StartAsync(member: false), foldedId)).SignedIn);
Assert.True((await Genuine(host, await host.StartAsync(member: false), survivorId)).SignedIn);
await MergeAsync(host, survivorId, foldedId, AccountMergeState.HeimdallMoved, dropFoldedMembership: false);
await Genuine(host, await host.StartAsync(member: true), foldedId, ["member_access"]);
Assert.Equal(MembershipStatus.Authenticated, (await host.Account(foldedId))!.Membership!.Status);
}
private static Task MergeAsync(HeimdallHost host, string survivorId, string foldedId, AccountMergeState state, bool dropFoldedMembership) =>
host.Db(async db =>
{
if (dropFoldedMembership)
{
db.Memberships.RemoveRange(db.Memberships.Where(x => x.UserAccount.HeimdallAccountId == foldedId));
}
var folded = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == foldedId);
var survivor = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == survivorId);
db.AccountMerges.Add(new AccountMerge { SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = folded.Id, State = state, CreatedUtc = DateTimeOffset.UtcNow });
await db.SaveChangesAsync();
return 0;
});
[Fact]
public async Task A_chat_only_account_that_later_signs_in_with_member_access_becomes_a_member()
{

View file

@ -243,31 +243,6 @@ public sealed class HeimdallGoogleLinkTests
AssertAttemptCleared(b.Response, start);
}
[Fact]
public async Task A_link_begun_before_a_merge_froze_the_account_does_not_continue_after_it()
{
using var host = new HeimdallHost(realSessions: true);
var account = HeimdallShapes.NewAccountId();
var survivorAccount = HeimdallShapes.NewAccountId();
var session = await host.SignInSessionAsync(account);
await host.SignInSessionAsync(survivorAccount);
var start = await host.StartLinkAsync(session);
await host.Db(async db =>
{
var folded = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == account);
var survivor = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == survivorAccount);
db.AccountMerges.Add(new AccountMerge { SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = folded.Id, State = AccountMergeState.Confirmed, CreatedUtc = DateTimeOffset.UtcNow });
await db.SaveChangesAsync();
return 0;
});
var starts = host.Heimdall.StartBodies.Count;
var b = await StepB(host, session, start, account);
Assert.Equal(starts, host.Heimdall.StartBodies.Count); // no Google link was asked for on the frozen account
Assert.Equal(LinkedPage + "?result=error", Location(b.Response));
}
[Fact]
public async Task A_session_of_another_account_cannot_continue_the_link()
{
@ -566,7 +541,7 @@ public sealed class HeimdallGoogleLinkTests
}
[Theory]
[InlineData("11")]
[InlineData("9")]
[InlineData("-1")]
[InlineData("99")]
public async Task An_attempt_cookie_with_an_undefined_purpose_is_no_attempt_and_asks_Heimdall_for_nothing(string purpose)

View file

@ -26,7 +26,6 @@ public sealed class HeimdallRedirectTests
[InlineData(typeof(HeimdallAuthService), 302)]
[InlineData(typeof(HeimdallMemberClient), 307)]
[InlineData(typeof(HeimdallMemberClient), 302)]
[InlineData(typeof(HeimdallIdentityMoveClient), 307)]
public async Task A_redirect_from_Heimdall_is_not_followed_and_no_secret_or_bearer_reaches_the_other_host(Type client, int code)
{
int first = FreePort(), second = FreePort();

View file

@ -33,6 +33,7 @@ public sealed class MigrationDiscoveryTests
"20261114130000_AddAccountMergeSaga",
"20261114140000_AddAccountMergeNoticeAcks",
"20261127120000_AddChatInvites",
"20261203120000_DropAccountMergeTables",
];
// Database.GetMigrations() reads assembly metadata only; no connection is opened.

View file

@ -121,33 +121,6 @@ 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,34 +95,6 @@ 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()
{

View file

@ -272,45 +272,6 @@ public sealed class SealedBallotTests
Assert.Equal(1, await rig.Db.AuditEvents.CountAsync(x => x.Action == "sealed.closed"));
}
private static async Task FreezeAsync(Rig rig, CurrentBifrostActor folded)
{
var survivor = rig.Member("Survivor");
rig.Db.AccountMerges.Add(new AccountMerge
{
SurvivorUserAccountId = survivor.UserAccount!.Id, FoldedUserAccountId = folded.UserAccount!.Id, State = AccountMergeState.Confirmed, CreatedUtc = T0
});
await rig.Db.SaveChangesAsync();
}
[Fact]
public async Task A_commit_from_an_actor_resolved_before_the_account_froze_writes_no_ballot()
{
var rig = new Rig();
var motion = await rig.OpenAsync("Ana", "Bo");
var staleActor = rig.Member("Folded"); // resolved before the merge was confirmed
await FreezeAsync(rig, staleActor);
var refusal = await Assert.ThrowsAsync<SealedBallotException>(() => rig.Cast(staleActor, motion.Id, "Ana", "Mine."));
Assert.Equal(SealedBallotFailure.Forbidden, refusal.Failure);
Assert.Empty(rig.Db.SealedBallots);
}
[Fact]
public async Task A_reveal_from_an_actor_resolved_before_the_account_froze_changes_nothing()
{
var rig = new Rig();
var motion = await rig.OpenAsync("Ana", "Bo");
var staleActor = rig.Member("Folded");
await rig.Cast(staleActor, motion.Id, "Ana", "Mine.");
await FreezeAsync(rig, staleActor);
rig.Clock.Now = T0.AddMinutes(90);
var refusal = await Assert.ThrowsAsync<SealedBallotException>(() => rig.Reveal(staleActor, motion.Id, "Ana", "Mine."));
Assert.Equal(SealedBallotFailure.Forbidden, refusal.Failure);
Assert.Null((await rig.Db.SealedBallots.SingleAsync()).RevealedAtUtc);
}
// Runs a callback once, just before the first save that closes a motion: the window between the close reading its ballots and writing.
private sealed class BeforeCloseSave(Func<Task> action) : SaveChangesInterceptor
{

View file

@ -200,11 +200,6 @@ public sealed class FakeHeimdall : HttpMessageHandler
public Exception? JwksFailure { get; set; }
/// <summary>The account model and route of POST /v1/apps/bifrost/identity-moves (the host's clock is <see cref="Now"/>).</summary>
public FakeMoves Moves { get; }
public FakeHeimdall() => Moves = new FakeMoves(() => Now());
public List<string> StartBodies { get; } = [];
public List<string?> StartSecrets { get; } = [];
@ -611,11 +606,6 @@ public sealed class FakeHeimdall : HttpMessageHandler
return StepUpRoute(request, await request.Content!.ReadAsStringAsync(cancellationToken));
}
if (request.Method == HttpMethod.Post && path == "/v1/apps/bifrost/identity-moves")
{
return Moves.Route(request, await request.Content!.ReadAsStringAsync(cancellationToken), RequiredAppSecret);
}
if (path.StartsWith("/v1/me/identities", StringComparison.Ordinal))
{
return MemberRoute(request, path);
@ -740,8 +730,6 @@ public sealed class HeimdallHost : TestWebApplicationFactory
private readonly bool _discordRoles;
private readonly bool _traceHttp;
private readonly bool _realSessions;
private readonly bool _accountMerge;
private readonly string? _chatNoticesToken;
public TestClock Clock { get; } = new();
@ -758,12 +746,8 @@ public sealed class HeimdallHost : TestWebApplicationFactory
bool discordRoles = true,
string appSlug = "bifrost",
bool traceHttp = false,
bool realSessions = false,
bool accountMerge = false,
string? chatNoticesToken = null)
bool realSessions = false)
{
_accountMerge = accountMerge;
_chatNoticesToken = chatNoticesToken;
_traceHttp = traceHttp;
_realSessions = realSessions;
_appSecret = appSecret;
@ -792,16 +776,6 @@ public sealed class HeimdallHost : TestWebApplicationFactory
["Heimdall:DiscordGuildId"] = "guild-1",
["Host:PublicBaseUrl"] = _publicBaseUrl
});
if (_accountMerge)
{
configuration.AddInMemoryCollection(new Dictionary<string, string?> { ["AccountMerge:Enabled"] = "true" });
}
if (_chatNoticesToken is not null)
{
configuration.AddInMemoryCollection(new Dictionary<string, string?> { ["ChatNotices:Token"] = _chatNoticesToken });
}
if (_discordRoles)
{
configuration.AddInMemoryCollection(new Dictionary<string, string?> { ["Heimdall:DiscordAllowedRoleIds:0"] = "role-1" });
@ -830,15 +804,9 @@ public sealed class HeimdallHost : TestWebApplicationFactory
services.RemoveAll<TimeProvider>();
services.AddSingleton<TimeProvider>(Clock);
// The merge sweeper ticks on the wall clock; a host on a manual clock drives the saga itself (AccountMergeSagaTests runs the sweeper's own loop).
foreach (var sweeper in services.Where(x => x.ImplementationType == typeof(Bifrost.Web.Features.Membership.AccountMergeSweeper)).ToList())
{
services.Remove(sweeper);
}
services.AddHttpClient(HeimdallTokenVerifier.ClientName).ConfigurePrimaryHttpMessageHandler(() => Heimdall);
services.AddHttpClient<HeimdallAuthService>().ConfigurePrimaryHttpMessageHandler(() => Heimdall);
services.AddHttpClient<HeimdallMemberClient>().ConfigurePrimaryHttpMessageHandler(() => Heimdall);
services.AddHttpClient<HeimdallIdentityMoveClient>().ConfigurePrimaryHttpMessageHandler(() => Heimdall);
});
}

View file

@ -20,9 +20,6 @@ public class TestWebApplicationFactory : WebApplicationFactory<Program>
private static readonly InMemoryDatabaseRoot _databaseRoot = new();
private readonly string _databaseName = $"bifrost-tests-{Guid.NewGuid():N}";
/// <summary>Armed by a test to crash a chosen save; every context of this host carries it.</summary>
public FaultOnSave Fault { get; } = new();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
@ -62,7 +59,7 @@ public class TestWebApplicationFactory : WebApplicationFactory<Program>
services.AddDbContext<BifrostDbContext>(options =>
{
options.UseInMemoryDatabase(_databaseName, _databaseRoot).AddInterceptors(Fault);
options.UseInMemoryDatabase(_databaseName, _databaseRoot);
});
services.AddAuthentication(options =>