From 51d23f0ba4947d2b5afff9e1cf59cc331754067c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:28:35 +0100 Subject: [PATCH] Relocate HeimdallClientServices and delete AccountMerge files --- docs/account-merge.md | 136 -- .../Configuration/AccountMergeOptions.cs | 13 - .../Configuration/ChatNoticesOptions.cs | 10 - src/Bifrost.Web/Domain/AccountMergeModels.cs | 165 --- .../Features/Heimdall/HeimdallAuthService.cs | 23 + .../Heimdall/HeimdallIdentityMoveClient.cs | 351 ------ .../Features/Membership/AccountMergeLedger.cs | 780 ------------ .../Features/Membership/AccountMergeSaga.cs | 576 --------- .../Membership/MergeNoticeEndpoints.cs | 131 -- .../Features/Membership/MergeNoticeFeed.cs | 96 -- .../Features/Membership/MergePreview.cs | 93 -- .../Features/Membership/MergeProofs.cs | 238 ---- .../Features/Membership/MergeWording.cs | 114 -- src/Bifrost.Web/Pages/App/Merges/Index.cshtml | 72 -- .../Pages/App/Merges/Index.cshtml.cs | 82 -- .../Pages/Membership/MergeAccounts.cshtml | 148 --- .../Pages/Membership/MergeAccounts.cshtml.cs | 270 ---- .../Pages/Membership/MergeStatus.cshtml | 100 -- .../Pages/Membership/MergeStatus.cshtml.cs | 206 --- .../Components/MergeNotice/Default.cshtml | 5 - src/Bifrost.Web/ViewComponents/MergeNotice.cs | 57 - .../AccountMergeHttpTests.cs | 439 ------- .../AccountMergeLedgerTests.cs | 1121 ----------------- .../AccountMergePostgresTests.cs | 981 --------------- .../AccountMergeSagaTests.cs | 732 ----------- .../AccountMergeSettlePageTests.cs | 160 --- .../AccountMergeSettleTests.cs | 292 ----- .../FakeHeimdallMoverTests.cs | 168 --- .../HeimdallIdentityMoveClientTests.cs | 728 ----------- .../MergeAccountsPageTests.cs | 574 --------- .../Bifrost.Web.Tests/MergeNoticeAuthTests.cs | 128 -- .../Bifrost.Web.Tests/MergeNoticeFeedTests.cs | 341 ----- tests/Bifrost.Web.Tests/MergePreviewTests.cs | 106 -- .../MergeProofCompletionTests.cs | 230 ---- tests/Bifrost.Web.Tests/MergeProofsTests.cs | 243 ---- tests/Bifrost.Web.Tests/MergeStatusTests.cs | 222 ---- tests/Bifrost.Web.Tests/MergeUndoPageTests.cs | 255 ---- tests/Bifrost.Web.Tests/MergeWordingTests.cs | 78 -- tests/Bifrost.Web.Tests/Support/FakeMoves.cs | 381 ------ .../Bifrost.Web.Tests/Support/FaultOnSave.cs | 16 - .../Bifrost.Web.Tests/Support/MergePageKit.cs | 45 - 41 files changed, 23 insertions(+), 10883 deletions(-) delete mode 100644 docs/account-merge.md delete mode 100644 src/Bifrost.Web/Configuration/AccountMergeOptions.cs delete mode 100644 src/Bifrost.Web/Configuration/ChatNoticesOptions.cs delete mode 100644 src/Bifrost.Web/Domain/AccountMergeModels.cs delete mode 100644 src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs delete mode 100644 src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs delete mode 100644 src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs delete mode 100644 src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs delete mode 100644 src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs delete mode 100644 src/Bifrost.Web/Features/Membership/MergePreview.cs delete mode 100644 src/Bifrost.Web/Features/Membership/MergeProofs.cs delete mode 100644 src/Bifrost.Web/Features/Membership/MergeWording.cs delete mode 100644 src/Bifrost.Web/Pages/App/Merges/Index.cshtml delete mode 100644 src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs delete mode 100644 src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml delete mode 100644 src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml.cs delete mode 100644 src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml delete mode 100644 src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml.cs delete mode 100644 src/Bifrost.Web/Pages/Shared/Components/MergeNotice/Default.cshtml delete mode 100644 src/Bifrost.Web/ViewComponents/MergeNotice.cs delete mode 100644 tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs delete mode 100644 tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs delete mode 100644 tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs delete mode 100644 tests/Bifrost.Web.Tests/AccountMergeSagaTests.cs delete mode 100644 tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs delete mode 100644 tests/Bifrost.Web.Tests/AccountMergeSettleTests.cs delete mode 100644 tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs delete mode 100644 tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs delete mode 100644 tests/Bifrost.Web.Tests/MergeAccountsPageTests.cs delete mode 100644 tests/Bifrost.Web.Tests/MergeNoticeAuthTests.cs delete mode 100644 tests/Bifrost.Web.Tests/MergeNoticeFeedTests.cs delete mode 100644 tests/Bifrost.Web.Tests/MergePreviewTests.cs delete mode 100644 tests/Bifrost.Web.Tests/MergeProofCompletionTests.cs delete mode 100644 tests/Bifrost.Web.Tests/MergeProofsTests.cs delete mode 100644 tests/Bifrost.Web.Tests/MergeStatusTests.cs delete mode 100644 tests/Bifrost.Web.Tests/MergeUndoPageTests.cs delete mode 100644 tests/Bifrost.Web.Tests/MergeWordingTests.cs delete mode 100644 tests/Bifrost.Web.Tests/Support/FakeMoves.cs delete mode 100644 tests/Bifrost.Web.Tests/Support/FaultOnSave.cs delete mode 100644 tests/Bifrost.Web.Tests/Support/MergePageKit.cs diff --git a/docs/account-merge.md b/docs/account-merge.md deleted file mode 100644 index 67e224b..0000000 --- a/docs/account-merge.md +++ /dev/null @@ -1,136 +0,0 @@ -# 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. The ledger owns what a merge does to Bifrost records; the saga (below) owns the merge's lifecycle around it and every Heimdall call. The member's pages are in Pages and flags below; with `AccountMerge:Enabled` false (the default) no page can start a merge. - -## 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 | - -An alias is one hop: a landed merge's survivor never folds into a third account (the `folded_is_survivor` block), so a folded account's survivor is always the account that carries the person. Every patron event is recorded through `PatronageService.RecordSupportEventAsync`, which writes through the gate below: an event for a folded account (Heimdall intake, Stripe webhook, the admin Ledger's manual record) records on the survivor and is journalled in the same save, so an undo moves it back; a provider retry returns the stored event and journals it once if it sits 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. The same standing is read at the other doors: the desk bearer door (`ActiveMemberIdAsync`) refuses a Frozen or Folded subject, the linked-accounts page and the link step of Heimdall completion refuse one (no login linked or unlinked, no passkey enrolled while the saga moves them), and every writer reads it again at the write, through the gate below, so an actor resolved before the merge froze the account writes nothing after it. - -## 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_is_survivor`, `sealed_ballot_pending`. The database backs the two overlap blocks the plan checks first (check-then-act): a partial unique index lets an account be folded by one live merge only (Confirmed through HeimdallReversed), and a trigger refuses a live merge whose survivor is another live merge's folded account, taking advisory locks on both accounts so racing transactions serialise. - -`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 )`. A survivor without a membership row (the chat tier holds none) is given a Suspended one, journalled as `Standing`/`Created`, because an absent membership chats and the next member-access claim would create an Active one; undo removes it unless an admin has taken it over since. -- **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 cast time and takes the survivor's weight, derived from the survivor's tiers after the patron events moved (the folded weight is journalled for undo); 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:` as a Member voter if the survivor is Active, else it is voided (the prior class and key are journalled). -- **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 (only `PatronageService` writes Patron snapshots, so a merge with no folded events leaves both tiers as they were). - -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`, one save per merge; `AccountMergeSweeper` runs it every 30 seconds, after the saga's due steps (see Saga). `State` is the merge's concurrency token, so a transition computed from a stale read (the sweeper's Final over the saga's UndoRequested, or the reverse) fails its save and the other transition stands; the sweep skips a merge it lost. `UndoLocalAsync` also refuses a merge with `FinalizedUtc` set: undo is never allowed past Final. - -## Saga - -`Features/Membership/AccountMergeSaga.cs` is the one owner of the merge row's lifecycle outside the ledger's Committed, Final and Undone, and the only caller of `HeimdallIdentityMoveClient.MoveAsync` (whose closed `Moved`/`Refused`/`Unknown` answer it consumes as is; the client retries nothing). It writes Confirmed, HeimdallMoved, Failed, UndoRequested and HeimdallReversed, the return UndoRequested to Committed, the move ids and the sealed proofs; it never writes a vote, membership or journal row (it calls `CommitAsync` and `UndoLocalAsync`), reads no standing of its own, and never judges a proof's tier or freshness (Heimdall's). - -| State | Written by | Key and proofs | A crash here | -| --- | --- | --- | --- | -| Confirmed | `ConfirmAsync`: one insert, the consent record | `HeimdallMoveId` minted (random, never derived from the merge id); both sides' Heimdall bearers sealed | Before the insert nothing exists. After it the sweep calls Heimdall with the stored id; a lost answer replays to the same receipt, because Heimdall answers a replay before it judges liveness. | -| HeimdallMoved | `AdvanceAsync` on `Moved`, one save | proofs wiped; receipt tiers and moved login ids stored | `CommitAsync` is total and idempotent; the sweep retries it. | -| Failed | `AdvanceAsync` on any `Refused` | proofs wiped; `FailureCode` is Heimdall's code | Terminal. Heimdall applied nothing, Bifrost changed nothing, the folded account stands as before. | -| Committed | ledger `CommitAsync`, one save with every reduction | grace 7 days | A crash before the save leaves HeimdallMoved. | -| UndoRequested | `RequestUndoAsync`: the survivor, fresh survivor proofs, inside the grace | `HeimdallReverseMoveId` minted; survivor bearers sealed | The sweep replays the reversal (past the grace too). A refused reversal returns the merge to Committed, proofs wiped, `LastOutcome` `undo_`. | -| HeimdallReversed | `AdvanceAsync` on the reversal's `Moved` | proofs wiped | `UndoLocalAsync` is retried. | -| Undone, Final | ledger | | | - -`AdvanceAsync(mergeId)` is the one step function: the confirm's inline advance, the sweeper's resume and an undo request all run it, forward move and reversal alike (same seal, same outcome handling, same backoff). Every transition is one save guarded by `State`, the concurrency token; the loser of a race clears its tracker, reloads and continues from the stored state, so two advances make one Heimdall move and one commit. `Proposed` is declared by the ledger and written by nobody in this cut. - -`ConfirmAsync` refuses (writing nothing) a third-party actor (`NotParty`), a plan with blocks (`Blocked`, codes only), a plan other than the one the member saw (`PreviewStale`: `MergePlan.Digest(survivorId, foldedId)`, a SHA-256 over a length-prefixed canonical text of the plan), and any proof of another Heimdall account (`ProofAccountMismatch`). A second live merge folding the same account, or a chain, is refused by the database (the live-merge unique index and the chain trigger) and answered `Blocked(merge_in_flight)`. Confirm and the undo request run through `AccountMergeLedger.WriteAsAsync` for the acting member, like every writer that acts for an account. - -**Heimdall down.** `Unknown` (a timeout, a 5xx, a 429, an unrecognised 4xx, `move_id_conflict`) never fails a merge: the saga counts `Attempts`, sets `NextAttemptUtc` (15 s, 1 min, 5 min, then 15 min) and replays the same stored id; the folded account stays Frozen until Heimdall answers. Heimdall's answer to a replay of a move it already stored does not depend on the proofs' age, but a move that never reached Heimdall does: an outage longer than the proofs' freshness (300 s for a login's weak proof, 600 s for a passkey's strong one) ends, when Heimdall is back, in `Refused proof_stale` and a Failed merge; the member confirms again with fresh sign-ins. A replay whose proofs no longer verify (Heimdall's key regenerated) answers `move_id_conflict` and stays Unknown; a receipt that names an account other than the destination is `receipt_mismatch` (proofs wiped, no retry); a sealed payload the key ring can no longer open is `proofs_unreadable` (retried in an hour, state unchanged, because Heimdall may already have moved). None of the three ends by itself: see Stuck merges. - -**Sealed proofs.** The saga holds the two Heimdall bearers (`ruling merge-sealed-proofs-until-move-final`) only between Confirmed (or UndoRequested) and Heimdall's final answer: protected with Data Protection (purpose `Bifrost.AccountMerge.Proofs.v1`), never logged, wiped in the save that records Moved or Refused. Logs name the merge id, state, outcome class and refusal code; never a token, account id, identity id or provider user id. Proof coverage is Heimdall's rule (`move-proof-strict-passkey`): a proof through one login moves only that login, and only an asserted passkey speaks for the whole account, so a folded account's every login must be proved (or a passkey asserted) or Heimdall answers `identity_not_proved`. A `moveId` replayed with other identities returns the first receipt (`move-replay-first-receipt`). - -`AccountMergeSweeper` is the one merge loop (30 s): per tick, in one scope, `MergeProofs.PruneExpired` (a proof bearer lives only in process memory and is dropped 270 s after its proof, on access and by this tick, so none outlives that plus one tick whether or not anyone opens the page; `heimdall-body:ruling:merge-proof-bearers-memory-bound`), then `AccountMergeSaga.AdvanceDueAsync` (every in-flight merge whose `NextAttemptUtc` is null or due, oldest first, a failure logged and skipped), then `FinalizeDueAsync`. - -## Stuck merges - -`/App/Merges` (platform admins only; the `/App` folder's ActiveMember policy, then `IsPlatformAdmin`) lists in-flight merges (Confirmed or UndoRequested) that stopped on `receipt_mismatch`, `proofs_unreadable` or `move_id_conflict`, or were retried eight times, with the merge id, state, last outcome, attempts and the stored move id of the leg in flight. It shows no Heimdall account id, login or account name, and calls no Heimdall. Only the first three outcomes can be ended (`AccountMergeSaga.SettleableOutcomes`); a merge listed for its attempts alone is still being retried. - -Two actions (`heimdall-body:ruling:merge-stuck-end-only-typed-id`), both `AccountMergeSaga.SettleStuckAsync`, both needing the leg's stored move id typed back (the forward id for a Confirmed merge, the reverse id for an UndoRequested one) and both writing one `merge.settled` audit row that names the merge and the choice only: - -| Action | Applies to | Result | -| --- | --- | --- | -| Fail the merge (`FailForward`) | Confirmed, stuck | `Failed`, `FailureCode` and `LastOutcome` `operator_failed`, proofs wiped. The folded account is free again; the pair can be confirmed anew. | -| Give up the undo (`AbandonUndo`) | UndoRequested, stuck | back to `Committed`, `LastOutcome` `undo_operator_abandoned`, proofs wiped, the grace as it was. The merge stands; the logins stay with the survivor. | - -HeimdallMoved and Committed are never settleable: Heimdall answered Moved with a matching receipt there, and the saga rolls forward. A settle and the sweeper's `AdvanceAsync` meet at the `State` concurrency token; the loser changes nothing and the other transition stands (answered `lost`). A settle does not fence a replay already in flight to Heimdall, so read `identity_moves` first and read it again after. - -Before ending a merge, read Heimdall's `identity_moves` row by the stored move id. If Heimdall did move the logins, failing the merge leaves them moved with no Bifrost merge to match: repair or reverse at Heimdall first. For `receipt_mismatch`, repair Heimdall's or Bifrost's account link before failing. Adopting a move Heimdall made (writing HeimdallMoved from a receipt) stays manual SQL until follow-up `merge-operator-adopt-moved`; the page never does it. - -## Pages and flags - -`Pages/Membership/MergeAccounts` is the one page that creates a merge. It is `[Authorize]`, no-store, a 404 unless `AccountMergeOptions.Enabled` (section `AccountMerge`, default false; environment `AccountMerge__Enabled`) and forbidden to a frozen or folded account, as Linked accounts is. Linked accounts shows one "Merge two accounts" link, only when the flag is on and the session is Heimdall-backed. - -Its stage is derived on every request from `MergeProofs.Snapshot` and the `keep` query; no cookie or form field carries progress except the chosen direction and the preview digest, which the saga re-checks. - -1. Prove: the member names a provider for this account (`MergeProveSelf`) and for the other (`MergeProveOther`). Nothing about the other account is rendered until both proofs are held. -2. Choose: both accounts are named by display name only, and `keep=self` or `keep=other` shows the preview. No survivor is preselected (the chat-history default needs `ChatFirstSignInUtc`, follow-up `merge-chat-default-survivor`; the chat paragraph carries the warning meanwhile). -3. Prove the rest: one fresh sign-in for each login of the account that would be folded and is not yet proved (`ProveRemaining`). Proofs older than `MergeProofs.ProofLifetime` fall out and are asked again. -4. Confirm: two checkboxes, one per account, the direction and the digest. `AccountMergeSaga.ConfirmAsync` inserts the Confirmed row, which is the consent record (actor, time, digest, proof providers); the page then runs `AdvanceAsync` once (a throw is logged and the sweeper resumes) and sends the member to Merge status. `MergeProofs.Clear` runs after a Confirmed outcome only: Blocked, PreviewStale, NotParty and ProofAccountMismatch come back as closed codes (`?merge=`), keep the proofs and write nothing. - -`MergePreview` is the one wording of the plan (counts by entry kind and action, the nine block codes, the static statements about chat, connections, StreamPixels, roles, one vote per motion, the 7-day undo and ordinary sign-ins); the digest is `MergePlan.Digest` of the plan just rendered. `MergeWording.Confirm` holds the refusal words. The page writes no merge, vote, membership or journal row. - -Deploy: set `AccountMerge__Enabled` only after Heimdall's identity-moves route is deployed and probed. A Confirmed merge against a Heimdall without it stays Unknown and keeps the folded account frozen. - -## Notices - -The chat host learns of merges by pulling, never by being pushed to: Bifrost has no event receiver and no outbox. `MergeNoticeFeed` derives the notices from the `AccountMerges` row on every read (merged: `CommittedUtc` set; undone: `UndoneUtc` set; final: `FinalizedUtc` set), so a notice cannot disagree with its merge, and a Failed, Frozen or Confirmed merge (no `CommittedUtc`) yields none. The only stored fact is the reader's ack, one `AccountMergeNoticeAcks` row per (merge, kind, target), written by nothing else (migration `AddAccountMergeNoticeAcks`; the table holds only acks, so its `Down` drops it). The feed never writes a merge column. - -``` -GET /api/merge-notices/chat?after=&limit= -> 200 JSON array, oldest first by (occurred_at, merge_id, kind) -POST /api/merge-notices/chat/ack {"merge_id": "...", "type": "merged"} -> 204 -``` - -Payload, exactly these keys: `type` (`merged`, `undone`, `final`), `merge_id`, `occurred_at` (the matching timestamp, ISO 8601 UTC), `grace_ends_at`, `old_subject` (the folded `UserAccount.Id`, format D, the OIDC `sub` the chat session knew), `new_subject` (the survivor's), `old_preferred_username`, `new_preferred_username` (`NormalizedBifrostIdentity`). `limit` defaults to 50 and is capped at 200. Acks are the cursor: a read returns every unacked notice; `after` only narrows the scan to notices strictly later than that time, so a reader must not skip unacked ones by it. An ack is idempotent (a repeat is 204); an ack for a (merge, kind) the feed would not emit now, such as `undone` for a merge not undone, is 404; a malformed body or unknown `type` is 400. - -Auth: `Authorization: Bearer `, compared in constant time after SHA-256 of both sides against `ChatNotices:Token` (environment `ChatNotices__Token`). An empty token turns both routes off (404). A missing or wrong bearer is 401 with an empty body. No cookie, no CORS, `Cache-Control: no-store`. Startup does not require the token. - -``` -curl -sS -H "Authorization: Bearer $TOKEN" "$BIFROST/api/merge-notices/chat?limit=50" -curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ - -d '{"merge_id":"","type":"merged"}' "$BIFROST/api/merge-notices/chat/ack" -``` - -The feed carries no email, display name, Heimdall id, Matrix id or history flag. It is information for the chat operator's side; back-channel logout (`OidcLogoutReconciler`) stays what ends chat sessions. Chat-side rules that bind Bifrost already hold: undo is refused past Final, and `preferred_username` never changes. A later reader (StreamPixels) adds a target constant and its own token over the same derivation. - -Deploy: set `ChatNotices__Token` on Bifrost and hand the same value to the chat host's timer script (the secret's path is the chat steward's). - -## Merged is terminal - -Only the ledger writes `Membership.Status = Merged` or leaves it. The other status writers refuse a merged row (`Membership.IsMerged`): the bootstrap-admin promotion (startup and every GitHub sign-in, which is the one status write sign-in sync makes on an existing account) skips it, the Heimdall member-access claim does not activate it, member approval refuses it and the suspension service reports `NotApplicable`. Folded standing itself is still derived from the merge state, never from this status. - -## Rollback - -Bifrost is **roll-forward only** once a merge exists (`heimdall-body:ruling:merge-roll-forward-only`). A build older than `AddAccountMerges` cannot read the `Merged` membership status (EF throws on `/App/Members` and on the folded account's sign-in) and has no query filter, so it counts voided votes and appraisals again. Deploy the merge migration knowing that a code rollback past it is not available after the first merge lands; fix forward. The migration's `Down` refuses while any `AccountMerges` row exists, whatever state, so it cannot drop the merge record and journal under a `Merged` membership. No tombstone table is built: it would fix only the recount, not the enum. - -## Not covered - -`MembershipSynchronizationService` still writes the profile of a GitHub-signed-in row that is not merged. Sealed-ballot rows of a folded account on a motion that is already closed stay as they are. Every writer that acts for an account (votes, concept appraisals, sealed-ballot commit and reveal, patron events, the Heimdall sign-in's membership) passes through `AccountMergeLedger.WriteAsAsync`. On Postgres it opens a transaction, takes a shared advisory lock on the account (`pg_advisory_xact_lock_shared(hashtextextended(id::text, 0))`, the key the chain trigger takes exclusively when a merge row is inserted or changes state), reads standing, runs the writer's save and commits. `CommitAsync` takes the exclusive lock on the folded account before it reduces, then re-reads the merge. So: a writer whose standing read found no merge saves before a merge can freeze or fold the account, and the commit's reduction sees what it saved; a merge that is already frozen or folded when the writer reads is refused (votes, appraisals, ballots, sign-in membership) or routed (patron events). Guaranteed only for writes made through the gate, and only on Postgres: the in-memory provider has no lock or transaction (tests that rest on the lock run on live Postgres), and a writer that catches a database error inside the gate cannot continue, because the transaction is aborted. Not closed: writers outside the gate (nothing in the code base today; a new one must use it), and a writer's own stale reads taken before the gate opened (the motion a vote was loaded with), which concern the motion, not the account's standing. No operator void tool exists. - -`UX_TierSnapshots_MembershipId_CurrentPatron` allows one current Patron snapshot per membership, so two restages of one survivor racing cannot both leave a current snapshot: the loser's save fails on the unique index, a merge commit rolls back whole and is retried by the saga, and a patron refresh re-reads and derives again. diff --git a/src/Bifrost.Web/Configuration/AccountMergeOptions.cs b/src/Bifrost.Web/Configuration/AccountMergeOptions.cs deleted file mode 100644 index c862f67..0000000 --- a/src/Bifrost.Web/Configuration/AccountMergeOptions.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Bifrost.Web.Configuration; - -/// -/// Gates on the account-merge page (section AccountMerge). Dark by default: a merge Bifrost confirms against a Heimdall without -/// the identity-move route stays Unknown forever and freezes the folded account, so set AccountMerge__Enabled only after -/// Heimdall's identity-moves is deployed and probed. -/// -public sealed class AccountMergeOptions -{ - public const string SectionName = "AccountMerge"; - - public bool Enabled { get; init; } -} diff --git a/src/Bifrost.Web/Configuration/ChatNoticesOptions.cs b/src/Bifrost.Web/Configuration/ChatNoticesOptions.cs deleted file mode 100644 index 35f865e..0000000 --- a/src/Bifrost.Web/Configuration/ChatNoticesOptions.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Bifrost.Web.Configuration; - -/// The chat host's pull of merge notices (MergeNoticeFeed). An empty token turns both routes off (404); startup does not require it. -public sealed class ChatNoticesOptions -{ - public const string SectionName = "ChatNotices"; - - /// The bearer the chat host presents (environment ChatNotices__Token). Its own secret: it grants nothing else. - public string Token { get; init; } = string.Empty; -} diff --git a/src/Bifrost.Web/Domain/AccountMergeModels.cs b/src/Bifrost.Web/Domain/AccountMergeModels.cs deleted file mode 100644 index e95d6f6..0000000 --- a/src/Bifrost.Web/Domain/AccountMergeModels.cs +++ /dev/null @@ -1,165 +0,0 @@ -namespace Bifrost.Web.Domain; - -/// The whole lifecycle of an account merge, declared once; later cuts add columns, not states. Stored as a string. -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, - Created, - Restored, - KeptAfterUndo -} - -/// -/// 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. -/// -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; - - // ---- the saga's columns (AccountMergeSaga is their one writer; docs/account-merge.md, Saga) ---- - - /// Heimdall's idempotency key of the forward move: random, minted in the save that enters Confirmed, never derived from , never re-minted. - public string? HeimdallMoveId { get; set; } - - /// The same for the reversal, minted in the save that enters UndoRequested. - public string? HeimdallReverseMoveId { get; set; } - - /// The Heimdall bearers the move or reversal will replay, protected; non-null only from Confirmed/UndoRequested until Heimdall's final answer. - public string? SealedProofs { get; set; } - - /// Digest of the plan the member saw when confirming (MergePlan.Digest); with the next four columns it is the consent record. - public string PreviewDigest { get; set; } = string.Empty; - - public Guid? ConfirmedByUserAccountId { get; set; } - - public DateTimeOffset? ConfirmedUtc { get; set; } - - public string SurvivorProofProvider { get; set; } = string.Empty; - - /// The providers of the folded side's proofs, sorted and comma-joined. - public string FoldedProofProviders { get; set; } = string.Empty; - - /// The proof tiers Heimdall's receipt named (weak or strong); ProofToTier is null for a receipt without one. - public string? ProofFromTier { get; set; } - - public string? ProofToTier { get; set; } - - /// The logins the forward move carried, a JSON array of Heimdall identity ids, from the receipt. - public string? MovedIdentityIds { get; set; } - - public int Attempts { get; set; } - - public DateTimeOffset? NextAttemptUtc { get; set; } - - /// The last Heimdall answer's class or refusal code, or the saga's own stall code; never an input value. - public string LastOutcome { get; set; } = string.Empty; - - public DateTimeOffset? UndoRequestedUtc { get; set; } - - public DateTimeOffset? ReversedUtc { get; set; } - - public ICollection Entries { get; set; } = []; -} - -/// Append-only journal of what a merge did to one record; undo and the later preview read it, tallies and gates never do. -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; } - - /// 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). - public string? PriorText { get; set; } - - /// The cast time of a moved vote or appraisal, so undo can tell whether the survivor re-cast it. - public DateTimeOffset? PriorAtUtc { get; set; } - - public DateTimeOffset AtUtc { get; set; } - - public AccountMerge Merge { get; set; } = null!; -} - -/// What a merge notice tells its reader: the merge committed, was undone, or can no longer be undone. Stored as a string. -public enum AccountMergeNoticeKind -{ - Merged, - Undone, - Final -} - -/// Who reads the notice feed. A closed set: a new reader is a new constant (and its own token), never a string from a request. Stored as a string. -public enum AccountMergeNoticeTarget -{ - Chat -} - -/// -/// The one fact a notice reader adds: it has seen this notice. The notice itself is derived from the merge row on every read -/// (MergeNoticeFeed) and has no stored status; nothing but the feed writes this row. -/// -public sealed class AccountMergeNoticeAck -{ - public Guid MergeId { get; set; } - - public AccountMergeNoticeKind Kind { get; set; } - - public AccountMergeNoticeTarget Target { get; set; } - - public DateTimeOffset AckedUtc { get; set; } -} diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs index ff21623..ad77f07 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs @@ -1303,3 +1303,26 @@ public static class HeimdallAttemptCookie /// public static CookieOptions DeleteOptions() => new() { Path = BifrostCookies.Path, Secure = true }; } + +public static class HeimdallClientServices +{ + /// + /// Every Heimdall client Bifrost owns. The auth client carries the app secret and the member client only the member's + /// bearer; both share the header redaction. + /// + public static void AddHeimdallClients(this IServiceCollection services) + { + services.AddHttpClient((serviceProvider, client) => + HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value)) + .WithoutRedirects() + .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader); + services.AddHttpClient((serviceProvider, client) => + HeimdallMemberClient.ConfigureClient(client, serviceProvider.GetRequiredService>().Value)) + .WithoutRedirects() + .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader); + } + + /// A 3xx from Heimdall is its answer: following it would carry the app secret or a member's bearer to another origin. + public static IHttpClientBuilder WithoutRedirects(this IHttpClientBuilder builder) => + builder.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { AllowAutoRedirect = false, PooledConnectionLifetime = TimeSpan.FromMinutes(2) }); +} diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs deleted file mode 100644 index a92e916..0000000 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs +++ /dev/null @@ -1,351 +0,0 @@ -using System.Net; -using System.Text; -using System.Text.Json; -using System.Text.RegularExpressions; -using Bifrost.Web.Configuration; -using Microsoft.Extensions.Options; - -namespace Bifrost.Web.Features.Heimdall; - -/// -/// What Bifrost asks Heimdall to move (docs/service-contract.md, POST /v1/apps/{app}/identity-moves). Exactly one of -/// (a forward move, optionally of ) and (the undo). The body -/// never names an account: the proofs, live Heimdall access tokens, say which accounts are meant. -/// -public sealed record HeimdallMoveRequest( - string MoveId, IReadOnlyList FromProofs, string? ToProof = null, IReadOnlyList? IdentityIds = null, string? ReversesMoveId = null) -{ - // The proofs are live bearers: the generated ToString would print them into any log or exception that holds the request. - private bool PrintMembers(StringBuilder builder) - { - builder.Append($"MoveId = {MoveId}, FromProofs = {FromProofs?.Count}, ToProof = {(ToProof is null ? "none" : "present")}, ReversesMoveId = {ReversesMoveId}"); - return true; - } -} - -public enum HeimdallProofTier -{ - Strong, - Weak -} - -/// The receipt of a move: the destination account, the logins that moved and the tier of the proofs that carried it. -public sealed record HeimdallMoveReceipt( - string MoveId, string AccountId, IReadOnlyList MovedIdentityIds, HeimdallProofTier ProofFrom, HeimdallProofTier? ProofTo, string? ReversesMoveId); - -/// Heimdall's fixed refusal codes for a move, plus invalid_request, Heimdall's own schema 400. -public enum HeimdallMoveRefusal -{ - AppAuthRequired, - NotAllowedForApp, - NotReversible, - ProofInvalid, - SameAccount, - ProofStale, - IdentityNotProved, - AlreadyMoved, - ProviderConflict, - IdentityNotFound, - RequestInvalid -} - -public enum HeimdallProofSide -{ - From, - To -} - -/// -/// The closed answer to a move. Moved: the receipt. Refused: Heimdall answered a 4xx before applying anything, so nothing changed. -/// Unknown: anything else (a 5xx may follow a committed move, a timeout may hide one, and so may a 409 move_id_conflict: Heimdall -/// answers it to a replay of a committed move whose proofs no longer verify): the caller keeps its proofs and replays the same request. -/// -public abstract record HeimdallMoveOutcome -{ - private HeimdallMoveOutcome() - { - } - - public sealed record Moved(HeimdallMoveReceipt Receipt) : HeimdallMoveOutcome; - - public sealed record Refused(HeimdallMoveRefusal Code, HeimdallProofSide? Side = null, string? Provider = null) : HeimdallMoveOutcome; - - public sealed record Unknown(string Reason) : HeimdallMoveOutcome; -} - -/// -/// Heimdall's move route under Bifrost's app secret (HeimdallAuthService.ConfigureClient adds the header). Each call sends one request and -/// retries nothing: replay with the same is the caller's, and Heimdall answers it with the stored -/// receipt. Logs name the outcome class and refusal code only. -/// -public sealed partial class HeimdallIdentityMoveClient( - HttpClient httpClient, IOptions heimdallOptions, ILogger logger) -{ - /// The deadline of one call, headers and body together, set on the HttpClient by . - public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(15); - - private const int MaxMovedIdentities = 256; - private const int MaxIdentityIdLength = 128; - private const int MaxReceiptBytes = 64 * 1024; - public const int MaxProofLength = 8192; - - // \z, not $: $ also matches before a final line feed, which Heimdall's schema pattern refuses with a 400. - [GeneratedRegex("^[A-Za-z0-9_-]{16,64}\\z")] - private static partial Regex MoveIdShape(); - - public async Task MoveAsync(HeimdallMoveRequest request, CancellationToken cancellationToken) - { - var body = Serialize(request); - var outcome = await SendAsync(request, body, cancellationToken); - logger.LogInformation("Heimdall identity move: {Outcome} {Code}", outcome.GetType().Name, outcome is HeimdallMoveOutcome.Refused refused ? refused.Code : null); - return outcome; - } - - private async Task SendAsync(HeimdallMoveRequest request, string body, CancellationToken cancellationToken) - { - // One deadline over the whole call: HttpClient.Timeout ends at the headers, and a stalled body must not outlive it. - using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - deadline.CancelAfter(httpClient.Timeout); - var token = deadline.Token; - try - { - using var message = new HttpRequestMessage( - HttpMethod.Post, $"/v1/apps/{Uri.EscapeDataString(heimdallOptions.Value.AppSlug)}/identity-moves") - { - Content = new StringContent(body, Encoding.UTF8, "application/json") - }; - using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, token); - var status = (int)response.StatusCode; - if (response.StatusCode == HttpStatusCode.OK) - { - return await ReadReceiptAsync(response, request, token) is { } receipt - ? new HeimdallMoveOutcome.Moved(receipt) - : new HeimdallMoveOutcome.Unknown("malformed or mismatched receipt"); - } - - if (status is < 400 or >= 500 || status == 429) - { - return new HeimdallMoveOutcome.Unknown($"HTTP {status}"); - } - - return Refused(await HeimdallRefusal.ReadAsync(response, token), status); - } - catch (Exception) when (!cancellationToken.IsCancellationRequested) - { - // Whatever the pipeline throws after the request may have gone out is not a refusal; only the caller's own cancellation propagates. - return new HeimdallMoveOutcome.Unknown("transport"); - } - } - - /// - /// Refused only for the coded refusals Heimdall's move route emits (4fe367a moveIdentitiesRoute, and its error handler's invalid_request 400). A 4xx without one of those codes - /// (a gateway's HTML 404, a 408, a code a later Heimdall adds) proves nothing was applied, so it is Unknown. move_id_conflict is - /// Unknown too: a committed move answers it when its proofs no longer verify. - /// - private static HeimdallMoveOutcome Refused(HeimdallRefusalBody? refusal, int status) - { - if (refusal?.Code == "move_id_conflict") - { - return new HeimdallMoveOutcome.Unknown("move_id_conflict"); - } - - var code = refusal?.Code switch - { - "app_auth_required" => HeimdallMoveRefusal.AppAuthRequired, - "not_allowed_for_app" => HeimdallMoveRefusal.NotAllowedForApp, - "not_reversible" => HeimdallMoveRefusal.NotReversible, - "proof_invalid" => HeimdallMoveRefusal.ProofInvalid, - "same_account" => HeimdallMoveRefusal.SameAccount, - "proof_stale" => HeimdallMoveRefusal.ProofStale, - "identity_not_proved" => HeimdallMoveRefusal.IdentityNotProved, - "already_moved" => HeimdallMoveRefusal.AlreadyMoved, - "provider_conflict" => HeimdallMoveRefusal.ProviderConflict, - "identity_not_found" => HeimdallMoveRefusal.IdentityNotFound, - // Heimdall's error handler gives its own 400 this code; an nginx or other edge 400 has none, so it is not Heimdall's refusal. - "invalid_request" when status == 400 => HeimdallMoveRefusal.RequestInvalid, - _ => (HeimdallMoveRefusal?)null - }; - if (code is not { } known) - { - return new HeimdallMoveOutcome.Unknown($"HTTP {status} without a Heimdall refusal code"); - } - - return known switch - { - HeimdallMoveRefusal.ProofInvalid or HeimdallMoveRefusal.ProofStale => new HeimdallMoveOutcome.Refused(known, Side: refusal?.Proof switch - { - "from" => HeimdallProofSide.From, - "to" => HeimdallProofSide.To, - _ => null - }), - HeimdallMoveRefusal.ProviderConflict => new HeimdallMoveOutcome.Refused(known, Provider: refusal?.Provider), - _ => new HeimdallMoveOutcome.Refused(known) - }; - } - - /// - /// A 200 body is a receipt only when it is whole and answers this request: its moveId (and reversesMoveId) equal the request's, - /// a forward move names a destination proof tier and a reversal does not. Anything else is not trusted as a move. - /// - private static async Task ReadReceiptAsync(HttpResponseMessage response, HeimdallMoveRequest request, CancellationToken cancellationToken) - { - await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); - using var buffer = new MemoryStream(); - var chunk = new byte[4096]; - while (await stream.ReadAsync(chunk, cancellationToken) is > 0 and var read) - { - if (buffer.Length + read > MaxReceiptBytes) - { - return null; - } - - buffer.Write(chunk, 0, read); - } - - using var document = JsonDocument.Parse(buffer.ToArray()); - var root = document.RootElement; - if (root.ValueKind != JsonValueKind.Object - || Text(root, "moveId") != request.MoveId - || Text(root, "reversesMoveId") != request.ReversesMoveId - || Text(root, "accountId") is not { Length: > 0 } account - || !root.TryGetProperty("movedIdentityIds", out var moved) - || moved.ValueKind != JsonValueKind.Array - || moved.GetArrayLength() is 0 or > MaxMovedIdentities - || !root.TryGetProperty("proof", out var proof) - || proof.ValueKind != JsonValueKind.Object - || Tier(proof, "from") is not { } from) - { - return null; - } - - var ids = new List(); - foreach (var item in moved.EnumerateArray()) - { - if (item.ValueKind != JsonValueKind.String || item.GetString() is not { Length: > 0 and <= MaxIdentityIdLength }) - { - return null; - } - - ids.Add(item.GetString()!); - } - - HeimdallProofTier? to = null; - if (request.ReversesMoveId is null) - { - to = Tier(proof, "to"); - if (to is null) - { - return null; - } - } - else if (!proof.TryGetProperty("to", out var none) || none.ValueKind != JsonValueKind.Null) - { - return null; - } - - return new HeimdallMoveReceipt(request.MoveId, account, ids, from, to, request.ReversesMoveId); - } - - private static HeimdallProofTier? Tier(JsonElement proof, string name) => Text(proof, name) switch - { - "strong" => HeimdallProofTier.Strong, - "weak" => HeimdallProofTier.Weak, - _ => null - }; - - private static string? Text(JsonElement item, string name) => - item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; - - private static bool IsBadProof(string? proof) => string.IsNullOrEmpty(proof) || proof.Length > MaxProofLength; - - /// The contract's closed body, or ArgumentException before any I/O when the request breaks it. - private static string Serialize(HeimdallMoveRequest request) - { - if (request.MoveId is null || !MoveIdShape().IsMatch(request.MoveId)) - { - throw new ArgumentException("moveId must match ^[A-Za-z0-9_-]{16,64}$", nameof(request)); - } - - if (request.FromProofs is not { Count: >= 1 and <= 8 } || request.FromProofs.Any(IsBadProof)) - { - throw new ArgumentException("fromProofs must hold 1 to 8 proofs", nameof(request)); - } - - if ((request.ToProof is null) == (request.ReversesMoveId is null)) - { - throw new ArgumentException("exactly one of toProof and reversesMoveId is required", nameof(request)); - } - - if (request.ToProof is not null && IsBadProof(request.ToProof)) - { - throw new ArgumentException("toProof is empty", nameof(request)); - } - - if (request.ReversesMoveId is not null && !MoveIdShape().IsMatch(request.ReversesMoveId)) - { - throw new ArgumentException("reversesMoveId must match the moveId shape", nameof(request)); - } - - if (request.IdentityIds is not null - && (request.ToProof is null || request.IdentityIds.Count is < 1 or > 32 || request.IdentityIds.Any(string.IsNullOrEmpty) - || request.IdentityIds.Distinct().Count() != request.IdentityIds.Count)) - { - throw new ArgumentException("identityIds are 1 to 32 unique ids and only with toProof", nameof(request)); - } - - var body = new Dictionary { ["moveId"] = request.MoveId, ["fromProofs"] = request.FromProofs }; - if (request.ToProof is not null) - { - body["toProof"] = request.ToProof; - } - - if (request.IdentityIds is not null) - { - body["identityIds"] = request.IdentityIds; - } - - if (request.ReversesMoveId is not null) - { - body["reversesMoveId"] = request.ReversesMoveId; - } - - return JsonSerializer.Serialize(body); - } -} - -public static class HeimdallClientServices -{ - /// - /// Every Heimdall client Bifrost owns. The auth client carries the app secret, the member client only the member's bearer and - /// the mover the app secret and its call deadline; all share the header redaction. - /// - public static void AddHeimdallClients(this IServiceCollection services) - { - services.AddHttpClient((serviceProvider, client) => - HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value)) - .WithoutRedirects() - .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader); - services.AddHttpClient((serviceProvider, client) => - HeimdallMemberClient.ConfigureClient(client, serviceProvider.GetRequiredService>().Value)) - .WithoutRedirects() - .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader); - services.AddHeimdallIdentityMoveClient(); - } - - /// A 3xx from Heimdall is its answer: following it would carry the app secret or a member's bearer to another origin. - public static IHttpClientBuilder WithoutRedirects(this IHttpClientBuilder builder) => - builder.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { AllowAutoRedirect = false, PooledConnectionLifetime = TimeSpan.FromMinutes(2) }); - - /// - /// The mover's HttpClient: Heimdall's base address and app secret from HeimdallAuthService.ConfigureClient (the one secret path), the - /// call deadline, no redirects (a 3xx must never carry the secret or the proofs to another origin), and the shared header redaction. - /// - public static IHttpClientBuilder AddHeimdallIdentityMoveClient(this IServiceCollection services) => - services.AddHttpClient((serviceProvider, client) => - { - HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value); - client.Timeout = HeimdallIdentityMoveClient.Timeout; - }) - .WithoutRedirects() - .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader); -} diff --git a/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs b/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs deleted file mode 100644 index 7e3b6e3..0000000 --- a/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs +++ /dev/null @@ -1,780 +0,0 @@ -using System.Globalization; -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Patronage; -using Microsoft.EntityFrameworkCore; - -namespace Bifrost.Web.Features.Membership; - -/// How an account stands under a merge: the folded account of an unfinished merge is Frozen, of a landed one Folded. -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); - -/// A dry run: the block codes (never account names), the journal entries a commit would write, and the record counts left untouched. -public sealed record MergePlan( - IReadOnlyList Blocks, - IReadOnlyList Entries, - IReadOnlyDictionary Left) -{ - /// - /// Lowercase hex SHA-256 over a canonical text of the plan, in plan order (Left by key): what the member saw, comparable at confirm. - /// Every field is length-prefixed, so no value can imitate a separator. The plan holds no account ids of its own, so the caller - /// names the pair the plan was made for. - /// - public string Digest(Guid survivorId, Guid foldedId) - { - var text = new System.Text.StringBuilder(); - void Field(string? value) => text.Append(value is null ? "-" : $"{value.Length}:{value}").Append('|'); - Field(survivorId.ToString("N")); - Field(foldedId.ToString("N")); - foreach (var entry in Entries) - { - Field(entry.Kind.ToString()); - Field(entry.Action.ToString()); - // A Created row does not exist yet: its id is minted anew by every plan, so it cannot be part of what the member saw. - // Left unpinned on purpose: the mutant that keeps the id in (digest-includes-created-id in tools/merge-saga-mutants.py) is behaviourally equivalent bar one benign case. - Field(entry.Action == AccountMergeEntryAction.Created ? null : entry.RecordId.ToString("N")); - Field(entry.PriorUserAccountId?.ToString("N")); - Field(entry.PriorText); - Field(entry.PriorAtUtc?.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture)); - text.Append('\n'); - } - - text.Append("left\n"); - foreach (var (key, count) in Left.OrderBy(x => x.Key, StringComparer.Ordinal)) - { - Field(key); - Field(count.ToString(CultureInfo.InvariantCulture)); - } - - text.Append("\nblocks\n"); - foreach (var block in Blocks) - { - Field(block); - } - - return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text.ToString()))).ToLowerInvariant(); - } -} - -/// -/// 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 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. -/// -public sealed class AccountMergeLedger( - BifrostDbContext dbContext, - PatronageService patronageService, - TimeProvider timeProvider) -{ - public static readonly TimeSpan Grace = TimeSpan.FromDays(7); - - 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 StandingAsync(Guid userAccountId, CancellationToken cancellationToken) => - StandingAsync(dbContext, userAccountId, cancellationToken); - - /// - /// The earliest chat-invite time among the accounts folded into this one by merges that stand now (landed, not undone). Derived from - /// the merge state on every call, never copied onto the survivor, so undoing merges in any order leaves exactly the merges still standing. - /// - public static async Task CarriedInviteAsync(BifrostDbContext db, Guid survivorId, CancellationToken cancellationToken) => - await db.AccountMerges.AsNoTracking() - .Where(m => m.SurvivorUserAccountId == survivorId && FoldedStates.Contains(m.State)) - .Join(db.UserAccounts, m => m.FoldedUserAccountId, a => a.Id, (m, a) => a.ChatInvitedAtUtc) - .Where(at => at != null) - .OrderBy(at => at) - .FirstOrDefaultAsync(cancellationToken); - - /// 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. - public static async Task 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); - } - - /// - /// The one gate every writer that acts for an account passes through (votes, appraisals, sealed ballots, patron events, the Heimdall - /// sign-in's membership). On Postgres it holds a shared advisory lock on the account, the key the chain trigger locks exclusively - /// when a merge row is inserted or changes state and that takes exclusively before it reduces, across the - /// standing read and everything saves, then commits. So a merge cannot freeze or fold the account between a - /// writer's standing read and its save: it waits for the writer, and a writer that starts after it reads the new standing. The - /// lock covers writes made through this gate and nothing else; it is held until the transaction ends, so a writer must not - /// catch a database error inside and carry on (the transaction is already aborted). On the in-memory - /// provider there is no lock and no transaction: the standing is read, then the writer saves. - /// - public static async Task WriteAsAsync(BifrostDbContext db, Guid userAccountId, Func> write, CancellationToken cancellationToken) - { - await using var transaction = await BeginAsync(db, cancellationToken); - await LockAsync(db, userAccountId, exclusive: false, cancellationToken); - var result = await write(await StandingAsync(db, userAccountId, cancellationToken)); - if (transaction is not null) - { - await transaction.CommitAsync(cancellationToken); - } - - return result; - } - - /// A transaction for the caller to commit, or null where there is none to open: not Postgres, or one already open (its owner commits). - private static async Task BeginAsync(BifrostDbContext db, CancellationToken cancellationToken) => - db.Database.IsNpgsql() && db.Database.CurrentTransaction is null ? await db.Database.BeginTransactionAsync(cancellationToken) : null; - - /// The account's lock, on the key the chain trigger uses (hashtextextended of the id's text). A no-op off Postgres. - private static async Task LockAsync(BifrostDbContext db, Guid userAccountId, bool exclusive, CancellationToken cancellationToken) - { - if (!db.Database.IsNpgsql()) - { - return; - } - - var key = userAccountId.ToString(); - await (exclusive - ? db.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock(hashtextextended({key}, 0))", cancellationToken) - : db.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock_shared(hashtextextended({key}, 0))", cancellationToken)); - } - - /// Writes nothing. lets the saga re-plan a merge it already holds without it blocking itself. - public async Task PlanAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? exceptMergeId = null) - { - var blocks = await BlocksAsync(survivorId, foldedId, exceptMergeId, cancellationToken); - var entries = new List(); - var left = new Dictionary(); - - 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> BlocksAsync(Guid survivorId, Guid foldedId, Guid? exceptMergeId, CancellationToken cancellationToken) - { - var blocks = new List(); - 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"); - } - - // 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 && FoldedStates.Contains(x.State) && x.SurvivorUserAccountId == foldedId, - cancellationToken)) - { - blocks.Add("folded_is_survivor"); - } - - if (await dbContext.SealedBallots.AnyAsync( - x => x.UserAccountId == foldedId && x.Motion.Status == MotionStatus.Open, - cancellationToken)) - { - blocks.Add("sealed_ballot_pending"); - } - - return blocks; - } - - private Task FoldedLinkAsync(Guid accountId, Guid? exceptMergeId, CancellationToken cancellationToken) => - dbContext.AccountMerges.AnyAsync( - x => x.Id != exceptMergeId && x.FoldedUserAccountId == accountId && FoldedStates.Contains(x.State), - cancellationToken); - - /// - /// 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. - /// - public async Task CommitAsync(Guid mergeId, CancellationToken cancellationToken) - { - var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, cancellationToken); - - // The exclusive lock first, so no writer that read the folded account's standing is still to save when the reduction reads its - // rows, then the state again: a commit that waited here found the merge landed and returns its receipt. - await using var transaction = await BeginAsync(dbContext, cancellationToken); - await LockAsync(dbContext, merge.FoldedUserAccountId, exclusive: true, cancellationToken); - await dbContext.Entry(merge).ReloadAsync(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); - } - - reduction.ReweighMovedVotes(); - merge.State = AccountMergeState.Committed; - merge.CommittedUtc = now; - merge.GraceEndsUtc = now + Grace; - await dbContext.SaveChangesAsync(cancellationToken); - if (transaction is not null) - { - await transaction.CommitAsync(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; - } - } - - /// 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. - public async Task 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."); - } - - 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(); - 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 or AccountMergeEntryAction.Created)) - { - 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; - if (decimal.TryParse(entry.PriorText, NumberStyles.Number, CultureInfo.InvariantCulture, out var priorWeight)) - { - vote.Weight = priorWeight; - } - } - - 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; - var (priorClass, priorKey) = ParseAppraisalPrior(entry.PriorText); - row.VoterKey = priorKey ?? row.VoterKey; - row.VoterClass = priorClass ?? row.VoterClass; - } - - Record(entry, restore); - break; - } - case (AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed): - { - var restore = folded.Membership is { Status: MembershipStatus.Merged } && Enum.TryParse(entry.PriorText, out _); - if (restore) - { - folded.Membership!.Status = Enum.Parse(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(entry.PriorText, out _); - if (restore) - { - survivor.Membership!.Status = Enum.Parse(entry.PriorText!); - survivor.Membership.SuspensionReason = null; - } - - 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); - 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; - } - } - - /// - /// 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. - /// - public async Task FinalizeDueAsync(DateTimeOffset now, CancellationToken cancellationToken) - { - var dueIds = await dbContext.AccountMerges.AsNoTracking() - .Where(x => x.State == AccountMergeState.Committed && x.GraceEndsUtc <= now) - .Select(x => x.Id) - .ToListAsync(cancellationToken); - 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; - } - - /// - /// Stages the journal entry for a patron event that is on a folded account's survivor, so undo moves it back with the rest; saved - /// with the event by , the only caller. Idempotent: a provider retry stages nothing. - /// - public static async Task StageIntakeJournalAsync(BifrostDbContext db, Guid mergeId, Guid foldedUserAccountId, Guid supportEventId, DateTimeOffset now, CancellationToken cancellationToken) - { - if (await db.AccountMergeEntries.AnyAsync( - x => x.MergeId == mergeId && x.Kind == AccountMergeEntryKind.PatronSupportEvent && x.RecordId == supportEventId, - cancellationToken)) - { - return; - } - - var seq = await db.AccountMergeEntries.Where(x => x.MergeId == mergeId).MaxAsync(x => (int?)x.Seq, cancellationToken) ?? 0; - db.AccountMergeEntries.Add(Journal( - mergeId, - seq + 1, - new MergePlanEntry(AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved, supportEventId, foldedUserAccountId), - now)); - } - - private sealed class Reduction( - UserAccount survivor, - UserAccount folded, - List entries, - List> effects, - List movedVotes, - bool movedPatronEvents) - { - public UserAccount Survivor { get; } = survivor; - - public UserAccount Folded { get; } = folded; - - public IReadOnlyList Entries => entries; - - public bool MovedPatronEvents { get; } = movedPatronEvents; - - public Guid MergeId { get; set; } - - /// 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. - public void ReweighMovedVotes() - { - foreach (var vote in movedVotes) - { - vote.Weight = Survivor.Membership!.EffectiveVotingWeight; - } - } - - public void Apply(DateTimeOffset now) - { - foreach (var effect in effects) - { - effect(MergeId, now); - } - } - } - - /// - /// 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. - /// - private async Task ReduceAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? mergeId = null) - { - 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!).ThenInclude(x => x.TierSnapshots).Include(x => x.PatronSupportEvents) - .SingleAsync(x => x.Id == foldedId, cancellationToken); - - var entries = new List(); - var effects = new List>(); - var movedVotes = new List(); - - var foldedSuspended = folded.Membership?.Status == MembershipStatus.Suspended; - var survivorSuspendedNow = survivor.Membership?.Status == MembershipStatus.Suspended; - var survivorStanding = survivor.Membership?.Status; - if (foldedSuspended && !survivorSuspendedNow) - { - if (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); - }); - } - 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; - } - - 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, vote.Weight.ToString(CultureInfo.InvariantCulture), vote.CastAtUtc)); - movedVotes.Add(vote); - 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.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 - }); - } - } - - 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, movedVotes, 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 events, DateTimeOffset now, CancellationToken cancellationToken) - { - if (membership is not null && dbContext.Entry(membership).State != EntityState.Deleted) - { - 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"); - - private static (VoterClass? Class, string? Key) ParseAppraisalPrior(string? prior) - { - var split = prior?.IndexOf('|') ?? -1; - return split > 0 && Enum.TryParse(prior![..split], out var voterClass) ? (voterClass, prior[(split + 1)..]) : (null, null); - } -} - -/// -/// The one merge loop, every 30 seconds: the proof holder drops expired bearers, the saga advances every due in-flight merge (confirm, -/// replay, undo), then the ledger finalizes merges past their grace. A new scope per tick, a warning on failure, the SealedBallotCloser shape. No second merge hosted service exists. -/// -public sealed class AccountMergeSweeper(IServiceScopeFactory scopes, TimeProvider clock, ILogger logger) : BackgroundService -{ - public static readonly TimeSpan Tick = TimeSpan.FromSeconds(30); - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - using var timer = new PeriodicTimer(Tick); - do - { - try - { - using var scope = scopes.CreateScope(); - var now = clock.GetUtcNow(); - scope.ServiceProvider.GetRequiredService().PruneExpired(); - await scope.ServiceProvider.GetRequiredService().AdvanceDueAsync(now, stoppingToken); - await scope.ServiceProvider.GetRequiredService().FinalizeDueAsync(now, stoppingToken); - } - catch (Exception error) when (error is not OperationCanceledException) - { - logger.LogWarning(error, "Account merge sweep failed; retrying next tick."); - } - } - while (await timer.WaitForNextTickAsync(stoppingToken)); - } -} diff --git a/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs b/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs deleted file mode 100644 index 153ee80..0000000 --- a/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs +++ /dev/null @@ -1,576 +0,0 @@ -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.Features.Heimdall; -using Bifrost.Web.Features.Shared; -using Microsoft.AspNetCore.DataProtection; -using Microsoft.EntityFrameworkCore; -using Npgsql; - -namespace Bifrost.Web.Features.Membership; - -/// -/// A live Heimdall bearer a member redeemed from a fresh sign-in, with the Heimdall account and provider it came through. The token is a -/// secret: never prints it (nor the account id), so no log or exception that holds a proof can leak it. -/// -public sealed record MergeProof(string AccessToken, string HeimdallAccountId, string Provider) -{ - private bool PrintMembers(StringBuilder builder) - { - builder.Append($"Provider = {Provider}"); - return true; - } -} - -/// What the member confirmed: the pair, the plan digest they saw, and a proof for every login of each side that must speak. -public sealed record ConfirmMergeRequest( - Guid ActorUserAccountId, - Guid SurvivorUserAccountId, - Guid FoldedUserAccountId, - string PreviewDigest, - MergeProof SurvivorProof, - IReadOnlyList FoldedProofs); - -/// The closed answer to a confirm. Only Confirmed wrote a row. -public abstract record ConfirmOutcome -{ - private ConfirmOutcome() - { - } - - public sealed record Confirmed(Guid MergeId) : ConfirmOutcome; - - /// The plan's block codes (never account names), or merge_in_flight when the database refused an overlapping merge. - public sealed record Blocked(IReadOnlyList Codes) : ConfirmOutcome; - - public sealed record PreviewStale : ConfirmOutcome; - - public sealed record NotParty : ConfirmOutcome; - - public sealed record ProofAccountMismatch : ConfirmOutcome; -} - -/// The closed answer to an undo request. Only Requested wrote. -public abstract record UndoOutcome -{ - private UndoOutcome() - { - } - - public sealed record Requested : UndoOutcome; - - public sealed record NotCommitted : UndoOutcome; - - public sealed record GraceOver : UndoOutcome; - - public sealed record NotSurvivor : UndoOutcome; - - public sealed record ProofAccountMismatch : UndoOutcome; -} - -/// The two ways an operator may end a stuck leg: the forward move is failed, or the undo is given up and the merge stands. -public enum SettleChoice -{ - FailForward, - AbandonUndo -} - -/// The closed answer to an operator's settle. Only Settled wrote. -public abstract record SettleOutcome -{ - private SettleOutcome() - { - } - - public sealed record Settled : SettleOutcome; - - /// The merge is missing, in another state than the choice ends, or not stuck on one of the settleable outcomes. - public sealed record NotStuck : SettleOutcome; - - public sealed record WrongMoveId : SettleOutcome; - - /// The State token went to another writer first; the other transition stands and nothing was changed. - public sealed record Lost : SettleOutcome; -} - -/// -/// The one owner of an account merge's lifecycle outside the ledger's Committed, Final and Undone, and the only caller of -/// . It inserts Confirmed (the consent record, with the Heimdall bearers sealed and the move -/// id minted), runs the one idempotent step function (move, commit, reverse, undo), and writes -/// HeimdallMoved, Failed, UndoRequested and HeimdallReversed. It never writes votes, memberships or journal rows (the ledger's), never -/// judges a proof's tier or freshness (Heimdall's), and reads no standing of its own: the plan's blocks and the database's live-merge -/// index answer overlap, and the writers that act for an account go through . -/// Every transition is one save guarded by State, the merge's concurrency token; the loser of a race reloads and continues from the -/// stored state. Heimdall's closed outcome is consumed as is: Unknown (a lost answer, an outage) is replayed with the same stored -/// move id and never fails a merge. Logs name the merge id, state, outcome class and refusal code only. -/// -public sealed partial class AccountMergeSaga( - BifrostDbContext dbContext, - AccountMergeLedger ledger, - HeimdallIdentityMoveClient mover, - IDataProtectionProvider dataProtection, - AuditTrailService audit, - TimeProvider timeProvider, - ILogger logger) -{ - public const string MergeInFlight = "merge_in_flight"; - public const string ReceiptMismatch = "receipt_mismatch"; - public const string ProofsUnreadable = "proofs_unreadable"; - public const string MoveIdConflict = "move_id_conflict"; - public const string OperatorFailed = "operator_failed"; - public const string UndoOperatorAbandoned = "undo_operator_abandoned"; - - private const string LiveMergeIndex = "UX_AccountMerges_FoldedUserAccountId_Live"; - private const int MaxProofs = 8; - - private static readonly TimeSpan[] Backoff = [TimeSpan.FromSeconds(15), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15)]; - private static readonly TimeSpan UnreadableRetry = TimeSpan.FromHours(1); - - private static readonly AccountMergeState[] DueStates = - [AccountMergeState.Confirmed, AccountMergeState.HeimdallMoved, AccountMergeState.UndoRequested, AccountMergeState.HeimdallReversed]; - - private readonly IDataProtector _seal = dataProtection.CreateProtector("Bifrost.AccountMerge.Proofs.v1"); - - private sealed record ProofSeal(List From, string? To) - { - // The seal holds live bearers: the generated ToString would print them into any log or exception that holds it. - private bool PrintMembers(StringBuilder builder) - { - builder.Append($"From = {From?.Count}, To = {(To is null ? "none" : "present")}"); - return true; - } - } - - // ---- confirm ---- - - /// - /// The member's consent, as one insert. The actor must be one of the pair; the plan must have no blocks and be the one the member - /// saw (digest); every proof must be of its side's Heimdall account. Calls no Heimdall: the caller runs . - /// - public async Task ConfirmAsync(ConfirmMergeRequest request, CancellationToken cancellationToken) - { - RequireProofs(request.SurvivorProof, request.FoldedProofs); - if (request.ActorUserAccountId != request.SurvivorUserAccountId && request.ActorUserAccountId != request.FoldedUserAccountId) - { - return new ConfirmOutcome.NotParty(); - } - - try - { - return await AccountMergeLedger.WriteAsAsync(dbContext, request.ActorUserAccountId, _ => InsertConfirmedAsync(request, cancellationToken), cancellationToken); - } - catch (DbUpdateException error) when (IsLiveMergeViolation(error)) - { - dbContext.ChangeTracker.Clear(); - return new ConfirmOutcome.Blocked([MergeInFlight]); - } - } - - private async Task InsertConfirmedAsync(ConfirmMergeRequest request, CancellationToken cancellationToken) - { - var plan = await ledger.PlanAsync(request.SurvivorUserAccountId, request.FoldedUserAccountId, cancellationToken); - if (plan.Blocks.Count > 0) - { - return new ConfirmOutcome.Blocked(plan.Blocks); - } - - if (!string.Equals(plan.Digest(request.SurvivorUserAccountId, request.FoldedUserAccountId), request.PreviewDigest, StringComparison.Ordinal)) - { - return new ConfirmOutcome.PreviewStale(); - } - - var survivorHeimdall = await HeimdallAccountAsync(request.SurvivorUserAccountId, cancellationToken); - var foldedHeimdall = await HeimdallAccountAsync(request.FoldedUserAccountId, cancellationToken); - if (request.SurvivorProof.HeimdallAccountId != survivorHeimdall || request.FoldedProofs.Any(x => x.HeimdallAccountId != foldedHeimdall)) - { - return new ConfirmOutcome.ProofAccountMismatch(); - } - - var now = timeProvider.GetUtcNow(); - var merge = new AccountMerge - { - State = AccountMergeState.Confirmed, - SurvivorUserAccountId = request.SurvivorUserAccountId, - FoldedUserAccountId = request.FoldedUserAccountId, - CreatedUtc = now, - ConfirmedByUserAccountId = request.ActorUserAccountId, - ConfirmedUtc = now, - PreviewDigest = request.PreviewDigest, - SurvivorProofProvider = request.SurvivorProof.Provider, - FoldedProofProviders = string.Join(',', request.FoldedProofs.Select(x => x.Provider).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)), - // Heimdall's idempotency key: random, minted once here, read back from the row on every call, never derived from the merge id. - HeimdallMoveId = Guid.NewGuid().ToString("N"), - SealedProofs = Seal(request.FoldedProofs.Select(x => x.AccessToken), request.SurvivorProof.AccessToken), - LastOutcome = "confirmed" - }; - dbContext.AccountMerges.Add(merge); - await dbContext.SaveChangesAsync(cancellationToken); - logger.LogInformation("Account merge {MergeId} {State}", merge.Id, merge.State); - return new ConfirmOutcome.Confirmed(merge.Id); - } - - // ---- undo request ---- - - /// - /// The survivor's request to give the moved logins back, inside the grace and with fresh survivor proofs. One save: UndoRequested, a - /// freshly minted reverse move id, the sealed proofs. Losing the race to the Final sweep is the State token's, answered GraceOver. - /// - public async Task RequestUndoAsync( - Guid mergeId, Guid actorUserAccountId, IReadOnlyList survivorProofs, CancellationToken cancellationToken) - { - RequireProofs(null, survivorProofs); - try - { - return await AccountMergeLedger.WriteAsAsync(dbContext, actorUserAccountId, _ => WriteUndoRequestedAsync(mergeId, actorUserAccountId, survivorProofs, cancellationToken), cancellationToken); - } - catch (DbUpdateConcurrencyException) - { - dbContext.ChangeTracker.Clear(); - return new UndoOutcome.GraceOver(); - } - } - - private async Task WriteUndoRequestedAsync( - Guid mergeId, Guid actorUserAccountId, IReadOnlyList survivorProofs, CancellationToken cancellationToken) - { - var merge = await LoadAsync(mergeId, cancellationToken); - if (merge is null) - { - return new UndoOutcome.NotCommitted(); - } - - var now = timeProvider.GetUtcNow(); - if (actorUserAccountId != merge.SurvivorUserAccountId) - { - return new UndoOutcome.NotSurvivor(); - } - - if (merge.State == AccountMergeState.Final || merge.FinalizedUtc is not null) - { - return new UndoOutcome.GraceOver(); - } - - if (merge.State != AccountMergeState.Committed) - { - return new UndoOutcome.NotCommitted(); - } - - if (merge.GraceEndsUtc is not { } graceEnds || now >= graceEnds) - { - return new UndoOutcome.GraceOver(); - } - - var survivorHeimdall = await HeimdallAccountAsync(merge.SurvivorUserAccountId, cancellationToken); - if (survivorProofs.Any(x => x.HeimdallAccountId != survivorHeimdall)) - { - return new UndoOutcome.ProofAccountMismatch(); - } - - merge.State = AccountMergeState.UndoRequested; - merge.UndoRequestedUtc = now; - merge.HeimdallReverseMoveId = Guid.NewGuid().ToString("N"); - merge.SealedProofs = Seal(survivorProofs.Select(x => x.AccessToken), null); - merge.Attempts = 0; - merge.NextAttemptUtc = null; - merge.LastOutcome = "undo_requested"; - await dbContext.SaveChangesAsync(cancellationToken); - logger.LogInformation("Account merge {MergeId} {State}", merge.Id, merge.State); - return new UndoOutcome.Requested(); - } - - // ---- the step function ---- - - /// - /// The one step function: confirm's inline advance, the sweeper's resume after a crash and an undo request all run it. From the - /// stored state it makes the Heimdall move (or reversal) under the stored id, records the answer, and calls the ledger's commit (or - /// local undo). Idempotent: every state has one next step and every step is safe to repeat. Other states are a no-op. - /// - public async Task AdvanceAsync(Guid mergeId, CancellationToken cancellationToken) - { - for (var lost = 0; ; lost++) - { - try - { - return await AdvanceOnceAsync(mergeId, cancellationToken); - } - catch (DbUpdateConcurrencyException) when (lost < 2) - { - // Another advancer saved first: forget what this context staged and continue from the stored state. - dbContext.ChangeTracker.Clear(); - } - } - } - - private async Task AdvanceOnceAsync(Guid mergeId, CancellationToken cancellationToken) - { - var merge = await LoadAsync(mergeId, cancellationToken) ?? throw new InvalidOperationException($"Merge {mergeId} does not exist."); - if (merge.State is AccountMergeState.Confirmed or AccountMergeState.UndoRequested) - { - merge = await MoveAsync(merge, cancellationToken); - } - - return merge.State switch - { - AccountMergeState.HeimdallMoved => await ledger.CommitAsync(merge.Id, cancellationToken), - AccountMergeState.HeimdallReversed => await ledger.UndoLocalAsync(merge.Id, cancellationToken), - _ => merge - }; - } - - private async Task MoveAsync(AccountMerge merge, CancellationToken cancellationToken) - { - if (merge.LastOutcome == ReceiptMismatch) - { - return merge; // Heimdall answered, wrongly, and its proofs are wiped: replay can only repeat the same answer. - } - - var forward = merge.State == AccountMergeState.Confirmed; - var now = timeProvider.GetUtcNow(); - if (Open(merge.SealedProofs) is not { } proofs) - { - // The key ring is lost or rotated out. Heimdall may already have moved, so nothing changes but the retry time. - merge.LastOutcome = ProofsUnreadable; - merge.NextAttemptUtc = now + UnreadableRetry; - await dbContext.SaveChangesAsync(cancellationToken); - logger.LogError("Account merge {MergeId} {State}: sealed proofs unreadable", merge.Id, merge.State); - return merge; - } - - var request = forward - ? new HeimdallMoveRequest(merge.HeimdallMoveId!, proofs.From, proofs.To) - : new HeimdallMoveRequest(merge.HeimdallReverseMoveId!, proofs.From, ReversesMoveId: merge.HeimdallMoveId); - var outcome = await mover.MoveAsync(request, cancellationToken); - var code = outcome is HeimdallMoveOutcome.Refused refused ? RefusalCode(refused.Code) : null; - switch (outcome) - { - case HeimdallMoveOutcome.Moved moved: - // The leg's destination is the survivor going forward and the folded account coming back. - var destination = await HeimdallAccountAsync(forward ? merge.SurvivorUserAccountId : merge.FoldedUserAccountId, cancellationToken); - merge.SealedProofs = null; - if (moved.Receipt.AccountId != destination) - { - merge.LastOutcome = ReceiptMismatch; - break; - } - - merge.Attempts = 0; - merge.NextAttemptUtc = null; - merge.LastOutcome = "moved"; - if (forward) - { - merge.State = AccountMergeState.HeimdallMoved; - merge.ProofFromTier = Tier(moved.Receipt.ProofFrom); - merge.ProofToTier = moved.Receipt.ProofTo is { } to ? Tier(to) : null; - merge.MovedIdentityIds = JsonSerializer.Serialize(moved.Receipt.MovedIdentityIds); - } - else - { - merge.State = AccountMergeState.HeimdallReversed; - merge.ReversedUtc = now; - } - - break; - case HeimdallMoveOutcome.Refused: - // Heimdall applied nothing before a 4xx. A forward refusal ends the merge; a refused undo leaves it as it was. - merge.SealedProofs = null; - merge.NextAttemptUtc = null; - if (forward) - { - merge.State = AccountMergeState.Failed; - merge.FailedUtc = now; - merge.FailureCode = code!; - merge.LastOutcome = "refused"; - } - else - { - merge.State = AccountMergeState.Committed; - merge.LastOutcome = "undo_" + code; - } - - break; - case HeimdallMoveOutcome.Unknown unknown: - merge.Attempts++; - merge.NextAttemptUtc = now + Backoff[Math.Min(merge.Attempts, Backoff.Length) - 1]; - merge.LastOutcome = unknown.Reason.Length > 64 ? unknown.Reason[..64] : unknown.Reason; - break; - } - - await dbContext.SaveChangesAsync(cancellationToken); - logger.LogInformation("Account merge {MergeId} {State}: {Outcome} {Code}", merge.Id, merge.State, outcome.GetType().Name, code); - return merge; - } - - /// Advances every in-flight merge that is due, oldest first. One that throws is logged and skipped; returns how many were advanced. - public async Task AdvanceDueAsync(DateTimeOffset now, CancellationToken cancellationToken) - { - var due = await dbContext.AccountMerges.AsNoTracking() - .Where(x => DueStates.Contains(x.State) && (x.NextAttemptUtc == null || x.NextAttemptUtc <= now)) - .OrderBy(x => x.CreatedUtc) - .Select(x => x.Id) - .ToListAsync(cancellationToken); - var advanced = 0; - foreach (var id in due) - { - try - { - await AdvanceAsync(id, cancellationToken); - advanced++; - } - catch (Exception error) when (error is not OperationCanceledException) - { - dbContext.ChangeTracker.Clear(); - logger.LogWarning("Account merge {MergeId} advance failed: {Error}", id, error.GetType().Name); - } - } - - return advanced; - } - - // ---- operator settle ---- - - /// The Heimdall answers no replay can change: the one the saga recorded and stopped on, the key ring's loss, and a move Heimdall holds but will not confirm. - public static readonly IReadOnlyList SettleableOutcomes = [ReceiptMismatch, ProofsUnreadable, MoveIdConflict]; - - /// - /// Whether an operator may end this merge's leg: in flight (Confirmed or UndoRequested) and stopped on one of the closed - /// outcomes. Derived from the row on every read; there is no stuck flag. - /// - public static bool IsSettleable(AccountMerge merge) => - merge.State is AccountMergeState.Confirmed or AccountMergeState.UndoRequested && SettleableOutcomes.Contains(merge.LastOutcome); - - /// - /// A platform admin's end of a stuck leg (ruling merge-stuck-end-only-typed-id): FailForward turns a stuck Confirmed merge into - /// Failed, AbandonUndo returns a stuck UndoRequested merge to Committed with its grace. Only with the leg's stored move id typed back. - /// Never adopts or invents a Heimdall receipt; a merge Heimdall moved (HeimdallMoved, Committed) is never settleable. One save - /// guarded by State carries the transition and its audit row (choice only): the loser of a race with - /// answers Lost and changes nothing. The caller has checked the operator's authority. - /// - public async Task SettleStuckAsync( - Guid mergeId, SettleChoice choice, string typedMoveId, Guid operatorUserAccountId, CancellationToken cancellationToken) - { - var forward = choice == SettleChoice.FailForward; - var merge = await LoadAsync(mergeId, cancellationToken); - if (merge is null || merge.State != (forward ? AccountMergeState.Confirmed : AccountMergeState.UndoRequested) || !IsSettleable(merge)) - { - return new SettleOutcome.NotStuck(); - } - - if (!string.Equals(typedMoveId, forward ? merge.HeimdallMoveId : merge.HeimdallReverseMoveId, StringComparison.Ordinal)) - { - return new SettleOutcome.WrongMoveId(); - } - - merge.SealedProofs = null; - merge.NextAttemptUtc = null; - if (forward) - { - merge.State = AccountMergeState.Failed; - merge.FailedUtc = timeProvider.GetUtcNow(); - merge.FailureCode = OperatorFailed; - merge.LastOutcome = OperatorFailed; - } - else - { - merge.State = AccountMergeState.Committed; - merge.LastOutcome = UndoOperatorAbandoned; - } - - try - { - await audit.RecordAsync(operatorUserAccountId, nameof(AccountMerge), merge.Id, "merge.settled", choice.ToString(), cancellationToken); - } - catch (DbUpdateConcurrencyException) - { - dbContext.ChangeTracker.Clear(); - return new SettleOutcome.Lost(); - } - - logger.LogInformation("Account merge {MergeId} {State}: settled by an operator ({Choice})", merge.Id, merge.State, choice); - return new SettleOutcome.Settled(); - } - - // ---- helpers ---- - - /// The merge as stored now: a row this context already tracks is reloaded, never trusted. - private async Task LoadAsync(Guid mergeId, CancellationToken cancellationToken) - { - var tracked = dbContext.AccountMerges.Local.FirstOrDefault(x => x.Id == mergeId); - if (tracked is not null) - { - await dbContext.Entry(tracked).ReloadAsync(cancellationToken); - return dbContext.Entry(tracked).State == EntityState.Detached ? null : tracked; - } - - return await dbContext.AccountMerges.SingleOrDefaultAsync(x => x.Id == mergeId, cancellationToken); - } - - private Task HeimdallAccountAsync(Guid userAccountId, CancellationToken cancellationToken) => - dbContext.UserAccounts.AsNoTracking().Where(x => x.Id == userAccountId).Select(x => x.HeimdallAccountId).SingleAsync(cancellationToken); - - /// Shapes Heimdall would 400 are refused before a row exists, so a confirm can never store a merge that cannot call. Messages name no value. - private static void RequireProofs(MergeProof? one, IReadOnlyList many) - { - if (many is not { Count: >= 1 and <= MaxProofs }) - { - throw new ArgumentException("1 to 8 proofs are required", nameof(many)); - } - - foreach (var proof in one is null ? many : [one, .. many]) - { - if (string.IsNullOrEmpty(proof.AccessToken) || proof.AccessToken.Length > HeimdallIdentityMoveClient.MaxProofLength - || string.IsNullOrEmpty(proof.HeimdallAccountId) || string.IsNullOrEmpty(proof.Provider) || proof.Provider.Length > 32) - { - throw new ArgumentException("a proof is malformed", nameof(many)); - } - } - - if (many.Select(x => x.Provider).Distinct(StringComparer.Ordinal).Sum(x => x.Length + 1) > 121) - { - throw new ArgumentException("the proofs' providers do not fit the record", nameof(many)); - } - } - - private string Seal(IEnumerable from, string? to) => _seal.Protect(JsonSerializer.Serialize(new ProofSeal([.. from], to))); - - private ProofSeal? Open(string? sealedProofs) - { - if (sealedProofs is null) - { - return null; - } - - try - { - return JsonSerializer.Deserialize(_seal.Unprotect(sealedProofs)) is { From.Count: > 0 } proofs ? proofs : null; - } - catch (Exception error) when (error is CryptographicException or JsonException) - { - return null; - } - } - - private static string Tier(HeimdallProofTier tier) => tier == HeimdallProofTier.Strong ? "strong" : "weak"; - - private static string RefusalCode(HeimdallMoveRefusal code) => - code == HeimdallMoveRefusal.RequestInvalid ? "invalid_request" : WordBoundary().Replace(code.ToString(), "_$1").ToLowerInvariant(); - - [GeneratedRegex("(?The database's refusal of an overlapping merge: the live-merge unique index or the chain trigger's exclusion violation. - private static bool IsLiveMergeViolation(DbUpdateException error) - { - for (var current = (Exception?)error; current is not null; current = current.InnerException) - { - if (current is PostgresException { SqlState: "23P01" } or PostgresException { SqlState: "23505", ConstraintName: LiveMergeIndex }) - { - return true; - } - } - - return false; - } -} diff --git a/src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs b/src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs deleted file mode 100644 index 909d8b9..0000000 --- a/src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System.Globalization; -using System.Security.Cryptography; -using System.Text; -using System.Text.Json; -using Bifrost.Web.Configuration; -using Bifrost.Web.Domain; -using Microsoft.Extensions.Options; - -namespace Bifrost.Web.Features.Membership; - -/// -/// The chat host's pull of merge notices: GET the unacked feed, POST an ack. JSON only because the reader is the chat host's script (a xenos -/// boundary). The bearer is the chat host's own secret (ChatNotices:Token); an empty token turns both routes off. No cookie, no CORS, never stored. -/// -public static class MergeNoticeEndpoints -{ - private const int MaxAckBodyBytes = 1024; - - public static void Map(WebApplication app) - { - app.MapGet("/api/merge-notices/chat", async (HttpContext http, IOptions options, MergeNoticeFeed feed, CancellationToken ct) => - { - if (Gate(http, options.Value) is { } refused) - { - return refused; - } - - DateTimeOffset? after = null; - if (http.Request.Query.TryGetValue("after", out var raw) && raw.Count > 0) - { - if (!DateTimeOffset.TryParse(raw[0], CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var parsed)) - { - return Results.StatusCode(StatusCodes.Status400BadRequest); - } - - after = parsed; - } - - int? limit = http.Request.Query.TryGetValue("limit", out var rawLimit) && int.TryParse(rawLimit[0], CultureInfo.InvariantCulture, out var n) ? n : null; - var notices = await feed.ReadAsync(AccountMergeNoticeTarget.Chat, after, limit, ct); - return Results.Text(JsonSerializer.Serialize(notices.Select(Wire)), "application/json"); - }).AllowAnonymous(); - - app.MapPost("/api/merge-notices/chat/ack", async (HttpContext http, IOptions options, MergeNoticeFeed feed, CancellationToken ct) => - { - if (Gate(http, options.Value) is { } refused) - { - return refused; - } - - if (await ReadAckAsync(http.Request, ct) is not var (mergeId, kind)) - { - return Results.StatusCode(StatusCodes.Status400BadRequest); - } - - return await feed.AckAsync(AccountMergeNoticeTarget.Chat, mergeId, kind, ct) - ? Results.StatusCode(StatusCodes.Status204NoContent) - : Results.StatusCode(StatusCodes.Status404NotFound); - }).AllowAnonymous(); - } - - private static IResult? Gate(HttpContext http, ChatNoticesOptions options) - { - http.Response.Headers.CacheControl = "no-store"; - if (string.IsNullOrEmpty(options.Token)) - { - return Results.StatusCode(StatusCodes.Status404NotFound); - } - - var header = http.Request.Headers.Authorization.ToString(); - const string scheme = "Bearer "; - var presented = header.StartsWith(scheme, StringComparison.Ordinal) ? header[scheme.Length..] : string.Empty; - // Both sides are hashed first, so the comparison is over equal-length digests and says nothing about the token's length. - var matches = CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(presented)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Token))); - return matches && presented.Length > 0 ? null : Results.StatusCode(StatusCodes.Status401Unauthorized); - } - - private static async Task<(Guid MergeId, AccountMergeNoticeKind Kind)?> ReadAckAsync(HttpRequest request, CancellationToken ct) - { - var buffer = new byte[MaxAckBodyBytes + 1]; - var read = 0; - int n; - while (read < buffer.Length && (n = await request.Body.ReadAsync(buffer.AsMemory(read), ct)) > 0) - { - read += n; - } - - if (read == 0 || read > MaxAckBodyBytes) - { - return null; - } - - try - { - using var document = JsonDocument.Parse(buffer.AsMemory(0, read)); - var root = document.RootElement; - if (root.ValueKind != JsonValueKind.Object || - !root.TryGetProperty("merge_id", out var id) || id.ValueKind != JsonValueKind.String || !Guid.TryParse(id.GetString(), out var mergeId) || - !root.TryGetProperty("type", out var type) || type.ValueKind != JsonValueKind.String) - { - return null; - } - - AccountMergeNoticeKind? kind = type.GetString() switch - { - "merged" => AccountMergeNoticeKind.Merged, - "undone" => AccountMergeNoticeKind.Undone, - "final" => AccountMergeNoticeKind.Final, - _ => null - }; - return kind is { } k ? (mergeId, k) : null; - } - catch (JsonException) - { - return null; - } - } - - /// The wire shape, exactly these keys: ids in format D, times ISO 8601 UTC, no email, display name, Heimdall id or Matrix id. - private static Dictionary Wire(MergeNotice notice) => new() - { - ["type"] = notice.Kind.ToString().ToLowerInvariant(), - ["merge_id"] = notice.MergeId.ToString("D"), - ["occurred_at"] = notice.OccurredAt.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture), - ["grace_ends_at"] = notice.GraceEndsAt?.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture), - ["old_subject"] = notice.OldSubject.ToString("D"), - ["new_subject"] = notice.NewSubject.ToString("D"), - ["old_preferred_username"] = notice.OldPreferredUsername, - ["new_preferred_username"] = notice.NewPreferredUsername - }; -} diff --git a/src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs b/src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs deleted file mode 100644 index bc0fe05..0000000 --- a/src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs +++ /dev/null @@ -1,96 +0,0 @@ -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Microsoft.EntityFrameworkCore; - -namespace Bifrost.Web.Features.Membership; - -/// What the chat host is told about one merge. Derived from the merge row on every read; never stored. -public sealed record MergeNotice( - AccountMergeNoticeKind Kind, - Guid MergeId, - DateTimeOffset OccurredAt, - DateTimeOffset? GraceEndsAt, - Guid OldSubject, - Guid NewSubject, - string OldPreferredUsername, - string NewPreferredUsername); - -/// -/// The one owner of what a notice reader is told about merges: merged (CommittedUtc), undone (UndoneUtc) and final (FinalizedUtc) are read off -/// the AccountMerges row on every call, so a notice cannot disagree with the merge, and the reader's ack row is the only thing stored. -/// Reads only AccountMerges and UserAccounts; writes only AccountMergeNoticeAck. -/// -public sealed class MergeNoticeFeed(BifrostDbContext dbContext, TimeProvider timeProvider) -{ - public const int DefaultLimit = 50; - public const int MaxLimit = 200; - - private static readonly AccountMergeNoticeKind[] Kinds = [AccountMergeNoticeKind.Merged, AccountMergeNoticeKind.Undone, AccountMergeNoticeKind.Final]; - - private static DateTimeOffset? OccurredAt(AccountMerge merge, AccountMergeNoticeKind kind) => kind switch - { - AccountMergeNoticeKind.Merged => merge.CommittedUtc, - AccountMergeNoticeKind.Undone => merge.UndoneUtc, - _ => merge.FinalizedUtc - }; - - /// Unacked notices for , oldest first by (occurred_at, merge_id, kind), strictly later than when given. Acks are the cursor; after only narrows the scan. - public async Task> ReadAsync(AccountMergeNoticeTarget target, DateTimeOffset? after, int? limit, CancellationToken cancellationToken) - { - var take = limit is > 0 ? Math.Min(limit.Value, MaxLimit) : DefaultLimit; - var picked = new List<(AccountMerge Merge, AccountMergeNoticeKind Kind, DateTimeOffset At)>(); - // Each kind's own oldest `take` rows contain every row of the overall oldest `take`, so merging three bounded lists is exact. - foreach (var kind in Kinds) - { - var rows = await dbContext.AccountMerges.AsNoTracking() - .Where(x => (kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) != null) - .Where(x => after == null || (kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) > after) - .Where(x => !dbContext.AccountMergeNoticeAcks.Any(a => a.MergeId == x.Id && a.Kind == kind && a.Target == target)) - .OrderBy(x => kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) - .ThenBy(x => x.Id) - .Take(take) - .ToListAsync(cancellationToken); - picked.AddRange(rows.Select(x => (x, kind, OccurredAt(x, kind)!.Value))); - } - - var page = picked.OrderBy(x => x.At).ThenBy(x => x.Merge.Id).ThenBy(x => x.Kind).Take(take).ToList(); - var ids = page.SelectMany(x => new[] { x.Merge.FoldedUserAccountId, x.Merge.SurvivorUserAccountId }).Distinct().ToList(); - var names = await dbContext.UserAccounts.AsNoTracking().Where(x => ids.Contains(x.Id)) - .Select(x => new { x.Id, x.NormalizedBifrostIdentity }).ToDictionaryAsync(x => x.Id, x => x.NormalizedBifrostIdentity, cancellationToken); - return [.. page.Select(x => new MergeNotice( - x.Kind, x.Merge.Id, x.At, x.Merge.GraceEndsUtc, x.Merge.FoldedUserAccountId, x.Merge.SurvivorUserAccountId, - names.GetValueOrDefault(x.Merge.FoldedUserAccountId, string.Empty), names.GetValueOrDefault(x.Merge.SurvivorUserAccountId, string.Empty)))]; - } - - /// Records that the reader has seen (merge, kind). False when the feed would not emit that notice now (no such merge, or its timestamp unset); true otherwise, a repeat included. - public async Task AckAsync(AccountMergeNoticeTarget target, Guid mergeId, AccountMergeNoticeKind kind, CancellationToken cancellationToken) - { - var merge = await dbContext.AccountMerges.AsNoTracking().SingleOrDefaultAsync(x => x.Id == mergeId, cancellationToken); - if (merge is null || OccurredAt(merge, kind) is null) - { - return false; - } - - if (await dbContext.AccountMergeNoticeAcks.AnyAsync(x => x.MergeId == mergeId && x.Kind == kind && x.Target == target, cancellationToken)) - { - return true; - } - - dbContext.AccountMergeNoticeAcks.Add(new AccountMergeNoticeAck { MergeId = mergeId, Kind = kind, Target = target, AckedUtc = timeProvider.GetUtcNow() }); - try - { - await dbContext.SaveChangesAsync(cancellationToken); - } - catch (DbUpdateException) - { - // A concurrent ack of the same key won the unique index; the notice is acked, which is what the caller asked for. - dbContext.ChangeTracker.Clear(); - if (!await dbContext.AccountMergeNoticeAcks.AnyAsync(x => x.MergeId == mergeId && x.Kind == kind && x.Target == target, cancellationToken)) - { - throw; - } - } - - return true; - } -} diff --git a/src/Bifrost.Web/Features/Membership/MergePreview.cs b/src/Bifrost.Web/Features/Membership/MergePreview.cs deleted file mode 100644 index d241a68..0000000 --- a/src/Bifrost.Web/Features/Membership/MergePreview.cs +++ /dev/null @@ -1,93 +0,0 @@ -using Bifrost.Web.Domain; - -namespace Bifrost.Web.Features.Membership; - -/// -/// The only wording of what a merge would do, in closed vocabulary: counts by entry kind and action from , the -/// sentence for each block code, and the statements every merge carries. It decides nothing, and names no account: the plan holds none. -/// -public static class MergePreview -{ - public static IReadOnlyList Lines(MergePlan plan) - { - var lines = new List(); - foreach (var group in plan.Entries.GroupBy(x => (x.Kind, x.Action))) - { - var n = group.Count(); - lines.Add(group.Key switch - { - (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved) => - $"{Count(n, "open vote")} of the other account on motions you did not vote on move to the kept account.", - (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided) => - $"{Count(n, "open vote")} of the other account are set aside: the kept account already voted on that motion or cannot vote.", - (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved) => - $"{Count(n, "appraisal")} of the other account move to the kept account.", - (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Voided) => - $"{Count(n, "appraisal")} of the other account are set aside: the kept account already appraised the same thing or cannot.", - (AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed) => - "The other account's membership closes; the kept account's membership stays.", - (AccountMergeEntryKind.Standing, _) => - "The kept account is suspended too, because the other account is.", - (AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved) => - $"{Count(n, "patron event")} of the other account count for the kept account.", - _ => $"{Count(n, "other record")} change." - }); - } - - foreach (var (key, n) in plan.Left.OrderBy(x => x.Key, StringComparer.Ordinal)) - { - if (n > 0 && Remains(key) is { } noun) - { - lines.Add($"{Count(n, noun)} stay{(n == 1 ? "s" : string.Empty)} where {(n == 1 ? "it is" : "they are")}."); - } - } - - if (lines.Count == 0) - { - lines.Add("No votes, appraisals or patron events change."); - } - - return lines; - } - - /// Why a pair cannot be merged, by the plan's block code. No account is named; a code this class does not know gets a generic line, never an echo. - public static string Block(string code) => code switch - { - "same_account" => "These are the same account.", - "account_missing" => "One of the accounts no longer exists.", - "mind_account" => "An account that belongs to a Mind cannot be merged.", - "native_account" => "An account without a Heimdall sign-in cannot be merged.", - "merge_in_flight" => "One of the accounts is already part of a merge that has not finished.", - "survivor_is_folded" => "The account you would keep was already merged into another account.", - "already_folded" => "The other account was already merged into another account.", - "folded_is_survivor" => "Another account was merged into the other account, so it cannot be folded in turn.", - "sealed_ballot_pending" => "The other account has a sealed ballot on an open motion; wait until it is revealed.", - _ => "These accounts cannot be merged now." - }; - - /// The block for two accounts that both hold a login of one provider, which Heimdall will not combine. Providers only: no account is named. - public static string ProviderConflict(IEnumerable providerNames) => - $"Both accounts hold a {string.Join(" and ", providerNames)} login, and Heimdall will not combine two logins of one provider. Unlink one of them first, then prove that account again: the sign-in you gave still carries the old list of its logins."; - - /// What every merge says, whatever the plan: what it cannot carry over, what it asks again, and how long it can be undone. - public static IReadOnlyList Statements { get; } = - [ - "Chat: your chat history, rooms and keys belong to one chat id and cannot be moved. Keep the account you use in chat. Whichever you keep, the other chat id stays behind: rooms you were in on it must be joined again with the kept one, and messages encrypted for it cannot be read on the kept one.", - "Your connections (Twitch, Discord and others) will ask for consent again.", - "If you stream or moderate with StreamPixels and one of these connections is the one it uses for your channel, that connection stops until you reconnect it.", - "Roles and admin rights of the other account end; a steward must grant them again.", - "You will have one membership and one vote per motion: where both accounts voted on an open motion, the kept account's vote counts and the other is set aside. Nothing is added together.", - "You can undo this for 7 days, from Merge status. After that it is final.", - "The merge is approved with ordinary sign-ins, which is the weaker proof, and a notice stays on your account until the 7 days end." - ]; - - private static string Count(int n, string noun) => n == 1 ? $"1 {noun}" : $"{n} {noun}s"; - - private static string? Remains(string key) => key switch - { - "ConsentReceipts" => "consent record", - "PasskeyCredentials" => "passkey", - "LedgerEntries" => "ledger entry", - _ => null - }; -} diff --git a/src/Bifrost.Web/Features/Membership/MergeProofs.cs b/src/Bifrost.Web/Features/Membership/MergeProofs.cs deleted file mode 100644 index 86b45f4..0000000 --- a/src/Bifrost.Web/Features/Membership/MergeProofs.cs +++ /dev/null @@ -1,238 +0,0 @@ -using Bifrost.Web.Features.Heimdall; - -namespace Bifrost.Web.Features.Membership; - -public enum MergeSide -{ - /// The account signed in here. - Self, - - /// The second account, proved by its own fresh sign-in. - Other -} - -public enum PutOutcome -{ - Stored, - AmbiguousLogins, - TooManyProofs -} - -/// What a page may know of one side: no bearer, no Heimdall account id, no login names. -public sealed record MergeSideView( - Guid UserAccountId, IReadOnlyList ProvedProviders, IReadOnlyList LoginProviders, TimeSpan OldestProofAge, DateTimeOffset ExpiresAt); - -public sealed record MergeProofsView(MergeSideView? Self, MergeSideView? Other); - -public abstract record PeekResult -{ - private PeekResult() - { - } - - public sealed record Ready(MergeProof Survivor, IReadOnlyList Folded) : PeekResult; - - /// A side holds no live proof. - public sealed record Expired : PeekResult; - - /// Logins whose provider has no live proof, by provider name only. - public sealed record LoginsUnproved(IReadOnlyList Providers) : PeekResult; - - /// Both accounts hold a login of these providers, a pair Heimdall always refuses; by provider name only. - public sealed record ProviderConflict(IReadOnlyList Providers) : PeekResult; -} - -public abstract record UndoPeekResult -{ - private UndoPeekResult() - { - } - - public sealed record Ready(IReadOnlyList Proofs) : UndoPeekResult; - - public sealed record Expired : UndoPeekResult; - - public sealed record LoginsUnproved(IReadOnlyList Providers) : UndoPeekResult; -} - -/// -/// The one holder of live Heimdall bearers between a merge-proof sign-in's completion and the page's call into the saga, keyed by the -/// acting Bifrost account. It lives in this process's memory only and is never persisted, logged or sent to a browser; after a restart -/// the member proves again. It decides nothing about the merge: the saga owns consent, the move and the lifecycle, and Heimdall judges -/// each proof's tier and freshness. is only a margin under Heimdall's 300 s weak window, so a stale proof -/// is not sent to fail a merge. Provider is the only proof bookkeeping Bifrost has (the redeem names the provider, not the identity), -/// so a login list holding two logins of one provider is refused, and two sides holding a login of one provider are a conflict Peek names before consent. Every access, and the merge sweeper's tick, drops expired bearers. Peek never consumes: the caller s once the saga -/// has taken the proofs, so a refusal that wrote nothing does not cost a re-proof. -/// -public sealed class MergeProofs(TimeProvider timeProvider) -{ - public static readonly TimeSpan ProofLifetime = TimeSpan.FromSeconds(270); - - /// The saga's own bound on the proofs of one move. - public const int MaxProofsPerSide = 8; - - private sealed record Held(MergeProof Proof, DateTimeOffset RedeemedAt); - - private sealed class Side(Guid userAccountId, string heimdallAccountId) - { - public Guid UserAccountId { get; } = userAccountId; - - public string HeimdallAccountId { get; } = heimdallAccountId; - - public IReadOnlyList Logins { get; set; } = []; - - public Dictionary Proofs { get; } = new(StringComparer.Ordinal); - } - - private readonly Dictionary> _held = []; - private readonly object _gate = new(); - - public PutOutcome Put(Guid actorId, MergeSide side, MergeProof proof, Guid userAccountId, IReadOnlyList logins) - { - if (logins.GroupBy(x => x.Provider, StringComparer.Ordinal).Any(x => x.Count() > 1)) - { - return PutOutcome.AmbiguousLogins; - } - - lock (_gate) - { - var now = timeProvider.GetUtcNow(); - Prune(now); - var sides = _held.TryGetValue(actorId, out var existing) ? existing : _held[actorId] = []; - if (!sides.TryGetValue(side, out var held) || held.UserAccountId != userAccountId || held.HeimdallAccountId != proof.HeimdallAccountId) - { - held = new Side(userAccountId, proof.HeimdallAccountId); - } - - if (!held.Proofs.ContainsKey(proof.Provider) && held.Proofs.Count >= MaxProofsPerSide) - { - return PutOutcome.TooManyProofs; - } - - held.Logins = logins; - held.Proofs[proof.Provider] = new Held(proof, now); - sides[side] = held; - return PutOutcome.Stored; - } - } - - public MergeProofsView Snapshot(Guid actorId) - { - lock (_gate) - { - var now = timeProvider.GetUtcNow(); - Prune(now); - var sides = _held.GetValueOrDefault(actorId); - return new MergeProofsView(View(sides, MergeSide.Self, now), View(sides, MergeSide.Other, now)); - } - } - - public PeekResult Peek(Guid actorId, MergeSide survivorSide) - { - lock (_gate) - { - Prune(timeProvider.GetUtcNow()); - var sides = _held.GetValueOrDefault(actorId); - if (sides is null || !sides.TryGetValue(survivorSide, out var survivor) - || !sides.TryGetValue(survivorSide == MergeSide.Self ? MergeSide.Other : MergeSide.Self, out var folded)) - { - return new PeekResult.Expired(); - } - - var shared = survivor.Logins.Select(x => x.Provider).Intersect(folded.Logins.Select(x => x.Provider), StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); - if (shared.Length > 0) - { - return new PeekResult.ProviderConflict(shared); - } - - var unproved = UnprovedProviders(folded, folded.Logins.Select(x => x.Provider)); - return unproved.Count > 0 - ? new PeekResult.LoginsUnproved(unproved) - : new PeekResult.Ready(survivor.Proofs.Values.MaxBy(x => x.RedeemedAt)!.Proof, [.. folded.Proofs.Values.Select(x => x.Proof)]); - } - } - - /// The Self side's proofs for an undo, once every login whose id is in is proved. - public UndoPeekResult PeekUndo(Guid actorId, IReadOnlyCollection movedIdentityIds) - { - lock (_gate) - { - Prune(timeProvider.GetUtcNow()); - if (!_held.TryGetValue(actorId, out var sides) || !sides.TryGetValue(MergeSide.Self, out var self)) - { - return new UndoPeekResult.Expired(); - } - - var needed = self.Logins.Where(x => movedIdentityIds.Contains(x.Id)).Select(x => x.Provider).ToArray(); - var unproved = UnprovedProviders(self, needed); - if (needed.Length < movedIdentityIds.Count) - { - // A moved login the list does not hold cannot be proved by it. - return new UndoPeekResult.LoginsUnproved(unproved); - } - - return unproved.Count > 0 - ? new UndoPeekResult.LoginsUnproved(unproved) - : new UndoPeekResult.Ready([.. needed.Distinct(StringComparer.Ordinal).Select(x => self.Proofs[x].Proof)]); - } - } - - public void Clear(Guid actorId) - { - lock (_gate) - { - Prune(timeProvider.GetUtcNow()); - _held.Remove(actorId); - } - } - - /// Drops every expired bearer without any member touching the page; the merge sweeper's tick calls it, so none outlives plus one tick. - public void PruneExpired() - { - lock (_gate) - { - Prune(timeProvider.GetUtcNow()); - } - } - - private static List UnprovedProviders(Side side, IEnumerable providers) => - [.. providers.Distinct(StringComparer.Ordinal).Where(x => !side.Proofs.ContainsKey(x))]; - - private MergeSideView? View(Dictionary? sides, MergeSide which, DateTimeOffset now) => - sides is not null && sides.TryGetValue(which, out var side) - ? new MergeSideView( - side.UserAccountId, - [.. side.Proofs.Keys], - [.. side.Logins.Select(x => x.Provider)], - now - side.Proofs.Values.Min(x => x.RedeemedAt), - side.Proofs.Values.Min(x => x.RedeemedAt) + ProofLifetime) - : null; - - /// Drops every proof at or past its lifetime, then every side without one, then every actor without a side. - private void Prune(DateTimeOffset now) - { - foreach (var (actor, sides) in _held.ToArray()) - { - foreach (var (which, side) in sides.ToArray()) - { - foreach (var (provider, held) in side.Proofs.ToArray()) - { - if (now - held.RedeemedAt >= ProofLifetime) - { - side.Proofs.Remove(provider); - } - } - - if (side.Proofs.Count == 0) - { - sides.Remove(which); - } - } - - if (sides.Count == 0) - { - _held.Remove(actor); - } - } - } -} diff --git a/src/Bifrost.Web/Features/Membership/MergeWording.cs b/src/Bifrost.Web/Features/Membership/MergeWording.cs deleted file mode 100644 index 9d6984d..0000000 --- a/src/Bifrost.Web/Features/Membership/MergeWording.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System.Globalization; -using Bifrost.Web.Domain; - -namespace Bifrost.Web.Features.Membership; - -/// -/// The one closed set of words the merge pages say, so no page ever prints what the store holds: a state, a Heimdall refusal code, a -/// saga outcome and an undo answer each map to a sentence here, and anything this class does not know gets a generic line, never an -/// echo. Dates are UTC. -/// -public static class MergeWording -{ - public static string State(AccountMergeState state) => state switch - { - AccountMergeState.Proposed => "Proposed, not yet confirmed.", - AccountMergeState.Confirmed => "Confirmed; Heimdall has not yet moved the logins.", - AccountMergeState.HeimdallMoved => "The logins have moved; Bifrost is finishing the merge.", - AccountMergeState.Committed => "Merged. You can still undo it.", - AccountMergeState.Final => "Merged for good; the undo window has ended.", - AccountMergeState.UndoRequested => "Undo requested; the logins are being given back.", - AccountMergeState.HeimdallReversed => "The logins are back; Bifrost is restoring the accounts.", - AccountMergeState.Undone => "Undone; the accounts are separate again.", - AccountMergeState.Failed => "The merge did not happen and nothing was merged.", - _ => "In an unknown state." - }; - - /// Why Heimdall refused a merge, by its refusal code; null for a code this class does not know. - public static string? Failure(string code) => code switch - { - "app_auth_required" or "not_allowed_for_app" => "Heimdall would not take Bifrost's request.", - "not_reversible" => "Heimdall says those logins cannot be moved back.", - "proof_invalid" => "Heimdall did not accept a sign-in as proof.", - "same_account" => "Both sides were the same Heimdall account.", - "proof_stale" => "A sign-in was too old by the time Heimdall saw it.", - "identity_not_proved" => "A login was not proved by a fresh sign-in.", - "already_moved" => "Heimdall had already moved one of those logins.", - "provider_conflict" => "Both accounts hold a login of the same provider, which Heimdall will not combine.", - "identity_not_found" => "A login was no longer on its account.", - "invalid_request" => "Heimdall could not read the request.", - _ => null - }; - - /// The saga's last note on a merge, in words. Always a sentence: an outcome this class does not know is a retry line, never its own text. - public static string Outcome(string lastOutcome) => lastOutcome switch - { - "confirmed" => "Waiting for Heimdall to move the logins.", - "moved" => "Heimdall moved the logins.", - "refused" => "Heimdall refused the merge.", - "undo_requested" => "Waiting for Heimdall to give the logins back.", - "operator_failed" => "A steward ended this merge. Nothing was merged.", - "undo_operator_abandoned" => "A steward ended the undo, so the merge stands.", - "receipt_mismatch" => "Heimdall's answer did not match the merge. An operator must look at it.", - "proofs_unreadable" => "The stored proofs cannot be read. An operator must look at it.", - "transport" or "move_id_conflict" or "malformed or mismatched receipt" => "Heimdall could not be reached or gave an answer Bifrost could not use. It will try again.", - _ when lastOutcome.StartsWith("undo_", StringComparison.Ordinal) && Failure(lastOutcome["undo_".Length..]) is { } reason => - "Heimdall refused the undo, so the merge stands. " + reason, - _ => "Waiting to try again." - }; - - /// The words for a closed undo code ( or logins_unproved); empty for anything else. - public static string Undo(string code) => code switch - { - "requested" => "Undo requested. The logins are being given back.", - "not_committed" => "This merge is not in a state that can be undone.", - "grace_over" => "The undo window has ended.", - "not_survivor" => "Only the account the merge kept can undo it.", - "proof_account_mismatch" => "That sign-in was not for this account. Nothing was changed.", - "logins_unproved" => "Every login that moved needs a fresh sign-in first. Nothing was changed.", - _ => string.Empty - }; - - /// The words for a closed code the merge page answers a confirm or a start with; empty for anything else. - public static string Confirm(string code) => code switch - { - "blocked" => "These accounts cannot be merged now. Nothing was changed.", - "preview_stale" => "Something changed since you looked; review the merge again. Nothing was changed and your sign-ins are kept.", - "not_party" => "Only one of the two accounts can confirm this merge. Nothing was changed.", - "proof_account_mismatch" => "A sign-in was not for the account it was meant for. Nothing was changed.", - "proofs_needed" => "Both accounts need a fresh sign-in, one for every login of the account that would be folded. Nothing was changed.", - "consent_needed" => "Tick both boxes to confirm. Nothing was changed.", - "bad_choice" => "Choose which account to keep. Nothing was changed.", - _ => string.Empty - }; - - public static string UndoCode(UndoOutcome outcome) => outcome switch - { - UndoOutcome.Requested => "requested", - UndoOutcome.NotCommitted => "not_committed", - UndoOutcome.GraceOver => "grace_over", - UndoOutcome.NotSurvivor => "not_survivor", - UndoOutcome.ProofAccountMismatch => "proof_account_mismatch", - _ => "not_committed" - }; - - public static string TierNote(string? fromTier, DateTimeOffset graceEnds) => fromTier == "strong" - ? $"Approved with a passkey; you have until {Date(graceEnds)} to undo." - : $"Approved with ordinary sign-ins; you have until {Date(graceEnds)} to undo."; - - /// Whole days from to , rounded up, at least one while the window is open. - public static int DaysUntil(DateTimeOffset end, DateTimeOffset now) => Math.Max(1, (int)Math.Ceiling((end - now).TotalDays)); - - public static string DaysLeft(int days) => days == 1 ? "1 day left" : $"{days} days left"; - - public static string SurvivorNotice(int days) => $"A merge into your account can still be undone: {DaysLeft(days)}. Review it on Merge status."; - - public static string UndoRequestedNotice() => "A merge into your account is being undone: Heimdall is giving the logins back. Review it on Merge status."; - - public static string FrozenNotice() => "A merge is in progress; you cannot act until it settles."; - - public static string FoldedNotice(DateTimeOffset mergedOn) => - $"This account was merged on {Date(mergedOn)}; sign in with a login you had on it to reach the account that holds them."; - - public static string Date(DateTimeOffset when) => when.UtcDateTime.ToString("d MMM yyyy", CultureInfo.InvariantCulture) + " UTC"; -} diff --git a/src/Bifrost.Web/Pages/App/Merges/Index.cshtml b/src/Bifrost.Web/Pages/App/Merges/Index.cshtml deleted file mode 100644 index 1f8d341..0000000 --- a/src/Bifrost.Web/Pages/App/Merges/Index.cshtml +++ /dev/null @@ -1,72 +0,0 @@ -@page -@using Bifrost.Web.Domain -@model Bifrost.Web.Pages.App.Merges.IndexModel -@{ - ViewData["Title"] = "Stuck merges"; -} - -
-
- Merges -

Stuck account merges

-

- A merge listed here has stopped advancing on its own. Before ending one, read Heimdall's identity move by the move id shown - (docs/account-merge.md, Stuck merges). Ending a merge cannot be undone, and Bifrost never adopts a move Heimdall made. -

- - @if (!string.IsNullOrEmpty(Model.Notice)) - { - - } -
-
- -
- @if (Model.Merges.Count == 0) - { -
No merge is stuck.
- } - else - { -
- - - - - - - - - - - - - @foreach (var merge in Model.Merges) - { - - - - - - - - - } - -
MergeStateLast outcomeAttemptsMove id of this legEnd it
@merge.Id@merge.State@merge.LastOutcome@merge.Attempts@merge.MoveId - @if (!merge.CanSettle) - { - Still being retried; nothing to end. - } - else - { -
- - - -
- } -
-
- } -
diff --git a/src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs b/src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs deleted file mode 100644 index 865cb42..0000000 --- a/src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Features.Shared; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; -using Microsoft.EntityFrameworkCore; - -namespace Bifrost.Web.Pages.App.Merges; - -/// One in-flight merge the sweeper has stopped advancing, as an operator may see it: no account, Heimdall id or login of either side. -public sealed record StuckMerge(Guid Id, AccountMergeState State, string LastOutcome, int Attempts, string MoveId, bool CanSettle); - -/// -/// The operator's door for a stuck merge (ruling merge-stuck-end-only-typed-id), platform admins only. It lists in-flight merges that -/// stopped on a settleable outcome or have been retried eight times, with the stored move id of the leg in flight, and passes an -/// admin's choice and the typed move id to , the one writer. It calls no Heimdall. -/// -public sealed class IndexModel(BifrostDbContext dbContext, ICurrentBifrostActorAccessor actorAccessor, AccountMergeSaga saga) : PageModel -{ - private const int RetriesBeforeListed = 8; - - public const string Url = "/App/Merges"; - - private static readonly IReadOnlyDictionary ResultWords = new Dictionary - { - ["settled"] = "The merge was ended and the sweeper will not touch it again.", - ["not_stuck"] = "Nothing changed: that merge is not stuck on a state this choice can end.", - ["wrong_move_id"] = "Nothing changed: the move id typed is not the stored one of that leg.", - ["lost"] = "Nothing changed: the merge moved on by itself while you were settling it." - }; - - public IReadOnlyList Merges { get; private set; } = []; - - /// The words for the closed ?result= code of the last settle; null for no code or one this page does not know. - public string? Notice { get; private set; } - - public async Task OnGetAsync(string? result, CancellationToken cancellationToken) - { - if (!(await actorAccessor.GetAsync(cancellationToken)).IsPlatformAdmin) - { - return Forbid(); - } - - Notice = result is not null && ResultWords.TryGetValue(result, out var words) ? words : null; - var rows = await dbContext.AccountMerges.AsNoTracking() - .Where(x => (x.State == AccountMergeState.Confirmed || x.State == AccountMergeState.UndoRequested) - && (AccountMergeSaga.SettleableOutcomes.Contains(x.LastOutcome) || x.Attempts >= RetriesBeforeListed)) - .OrderBy(x => x.CreatedUtc) - .ToListAsync(cancellationToken); - Merges = [.. rows.Select(x => new StuckMerge( - x.Id, x.State, x.LastOutcome, x.Attempts, - (x.State == AccountMergeState.UndoRequested ? x.HeimdallReverseMoveId : x.HeimdallMoveId) ?? string.Empty, - AccountMergeSaga.IsSettleable(x)))]; - return Page(); - } - - public Task OnPostFailForwardAsync(Guid mergeId, string? moveId, CancellationToken cancellationToken) => - SettleAsync(mergeId, SettleChoice.FailForward, moveId, cancellationToken); - - public Task OnPostAbandonUndoAsync(Guid mergeId, string? moveId, CancellationToken cancellationToken) => - SettleAsync(mergeId, SettleChoice.AbandonUndo, moveId, cancellationToken); - - private async Task SettleAsync(Guid mergeId, SettleChoice choice, string? moveId, CancellationToken cancellationToken) - { - var actor = await actorAccessor.GetAsync(cancellationToken); - if (!actor.CanManageMembership || actor.UserAccount is null) - { - return Forbid(); - } - - var outcome = await saga.SettleStuckAsync(mergeId, choice, moveId ?? string.Empty, actor.UserAccount.Id, cancellationToken); - var code = outcome switch - { - SettleOutcome.Settled => "settled", - SettleOutcome.WrongMoveId => "wrong_move_id", - SettleOutcome.Lost => "lost", - _ => "not_stuck" - }; - return Redirect($"{Url}?result={code}"); - } -} diff --git a/src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml b/src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml deleted file mode 100644 index 1b72e29..0000000 --- a/src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml +++ /dev/null @@ -1,148 +0,0 @@ -@page -@model Bifrost.Web.Pages.Membership.MergeAccountsModel -@{ - ViewData["Title"] = "Merge two accounts"; -} - -
- Account merge -

Merge two accounts

-

- If one person holds two accounts, they can be merged into one. You prove both accounts with a fresh sign-in each, choose - which one stays, see what changes and confirm; nothing is named until both proofs exist, and the other account is only - ever the one Heimdall identified from your second sign-in. -

- - @if (Model.ResultMessage is not null) - { -
@Model.ResultMessage
- } - - @if (Model.ConfirmMessage is not null) - { -
@Model.ConfirmMessage
- } - - @if (Model.Stage == Bifrost.Web.Pages.Membership.MergeAccountsModel.MergeStage.Prove) - { -

Prove both accounts

-

- Sign-ins are held in memory for a few minutes and then dropped. For each account, name a provider that account holds: - signing in through a provider it does not hold would make an unrelated account. -

- -

This account

- @if (Model.SelfProved) - { -

This account is proved.

- } - else - { -
- @foreach (var provider in Model.LinkableProviders) - { -
- - -
- } -
- } - -

The other account

- @if (Model.OtherProved) - { -

The other account is proved.

- } - else - { -
- @foreach (var provider in Model.LinkableProviders) - { -
- - -
- } -
- } - } - else - { -

The two accounts

-
    -
  • This account: @Model.SelfName
  • -
  • The other account: @Model.OtherName
  • -
- - @if (Model.Keep is null) - { -

Choose the account that stays. The other one is folded into it.

- - } - else - { -

Keep @Model.KeptName

-

@Model.FoldedName is folded into it.

-
    - @foreach (var line in Model.PreviewLines) - { -
  • @line
  • - } -
- @foreach (var statement in Model.Statements) - { -

@statement

- } - -

- Keep @Model.FoldedName instead -

- - @if (Model.BlockWords.Count > 0) - { -
-
    - @foreach (var words in Model.BlockWords) - { -
  • @words
  • - } -
-
- } - else if (Model.Stage == Bifrost.Web.Pages.Membership.MergeAccountsModel.MergeStage.ProveRemaining) - { -

- @Model.FoldedName holds more logins. Sign in once more through each one, so Heimdall knows the whole account agrees. -

-
- @foreach (var provider in Model.ProvidersToProve) - { -
- - - -
- } -
- } - else if (Model.Stage == Bifrost.Web.Pages.Membership.MergeAccountsModel.MergeStage.Confirm) - { -
- - -

- -

-

- -

- -
- } - } - } -
diff --git a/src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml.cs b/src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml.cs deleted file mode 100644 index 1b2e0c1..0000000 --- a/src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml.cs +++ /dev/null @@ -1,270 +0,0 @@ -using System.Security.Claims; -using Bifrost.Web.Configuration; -using Bifrost.Web.Data; -using Bifrost.Web.Features.Heimdall; -using Bifrost.Web.Features.Membership; -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.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace Bifrost.Web.Pages.Membership; - -/// -/// Where a member merges two accounts: proves both by fresh sign-ins, chooses which one stays against a preview, ticks one box for each -/// account and confirms. The page owns only that choice and that consent. Its stage is derived from and the -/// query on every request, nothing about progress is kept in a cookie or a hidden field except the chosen direction and the preview's -/// digest, and both are re-checked by the saga. The other account is named (by display name only) once both proofs are held, and -/// found by no email, name or login string: it is the account Heimdall identified from the second proof. The page writes no merge, -/// vote, membership or journal row: inserts the one Confirmed row that is the consent. -/// -[Authorize] -[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] -public sealed class MergeAccountsModel( - ICurrentBifrostActorAccessor actors, - BifrostDbContext dbContext, - AccountMergeLedger ledger, - AccountMergeSaga saga, - MergeProofs proofs, - HeimdallAuthService heimdallAuthService, - IOptions hostOptions, - IOptions mergeOptions, - ILogger logger) : PageModel -{ - private const string KeepParameter = "keep"; - private const string MergeParameter = "merge"; - private const string Self = "self"; - private const string Other = "other"; - - public enum MergeStage - { - /// One side or both lack a proof: nothing is named. - Prove, - - /// Both sides are proved: the member chooses which stays. - Choose, - - /// A direction is chosen and the folded account's remaining logins are asked one sign-in each. - ProveRemaining, - - /// Everything the saga needs is held: the confirm form. - Confirm - } - - public MergeStage Stage { get; private set; } = MergeStage.Prove; - - public string? ResultMessage { get; private set; } - - public string? ConfirmMessage { get; private set; } - - public bool SelfProved { get; private set; } - - public bool OtherProved { get; private set; } - - /// Display names, set only once both sides are proved. - public string? SelfName { get; private set; } - - public string? OtherName { get; private set; } - - /// The chosen direction, "self" or "other", or null. - public string? Keep { get; private set; } - - public string? KeptName => Keep == Self ? SelfName : Keep == Other ? OtherName : null; - - public string? FoldedName => Keep == Self ? OtherName : Keep == Other ? SelfName : null; - - public IReadOnlyList PreviewLines { get; private set; } = []; - - public IReadOnlyList BlockWords { get; private set; } = []; - - public IReadOnlyList Statements => MergePreview.Statements; - - public IReadOnlyList ProvidersToProve { get; private set; } = []; - - public string Digest { get; private set; } = string.Empty; - - public IReadOnlyList LinkableProviders => HeimdallAuthService.LinkableProviders; - - public static string ProviderName(string provider) => MergeStatusModel.ProviderName(provider); - - private string? AccountId => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 } id ? id : null; - - /// Off, the page does not exist; a folded or frozen account is forbidden it, as it is Linked accounts. - public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) - { - if (!mergeOptions.Value.Enabled) - { - context.Result = NotFound(); - return; - } - - var actor = await actors.GetAsync(context.HttpContext.RequestAborted); - if (actor.Merge is not null || actor.UserAccount is null || AccountId is null) - { - context.Result = Forbid(); - return; - } - - await base.OnPageHandlerExecutionAsync(context, next); - } - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - ResultMessage = HeimdallLinkOutcomes.Wording(Request.Query[HeimdallLinkOutcomes.ResultParameter].ToString()); - ConfirmMessage = MergeWording.Confirm(Request.Query[MergeParameter].ToString()) is { Length: > 0 } words ? words : null; - - var me = (await actors.GetAsync(cancellationToken)).UserAccount!.Id; - var held = proofs.Snapshot(me); - SelfProved = held.Self is not null; - OtherProved = held.Other is not null; - if (held.Self is not { } self || held.Other is not { } other) - { - return; - } - - var names = await dbContext.UserAccounts.AsNoTracking() - .Where(x => x.Id == self.UserAccountId || x.Id == other.UserAccountId) - .ToDictionaryAsync(x => x.Id, x => x.DisplayName, cancellationToken); - SelfName = names.GetValueOrDefault(self.UserAccountId); - OtherName = names.GetValueOrDefault(other.UserAccountId); - Stage = MergeStage.Choose; - if (SideOf(Request.Query[KeepParameter].ToString()) is not { } survivorSide) - { - return; - } - - Keep = survivorSide == MergeSide.Self ? Self : Other; - var (survivor, folded) = survivorSide == MergeSide.Self ? (self, other) : (other, self); - var plan = await ledger.PlanAsync(survivor.UserAccountId, folded.UserAccountId, cancellationToken); - Digest = plan.Digest(survivor.UserAccountId, folded.UserAccountId); - PreviewLines = MergePreview.Lines(plan); - BlockWords = [.. plan.Blocks.Select(MergePreview.Block)]; - switch (proofs.Peek(me, survivorSide)) - { - case PeekResult.ProviderConflict conflict: - BlockWords = [.. BlockWords, MergePreview.ProviderConflict(conflict.Providers.Select(ProviderName))]; - break; - case PeekResult.Ready when plan.Blocks.Count == 0: - Stage = MergeStage.Confirm; - break; - case PeekResult.LoginsUnproved unproved: - ProvidersToProve = unproved.Providers; - Stage = MergeStage.ProveRemaining; - break; - } - } - - /// Starts a fresh sign-in of the account signed in here. - public Task OnPostProveSelfAsync(string? via, CancellationToken cancellationToken) => BeginAsync(MergeSide.Self, via, cancellationToken); - - /// Starts a fresh sign-in of the other account. The member names the provider: Bifrost never guesses one. - public Task OnPostProveOtherAsync(string? via, CancellationToken cancellationToken) => BeginAsync(MergeSide.Other, via, cancellationToken); - - /// Starts the next sign-in the chosen folded account still owes; its side follows from the chosen direction. - public Task OnPostProveRemainingAsync(string? via, string? keep, CancellationToken cancellationToken) => - SideOf(keep) is { } survivorSide - ? BeginAsync(survivorSide == MergeSide.Self ? MergeSide.Other : MergeSide.Self, via, cancellationToken) - : Task.FromResult(Refused(null, "bad_choice")); - - /// - /// The member's consent: both boxes, the direction and the digest of the preview they saw. A refusal writes nothing and keeps the - /// proofs; only a Confirmed row spends them. - /// - public async Task OnPostConfirmAsync(string? keep, string? digest, bool consentSelf, bool consentOther, CancellationToken cancellationToken) - { - if (SideOf(keep) is not { } survivorSide) - { - return Refused(null, "bad_choice"); - } - - if (!consentSelf || !consentOther) - { - return Refused(keep, "consent_needed"); - } - - var me = (await actors.GetAsync(cancellationToken)).UserAccount!.Id; - var held = proofs.Snapshot(me); - var peeked = proofs.Peek(me, survivorSide); - if (peeked is PeekResult.ProviderConflict) - { - return Refused(keep, "blocked"); - } - - if (held.Self is not { } self || held.Other is not { } other || peeked is not PeekResult.Ready ready) - { - return Refused(keep, "proofs_needed"); - } - - var (survivor, folded) = survivorSide == MergeSide.Self ? (self, other) : (other, self); - var outcome = await saga.ConfirmAsync( - new ConfirmMergeRequest(me, survivor.UserAccountId, folded.UserAccountId, digest ?? string.Empty, ready.Survivor, ready.Folded), cancellationToken); - switch (outcome) - { - case ConfirmOutcome.Confirmed confirmed: - proofs.Clear(me); - try - { - await saga.AdvanceAsync(confirmed.MergeId, cancellationToken); - } - catch (Exception error) when (error is not OperationCanceledException) - { - // The stored state is the truth and the sweeper resumes it. - logger.LogWarning("Account merge {MergeId} inline advance failed: {Error}", confirmed.MergeId, error.GetType().Name); - } - - return RedirectToPage("/Membership/MergeStatus"); - case ConfirmOutcome.Blocked: - return Refused(keep, "blocked"); - case ConfirmOutcome.PreviewStale: - return Refused(keep, "preview_stale"); - case ConfirmOutcome.NotParty: - return Refused(keep, "not_party"); - default: - return Refused(keep, "proof_account_mismatch"); - } - } - - private static MergeSide? SideOf(string? keep) => keep switch - { - Self => MergeSide.Self, - Other => MergeSide.Other, - _ => null - }; - - private async Task BeginAsync(MergeSide side, string? via, CancellationToken cancellationToken) - { - try - { - var start = side == MergeSide.Self - ? (Func>)(id => heimdallAuthService.StartMergeProveSelfAsync( - id, via, ReturnPath, hostOptions.Value.PublicBaseUrl, Request.Cookies, cancellationToken)) - : id => heimdallAuthService.StartMergeProveOtherAsync( - id, via, ReturnPath, hostOptions.Value.PublicBaseUrl, Request.Cookies, cancellationToken); - var started = await start(AccountId!); - Response.Cookies.Append(started.CookieName, started.CookieValue, HeimdallAttemptCookie.Options()); - return Redirect(started.AuthorizationUrl.ToString()); - } - catch (HeimdallAuthException error) - { - logger.LogWarning("Merge proof start refused: {Reason}", error.Message); - return RedirectToPage(null, new Dictionary { [HeimdallLinkOutcomes.ResultParameter] = HeimdallLinkOutcomes.Code(HeimdallLinkOutcome.Error) }); - } - } - - private const string ReturnPath = "/Membership/MergeAccounts"; - - private IActionResult Refused(string? keep, string code) - { - var query = new Dictionary(); - if (keep is Self or Other) - { - query[KeepParameter] = keep; - } - - query[MergeParameter] = code; - return RedirectToPage(null, query); - } -} diff --git a/src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml b/src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml deleted file mode 100644 index 95f2d32..0000000 --- a/src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml +++ /dev/null @@ -1,100 +0,0 @@ -@page -@model Bifrost.Web.Pages.Membership.MergeStatusModel -@{ - ViewData["Title"] = "Merge status"; -} - -
- Account merge -

Merge status

-

- A merge folds one account into another. The account it kept can undo it for seven days, with a fresh sign-in for - every login that moved. -

- - @if (Model.ResultMessage is not null) - { -
@Model.ResultMessage
- } - - @if (Model.UndoMessage is not null) - { -
@Model.UndoMessage
- } - - @if (Model.Merges.Count == 0) - { -

There is no merge to show for this account.

- } - - @foreach (var merge in Model.Merges) - { -
- @merge.State - @if (merge.Why is not null) - { -

@merge.Why

- } - @if (merge.Outcome is not null) - { -

@merge.Outcome

- } -
    - @if (merge.Confirmed is not null) - { -
  • Confirmed @merge.Confirmed
  • - } - @if (merge.Committed is not null) - { -
  • Merged @merge.Committed
  • - } - @if (merge.GraceEnds is not null) - { -
  • Undo window ends @merge.GraceEnds
  • - } - @if (merge.Final is not null) - { -
  • Final @merge.Final
  • - } - @if (merge.SurvivorProofs.Count > 0) - { -
  • Kept account proved with: @string.Join(", ", merge.SurvivorProofs)
  • - } - @if (merge.FoldedProofs.Count > 0) - { -
  • Folded account proved with: @string.Join(", ", merge.FoldedProofs)
  • - } -
- @if (merge.DaysLeft is not null) - { -

@merge.DaysLeft

- } - @if (merge.TierNote is not null) - { -

@merge.TierNote

- } - - @if (merge.CanUndo) - { - @if (merge.Ready) - { -
- - -
- } - else - { -

To undo, sign in again through each login that moved. The sign-ins are held in memory for a few minutes.

- @foreach (var provider in merge.NeedProof) - { -
- - -
- } - } - } -
- } -
diff --git a/src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml.cs b/src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml.cs deleted file mode 100644 index 00cc86f..0000000 --- a/src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml.cs +++ /dev/null @@ -1,206 +0,0 @@ -using System.Security.Claims; -using System.Text.Json; -using Bifrost.Web.Configuration; -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Heimdall; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Features.Shared; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; - -namespace Bifrost.Web.Pages.Membership; - -/// -/// The member's own merge page: the merges that kept this account (up to five) and the one its frozen or folded standing names, in -/// 's closed words, and the undo. It reads merge rows and writes none: undo is the saga's -/// followed by its own , with fresh proofs -/// of every moved login held by . A person who signed in through a login that moved is the survivor here, so -/// there is no separate folded-side undo. Nothing the query, the form or the store holds is shown except as a closed code's words, and -/// no account name, id, email or login of either side is rendered. -/// -[Authorize] -[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] -public sealed class MergeStatusModel( - ICurrentBifrostActorAccessor actors, - BifrostDbContext dbContext, - AccountMergeSaga saga, - MergeProofs proofs, - HeimdallAuthService heimdallAuthService, - IOptions hostOptions, - TimeProvider timeProvider, - ILogger logger) : PageModel -{ - private const int MaxListed = 5; - private const string UndoParameter = "undo"; - private const string LoginsUnproved = "logins_unproved"; - - public sealed record MergeRow( - Guid Id, - string State, - string? Why, - string? Outcome, - string? Confirmed, - string? Committed, - string? GraceEnds, - string? Final, - string? DaysLeft, - string? TierNote, - IReadOnlyList SurvivorProofs, - IReadOnlyList FoldedProofs, - bool CanUndo, - bool Ready, - IReadOnlyList NeedProof); - - public IReadOnlyList Merges { get; private set; } = []; - - public string? ResultMessage { get; private set; } - - public string? UndoMessage { get; private set; } - - public static string ProviderName(string provider) => - HeimdallAuthService.LinkableProviders.Contains(provider) ? LinkedAccountsModel.ProviderName(provider) : provider == "passkey" ? "Passkey" : "another provider"; - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - ResultMessage = HeimdallLinkOutcomes.Wording(Request.Query[HeimdallLinkOutcomes.ResultParameter].ToString()); - UndoMessage = MergeWording.Undo(Request.Query[UndoParameter].ToString()) is { Length: > 0 } words ? words : null; - - var actor = await actors.GetAsync(cancellationToken); - var me = actor.UserAccount?.Id; - var rows = me is { } id - ? await dbContext.AccountMerges.AsNoTracking().Where(x => x.SurvivorUserAccountId == id).OrderByDescending(x => x.CreatedUtc).Take(MaxListed).ToListAsync(cancellationToken) - : []; - if (actor.Merge is { } standing && rows.All(x => x.Id != standing.MergeId) - && await dbContext.AccountMerges.AsNoTracking().SingleOrDefaultAsync(x => x.Id == standing.MergeId, cancellationToken) is { } named) - { - rows.Add(named); - } - - Merges = [.. rows.Select(x => Row(x, me))]; - } - - /// Starts a fresh sign-in of this account through , held in memory until the undo takes it. - public async Task OnPostProveForUndoAsync(string? via, CancellationToken cancellationToken) - { - if (User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is not { Length: > 0 } accountId) - { - return Result(HeimdallLinkOutcome.Error); - } - - try - { - var started = await heimdallAuthService.StartMergeProveSelfAsync( - accountId, via, HeimdallLinkReturn, hostOptions.Value.PublicBaseUrl, Request.Cookies, cancellationToken); - Response.Cookies.Append(started.CookieName, started.CookieValue, HeimdallAttemptCookie.Options()); - return Redirect(started.AuthorizationUrl.ToString()); - } - catch (HeimdallAuthException error) - { - logger.LogWarning("Merge undo proof start refused: {Reason}", error.Message); - return Result(HeimdallLinkOutcome.Error); - } - } - - /// Asks the saga to undo one merge with the proofs this member holds, then runs its step function once, as the sweeper would. - public async Task OnPostUndoAsync(string? mergeId, CancellationToken cancellationToken) - { - var actor = await actors.GetAsync(cancellationToken); - if (actor.UserAccount is not { } me || !Guid.TryParse(mergeId, out var id) - || await dbContext.AccountMerges.AsNoTracking().SingleOrDefaultAsync(x => x.Id == id, cancellationToken) is not { } merge - || merge.SurvivorUserAccountId != me.Id) - { - return Undone("not_survivor"); - } - - if (proofs.PeekUndo(me.Id, MovedIds(merge)) is not UndoPeekResult.Ready { Proofs.Count: > 0 } ready) - { - return Undone(LoginsUnproved); - } - - var outcome = await saga.RequestUndoAsync(id, me.Id, ready.Proofs, cancellationToken); - if (outcome is UndoOutcome.Requested) - { - proofs.Clear(me.Id); - try - { - await saga.AdvanceAsync(id, cancellationToken); - } - catch (Exception error) when (error is not OperationCanceledException) - { - // The saga's stored state is the truth and the sweeper resumes it. - logger.LogWarning("Account merge {MergeId} inline advance failed: {Error}", id, error.GetType().Name); - } - } - - return Undone(MergeWording.UndoCode(outcome)); - } - - private const string HeimdallLinkReturn = "/Membership/MergeStatus"; - - private MergeRow Row(AccountMerge merge, Guid? me) - { - var now = timeProvider.GetUtcNow(); - var open = merge.State == AccountMergeState.Committed && merge.GraceEndsUtc is { } end && now < end; - var canUndo = open && me == merge.SurvivorUserAccountId; - var ready = false; - IReadOnlyList need = []; - if (canUndo) - { - switch (proofs.PeekUndo(me!.Value, MovedIds(merge))) - { - case UndoPeekResult.Ready { Proofs.Count: > 0 }: - ready = true; - break; - case UndoPeekResult.LoginsUnproved { Providers.Count: > 0 } unproved: - need = unproved.Providers; - break; - default: - need = HeimdallAuthService.LinkableProviders; - break; - } - } - - var inGrace = merge.State is AccountMergeState.Committed or AccountMergeState.UndoRequested && merge.GraceEndsUtc > now; - return new MergeRow( - merge.Id, - MergeWording.State(merge.State), - merge.State == AccountMergeState.Failed ? MergeWording.Failure(merge.FailureCode) : null, - merge.State is AccountMergeState.Committed or AccountMergeState.Failed or AccountMergeState.Confirmed or AccountMergeState.HeimdallMoved - or AccountMergeState.UndoRequested or AccountMergeState.HeimdallReversed - ? MergeWording.Outcome(merge.LastOutcome) - : null, - merge.ConfirmedUtc is { } confirmed ? MergeWording.Date(confirmed) : null, - merge.CommittedUtc is { } committed ? MergeWording.Date(committed) : null, - merge.GraceEndsUtc is { } graceEnds ? MergeWording.Date(graceEnds) : null, - merge.FinalizedUtc is { } final ? MergeWording.Date(final) : null, - inGrace && merge.GraceEndsUtc is { } until ? MergeWording.DaysLeft(MergeWording.DaysUntil(until, now)) : null, - inGrace && merge.GraceEndsUtc is { } by ? MergeWording.TierNote(merge.ProofFromTier, by) : null, - merge.SurvivorProofProvider.Length > 0 ? [ProviderName(merge.SurvivorProofProvider)] : [], - [.. merge.FoldedProofProviders.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(ProviderName)], - canUndo, - ready, - need); - } - - private static IReadOnlyCollection MovedIds(AccountMerge merge) - { - try - { - return merge.MovedIdentityIds is { } json ? JsonSerializer.Deserialize(json) ?? [] : []; - } - catch (JsonException) - { - return []; - } - } - - private IActionResult Undone(string code) => - RedirectToPage(null, new Dictionary { [UndoParameter] = code }); - - private IActionResult Result(HeimdallLinkOutcome outcome) => - RedirectToPage(null, new Dictionary { [HeimdallLinkOutcomes.ResultParameter] = HeimdallLinkOutcomes.Code(outcome) }); -} diff --git a/src/Bifrost.Web/Pages/Shared/Components/MergeNotice/Default.cshtml b/src/Bifrost.Web/Pages/Shared/Components/MergeNotice/Default.cshtml deleted file mode 100644 index c9ea380..0000000 --- a/src/Bifrost.Web/Pages/Shared/Components/MergeNotice/Default.cshtml +++ /dev/null @@ -1,5 +0,0 @@ -@model string - diff --git a/src/Bifrost.Web/ViewComponents/MergeNotice.cs b/src/Bifrost.Web/ViewComponents/MergeNotice.cs deleted file mode 100644 index 5a3c779..0000000 --- a/src/Bifrost.Web/ViewComponents/MergeNotice.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Features.Shared; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; - -namespace Bifrost.Web.ViewComponents; - -/// -/// The layout's merge notice for a signed-in actor: the survivor of a Committed or UndoRequested merge inside its grace (days left), a -/// frozen account (a merge is in progress) or a folded one (where to sign in). It reads the merge row once per page view and keeps no -/// state of its own; the words are 's, and no account name or id is ever in them. -/// -public sealed class MergeNotice(ICurrentBifrostActorAccessor actors, BifrostDbContext dbContext, TimeProvider timeProvider) : ViewComponent -{ - public async Task InvokeAsync() - { - var actor = await actors.GetAsync(HttpContext.RequestAborted); - var text = await TextAsync(actor, HttpContext.RequestAborted); - return text is null ? Content(string.Empty) : View("Default", text); - } - - private async Task TextAsync(CurrentBifrostActor actor, CancellationToken cancellationToken) - { - var now = timeProvider.GetUtcNow(); - if (actor.Merge is { } standing) - { - if (standing is MergeStanding.Frozen) - { - return MergeWording.FrozenNotice(); - } - - var mergedOn = await dbContext.AccountMerges.AsNoTracking() - .Where(x => x.Id == standing.MergeId) - .Select(x => x.CommittedUtc ?? x.CreatedUtc) - .FirstOrDefaultAsync(cancellationToken); - return MergeWording.FoldedNotice(mergedOn); - } - - if (actor.UserAccount is not { } account) - { - return null; - } - - var open = await dbContext.AccountMerges.AsNoTracking() - .Where(x => x.SurvivorUserAccountId == account.Id - && (x.State == AccountMergeState.Committed || x.State == AccountMergeState.UndoRequested) - && x.GraceEndsUtc > now) - .OrderBy(x => x.GraceEndsUtc) - .Select(x => new { x.State, x.GraceEndsUtc }) - .FirstOrDefaultAsync(cancellationToken); - return open is null ? null - : open.State == AccountMergeState.UndoRequested ? MergeWording.UndoRequestedNotice() - : MergeWording.SurvivorNotice(MergeWording.DaysUntil(open.GraceEndsUtc!.Value, now)); - } -} diff --git a/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs b/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs deleted file mode 100644 index e148132..0000000 --- a/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs +++ /dev/null @@ -1,439 +0,0 @@ -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; - -/// A folded member's browser and Heimdall's patron intake, over HTTP: the merge ledger is the single gate behind both. -public sealed class AccountMergeHttpTests(TestWebApplicationFactory factory) : IClassFixture -{ - private sealed record Seeded(Guid Survivor, Guid Folded, Guid Motion, string FoldedHeimdallId, long SurvivorGitHubId, long FoldedGitHubId); - - private async Task SeedAsync() - { - using var scope = factory.Services.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - 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 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 VoteAsync(HttpClient client, Guid motion, string token) => - client.PostAsync("/App/Motions?handler=Vote", new FormUrlEncodedContent(new Dictionary - { - ["motionId"] = motion.ToString(), ["choice"] = "For", ["comment"] = "yes", ["__RequestVerificationToken"] = token - })); - - private async Task WithDb(Func> read) - { - using var scope = factory.Services.CreateScope(); - return await read(scope.ServiceProvider.GetRequiredService()); - } - - private Task VoteRowsAsync(Guid motion) => WithDb(db => db.Votes.IgnoreQueryFilters().CountAsync(x => x.MotionId == motion)); - - private async Task MergeAsync(Seeded s, AccountMergeState state) - { - using var scope = factory.Services.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - 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)); - } - - private async Task IntakeAsync(Seeded s, string eventId) - { - var payload = JsonSerializer.Serialize(new - { - heimdallAccountId = s.FoldedHeimdallId, provider = "PayPal", providerEventId = eventId, 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); - return response.StatusCode; - } - - private Task> EventOwnersAsync(Seeded s) => - WithDb(db => db.PatronSupportEvents.Where(x => x.UserAccountId == s.Survivor || x.UserAccountId == s.Folded).Select(x => x.UserAccountId).ToListAsync()); - - /// Lands the merge through the ledger's own commit, as the saga will: the move done, then the Bifrost records reduced. - private async Task CommitMergeAsync(Seeded s) - { - var merge = await MergeAsync(s, AccountMergeState.HeimdallMoved); - await WithDb(async db => - { - using var scope = factory.Services.CreateScope(); - await scope.ServiceProvider.GetRequiredService().CommitAsync(merge, default); - return 0; - }); - return merge; - } - - [Fact] - public async Task Patron_intake_for_a_folded_heimdall_id_records_on_the_survivor() - { - var s = await SeedAsync(); - await MergeAsync(s, AccountMergeState.Final); - - Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, $"WH-{Guid.NewGuid():N}")); - - Assert.Equal([s.Survivor], await EventOwnersAsync(s)); - } - - [Fact] - public async Task A_patron_event_that_lands_during_grace_is_journalled_once_and_undo_moves_it_back_to_the_folded_account() - { - var s = await SeedAsync(); - var merge = await CommitMergeAsync(s); - var eventId = $"WH-{Guid.NewGuid():N}"; - - Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId)); - Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId)); // the provider retries: nothing doubles - Assert.Equal([s.Survivor], await EventOwnersAsync(s)); - Assert.Equal(1, await WithDb(db => db.AccountMergeEntries.CountAsync(x => x.MergeId == merge && x.Kind == AccountMergeEntryKind.PatronSupportEvent))); - - await SetStateAsync(merge, AccountMergeState.HeimdallReversed); - await WithDb(async db => - { - using var scope = factory.Services.CreateScope(); - await scope.ServiceProvider.GetRequiredService().UndoLocalAsync(merge, default); - return 0; - }); - - Assert.Equal([s.Folded], await EventOwnersAsync(s)); - } - - private Task> PatronJournalAsync(Guid merge) => - WithDb(db => db.AccountMergeEntries.Where(x => x.MergeId == merge).OrderBy(x => x.Seq).ToListAsync()); - - [Fact] - public async Task A_single_patron_event_during_grace_is_journalled_by_its_own_delivery_and_undo_moves_it_back() - { - var s = await SeedAsync(); - var merge = await CommitMergeAsync(s); - - Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, $"WH-{Guid.NewGuid():N}")); // no retry follows - - var journal = await PatronJournalAsync(merge); - Assert.Single(journal, x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); - Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count()); // the new entry takes its own Seq - await SetStateAsync(merge, AccountMergeState.HeimdallReversed); - await WithDb(async db => - { - using var scope = factory.Services.CreateScope(); - await scope.ServiceProvider.GetRequiredService().UndoLocalAsync(merge, default); - return 0; - }); - Assert.Equal([s.Folded], await EventOwnersAsync(s)); - } - - [Fact] - public async Task A_provider_retry_journals_an_event_the_first_delivery_left_unjournalled() - { - var s = await SeedAsync(); - var merge = await CommitMergeAsync(s); - var eventId = $"WH-{Guid.NewGuid():N}"; - await WithDb(async db => // the first delivery recorded on the survivor, then died before journalling - { - db.PatronSupportEvents.Add(new PatronSupportEvent - { - UserAccountId = s.Survivor, Provider = ExternalPatronProvider.PayPal, ProviderEventId = eventId, ExternalSupportId = "CAPTURE-1", - Kind = PatronSupportEventKind.OneTimeDonation, Amount = 25m, SupportedAtUtc = DateTimeOffset.UtcNow, RecordedAtUtc = DateTimeOffset.UtcNow - }); - await db.SaveChangesAsync(); - return 0; - }); - Assert.DoesNotContain(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); - - Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId)); - - Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); - Assert.Equal([s.Survivor], await EventOwnersAsync(s)); - } - - [Fact] - public async Task A_stripe_checkout_opened_by_an_account_that_folded_pays_the_survivor_and_is_journalled() - { - var s = await SeedAsync(); - var merge = await CommitMergeAsync(s); - using var response = await StripeCheckoutAsync(s); - - Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); - Assert.Equal([s.Survivor], await EventOwnersAsync(s)); - var entry = Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); - Assert.Equal(s.Folded, entry.PriorUserAccountId); // the journal names the folded account as the previous owner - - await SetStateAsync(merge, AccountMergeState.HeimdallReversed); - await UndoAsync(merge); - Assert.Equal([s.Folded], await EventOwnersAsync(s)); // so an undo sends the donation back where it was opened - } - - private async Task StripeCheckoutAsync(Seeded s) - { - var payload = JsonSerializer.Serialize(new - { - id = $"evt_{Guid.NewGuid():N}", type = "checkout.session.completed", created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), - data = new { @object = new { id = $"cs_{Guid.NewGuid():N}", customer = "cus_1", currency = "usd", amount_total = 1900, payment_status = "paid", - metadata = new Dictionary { ["bifrost_user_account_id"] = s.Folded.ToString("N") } } } - }); - var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(); - using var hasher = new HMACSHA256(Encoding.UTF8.GetBytes("whsec_test_webhook_secret")); - using var request = new HttpRequestMessage(HttpMethod.Post, "/patronage/stripe/webhook"); - request.Headers.Add("Stripe-Signature", $"t={timestamp},v1={Convert.ToHexString(hasher.ComputeHash(Encoding.UTF8.GetBytes($"{timestamp}.{payload}"))).ToLowerInvariant()}"); - request.Content = new StringContent(payload, Encoding.UTF8, "application/json"); - using var client = factory.CreateClient(); - - return await client.SendAsync(request); - } - - private Task UndoAsync(Guid merge) => - WithDb(async db => - { - using var scope = factory.Services.CreateScope(); - await scope.ServiceProvider.GetRequiredService().UndoLocalAsync(merge, default); - return 0; - }); - - [Fact] - public async Task A_stripe_checkout_opened_by_an_account_that_folded_into_a_suspended_survivor_is_refused_as_not_configured_and_records_nothing() - { - var s = await SeedAsync(); - await CommitMergeAsync(s); - await WithDb(async db => - { - (await db.Memberships.SingleAsync(x => x.UserAccountId == s.Survivor)).Status = MembershipStatus.Suspended; - await db.SaveChangesAsync(); - return 0; - }); - - using var response = await StripeCheckoutAsync(s); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); - Assert.Empty(await EventOwnersAsync(s)); - } - - [Fact] - public async Task The_admin_ledgers_manual_patron_record_for_a_folded_account_lands_on_the_survivor_and_is_journalled() - { - var s = await SeedAsync(); - var merge = await CommitMergeAsync(s); - - await WithDb(async db => - { - using var scope = factory.Services.CreateScope(); - await scope.ServiceProvider.GetRequiredService().RecordSupportEventAsync( - s.Survivor, s.Folded, PatronSupportEventKind.OneTimeDonation, 10m, "USD", "manual-1", ExternalPatronProvider.Manual, - string.Empty, string.Empty, string.Empty, DateTimeOffset.UtcNow, false, string.Empty, default); // as Pages/App/Ledger records it - return 0; - }); - - Assert.Equal([s.Survivor], await EventOwnersAsync(s)); - var entry = Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); - Assert.Equal(s.Folded, entry.PriorUserAccountId); - } - - [Fact] - public async Task A_provider_retry_of_an_event_stranded_on_the_folded_account_journals_nothing_because_nothing_moved() - { - var s = await SeedAsync(); - var merge = await CommitMergeAsync(s); - var eventId = $"WH-{Guid.NewGuid():N}"; - await WithDb(async db => // recorded on the folded account by a delivery that straddled the commit - { - db.PatronSupportEvents.Add(new PatronSupportEvent - { - UserAccountId = s.Folded, Provider = ExternalPatronProvider.PayPal, ProviderEventId = eventId, ExternalSupportId = "CAPTURE-1", - Kind = PatronSupportEventKind.OneTimeDonation, Amount = 25m, SupportedAtUtc = DateTimeOffset.UtcNow, RecordedAtUtc = DateTimeOffset.UtcNow - }); - await db.SaveChangesAsync(); - return 0; - }); - - Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId)); - - Assert.DoesNotContain(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); - Assert.Equal([s.Folded], await EventOwnersAsync(s)); - } - - [Fact] - public async Task A_folded_bootstrap_admins_sign_in_does_not_reactivate_the_merged_membership_and_an_approval_is_refused() - { - var s = await SeedAsync(); - await CommitMergeAsync(s); - using var folded = ClientFor(s.FoldedGitHubId, "test-admin"); // the bootstrap login: every request would re-promote it - - using (await folded.GetAsync("/")) - { - } - - Assert.Equal((MembershipStatus.Merged, false), await WithDb(async db => - { - var membership = await db.Memberships.SingleAsync(x => x.UserAccountId == s.Folded); - return (membership.Status, membership.IsPlatformAdmin); - })); - - using var admin = ClientFor(Random.Shared.NextInt64(1_000_000_000, 2_000_000_000), "test-admin"); - var token = await TokenAsync(admin); - using var approve = await admin.PostAsync("/App/Members?handler=Approve", new FormUrlEncodedContent(new Dictionary - { - ["userAccountId"] = s.Folded.ToString(), ["__RequestVerificationToken"] = token - })); - Assert.Equal(HttpStatusCode.Redirect, approve.StatusCode); - Assert.Equal(MembershipStatus.Merged, await WithDb(async db => (await db.Memberships.SingleAsync(x => x.UserAccountId == s.Folded)).Status)); - } - - /// Forbid answers 403 or sends the browser to the access-denied page; either way the page and its Heimdall flows are not served. - private static void AssertRefused(HttpResponseMessage response) - { - Assert.True(response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.Found, response.StatusCode.ToString()); - Assert.DoesNotContain("heimdall", response.Headers.Location?.ToString() ?? "", StringComparison.OrdinalIgnoreCase); - } - - [Theory] - [InlineData(AccountMergeState.Confirmed)] - [InlineData(AccountMergeState.Committed)] - public async Task A_frozen_or_folded_cookie_cannot_reach_the_linked_accounts_page_or_start_one_of_its_flows(AccountMergeState state) - { - var s = await SeedAsync(); - using var folded = ClientFor(s.FoldedGitHubId, $"fold-{s.SurvivorGitHubId}"); - var token = await TokenAsync(folded); - using (var control = await folded.GetAsync("/Membership/LinkedAccounts")) - { - Assert.Equal(HttpStatusCode.OK, control.StatusCode); // before the merge the page is theirs - } - - await MergeAsync(s, state); - - using var page = await folded.GetAsync("/Membership/LinkedAccounts"); - AssertRefused(page); - using var refresh = await folded.PostAsync("/Membership/LinkedAccounts?handler=Refresh", new FormUrlEncodedContent(new Dictionary - { - ["via"] = "google", ["__RequestVerificationToken"] = token - })); - AssertRefused(refresh); - - using var survivor = ClientFor(s.SurvivorGitHubId, $"surv-{s.SurvivorGitHubId}"); - using var other = await survivor.GetAsync("/Membership/LinkedAccounts"); - Assert.Equal(HttpStatusCode.OK, other.StatusCode); - } -} - -/// The desk's bearer door judges standing the way the cookie gate and the chat refusal do. -public sealed class AccountMergeDeskTests -{ - [Theory] - [InlineData(AccountMergeState.Confirmed)] - [InlineData(AccountMergeState.Committed)] - public async Task A_frozen_or_folded_subjects_live_desk_token_is_forbidden(AccountMergeState state) - { - using var factory = new DeskWebApplicationFactory(); - DeskReplay.HoldVectorForks(factory.Door); - await factory.EnsureAccountAsync(DeskWebApplicationFactory.Alice, true); - var token = factory.Token(DeskWebApplicationFactory.Alice, "bifrost-desk", "desk.read"); - Task ListAsync() => factory.SendAsync("GET", DeskReplay.Target("list", "gamecult-chat", null), null, token); - - Assert.Equal(200, (await ListAsync()).Status); // the live member, before the merge - - using (var scope = factory.Services.CreateScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - var survivor = new UserAccount { BifrostIdentity = "desk-survivor", NormalizedBifrostIdentity = "desk-survivor", GitHubLogin = "desk-survivor", NormalizedGitHubLogin = "desk-survivor" }; - db.UserAccounts.Add(survivor); - db.AccountMerges.Add(new AccountMerge - { - SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = Guid.Parse(DeskWebApplicationFactory.Alice), State = state, CreatedUtc = DateTimeOffset.UtcNow - }); - await db.SaveChangesAsync(); - } - - Assert.Equal(403, (await ListAsync()).Status); - } -} diff --git a/tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs b/tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs deleted file mode 100644 index 3185be5..0000000 --- a/tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs +++ /dev/null @@ -1,1121 +0,0 @@ -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; - -/// -/// 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. -/// -public sealed class AccountMergeLedgerTests -{ - public static readonly DateTimeOffset T0 = new(2026, 11, 14, 12, 0, 0, TimeSpan.Zero); - - public sealed class Clock(DateTimeOffset start) : TimeProvider - { - public DateTimeOffset Now { get; set; } = start; - - public override DateTimeOffset GetUtcNow() => Now; - } - - /// The merge fixtures. In memory by default; points the same fixtures at a real database, where unique indexes, transactions, tokens and triggers exist. - public sealed class World - { - private readonly string _name = $"merge-{Guid.NewGuid():N}"; - private readonly SaveChangesInterceptor[] _interceptors; - private readonly string? _postgres; - - public World(params SaveChangesInterceptor[] interceptors) => _interceptors = interceptors; - - private World(string postgres, SaveChangesInterceptor[] interceptors) : this(interceptors) => _postgres = postgres; - - public static World OnPostgres(string connectionString, params SaveChangesInterceptor[] interceptors) => new(connectionString, interceptors); - - public Clock Clock { get; } = new(T0); - - public BifrostDbContext Db() - { - var options = new DbContextOptionsBuilder().AddInterceptors(_interceptors); - if (_postgres is null) - { - options.UseInMemoryDatabase(_name).ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)); - } - else - { - options.UseNpgsql(_postgres); - } - - return new BifrostDbContext(options.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 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 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 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 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 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 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 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> AllVotesAsync(Motion motion) - { - await using var db = Db(); - return await db.Votes.IgnoreQueryFilters().AsNoTracking().Where(x => x.MotionId == motion.Id).ToListAsync(); - } - - public async Task> 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 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)); - } - - // ---- 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 BlockCases() => - new[] { "same_account", "mind_account", "native_account", "merge_in_flight", "survivor_is_folded", "already_folded", "folded_is_survivor", "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_is_survivor": - await world.MergeAsync(folded, other, AccountMergeState.Final); - 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> SavingChangesAsync(DbContextEventData eventData, InterceptionResult 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(() => 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(() => world.Ledger(db).CommitAsync(merge.Id, default)); - await world.SetStateAsync(merge, AccountMergeState.Committed); - await using var db2 = world.Db(); - await Assert.ThrowsAsync(() => 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); - } - - // ---- verdict cut-merge-ledger.s1: the rules each fix decides ---- - - [Theory] - [InlineData(AccountMergeState.Confirmed)] - [InlineData(AccountMergeState.HeimdallMoved)] - [InlineData(AccountMergeState.UndoRequested)] - [InlineData(AccountMergeState.HeimdallReversed)] - public async Task Plan_blocks_while_either_account_is_in_a_merge_in_flight(AccountMergeState state) - { - foreach (var survivorSide in new[] { true, false }) - { - var world = new World(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var other = await world.AccountAsync("other"); - await (survivorSide ? world.MergeAsync(survivor, other, state) : world.MergeAsync(other, folded, state)); - - await using var read = world.Db(); - Assert.Contains("merge_in_flight", (await world.Ledger(read).PlanAsync(survivor.Id, folded.Id, default)).Blocks); - } - } - - [Theory] - [InlineData(AccountMergeState.Committed)] - [InlineData(AccountMergeState.Final)] - public async Task A_landed_merges_survivor_cannot_itself_fold_so_an_alias_is_never_a_chain(AccountMergeState state) - { - 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, state); - - await using var read = world.Db(); - Assert.Contains("folded_is_survivor", (await world.Ledger(read).PlanAsync(c.Id, b.Id, default)).Blocks); - Assert.Empty((await world.Ledger(read).PlanAsync(b.Id, c.Id, default)).Blocks); // the other direction is an ordinary merge - Assert.Equal(b.Id, ((MergeStanding.Folded)(await world.Ledger(read).StandingAsync(a.Id, default))!).SurvivorId); - } - - private static async Task DropMembershipAsync(World world, UserAccount account) - { - await using var db = world.Db(); - db.Memberships.Remove(await db.Memberships.SingleAsync(x => x.UserAccountId == account.Id)); - await db.SaveChangesAsync(); - } - - [Fact] - public async Task A_suspension_is_not_laundered_into_a_survivor_without_a_membership_and_undo_removes_the_row_it_made() - { - var world = new World(); - var survivor = await world.AccountAsync("survivor"); - await DropMembershipAsync(world, survivor); - var folded = await world.AccountAsync("folded", MembershipStatus.Suspended); - var merge = await world.MergeAsync(survivor, folded); - - await using (var db = world.Db()) - { - var plan = await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default); - Assert.Contains(plan.Entries, e => e is { Kind: AccountMergeEntryKind.Standing, Action: AccountMergeEntryAction.Created }); - Assert.Empty(db.Memberships.Where(x => x.UserAccountId == survivor.Id)); // a plan writes nothing - } - - await world.CommitAsync(merge); - - var carried = await world.MembershipOfAsync(survivor); - Assert.Equal(MembershipStatus.Suspended, carried.Status); - Assert.Equal(AccountMergeLedger.SuspensionReason(merge.Id), carried.SuspensionReason); - Assert.False((await world.ActorAsync(survivor.Id)).IsActiveMember); - - await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed); - await using (var db = world.Db()) - { - await world.Ledger(db).UndoLocalAsync(merge.Id, default); - } - - await using var read = world.Db(); - Assert.Empty(read.Memberships.Where(x => x.UserAccountId == survivor.Id)); - Assert.Contains(await world.JournalAsync(merge), e => e is { Kind: AccountMergeEntryKind.Standing, Action: AccountMergeEntryAction.Restored }); - } - - [Fact] - public async Task Undo_keeps_the_membership_a_merge_made_for_a_suspension_once_an_admin_has_taken_it_over() - { - var world = new World(); - var survivor = await world.AccountAsync("survivor"); - await DropMembershipAsync(world, survivor); - var folded = await world.AccountAsync("folded", MembershipStatus.Suspended); - var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded)); - await using (var db = world.Db()) - { - (await db.Memberships.SingleAsync(x => x.UserAccountId == survivor.Id)).SuspensionReason = "steward decision"; - await db.SaveChangesAsync(); - } - - await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed); - await using (var db = world.Db()) - { - await world.Ledger(db).UndoLocalAsync(merge.Id, default); - } - - Assert.Equal(MembershipStatus.Suspended, (await world.MembershipOfAsync(survivor)).Status); - Assert.Contains(await world.JournalAsync(merge), e => e is { Kind: AccountMergeEntryKind.Standing, Action: AccountMergeEntryAction.KeptAfterUndo }); - } - - [Fact] - public async Task A_moved_vote_carries_the_survivors_weight_not_the_folded_accounts_and_undo_restores_it() - { - 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, 5m); - - var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded)); - - var moved = Assert.Single(await world.AllVotesAsync(motion)); - Assert.Equal((survivor.Id, 1m), (moved.UserAccountId, moved.Weight)); - Assert.Equal(1m, (await world.StateOfAsync(motion, moderator)).VotesFor); - - await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed); - await using (var db = world.Db()) - { - await world.Ledger(db).UndoLocalAsync(merge.Id, default); - } - - var back = Assert.Single(await world.AllVotesAsync(motion)); - Assert.Equal((folded.Id, 5m), (back.UserAccountId, back.Weight)); - } - - [Fact] - public async Task A_moved_vote_takes_the_survivors_weight_after_the_patron_tiers_were_derived_again() - { - 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, 1m); - 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(); - } - - await world.CommitAsync(await world.MergeAsync(survivor, folded)); - - var weight = (await world.MembershipOfAsync(survivor)).EffectiveVotingWeight; - Assert.Equal(2m, weight); - Assert.Equal(weight, Assert.Single(await world.AllVotesAsync(motion)).Weight); - } - - private static async Task<(Guid Both, Guid OnlyFolded)> SeedAppraisalsAsync(World world, UserAccount survivor, UserAccount folded, VoterClass foldedClass) - { - await using var db = world.Db(); - var both = new ConceptSubject { Collection = "c", Key = "both", Title = "Both", RegisteredAtUtc = T0 }; - var only = new ConceptSubject { Collection = "c", Key = "only-folded", Title = "Only folded", RegisteredAtUtc = T0 }; - db.ConceptSubjects.AddRange(both, only); - ConceptAppraisal Row(ConceptSubject subject, UserAccount who, ConceptStance stance, VoterClass voterClass) => new() - { - SubjectId = subject.Id, UserAccountId = who.Id, VoterKey = "account:" + who.Id.ToString("N"), Stance = stance, VoterClass = voterClass, CastAtUtc = T0 - }; - db.ConceptAppraisals.AddRange(Row(both, survivor, ConceptStance.Up, VoterClass.Member), Row(both, folded, ConceptStance.Down, foldedClass), Row(only, folded, ConceptStance.Down, foldedClass)); - await db.SaveChangesAsync(); - return (both.Id, only.Id); - } - - [Fact] - public async Task A_lone_folded_appraisal_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 (_, onlyFolded) = await SeedAppraisalsAsync(world, survivor, folded, VoterClass.Member); - - var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded)); - - await using var read = world.Db(); - var row = await read.ConceptAppraisals.IgnoreQueryFilters().SingleAsync(x => x.SubjectId == onlyFolded); - Assert.Equal((merge.Id, folded.Id), (row.VoidedByMergeId, row.UserAccountId)); - Assert.Equal(0, (await world.Concepts(read).GetTalliesAsync("c", default))["only-folded"].Down); - } - - [Fact] - public async Task A_moved_appraisal_takes_the_member_class_and_undo_gives_back_the_class_and_key_unless_the_survivor_recast_it() - { - var world = new World(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var (_, onlyFolded) = await SeedAppraisalsAsync(world, survivor, folded, VoterClass.Account); - var survivorKey = "account:" + survivor.Id.ToString("N"); - var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded)); - - await using (var read = world.Db()) - { - var moved = await read.ConceptAppraisals.SingleAsync(x => x.SubjectId == onlyFolded); - Assert.Equal((survivor.Id, survivorKey, VoterClass.Member), (moved.UserAccountId, moved.VoterKey, moved.VoterClass)); - } - - await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed); - await using (var db = world.Db()) - { - await world.Ledger(db).UndoLocalAsync(merge.Id, default); - } - - await using (var read = world.Db()) - { - var back = await read.ConceptAppraisals.SingleAsync(x => x.SubjectId == onlyFolded); - Assert.Equal((folded.Id, "account:" + folded.Id.ToString("N"), VoterClass.Account), (back.UserAccountId, back.VoterKey, back.VoterClass)); - } - - // Again, but the survivor re-casts the moved appraisal before the undo: it is theirs now and stays. - var folded2 = await world.AccountAsync("folded2"); - await using (var db = world.Db()) - { - db.ConceptAppraisals.Add(new ConceptAppraisal - { - SubjectId = onlyFolded, UserAccountId = folded2.Id, VoterKey = "account:" + folded2.Id.ToString("N"), Stance = ConceptStance.Down, - VoterClass = VoterClass.Account, CastAtUtc = T0 - }); - await db.SaveChangesAsync(); - } - - var second = await world.CommitAsync(await world.MergeAsync(survivor, folded2)); - world.Clock.Now = T0.AddDays(1); - await using (var db = world.Db()) - { - var voter = new VoterIdentity(survivorKey, VoterClass.Member, survivor.Id); - Assert.Equal(CastResult.Changed, await world.Concepts(db).CastAsync("c", "only-folded", voter, ConceptStance.Up, null, default)); - } - - await world.SetStateAsync(second, AccountMergeState.HeimdallReversed); - await using (var db = world.Db()) - { - await world.Ledger(db).UndoLocalAsync(second.Id, default); - } - - await using var after = world.Db(); - var kept = await after.ConceptAppraisals.SingleAsync(x => x.SubjectId == onlyFolded && x.UserAccountId == survivor.Id); - Assert.Equal((survivorKey, ConceptStance.Up), (kept.VoterKey, kept.Stance)); - Assert.Contains(await world.JournalAsync(second), e => e is { Kind: AccountMergeEntryKind.ConceptAppraisal, Action: AccountMergeEntryAction.KeptAfterUndo }); - } - - [Fact] - public async Task Closed_motions_keep_their_votes_with_their_owners_and_journal_nothing_for_them() - { - var world = new World(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var closed = await world.MotionAsync(status: MotionStatus.Passed); - await world.VoteAsync(closed, survivor, VoteChoice.For, 1m); - await world.VoteAsync(closed, folded, VoteChoice.For, 2m); - var lone = await world.MotionAsync(status: MotionStatus.Failed); - await world.VoteAsync(lone, folded, VoteChoice.Against, 2m); - - var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded)); - - Assert.Equal(new[] { folded.Id, survivor.Id }.Order(), (await world.AllVotesAsync(closed)).Select(x => x.UserAccountId).Order()); - var loneVote = Assert.Single(await world.AllVotesAsync(lone)); - Assert.Equal((folded.Id, 2m), (loneVote.UserAccountId, loneVote.Weight)); // not re-pointed, not re-weighed - Assert.DoesNotContain(await world.JournalAsync(merge), e => e.Kind == AccountMergeEntryKind.Vote); - } - - [Theory] - [InlineData(AccountMergeState.Committed)] - [InlineData(AccountMergeState.Final)] - public async Task Commit_on_a_landed_merge_returns_the_receipt_and_writes_nothing(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); - - var receipt = await world.CommitAsync(merge); - - Assert.Equal((merge.Id, state), (receipt.Id, receipt.State)); - Assert.Empty(await world.JournalAsync(merge)); - Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(folded)).Status); - } - - [Fact] - public async Task Undo_is_refused_for_a_merge_that_was_ever_finalized() - { - var world = new World(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded)); - await using (var db = world.Db()) - { - var row = await db.AccountMerges.SingleAsync(x => x.Id == merge.Id); - row.State = AccountMergeState.HeimdallReversed; - row.FinalizedUtc = T0.AddDays(8); - await db.SaveChangesAsync(); - } - - await using var undo = world.Db(); - await Assert.ThrowsAsync(() => world.Ledger(undo).UndoLocalAsync(merge.Id, default)); - Assert.Equal(MembershipStatus.Merged, (await world.MembershipOfAsync(folded)).Status); - } - - [Fact] - public async Task A_vote_and_an_appraisal_from_an_actor_resolved_before_the_account_froze_write_nothing() - { - var world = new World(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var motion = await world.MotionAsync(); - var staleActor = await world.ActorAsync(folded.Id); // a request resolved this before the merge was confirmed - await using (var db = world.Db()) - { - db.ConceptSubjects.Add(new ConceptSubject { Collection = "c", Key = "k", Title = "K", RegisteredAtUtc = T0 }); - await db.SaveChangesAsync(); - } - - await world.MergeAsync(survivor, folded, AccountMergeState.Confirmed); - - await using (var db = world.Db()) - { - await world.Motions(db).CastVoteAsync(staleActor, motion.Id, VoteChoice.For, null, default); - Assert.Equal(CastResult.NoVoter, await world.Concepts(db).CastAsync("c", "k", VoterIdentity.For(staleActor, null), ConceptStance.Up, null, default)); - } - - Assert.Empty(await world.AllVotesAsync(motion)); - await using var read = world.Db(); - Assert.Empty(read.ConceptAppraisals.IgnoreQueryFilters()); - - // The survivor, not frozen, still writes. - await using var control = world.Db(); - await world.Motions(control).CastVoteAsync(await world.ActorAsync(survivor.Id), motion.Id, VoteChoice.For, null, default); - Assert.Single(await world.AllVotesAsync(motion)); - } - - [Fact] - public async Task A_merged_membership_is_never_rewritten_by_the_bootstrap_promotion_or_by_suspension() - { - var world = new World(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var admin = await world.AccountAsync("admin", roles: MemberRole.PlatformAdmin); - await world.CommitAsync(await world.MergeAsync(survivor, folded)); - - await using (var db = world.Db()) - { - var account = await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments).SingleAsync(x => x.Id == folded.Id); - Assert.False(ApplicationBootstrapper.TryPromoteBootstrapAdmin(account, T0, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance)); - Assert.Equal((MembershipStatus.Merged, false), (account.Membership!.Status, account.Membership.IsPlatformAdmin)); - } - - await using (var db = world.Db()) - { - var suspension = new MembershipSuspensionService(db, new AuditTrailService(db, world.Clock)); - var actor = await world.ActorAsync(admin.Id); - Assert.Equal(SuspensionOutcome.NotApplicable, await suspension.SuspendAsync(actor, folded.Id, "reason", default)); - Assert.Equal(SuspensionOutcome.NotApplicable, await suspension.UnsuspendAsync(actor, folded.Id, "reason", default)); - } - - Assert.Equal(MembershipStatus.Merged, (await world.MembershipOfAsync(folded)).Status); - } - - [Fact] - public async Task The_digest_names_the_survivor_so_two_memberless_survivors_with_identical_records_digest_differently() - { - // A memberless survivor leaves no entry that mentions it: the plan for (A, folded) and for (C, folded) is the same list of - // entries, so only the pair the digest is made for can tell them apart (heimdall-body:finding:cut-merge-saga.s2.digest-pair-binding-unpinned). - var world = new World(); - var folded = await world.AccountAsync("folded"); - var a = await MemberlessAsync(world, "survivor-a"); - var c = await MemberlessAsync(world, "survivor-c"); - - await using var db = world.Db(); - var forA = await world.Ledger(db).PlanAsync(a.Id, folded.Id, default); - var forC = await world.Ledger(db).PlanAsync(c.Id, folded.Id, default); - - Assert.Empty(forA.Blocks); - Assert.Empty(forC.Blocks); - Assert.Equal(forA.Entries.Select(x => (x.Kind, x.Action, x.PriorText)), forC.Entries.Select(x => (x.Kind, x.Action, x.PriorText))); - Assert.NotEqual(forA.Digest(a.Id, folded.Id), forC.Digest(c.Id, folded.Id)); - Assert.NotEqual(forA.Digest(a.Id, folded.Id), forA.Digest(c.Id, folded.Id)); // a digest made for one pair does not confirm the other - Assert.Equal(forA.Digest(a.Id, folded.Id), (await world.Ledger(db).PlanAsync(a.Id, folded.Id, default)).Digest(a.Id, folded.Id)); - } - - private static async Task MemberlessAsync(World world, string name) - { - await using var db = world.Db(); - var account = new UserAccount - { - DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = name, HeimdallAccountId = $"hd-{name}-{Guid.NewGuid():N}", - CreatedAtUtc = T0, LastSeenAtUtc = T0 - }; - db.UserAccounts.Add(account); - await db.SaveChangesAsync(); - return account; - } -} diff --git a/tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs b/tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs deleted file mode 100644 index cf01c9f..0000000 --- a/tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs +++ /dev/null @@ -1,981 +0,0 @@ -using Bifrost.Web.Configuration; -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Heimdall; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Features.Motions; -using Bifrost.Web.Features.Patronage; -using Bifrost.Web.Features.Shared; -using Bifrost.Web.Tests.Support; -using Microsoft.AspNetCore.DataProtection; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Diagnostics; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.Extensions.Logging.Abstractions; -using Microsoft.Extensions.Options; -using Npgsql; - -namespace Bifrost.Web.Tests; - -/// -/// The merge tests that need a real server run only when BIFROST_TEST_PG holds a Postgres connection string (no Database=; a role that -/// may create databases). Every other merge test runs on the in-memory provider, which enforces no unique index, transaction, -/// concurrency token or trigger, so the rules that rest on those are proven here, on a database each test creates, builds through the -/// real migrations and the class drops. See AGENTS.md (Live Postgres tests). -/// -public static class PostgresGate -{ - public const string Variable = "BIFROST_TEST_PG"; - - public static string? Skip => - string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(Variable)) - ? $"live Postgres tests: set {Variable} to a connection string without Database= (see AGENTS.md, Live Postgres tests)" - : null; -} - -public sealed class PostgresFactAttribute : FactAttribute -{ - public PostgresFactAttribute() => Skip = PostgresGate.Skip; -} - -public sealed class PostgresTheoryAttribute : TheoryAttribute -{ - public PostgresTheoryAttribute() => Skip = PostgresGate.Skip; -} - -public sealed class MergePostgres : IAsyncLifetime -{ - private readonly List _databases = []; - - private static string? Admin => Environment.GetEnvironmentVariable(PostgresGate.Variable); - - public Task InitializeAsync() => Task.CompletedTask; - - /// A fresh database, built by the real migrations, and a world over it. - public async Task NewWorldAsync(params Microsoft.EntityFrameworkCore.Diagnostics.SaveChangesInterceptor[] interceptors) - { - var name = $"bifrost_merge_{Guid.NewGuid():N}"; - await using (var admin = new NpgsqlConnection(Admin)) - { - await admin.OpenAsync(); - await using var create = new NpgsqlCommand($"CREATE DATABASE \"{name}\"", admin); - await create.ExecuteNonQueryAsync(); - } - - _databases.Add(name); - var world = AccountMergeLedgerTests.World.OnPostgres(new NpgsqlConnectionStringBuilder(Admin) { Database = name }.ConnectionString, interceptors); - await using var db = world.Db(); - await db.Database.MigrateAsync(); - return world; - } - - public async Task DisposeAsync() - { - if (_databases.Count == 0) - { - return; - } - - NpgsqlConnection.ClearAllPools(); - await using var admin = new NpgsqlConnection(Admin); - await admin.OpenAsync(); - foreach (var name in _databases) - { - await using var drop = new NpgsqlCommand($"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)", admin); - await drop.ExecuteNonQueryAsync(); - } - } -} - -public sealed class AccountMergePostgresTests(MergePostgres postgres) : IClassFixture -{ - private static PostgresException Pg(Exception error) - { - for (var current = error; current is not null; current = current.InnerException!) - { - if (current is PostgresException pg) - { - return pg; - } - } - - throw new Xunit.Sdk.XunitException($"no PostgresException under {error.GetType().Name}"); - } - - /// Runs an action once, just before the first save of a context: the rival writer that lands inside a read-then-save window. - private sealed class BeforeFirstSave(Func rival) : SaveChangesInterceptor - { - private int _fired; - - public override async ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) - { - if (Interlocked.Exchange(ref _fired, 1) == 0) - { - await rival(); - } - - return result; - } - } - - /// Holds each of two contexts at its save until both have arrived, so both have read before either writes. - private sealed class Rendezvous : SaveChangesInterceptor - { - private readonly Barrier _barrier = new(2); - - public override async ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) - { - await Task.Run(() => _barrier.SignalAndWait(TimeSpan.FromSeconds(30)), cancellationToken); - return result; - } - } - - private static IEnumerable Chain(Exception error) - { - for (var current = error; current is not null; current = current.InnerException!) - { - yield return current; - } - } - - private static string ConnectionOf(AccountMergeLedgerTests.World world) - { - using var db = world.Db(); - return db.Database.GetConnectionString()!; - } - - private static async Task ExecuteAsync(AccountMergeLedgerTests.World world, string sql) - { - await using var db = world.Db(); - await db.Database.ExecuteSqlRawAsync(sql); - } - - // ---- commit atomicity ---- - - [PostgresFact] - public async Task A_commit_that_fails_midway_leaves_nothing_applied_and_the_retry_commits_once() - { - var world = await postgres.NewWorldAsync(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var motion = await world.MotionAsync(); - await world.VoteAsync(motion, survivor, VoteChoice.For); - await world.VoteAsync(motion, folded, VoteChoice.Against); - var merge = await world.MergeAsync(survivor, folded); - await ExecuteAsync(world, """ - CREATE FUNCTION fail_merged() RETURNS trigger LANGUAGE plpgsql AS $$ - BEGIN IF NEW."Status" = 'Merged' THEN RAISE EXCEPTION 'injected fault'; END IF; RETURN NEW; END $$; - CREATE TRIGGER fail_merged BEFORE UPDATE ON "Memberships" FOR EACH ROW EXECUTE FUNCTION fail_merged(); - """); - - var fault = await Assert.ThrowsAsync(() => world.CommitAsync(merge)); - Assert.Contains("injected fault", Pg(fault).MessageText); - - await using (var check = world.Db()) - { - Assert.Equal(AccountMergeState.HeimdallMoved, (await check.AccountMerges.SingleAsync()).State); - Assert.Empty(check.AccountMergeEntries); - Assert.All(await check.Votes.IgnoreQueryFilters().ToListAsync(), v => Assert.Null(v.VoidedByMergeId)); - Assert.Equal(MembershipStatus.Active, (await check.Memberships.SingleAsync(x => x.UserAccountId == folded.Id)).Status); - } - - await ExecuteAsync(world, "DROP TRIGGER fail_merged ON \"Memberships\""); - Assert.Equal(AccountMergeState.Committed, (await world.CommitAsync(merge)).State); - var journal = await world.JournalAsync(merge); - Assert.Equal(1, journal.Count(x => x.Kind == AccountMergeEntryKind.Vote)); - Assert.Equal(AccountMergeState.Committed, (await world.CommitAsync(merge)).State); // a second commit is a no-op - Assert.Equal(journal.Count, (await world.JournalAsync(merge)).Count); - } - - [PostgresFact] - public async Task The_journal_refuses_a_second_entry_with_the_same_merge_and_seq() - { - var world = await postgres.NewWorldAsync(); - var merge = await world.MergeAsync(await world.AccountAsync("survivor"), await world.AccountAsync("folded")); - await using var db = world.Db(); - AccountMergeEntry Entry() => new() { MergeId = merge.Id, Seq = 1, Kind = AccountMergeEntryKind.Vote, Action = AccountMergeEntryAction.Voided, RecordId = Guid.NewGuid(), AtUtc = AccountMergeLedgerTests.T0 }; - db.AccountMergeEntries.Add(Entry()); - await db.SaveChangesAsync(); - db.AccountMergeEntries.Add(Entry()); - - var error = await Assert.ThrowsAsync(() => db.SaveChangesAsync()); - - Assert.Equal(("23505", "IX_AccountMergeEntries_MergeId_Seq"), (Pg(error).SqlState, Pg(error).ConstraintName)); - } - - [PostgresFact] - public async Task Two_commits_of_the_same_merge_racing_apply_it_exactly_once() - { - var world = await postgres.NewWorldAsync(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var motion = await world.MotionAsync(); - await world.VoteAsync(motion, survivor, VoteChoice.For); - await world.VoteAsync(motion, folded, VoteChoice.Against); - var merge = await world.MergeAsync(survivor, folded); - var committers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world)); - - async Task TryCommit() - { - try - { - await committers.CommitAsync(merge); - return null; - } - catch (Exception error) - { - return error; - } - } - - var results = await Task.WhenAll(Task.Run(TryCommit), Task.Run(TryCommit)); - - // The second commit waits on the folded account's exclusive lock, then finds the merge landed and returns its receipt. - Assert.All(results, e => Assert.Null(e)); - 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.Single((await world.AllVotesAsync(motion)).Where(v => v.VoidedByMergeId == merge.Id)); - } - - [PostgresFact] - public async Task A_voided_vote_leaves_every_tally_on_a_real_database() - { - var world = await postgres.NewWorldAsync(); - 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); - - await world.CommitAsync(await world.MergeAsync(survivor, folded)); - - var item = await world.StateOfAsync(motion, moderator); - Assert.Equal((0m, 1m), (item.VotesFor, item.VotesAgainst)); - Assert.Equal(MotionStatus.Failed, await world.CloseAsync(motion, moderator)); - } - - // ---- the sweeper against the saga ---- - - [PostgresFact] - public async Task The_sweep_does_not_overwrite_an_UndoRequested_written_after_it_read_the_merge() - { - var plain = await postgres.NewWorldAsync(); - var merge = await plain.CommitAsync(await plain.MergeAsync(await plain.AccountAsync("survivor"), await plain.AccountAsync("folded"))); - var sweeper = AccountMergeLedgerTests.World.OnPostgres( - ConnectionOf(plain), new BeforeFirstSave(() => plain.SetStateAsync(merge, AccountMergeState.UndoRequested))); - - await using (var db = sweeper.Db()) - { - Assert.Equal(0, await sweeper.Ledger(db).FinalizeDueAsync(AccountMergeLedgerTests.T0.AddDays(8), default)); - } - - await using var read = plain.Db(); - var row = await read.AccountMerges.SingleAsync(); - Assert.Equal(AccountMergeState.UndoRequested, row.State); - Assert.Null(row.FinalizedUtc); - } - - [PostgresFact] - public async Task An_UndoRequested_written_from_a_stale_Committed_read_cannot_overwrite_Final() - { - var world = await postgres.NewWorldAsync(); - var merge = await world.CommitAsync(await world.MergeAsync(await world.AccountAsync("survivor"), await world.AccountAsync("folded"))); - await using var saga = world.Db(); - var stale = await saga.AccountMerges.SingleAsync(x => x.Id == merge.Id); // the saga read Committed - - await using (var sweep = world.Db()) - { - Assert.Equal(1, await world.Ledger(sweep).FinalizeDueAsync(AccountMergeLedgerTests.T0.AddDays(8), default)); - } - - stale.State = AccountMergeState.UndoRequested; - await Assert.ThrowsAsync(() => saga.SaveChangesAsync()); - await using var read = world.Db(); - Assert.Equal(AccountMergeState.Final, (await read.AccountMerges.SingleAsync()).State); - } - - [PostgresFact] - public async Task A_sweep_that_loses_one_merge_to_the_saga_still_finalizes_the_others() - { - var plain = await postgres.NewWorldAsync(); - var survivor = await plain.AccountAsync("survivor"); - await plain.CommitAsync(await plain.MergeAsync(survivor, await plain.AccountAsync("folded-a"))); - await plain.CommitAsync(await plain.MergeAsync(survivor, await plain.AccountAsync("folded-b"))); - var sweeper = AccountMergeLedgerTests.World.OnPostgres( - ConnectionOf(plain), new BeforeFirstSave(async () => - { - // Whichever merge the sweep saves first, the saga takes one of the two before it does. - await using var rival = plain.Db(); - var taken = await rival.AccountMerges.Where(x => x.State == AccountMergeState.Committed).OrderBy(x => x.Id).FirstAsync(); - taken.State = AccountMergeState.UndoRequested; - await rival.SaveChangesAsync(); - })); - - await using (var db = sweeper.Db()) - { - Assert.Equal(1, await sweeper.Ledger(db).FinalizeDueAsync(AccountMergeLedgerTests.T0.AddDays(8), default)); - } - - await using var read = plain.Db(); - Assert.Equal([AccountMergeState.Final, AccountMergeState.UndoRequested], (await read.AccountMerges.ToListAsync()).Select(x => x.State).Order()); - } - - // ---- overlapping merges, refused by the database ---- - - [PostgresFact] - public async Task A_second_live_merge_folding_the_same_account_is_refused_and_a_finished_one_frees_it() - { - var world = await postgres.NewWorldAsync(); - var s1 = await world.AccountAsync("acct-s1"); - var s2 = await world.AccountAsync("acct-s2"); - var folded = await world.AccountAsync("folded"); - - var second = await world.MergeAsync(s2, folded, AccountMergeState.Proposed); // proposals may coexist - var first = await world.MergeAsync(s1, folded, AccountMergeState.Confirmed); - - var refused = await Assert.ThrowsAsync(() => world.SetStateAsync(second, AccountMergeState.Confirmed)); - Assert.Equal(("23505", "UX_AccountMerges_FoldedUserAccountId_Live"), (Pg(refused).SqlState, Pg(refused).ConstraintName)); - var inserted = await Assert.ThrowsAsync(() => world.MergeAsync(s2, folded, AccountMergeState.Final)); - Assert.Equal("23505", Pg(inserted).SqlState); - - await world.SetStateAsync(first, AccountMergeState.Undone); - await world.SetStateAsync(second, AccountMergeState.Confirmed); // the slot is free again - } - - [PostgresTheory] - [InlineData(AccountMergeState.Confirmed, AccountMergeState.Confirmed)] - [InlineData(AccountMergeState.Final, AccountMergeState.Confirmed)] - [InlineData(AccountMergeState.Committed, AccountMergeState.HeimdallMoved)] - public async Task A_chain_is_refused_in_either_arrival_order_and_the_same_survivor_twice_is_fine(AccountMergeState earlier, AccountMergeState later) - { - var world = await postgres.NewWorldAsync(); - foreach (var survivorFirst in new[] { true, false }) - { - var tag = survivorFirst ? "a" : "b"; - var s = await world.AccountAsync("acct-s" + tag); - var f = await world.AccountAsync("acct-f" + tag); - var g = await world.AccountAsync("acct-g" + tag); - var other = await world.AccountAsync("other" + tag); - - await world.MergeAsync(s, other, AccountMergeState.Confirmed); // one survivor may carry two folded accounts - await world.MergeAsync(s, f, earlier); - // f survives a live merge and folds into g, or s folds into g while it survives one: both are chains. - var chain = await Assert.ThrowsAsync(() => survivorFirst ? world.MergeAsync(f, g, later) : world.MergeAsync(g, s, later)); - Assert.Equal("23P01", Pg(chain).SqlState); - } - } - - [PostgresFact] - public async Task Two_transactions_racing_to_chain_the_same_account_cannot_both_commit() - { - var world = await postgres.NewWorldAsync(); - var s = await world.AccountAsync("acct-s"); - var f = await world.AccountAsync("acct-f"); - var g = await world.AccountAsync("acct-g"); - await using var first = world.Db(); - await using var firstTransaction = await first.Database.BeginTransactionAsync(); - first.AccountMerges.Add(new AccountMerge { SurvivorUserAccountId = s.Id, FoldedUserAccountId = f.Id, State = AccountMergeState.Confirmed, CreatedUtc = AccountMergeLedgerTests.T0 }); - await first.SaveChangesAsync(); - - await using var second = world.Db(); - await using var secondTransaction = await second.Database.BeginTransactionAsync(); - second.AccountMerges.Add(new AccountMerge { SurvivorUserAccountId = f.Id, FoldedUserAccountId = g.Id, State = AccountMergeState.Confirmed, CreatedUtc = AccountMergeLedgerTests.T0 }); - var racing = second.SaveChangesAsync(); - - await Task.Delay(1500); - Assert.False(racing.IsCompleted); // it waits on the first, which holds the lock on f - await firstTransaction.CommitAsync(); - - var refused = await Assert.ThrowsAsync(() => racing.WaitAsync(TimeSpan.FromSeconds(30))); - Assert.Equal("23P01", Pg(refused).SqlState); - } - - // ---- rollback ---- - - [PostgresFact] - public async Task Reverting_the_migration_is_refused_while_any_merge_exists_even_one_that_voided_nothing_and_allowed_after() - { - var world = await postgres.NewWorldAsync(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - await world.CommitAsync(await world.MergeAsync(survivor, folded)); // moves and voids nothing: only the Merged membership remains - - await using (var db = world.Db()) - { - var error = await Assert.ThrowsAnyAsync(() => db.GetService().MigrateAsync("20261113120000_AddPasskeyCredentials")); - Assert.Contains("roll-forward only", Pg(error).MessageText); - // The acks migration reverts first (it holds only acks); the saga migration is the one that refuses. - Assert.Equal("20261114130000_AddAccountMergeSaga", (await db.Database.GetAppliedMigrationsAsync()).Last()); - } - - await ExecuteAsync(world, "DELETE FROM \"AccountMergeEntries\"; DELETE FROM \"AccountMerges\""); - await using var down = world.Db(); - await down.GetService().MigrateAsync("20261113120000_AddPasskeyCredentials"); - Assert.Equal("20261113120000_AddPasskeyCredentials", (await down.Database.GetAppliedMigrationsAsync()).Last()); - await down.GetService().MigrateAsync(); // and up again, trigger and index and all - Assert.Equal(down.Database.GetMigrations().Last(), (await down.Database.GetAppliedMigrationsAsync()).Last()); // the newest the assembly knows, whatever it is - } - - // ---- restage and intake journal ---- - - [PostgresFact] - public async Task Two_merges_into_one_survivor_restaging_at_once_leave_one_current_patron_snapshot_and_the_loser_commits_on_retry() - { - var world = await postgres.NewWorldAsync(); - var survivor = await world.AccountAsync("survivor"); - var first = await world.AccountAsync("first"); - var second = await world.AccountAsync("second"); - await using (var db = world.Db()) - { - foreach (var who in new[] { first, second }) - { - db.PatronSupportEvents.Add(new PatronSupportEvent - { - UserAccountId = who.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = 1000m, - SupportedAtUtc = AccountMergeLedgerTests.T0, RecordedAtUtc = AccountMergeLedgerTests.T0 - }); - } - - await db.SaveChangesAsync(); - } - - var one = await world.MergeAsync(survivor, first); - var two = await world.MergeAsync(survivor, second); - var committers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new Rendezvous()); - - async Task TryCommit(AccountMerge merge) - { - try - { - await committers.CommitAsync(merge); - return null; - } - catch (Exception error) - { - return error; - } - } - - var results = await Task.WhenAll(Task.Run(() => TryCommit(one)), Task.Run(() => TryCommit(two))); - - Assert.Equal(1, results.Count(x => x is null)); - Assert.All(results.OfType(), e => Assert.Contains(Chain(e), x => x is PostgresException { SqlState: "23505", ConstraintName: "UX_TierSnapshots_MembershipId_CurrentPatron" })); - var loser = results[0] is null ? two : one; - Assert.Equal(AccountMergeState.Committed, (await world.CommitAsync(loser)).State); - await using var read = world.Db(); - var membership = await read.Memberships.Include(x => x.TierSnapshots).SingleAsync(x => x.UserAccountId == survivor.Id); - Assert.Single(membership.TierSnapshots, x => x.Kind == TierSnapshotKind.Patron && x.IsCurrent); - Assert.All(await read.PatronSupportEvents.ToListAsync(), e => Assert.Equal(survivor.Id, e.UserAccountId)); - } - - [PostgresFact] - public async Task A_patron_refresh_that_loses_the_restage_race_reads_the_winners_snapshot_and_derives_again() - { - var world = await postgres.NewWorldAsync(); - var patron = await world.AccountAsync("patron"); - await using (var db = world.Db()) - { - db.PatronSupportEvents.Add(new PatronSupportEvent - { - UserAccountId = patron.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = 1000m, - SupportedAtUtc = AccountMergeLedgerTests.T0, RecordedAtUtc = AccountMergeLedgerTests.T0 - }); - await db.SaveChangesAsync(); - } - - var clock = world.Clock; - var rival = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world)); - var loser = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () => - { - await using var rivalDb = rival.Db(); - await new PatronageService(rivalDb, new AuditTrailService(rivalDb, clock), clock).RefreshPatronTierSnapshotAsync(null, patron.Id, default); - })); - - await using (var db = loser.Db()) - { - var summary = await new PatronageService(db, new AuditTrailService(db, clock), clock).RefreshPatronTierSnapshotAsync(null, patron.Id, default); - Assert.True(summary.VotingWeight > 0m); - } - - await using var read = world.Db(); - var snapshots = await read.TierSnapshots.Where(x => x.Kind == TierSnapshotKind.Patron).ToListAsync(); - Assert.Single(snapshots, x => x.IsCurrent); - Assert.Equal(2, snapshots.Count); // the winner's, demoted by the retry, and the retry's own - } - - [PostgresFact] - public async Task The_migration_keeps_only_the_newest_of_duplicate_current_patron_snapshots_before_it_builds_the_index() - { - var world = await postgres.NewWorldAsync(); - var patron = await world.AccountAsync("patron"); - await using var db = world.Db(); - await db.GetService().MigrateAsync("20261113120000_AddPasskeyCredentials"); // the index does not exist yet - var membership = await db.Memberships.SingleAsync(x => x.UserAccountId == patron.Id); - TierSnapshot Snapshot(string label, int minutes) => new() - { - MembershipId = membership.Id, Kind = TierSnapshotKind.Patron, Label = label, Weight = 1m, IsCurrent = true, - EffectiveFromUtc = AccountMergeLedgerTests.T0, CapturedAtUtc = AccountMergeLedgerTests.T0.AddMinutes(minutes) - }; - db.TierSnapshots.AddRange(Snapshot("older", 0), Snapshot("newer", 5)); - await db.SaveChangesAsync(); - - await db.GetService().MigrateAsync(); - - await using var read = world.Db(); - Assert.Equal("newer", (await read.TierSnapshots.SingleAsync(x => x.IsCurrent)).Label); - Assert.Equal(2, await read.TierSnapshots.CountAsync()); - } - - [PostgresFact] - public async Task A_journalled_patron_intake_takes_the_next_seq_after_the_commits_entries_and_is_idempotent() - { - var world = await postgres.NewWorldAsync(); - 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.CommitAsync(await world.MergeAsync(survivor, folded)); - var committed = (await world.JournalAsync(merge)).Count; - Assert.True(committed > 0); - - var events = new[] { $"WH-{Guid.NewGuid():N}", $"WH-{Guid.NewGuid():N}" }; - foreach (var id in events.Concat(events)) // each twice: the provider retries - { - await using var db = world.Db(); - await new PatronageService(db, new AuditTrailService(db, world.Clock), world.Clock).RecordSupportEventAsync( - null, folded.Id, PatronSupportEventKind.OneTimeDonation, 1m, "USD", "ext", ExternalPatronProvider.PayPal, id, - string.Empty, string.Empty, AccountMergeLedgerTests.T0, false, string.Empty, default); - } - - var journal = await world.JournalAsync(merge); - Assert.Equal(committed + 2, journal.Count); - Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count()); - } - - [PostgresTheory] - [InlineData(AccountMergeState.Proposed)] - [InlineData(AccountMergeState.Confirmed)] - [InlineData(AccountMergeState.HeimdallMoved)] - [InlineData(AccountMergeState.Final)] - [InlineData(AccountMergeState.UndoRequested)] - [InlineData(AccountMergeState.HeimdallReversed)] - [InlineData(AccountMergeState.Undone)] - [InlineData(AccountMergeState.Failed)] - public async Task Reverting_the_migration_is_refused_for_a_merge_in_any_state(AccountMergeState state) - { - var world = await postgres.NewWorldAsync(); - await world.MergeAsync(await world.AccountAsync("survivor"), await world.AccountAsync("folded"), state); - - await using var db = world.Db(); - var error = await Assert.ThrowsAnyAsync(() => db.GetService().MigrateAsync("20261113120000_AddPasskeyCredentials")); - Assert.Contains("roll-forward only", Pg(error).MessageText); - } - - // ---- the write gate ---- - - [PostgresFact] - public async Task A_vote_that_read_no_merge_saves_before_a_merge_can_freeze_the_account_and_the_commit_then_moves_it() - { - var world = await postgres.NewWorldAsync(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var motion = await world.MotionAsync(); - var actor = await world.ActorAsync(folded.Id); - Task? freeze = null; - var blocked = false; - var voters = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () => - { - // The vote has read its standing (none) and is about to save: the freeze lands here and must wait for the save. - freeze = Task.Run(() => world.MergeAsync(survivor, folded, AccountMergeState.Confirmed)); - await Task.Delay(1500); - blocked = !freeze.IsCompleted; - })); - - await using (var db = voters.Db()) - { - await voters.Motions(db).CastVoteAsync(actor, motion.Id, VoteChoice.For, null, default); - } - - var merge = await freeze!.WaitAsync(TimeSpan.FromSeconds(30)); - Assert.True(blocked); - await world.SetStateAsync(merge, AccountMergeState.HeimdallMoved); - await world.CommitAsync(merge); - - var votes = await world.AllVotesAsync(motion); - Assert.Equal(survivor.Id, Assert.Single(votes).UserAccountId); // the commit saw the vote and moved it: no second voice stays on the folded account - Assert.Single(await world.JournalAsync(merge), x => x.Kind == AccountMergeEntryKind.Vote); - } - - [PostgresFact] - public async Task A_patron_event_that_read_a_Frozen_account_saves_before_the_commit_reduces_and_the_commit_moves_it() - { - var world = await postgres.NewWorldAsync(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var merge = await world.MergeAsync(survivor, folded); // HeimdallMoved: the folded account is Frozen - Task? commit = null; - var blocked = false; - var recorders = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () => - { - commit = Task.Run(() => world.CommitAsync(merge)); // takes the folded account's exclusive lock before it reduces - await Task.Delay(1500); - blocked = !commit.IsCompleted; - })); - - await using (var db = recorders.Db()) - { - await new PatronageService(db, new AuditTrailService(db, recorders.Clock), recorders.Clock).RecordSupportEventAsync( - null, folded.Id, PatronSupportEventKind.OneTimeDonation, 1m, "USD", "ext", ExternalPatronProvider.PayPal, "WH-frozen", - string.Empty, string.Empty, AccountMergeLedgerTests.T0, false, string.Empty, default); - } - - await commit!.WaitAsync(TimeSpan.FromSeconds(30)); - Assert.True(blocked); - await using var read = world.Db(); - Assert.Equal(survivor.Id, (await read.PatronSupportEvents.SingleAsync()).UserAccountId); // the reduction found the event and moved it - Assert.Single(await world.JournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); - } - - [PostgresFact] - public async Task A_sealed_reveal_that_retries_on_a_conflict_keeps_its_lock_so_no_merge_freezes_the_account_between_attempts() - { - const string salt = "00112233445566778899aabbccddeeff"; - var world = await postgres.NewWorldAsync(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var other = await world.AccountAsync("other"); - var moderator = await world.AccountAsync("moderator", moderator: true); - SealedBallotService Sealed(AccountMergeLedgerTests.World w, BifrostDbContext db) => new(db, new AuditTrailService(db, w.Clock), w.Clock); - SealedBallotDocument Doc(Guid motionId, string reason) => new(SealedBallotDocument.SchemaId, motionId, 1, "Ana", reason, salt); - - await using var setup = world.Db(); - var motionId = (await Sealed(world, setup).OpenAsync(await world.ActorAsync(moderator.Id), - new OpenSealedMotionCommand("Who", "Blind.", ["Ana", "Bo"], AccountMergeLedgerTests.T0.AddHours(1), AccountMergeLedgerTests.T0.AddHours(2)), default)).Id; - foreach (var (account, reason) in new[] { (folded, "mine"), (other, "theirs") }) - { - await using var db = world.Db(); - await Sealed(world, db).CommitAsync(await world.ActorAsync(account.Id), motionId, SealedBallotDocument.Commit(Doc(motionId, reason), account.Id), default); - } - - Task? freeze = null; - var blocked = false; - var revealers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () => - { - // The first attempt has read its standing (none). A freeze starts and must wait; another member's reveal then lands first, - // so this attempt's save conflicts on RevealSeq and the reveal retries while the freeze still waits. - freeze = Task.Run(() => world.MergeAsync(survivor, folded, AccountMergeState.Confirmed)); - await using var rival = world.Db(); - world.Clock.Now = AccountMergeLedgerTests.T0.AddMinutes(90); - await Sealed(world, rival).RevealAsync(await world.ActorAsync(other.Id), motionId, Doc(motionId, "theirs"), default); - await Task.Delay(1500); - blocked = !freeze.IsCompleted; - })); - revealers.Clock.Now = AccountMergeLedgerTests.T0.AddMinutes(90); - var actor = await world.ActorAsync(folded.Id); - - await using (var db = revealers.Db()) - { - Assert.True((await Sealed(revealers, db).RevealAsync(actor, motionId, Doc(motionId, "mine"), default)).Revealed); - } - - await freeze!.WaitAsync(TimeSpan.FromSeconds(30)); - Assert.True(blocked); - } - - // ---- the saga: races the State token and the live-merge index carry ---- - - /// Holds the first save of each of two contexts until both have arrived: both have read, neither has written. - private sealed class FirstSaveRendezvous : SaveChangesInterceptor - { - private readonly Barrier _barrier = new(2); - private readonly HashSet _seen = []; - - public override async ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) - { - bool first; - lock (_seen) - { - first = _seen.Add(eventData.Context!.ContextId.InstanceId); - } - - if (first) - { - await Task.Run(() => _barrier.SignalAndWait(TimeSpan.FromSeconds(30)), cancellationToken); - } - - return result; - } - } - - /// The fake Heimdall's account model behind the real move client, one key ring for every saga built over it. - private sealed class Heimdall - { - private readonly EphemeralDataProtectionProvider _keys = new(); - private readonly HeimdallIdentityMoveClient _mover; - - public Heimdall(AccountMergeLedgerTests.World clockOwner) - { - Fake = new FakeHeimdall { RequiredAppSecret = HeimdallHost.AppSecret, Now = () => clockOwner.Clock.Now }; - var options = new HeimdallOptions { BaseUrl = HeimdallShapes.Issuer, AppSecret = HeimdallHost.AppSecret }; - var client = new HttpClient(Fake); - HeimdallAuthService.ConfigureClient(client, options); - _mover = new HeimdallIdentityMoveClient(client, Options.Create(options), NullLogger.Instance); - } - - public FakeHeimdall Fake { get; } - - public AccountMergeSaga Saga(AccountMergeLedgerTests.World world, BifrostDbContext db) => - new(db, world.Ledger(db), _mover, _keys, new AuditTrailService(db, world.Clock), world.Clock, NullLogger.Instance); - - /// A world account with one login at the fake Heimdall and a weak proof through it. - public MergeProof Proof(UserAccount account, string provider) => - new(Fake.Moves.Issue(account.HeimdallAccountId, Fake.Moves.AddLogin(account.HeimdallAccountId, provider)), account.HeimdallAccountId, provider); - } - - [PostgresFact] - public async Task Two_concurrent_advances_of_one_confirmed_merge_make_one_move_commit_once_and_journal_once() - { - var world = await postgres.NewWorldAsync(); - 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 heimdall = new Heimdall(world); - var survivorProof = heimdall.Proof(survivor, "twitch"); - var foldedProof = heimdall.Proof(folded, "discord"); - Guid mergeId; - await using (var db = world.Db()) - { - var saga = heimdall.Saga(world, db); - var digest = (await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id); - mergeId = Assert.IsType(await saga.ConfirmAsync( - new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, digest, survivorProof, [foldedProof]), default)).MergeId; - } - - var racers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new FirstSaveRendezvous()); - async Task Advance() - { - await using var db = racers.Db(); - return await heimdall.Saga(racers, db).AdvanceAsync(mergeId, default); - } - - var both = await Task.WhenAll(Task.Run(Advance), Task.Run(Advance)); - - Assert.All(both, x => Assert.Equal(AccountMergeState.Committed, x.State)); - Assert.Single(heimdall.Fake.Moves.Stored); - var journal = await world.JournalAsync(new AccountMerge { Id = mergeId }); - Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count()); - Assert.Single(journal, x => x.Kind == AccountMergeEntryKind.Vote); - Assert.Equal(survivor.Id, Assert.Single(await world.AllVotesAsync(motion)).UserAccountId); - } - - [PostgresFact] - public async Task Two_confirms_folding_the_same_account_leave_one_row_and_the_other_is_blocked_by_the_database() - { - var world = await postgres.NewWorldAsync(); - var first = await world.AccountAsync("first"); - var second = await world.AccountAsync("second"); - var folded = await world.AccountAsync("folded"); - var heimdall = new Heimdall(world); - var proofs = new Dictionary(); - foreach (var survivor in new[] { first, second }) - { - await using var db = world.Db(); - proofs[survivor.Id] = (heimdall.Proof(survivor, "twitch"), (await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id)); - } - - var foldedProof = heimdall.Proof(folded, "discord"); - var racers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new FirstSaveRendezvous()); - async Task Confirm(UserAccount survivor) - { - await using var db = racers.Db(); - return await heimdall.Saga(racers, db).ConfirmAsync( - new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, proofs[survivor.Id].Digest, proofs[survivor.Id].Survivor, [foldedProof]), default); - } - - var results = await Task.WhenAll(Task.Run(() => Confirm(first)), Task.Run(() => Confirm(second))); - - Assert.Single(results.OfType()); - var blocked = Assert.Single(results.OfType()); - Assert.Contains(AccountMergeSaga.MergeInFlight, blocked.Codes); - await using var check = world.Db(); - Assert.Equal(1, await check.AccountMerges.CountAsync()); - } - - [PostgresFact] - public async Task Two_merges_cannot_share_a_Heimdall_move_id_or_a_reverse_move_id() - { - var world = await postgres.NewWorldAsync(); - var survivor = await world.AccountAsync("survivor"); - var one = await world.MergeAsync(survivor, await world.AccountAsync("one"), AccountMergeState.Confirmed); - var two = await world.MergeAsync(survivor, await world.AccountAsync("two"), AccountMergeState.Confirmed); - - foreach (var column in new[] { "HeimdallMoveId", "HeimdallReverseMoveId" }) - { - await ExecuteAsync(world, $"UPDATE \"AccountMerges\" SET \"{column}\" = 'shared-0123456789abcdef' WHERE \"Id\" = '{one.Id}'"); - var error = await Assert.ThrowsAnyAsync(() => - ExecuteAsync(world, $"UPDATE \"AccountMerges\" SET \"{column}\" = 'shared-0123456789abcdef' WHERE \"Id\" = '{two.Id}'")); - Assert.Equal("23505", Pg(error).SqlState); - } - } - - [PostgresFact] - public async Task Confirm_holds_the_actors_write_lock_until_its_row_is_saved() - { - var world = await postgres.NewWorldAsync(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var heimdall = new Heimdall(world); - var proof = heimdall.Proof(survivor, "twitch"); - var foldedProof = heimdall.Proof(folded, "discord"); - string digest; - await using (var db = world.Db()) - { - digest = (await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id); - } - - Task? exclusive = null; - var blocked = false; - var confirmers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () => - { - // A writer that needs the actor's exclusive lock (a commit freezing it) arrives while the confirm is about to save. - exclusive = Task.Run(async () => - { - await using var connection = new NpgsqlConnection(ConnectionOf(world)); - await connection.OpenAsync(); - await using var transaction = await connection.BeginTransactionAsync(); - await using var command = new NpgsqlCommand("SELECT pg_advisory_xact_lock(hashtextextended(@key, 0))", connection, transaction); - command.Parameters.AddWithValue("key", survivor.Id.ToString()); - await command.ExecuteNonQueryAsync(); - }); - await Task.Delay(1500); - blocked = !exclusive.IsCompleted; - })); - - await using (var db = confirmers.Db()) - { - Assert.IsType(await heimdall.Saga(confirmers, db).ConfirmAsync( - new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, digest, proof, [foldedProof]), default)); - } - - await exclusive!.WaitAsync(TimeSpan.FromSeconds(30)); - Assert.True(blocked); - } - - /// A Confirmed merge with sealed proofs, stopped on the given outcome, and the operator who will settle it. - private async Task<(AccountMergeLedgerTests.World World, Heimdall Heimdall, Guid Id, string MoveId, Guid Operator)> StuckConfirmedAsync(string outcome) - { - var world = await postgres.NewWorldAsync(); - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - var operatorId = (await world.AccountAsync("operator")).Id; - var heimdall = new Heimdall(world); - Guid id; - await using (var db = world.Db()) - { - var digest = (await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id); - id = Assert.IsType(await heimdall.Saga(world, db).ConfirmAsync( - new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, digest, heimdall.Proof(survivor, "twitch"), [heimdall.Proof(folded, "discord")]), default)).MergeId; - } - - await ExecuteAsync(world, $"UPDATE \"AccountMerges\" SET \"State\" = 'Confirmed', \"LastOutcome\" = '{outcome}' WHERE \"Id\" = '{id}'"); - await using var read = world.Db(); - var merge = await read.AccountMerges.AsNoTracking().SingleAsync(); - Assert.NotNull(merge.SealedProofs); - return (world, heimdall, id, merge.HeimdallMoveId!, operatorId); - } - - [PostgresFact] - public async Task A_settle_that_loses_to_a_rival_state_write_inside_its_save_window_writes_nothing_and_no_audit_row() - { - var (world, heimdall, id, moveId, operatorId) = await StuckConfirmedAsync("move_id_conflict"); - var settler = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(() => - ExecuteAsync(world, $"UPDATE \"AccountMerges\" SET \"State\" = 'HeimdallMoved' WHERE \"Id\" = '{id}'"))); - await using (var db = settler.Db()) - { - Assert.IsType(await heimdall.Saga(settler, db).SettleStuckAsync(id, SettleChoice.FailForward, moveId, operatorId, default)); - } - - await using var read = world.Db(); - var merge = await read.AccountMerges.AsNoTracking().SingleAsync(); - Assert.Equal(AccountMergeState.HeimdallMoved, merge.State); - Assert.NotNull(merge.SealedProofs); - Assert.Equal("move_id_conflict", merge.LastOutcome); - Assert.Equal(0, await read.AuditEvents.CountAsync()); - } - - [PostgresFact] - public async Task A_settle_whose_audit_insert_fails_rolls_the_transition_back() - { - var (world, heimdall, id, moveId, operatorId) = await StuckConfirmedAsync("receipt_mismatch"); - await ExecuteAsync(world, """ - CREATE FUNCTION fail_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected audit fault'; END $$; - CREATE TRIGGER fail_audit BEFORE INSERT ON "AuditEvents" FOR EACH ROW EXECUTE FUNCTION fail_audit(); - """); - await using (var db = world.Db()) - { - await Assert.ThrowsAsync(() => heimdall.Saga(world, db).SettleStuckAsync(id, SettleChoice.FailForward, moveId, operatorId, default)); - } - - await using var read = world.Db(); - var merge = await read.AccountMerges.AsNoTracking().SingleAsync(); - Assert.Equal(AccountMergeState.Confirmed, merge.State); - Assert.NotNull(merge.SealedProofs); - Assert.Equal("receipt_mismatch", merge.LastOutcome); - Assert.Equal(0, await read.AuditEvents.CountAsync()); - } - - [PostgresFact] - public async Task Two_concurrent_settles_of_one_stuck_merge_settle_once_lose_once_and_audit_once() - { - var (world, heimdall, id, moveId, operatorId) = await StuckConfirmedAsync("proofs_unreadable"); - var racers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new FirstSaveRendezvous()); - async Task Settle() - { - await using var db = racers.Db(); - return await heimdall.Saga(racers, db).SettleStuckAsync(id, SettleChoice.FailForward, moveId, operatorId, default); - } - - var both = await Task.WhenAll(Task.Run(Settle), Task.Run(Settle)); - - Assert.Single(both.OfType()); - Assert.Single(both.OfType()); - await using var read = world.Db(); - Assert.Equal(1, await read.AuditEvents.CountAsync()); - Assert.Equal(AccountMergeState.Failed, (await read.AccountMerges.AsNoTracking().SingleAsync()).State); - } - - [PostgresFact] - public async Task The_saga_migration_adds_and_drops_its_columns_and_keys_and_its_Down_is_refused_while_any_merge_exists() - { - var world = await postgres.NewWorldAsync(); - await world.MergeAsync(await world.AccountAsync("survivor"), await world.AccountAsync("folded"), AccountMergeState.Confirmed); - await using (var db = world.Db()) - { - var error = await Assert.ThrowsAnyAsync(() => db.GetService().MigrateAsync("20261114120000_AddAccountMerges")); - Assert.Contains("AddAccountMergeSaga cannot be reverted", Pg(error).MessageText); - // The acks migration reverts first (it holds only acks); the saga migration is the one that refuses. - Assert.Equal("20261114130000_AddAccountMergeSaga", (await db.Database.GetAppliedMigrationsAsync()).Last()); - } - - await ExecuteAsync(world, "DELETE FROM \"AccountMerges\""); - await using var down = world.Db(); - await down.GetService().MigrateAsync("20261114120000_AddAccountMerges"); - Assert.Equal(0, await ScalarAsync(world, "SELECT count(*) FROM information_schema.columns WHERE table_name = 'AccountMerges' AND column_name IN ('HeimdallMoveId','SealedProofs','Attempts')")); - Assert.Equal(0, await ScalarAsync(world, "SELECT count(*) FROM pg_indexes WHERE tablename = 'AccountMerges' AND indexname LIKE 'IX_AccountMerges_Heimdall%'")); - await down.GetService().MigrateAsync(); - Assert.Equal(3, await ScalarAsync(world, "SELECT count(*) FROM information_schema.columns WHERE table_name = 'AccountMerges' AND column_name IN ('HeimdallMoveId','SealedProofs','Attempts')")); - Assert.Equal(2, await ScalarAsync(world, "SELECT count(*) FROM pg_indexes WHERE tablename = 'AccountMerges' AND indexname LIKE 'IX_AccountMerges_Heimdall%'")); - } - - private static async Task ScalarAsync(AccountMergeLedgerTests.World world, string sql) - { - await using var connection = new NpgsqlConnection(ConnectionOf(world)); - await connection.OpenAsync(); - await using var command = new NpgsqlCommand(sql, connection); - return (long)(await command.ExecuteScalarAsync())!; - } -} diff --git a/tests/Bifrost.Web.Tests/AccountMergeSagaTests.cs b/tests/Bifrost.Web.Tests/AccountMergeSagaTests.cs deleted file mode 100644 index 0e73216..0000000 --- a/tests/Bifrost.Web.Tests/AccountMergeSagaTests.cs +++ /dev/null @@ -1,732 +0,0 @@ -using System.Net; -using System.Text.Json; -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Heimdall; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Tests.Support; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging.Abstractions; - -namespace Bifrost.Web.Tests; - -/// -/// The merge saga from its consumers' side: a request scope of the real host (DI, the move client's HttpClient, Data Protection, the shared -/// TestClock) driving Confirm, Advance and RequestUndo against the fake Heimdall's account model (Heimdall 4fe367a's contract). Every -/// operation takes a fresh scope, as a request or a sweeper tick would, so what survives is only what was saved. -/// -public sealed class AccountMergeSagaTests -{ - private const string Passkey = "bifrost-passkey"; - - internal sealed record Party(Guid Id, string HeimdallId, IReadOnlyDictionary Logins); - - /// A host plus the helpers every test needs: accounts with logins at the fake Heimdall, proofs, a scope per operation. - internal sealed class Rig(bool realSessions = false, bool accountMerge = false, string? chatNoticesToken = null) : IDisposable - { - public HeimdallHost Host { get; } = new(realSessions: realSessions, accountMerge: accountMerge, chatNoticesToken: chatNoticesToken); - - public FakeMoves Moves => Host.Heimdall.Moves; - - public TestClock Clock => Host.Clock; - - public void Dispose() => Host.Dispose(); - - public async Task AccountAsync(string name, params string[] providers) - { - var heimdallId = HeimdallShapes.NewAccountId(); - var logins = providers.ToDictionary(x => x, x => Moves.AddLogin(heimdallId, x)); - using var scope = Host.Services.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - var account = new UserAccount - { - DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = BifrostIdentityService.NormalizeIdentity(name), - HeimdallAccountId = heimdallId, CreatedAtUtc = Clock.Now, LastSeenAtUtc = Clock.Now, - MemberProfile = new MemberProfile { Nickname = name, Headline = "seed", UpdatedAtUtc = Clock.Now } - }; - account.Membership = new Membership { UserAccountId = account.Id, Status = MembershipStatus.Active }; - db.UserAccounts.Add(account); - await db.SaveChangesAsync(); - return new Party(account.Id, heimdallId, logins); - } - - /// A fresh sign-in through the login of : a weak proof of that login only. - public MergeProof Weak(Party who, string provider) => new(Moves.Issue(who.HeimdallId, who.Logins[provider]), who.HeimdallId, provider); - - /// A fresh sign-in of through a login that came from (a login the merge moved to it). - public MergeProof Moved(Party holder, Party origin, string provider) => new(Moves.Issue(holder.HeimdallId, origin.Logins[provider]), holder.HeimdallId, provider); - - /// A passkey assertion: a strong proof that speaks for the whole account. - public MergeProof Strong(Party who) => new(Moves.Issue(who.HeimdallId, stepUpMethod: Passkey), who.HeimdallId, "passkey"); - - public async Task InScopeAsync(Func> work) - { - using var scope = Host.Services.CreateScope(); - return await work(scope.ServiceProvider); - } - - public async Task DigestAsync(Party survivor, Party folded) => - await InScopeAsync(async sp => (await sp.GetRequiredService().PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id)); - - public async Task ConfirmAsync(Party survivor, Party folded, MergeProof survivorProof, params MergeProof[] foldedProofs) - { - var digest = await DigestAsync(survivor, folded); - return await InScopeAsync(sp => sp.GetRequiredService().ConfirmAsync( - new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, digest, survivorProof, foldedProofs), default)); - } - - public async Task ConfirmedAsync(Party survivor, Party folded, MergeProof survivorProof, params MergeProof[] foldedProofs) => - Assert.IsType(await ConfirmAsync(survivor, folded, survivorProof, foldedProofs)).MergeId; - - public Task AdvanceAsync(Guid id) => InScopeAsync(sp => sp.GetRequiredService().AdvanceAsync(id, default)); - - public Task AdvanceDueAsync() => InScopeAsync(sp => sp.GetRequiredService().AdvanceDueAsync(Clock.Now, default)); - - public Task MergeAsync(Guid id) => - InScopeAsync(sp => sp.GetRequiredService().AccountMerges.AsNoTracking().SingleAsync(x => x.Id == id)); - - public Task> JournalAsync(Guid id) => - InScopeAsync(sp => sp.GetRequiredService().AccountMergeEntries.Where(x => x.MergeId == id).ToListAsync()); - - public Task StandingAsync(Party who) => - InScopeAsync(sp => sp.GetRequiredService().StandingAsync(who.Id, default)); - - public Task MergeCountAsync() => InScopeAsync(sp => sp.GetRequiredService().AccountMerges.CountAsync()); - - public async Task MotionAsync(Party author) - { - using var scope = Host.Services.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - var motion = new Motion - { - CreatedByUserAccountId = author.Id, Title = "m", Status = MotionStatus.Open, Kind = MotionKind.Standard, OpensAtUtc = Clock.Now, - ClosesAtUtc = Clock.Now.AddDays(3), CreatedAtUtc = Clock.Now, ApprovalThreshold = 0.5m - }; - db.Motions.Add(motion); - await db.SaveChangesAsync(); - return motion; - } - - public async Task VoteAsync(Motion motion, Party who, VoteChoice choice) - { - using var scope = Host.Services.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - db.Votes.Add(new Vote { MotionId = motion.Id, UserAccountId = who.Id, Choice = choice, Weight = 1m, CastAtUtc = Clock.Now.AddHours(1) }); - await db.SaveChangesAsync(); - } - - public Task SeenMoveIdsAsync() => - Task.FromResult(Moves.Requests.Select(x => JsonDocument.Parse(x.Body).RootElement.GetProperty("moveId").GetString()!).ToArray()); - } - - // ---- the happy path and the stored move id ---- - - [Fact] - public async Task Two_weak_folded_proofs_and_a_survivor_proof_confirm_and_advance_to_committed_with_a_seven_day_grace_and_one_stored_move() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord", "patreon"); - - var digest = await rig.DigestAsync(survivor, folded); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"), rig.Weak(folded, "patreon")); - var confirmed = await rig.MergeAsync(id); - Assert.Equal(AccountMergeState.Confirmed, confirmed.State); - Assert.Equal(survivor.Id, confirmed.ConfirmedByUserAccountId); - Assert.Equal(rig.Clock.Now, confirmed.ConfirmedUtc); - Assert.Equal("twitch", confirmed.SurvivorProofProvider); - Assert.Equal("discord,patreon", confirmed.FoldedProofProviders); - Assert.Equal(digest, confirmed.PreviewDigest); - Assert.NotNull(confirmed.SealedProofs); - Assert.Matches("^[0-9a-f]{32}$", confirmed.HeimdallMoveId!); - Assert.Empty(rig.Moves.Requests); // confirm calls no Heimdall - Assert.IsType(await rig.StandingAsync(folded)); - - var done = await rig.AdvanceAsync(id); - - Assert.Equal(AccountMergeState.Committed, done.State); - Assert.Equal(done.CommittedUtc + AccountMergeLedger.Grace, done.GraceEndsUtc); - var stored = Assert.Single(rig.Moves.Stored); - Assert.Equal(confirmed.HeimdallMoveId, stored.MoveId); - var final = await rig.MergeAsync(id); - Assert.Null(final.SealedProofs); - Assert.Equal("weak", final.ProofFromTier); - Assert.Equal("weak", final.ProofToTier); - Assert.Equal(folded.Logins.Values.Order(), JsonSerializer.Deserialize(final.MovedIdentityIds!)!.Order()); - Assert.IsType(await rig.StandingAsync(folded)); - Assert.Equal(["twitch", "discord", "patreon"], rig.Moves.Logins[survivor.HeimdallId].Select(x => x.Provider)); - } - - [Fact] - public async Task A_vote_on_the_same_open_motion_from_both_accounts_counts_only_the_survivors_after_the_saga_lands() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var motion = await rig.MotionAsync(survivor); - await rig.VoteAsync(motion, survivor, VoteChoice.For); - await rig.VoteAsync(motion, folded, VoteChoice.Against); - - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - await rig.AdvanceAsync(id); - - await rig.InScopeAsync(async sp => - { - var db = sp.GetRequiredService(); - Assert.Equal(survivor.Id, (await db.Votes.SingleAsync(x => x.MotionId == motion.Id)).UserAccountId); - var all = await db.Votes.IgnoreQueryFilters().Where(x => x.MotionId == motion.Id).ToListAsync(); - Assert.Equal(id, Assert.Single(all, x => x.UserAccountId == folded.Id).VoidedByMergeId); - return 0; - }); - } - - [Fact] - public async Task Heimdall_sees_the_move_id_stored_on_the_row_and_it_is_not_derived_from_the_merge_id() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - Assert.NotEqual(id.ToString("N"), (await rig.MergeAsync(id)).HeimdallMoveId); - const string overwritten = "overwritten0123456789abcdef0123456789"; - await rig.InScopeAsync(async sp => - { - var db = sp.GetRequiredService(); - (await db.AccountMerges.SingleAsync(x => x.Id == id)).HeimdallMoveId = overwritten; - await db.SaveChangesAsync(); - return 0; - }); - - await rig.AdvanceAsync(id); - - Assert.Equal(overwritten, Assert.Single(rig.Moves.Stored).MoveId); - } - - // ---- crashes and lost answers ---- - - [Fact] - public async Task A_lost_answer_leaves_the_merge_confirmed_and_a_fresh_scope_after_the_proofs_expired_settles_it_by_replay() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - rig.Moves.MoveApplyThenFail = HttpStatusCode.InternalServerError; - - var lost = await rig.AdvanceAsync(id); - - Assert.Equal(AccountMergeState.Confirmed, lost.State); - Assert.Equal(1, lost.Attempts); - Assert.Equal(rig.Clock.Now + TimeSpan.FromSeconds(15), lost.NextAttemptUtc); - Assert.Equal("HTTP 500", lost.LastOutcome); - Assert.Single(rig.Moves.Stored); - rig.Moves.MoveApplyThenFail = null; - rig.Clock.Advance(TimeSpan.FromSeconds(601)); // every proof is stale and the bearers expired by now; Heimdall answers a replay first - - Assert.Equal(1, await rig.AdvanceDueAsync()); - - Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(id)).State); - Assert.Single(rig.Moves.Stored); - Assert.Equal(2, (await rig.SeenMoveIdsAsync()).Length); - } - - [Fact] - public async Task A_crash_on_the_save_that_writes_HeimdallMoved_is_resumed_with_the_same_move_id_and_one_stored_move() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - rig.Host.Fault.When = db => db.ChangeTracker.Entries().Any(x => x.Entity.State == AccountMergeState.HeimdallMoved); - - await Assert.ThrowsAsync(() => rig.AdvanceAsync(id)); - rig.Host.Fault.When = null; - Assert.Equal(AccountMergeState.Confirmed, (await rig.MergeAsync(id)).State); - Assert.NotNull((await rig.MergeAsync(id)).SealedProofs); - - Assert.Equal(AccountMergeState.Committed, (await rig.AdvanceAsync(id)).State); - - var seen = await rig.SeenMoveIdsAsync(); - Assert.Equal(2, seen.Length); - Assert.Single(seen.Distinct()); - Assert.Single(rig.Moves.Stored); - Assert.Equal(seen[0], (await rig.MergeAsync(id)).HeimdallMoveId); - } - - [Fact] - public async Task A_crash_on_the_Committed_save_leaves_HeimdallMoved_and_the_next_advance_commits_once_without_calling_Heimdall_again() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var motion = await rig.MotionAsync(survivor); - await rig.VoteAsync(motion, folded, VoteChoice.For); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - rig.Host.Fault.When = db => db.ChangeTracker.Entries().Any(x => x.Entity.State == AccountMergeState.Committed); - - await Assert.ThrowsAsync(() => rig.AdvanceAsync(id)); - rig.Host.Fault.When = null; - var moved = await rig.MergeAsync(id); - Assert.Equal(AccountMergeState.HeimdallMoved, moved.State); - Assert.Null(moved.SealedProofs); - Assert.Empty(await rig.JournalAsync(id)); - - Assert.Equal(AccountMergeState.Committed, (await rig.AdvanceAsync(id)).State); - Assert.Equal(AccountMergeState.Committed, (await rig.AdvanceAsync(id)).State); - - Assert.Single(rig.Moves.Requests); - var journal = await rig.JournalAsync(id); - Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count()); - Assert.Single(journal, x => x.Kind == AccountMergeEntryKind.Vote); - } - - [Fact] - public async Task The_sweepers_own_loop_resumes_a_confirmed_merge_after_a_restart_and_finalizes_it_after_the_grace() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - - await RunOneSweepAsync(rig); - Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(id)).State); - - rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromMinutes(1)); - await RunOneSweepAsync(rig); - Assert.Equal(AccountMergeState.Final, (await rig.MergeAsync(id)).State); - } - - /// Starts the production sweeper (its first pass runs at once, before its 30 s timer) and stops it once the pass is over. - private static async Task RunOneSweepAsync(Rig rig) - { - var sweeper = new AccountMergeSweeper(rig.Host.Services.GetRequiredService(), rig.Clock, NullLogger.Instance); - await sweeper.StartAsync(default); - var before = rig.Clock.Now; - var deadline = DateTime.UtcNow.AddSeconds(20); - while (DateTime.UtcNow < deadline && sweeper.ExecuteTask is { IsCompleted: false } && await rig.InScopeAsync(async sp => - await sp.GetRequiredService().AccountMerges.AnyAsync(x => - x.State == AccountMergeState.Confirmed || x.State == AccountMergeState.HeimdallMoved || (x.State == AccountMergeState.Committed && x.GraceEndsUtc <= before)))) - { - await Task.Delay(50); - } - - await sweeper.StopAsync(default); - } - - // ---- refusals ---- - - [Theory] - [InlineData("proof_stale")] - [InlineData("identity_not_proved")] - [InlineData("provider_conflict")] - [InlineData("already_moved")] - public async Task A_coded_refusal_fails_the_merge_wipes_the_proofs_and_changes_nothing_in_Bifrost(string code) - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", code == "provider_conflict" ? ["discord"] : ["twitch"]); - var folded = await rig.AccountAsync("folded", "discord", "patreon"); - var motion = await rig.MotionAsync(survivor); - await rig.VoteAsync(motion, folded, VoteChoice.For); - MergeProof[] foldedProofs = code == "identity_not_proved" - ? [rig.Weak(folded, "discord")] // the patreon login is not proved: no partial move - : [rig.Weak(folded, "discord"), rig.Weak(folded, "patreon")]; - var survivorProof = rig.Weak(survivor, code == "provider_conflict" ? "discord" : "twitch"); - if (code == "already_moved") - { - // Heimdall already moved the folded account elsewhere; Bifrost's merge does not know. - var elsewhere = await rig.AccountAsync("elsewhere", "twitch2"); - var move = new HeimdallMoveRequest("preexisting-move-0000", [rig.Strong(folded).AccessToken], rig.Weak(elsewhere, "twitch2").AccessToken); - Assert.IsType(await rig.InScopeAsync(sp => sp.GetRequiredService().MoveAsync(move, default))); - foldedProofs = [rig.Strong(folded)]; - } - - var id = await rig.ConfirmedAsync(survivor, folded, survivorProof, foldedProofs); - if (code == "proof_stale") - { - rig.Clock.Advance(TimeSpan.FromSeconds(400)); - } - - var failed = await rig.AdvanceAsync(id); - - Assert.Equal(AccountMergeState.Failed, failed.State); - Assert.Equal(code, failed.FailureCode); - Assert.Equal(rig.Clock.Now, failed.FailedUtc); - var stored = await rig.MergeAsync(id); - Assert.Null(stored.SealedProofs); - Assert.Empty(await rig.JournalAsync(id)); - Assert.Null(await rig.StandingAsync(folded)); - await rig.InScopeAsync(async sp => - { - var vote = await sp.GetRequiredService().Votes.SingleAsync(); - Assert.Equal(folded.Id, vote.UserAccountId); - return 0; - }); - Assert.DoesNotContain(rig.Moves.Stored, x => x.MoveId == stored.HeimdallMoveId); - } - - // ---- confirm's consent checks ---- - - [Fact] - public async Task Confirm_refuses_a_third_party_a_changed_plan_a_proof_of_another_account_and_a_blocked_pair_and_writes_no_row() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var stranger = await rig.AccountAsync("stranger", "github"); - var digest = await rig.DigestAsync(survivor, folded); - var good = rig.Weak(survivor, "twitch"); - var foldedProof = rig.Weak(folded, "discord"); - - Task Confirm(Guid actor, string digestSeen, MergeProof survivorProof, params MergeProof[] proofs) => - rig.InScopeAsync(sp => sp.GetRequiredService().ConfirmAsync( - new ConfirmMergeRequest(actor, survivor.Id, folded.Id, digestSeen, survivorProof, proofs), default)); - - Assert.IsType(await Confirm(stranger.Id, digest, good, foldedProof)); - Assert.IsType(await Confirm(survivor.Id, digest, rig.Weak(stranger, "github"), foldedProof)); - Assert.IsType(await Confirm(survivor.Id, digest, good, rig.Weak(survivor, "twitch"))); - var motion = await rig.MotionAsync(survivor); - await rig.VoteAsync(motion, folded, VoteChoice.For); // the plan the member saw is no longer the plan - Assert.IsType(await Confirm(survivor.Id, digest, good, foldedProof)); - Assert.Equal(0, await rig.MergeCountAsync()); - - var blocked = Assert.IsType(await rig.InScopeAsync(sp => sp.GetRequiredService().ConfirmAsync( - new ConfirmMergeRequest(survivor.Id, survivor.Id, survivor.Id, "x", good, [good]), default))); - Assert.Contains("same_account", blocked.Codes); - Assert.Equal(0, await rig.MergeCountAsync()); - - // a second confirm of the same fold, after the first - var fresh = await rig.DigestAsync(survivor, folded); - Assert.IsType(await Confirm(survivor.Id, fresh, good, foldedProof)); - var second = Assert.IsType(await Confirm(survivor.Id, fresh, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"))); - Assert.Contains(AccountMergeSaga.MergeInFlight, second.Codes); - Assert.Equal(1, await rig.MergeCountAsync()); - } - - [Fact] - public async Task A_malformed_confirm_throws_before_any_row_and_neither_the_message_nor_the_proof_text_carry_a_token() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - const string canary = "CANARY-bearer-9f3a"; - var proof = new MergeProof(canary, folded.HeimdallId, "discord"); - Assert.DoesNotContain(canary, proof.ToString()); - Assert.DoesNotContain(folded.HeimdallId, proof.ToString()); - var request = new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, "d", new MergeProof(canary, survivor.HeimdallId, "twitch"), [proof]); - Assert.DoesNotContain(canary, request.ToString()); - - var nine = Enumerable.Repeat(proof, 9).ToList(); - var tooMany = await Assert.ThrowsAsync(() => - rig.InScopeAsync(sp => sp.GetRequiredService().ConfirmAsync(request with { FoldedProofs = nine }, default))); - var tooLong = await Assert.ThrowsAsync(() => - rig.InScopeAsync(sp => sp.GetRequiredService().ConfirmAsync( - request with { FoldedProofs = [proof with { AccessToken = canary + new string('x', HeimdallIdentityMoveClient.MaxProofLength) }] }, default))); - - Assert.DoesNotContain(canary, tooMany.ToString()); - Assert.DoesNotContain(canary, tooLong.ToString()); - Assert.Equal(0, await rig.MergeCountAsync()); - } - - // ---- sealing ---- - - [Fact] - public async Task Sealed_proofs_never_hold_a_bearer_in_the_clear_are_wiped_at_each_final_answer_and_no_log_carries_a_bearer_or_an_account() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var survivorProof = rig.Weak(survivor, "twitch"); - var foldedProof = rig.Weak(folded, "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, survivorProof, foldedProof); - var sealedText = (await rig.MergeAsync(id)).SealedProofs!; - Assert.DoesNotContain(survivorProof.AccessToken, sealedText); - Assert.DoesNotContain(foldedProof.AccessToken, sealedText); - Assert.DoesNotContain("bearer", sealedText); - - await rig.AdvanceAsync(id); - Assert.Null((await rig.MergeAsync(id)).SealedProofs); - - var undoProof = rig.Moved(survivor, folded, "discord"); // the moved login now lives on the survivor - Assert.IsType(await RequestUndoAsync(rig, id, survivor, undoProof)); - var requested = (await rig.MergeAsync(id)).SealedProofs!; - Assert.DoesNotContain(undoProof.AccessToken, requested); - await rig.AdvanceAsync(id); - Assert.Null((await rig.MergeAsync(id)).SealedProofs); - - var log = string.Join('\n', rig.Host.Logs.Lines); - foreach (var secret in new[] { survivorProof.AccessToken, foldedProof.AccessToken, undoProof.AccessToken, survivor.HeimdallId, folded.HeimdallId } - .Concat(folded.Logins.Values).Concat(survivor.Logins.Values)) - { - Assert.DoesNotContain(secret, log); - } - - Assert.Contains(id.ToString(), log); - } - - private static Task RequestUndoAsync(Rig rig, Guid id, Party actor, params MergeProof[] proofs) => - rig.InScopeAsync(sp => sp.GetRequiredService().RequestUndoAsync(id, actor.Id, proofs, default)); - - [Fact] - public async Task Unreadable_sealed_proofs_change_no_state_and_retry_in_an_hour_and_the_error_log_names_only_the_merge() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - await rig.InScopeAsync(async sp => - { - var db = sp.GetRequiredService(); - (await db.AccountMerges.SingleAsync(x => x.Id == id)).SealedProofs = "CfDJ8-not-a-protected-payload"; - await db.SaveChangesAsync(); - return 0; - }); - - var stuck = await rig.AdvanceAsync(id); - - Assert.Equal(AccountMergeState.Confirmed, stuck.State); - Assert.Equal(AccountMergeSaga.ProofsUnreadable, stuck.LastOutcome); - Assert.Equal(rig.Clock.Now + TimeSpan.FromHours(1), stuck.NextAttemptUtc); - Assert.Empty(rig.Moves.Requests); - Assert.Contains(rig.Host.Logs.Lines, x => x.Contains(id.ToString()) && x.Contains("unreadable")); - Assert.Equal(0, await rig.AdvanceDueAsync()); // not due for an hour - } - - [Fact] - public async Task A_receipt_for_another_account_is_recorded_wipes_the_proofs_and_is_never_retried() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - await rig.InScopeAsync(async sp => - { - var db = sp.GetRequiredService(); - (await db.UserAccounts.SingleAsync(x => x.Id == survivor.Id)).HeimdallAccountId = HeimdallShapes.NewAccountId(); // Bifrost's own link drifted - await db.SaveChangesAsync(); - return 0; - }); - - var stuck = await rig.AdvanceAsync(id); - var again = await rig.AdvanceAsync(id); - - Assert.Equal(AccountMergeState.Confirmed, stuck.State); - Assert.Equal(AccountMergeSaga.ReceiptMismatch, stuck.LastOutcome); - // The answer stays what Heimdall gave: a later sweep does not turn it into an hourly "proofs unreadable" retry. - Assert.Equal(AccountMergeSaga.ReceiptMismatch, again.LastOutcome); - Assert.Null(again.NextAttemptUtc); - Assert.Null((await rig.MergeAsync(id)).SealedProofs); - Assert.Single(rig.Moves.Requests); - Assert.IsType(await rig.StandingAsync(folded)); - } - - // ---- Heimdall down ---- - - [Fact] - public async Task While_Heimdall_is_down_the_merge_stays_confirmed_and_the_folded_account_frozen_then_commits_when_it_answers() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Strong(survivor), rig.Strong(folded)); // strong proofs outlive the outage below - rig.Moves.MoveDown = new HttpRequestException("down"); - - Assert.Equal(1, await rig.AdvanceDueAsync()); - Assert.Equal(0, await rig.AdvanceDueAsync()); // backed off 15 s - rig.Clock.Advance(TimeSpan.FromSeconds(16)); - Assert.Equal(1, await rig.AdvanceDueAsync()); - rig.Clock.Advance(TimeSpan.FromSeconds(61)); - Assert.Equal(1, await rig.AdvanceDueAsync()); - - var down = await rig.MergeAsync(id); - Assert.Equal(AccountMergeState.Confirmed, down.State); - Assert.Equal(3, down.Attempts); - Assert.Equal(rig.Clock.Now + TimeSpan.FromMinutes(5), down.NextAttemptUtc); - Assert.IsType(await rig.StandingAsync(folded)); - Assert.Empty(rig.Moves.Stored); - - rig.Moves.MoveDown = null; - rig.Clock.Advance(TimeSpan.FromMinutes(5)); - Assert.Equal(1, await rig.AdvanceDueAsync()); - - Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(id)).State); - } - - // ---- undo ---- - - [Fact] - public async Task Undo_with_survivor_proofs_of_the_moved_logins_reverses_the_move_and_ends_Undone() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord", "patreon"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"), rig.Weak(folded, "patreon")); - await rig.AdvanceAsync(id); - var forward = (await rig.MergeAsync(id)).HeimdallMoveId; - - Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Moved(survivor, folded, "discord"), rig.Moved(survivor, folded, "patreon"))); - var requested = await rig.MergeAsync(id); - Assert.Equal(AccountMergeState.UndoRequested, requested.State); - Assert.Matches("^[0-9a-f]{32}$", requested.HeimdallReverseMoveId!); - Assert.NotEqual(forward, requested.HeimdallReverseMoveId); - Assert.IsType(await rig.StandingAsync(folded)); - - var done = await rig.AdvanceAsync(id); - - Assert.Equal(AccountMergeState.Undone, done.State); - Assert.NotNull((await rig.MergeAsync(id)).ReversedUtc); - Assert.Equal(2, rig.Moves.Stored.Count); - var reversal = Assert.Single(rig.Moves.Stored, x => x.ReversesMoveId is not null); - Assert.Equal(forward, reversal.ReversesMoveId); - Assert.Equal(requested.HeimdallReverseMoveId, reversal.MoveId); - Assert.Equal(["discord", "patreon"], rig.Moves.Logins[folded.HeimdallId].Select(x => x.Provider).Order()); - Assert.Null(await rig.StandingAsync(folded)); - } - - [Fact] - public async Task A_refused_undo_returns_the_merge_to_Committed_with_the_proofs_wiped_and_the_sweep_finalizes_it_after_the_grace() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - var committed = await rig.AdvanceAsync(id); - rig.Moves.Logins[survivor.HeimdallId].RemoveAll(x => x.Provider == "discord"); // the survivor unlinked a moved login - - Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Weak(survivor, "twitch"))); - var back = await rig.AdvanceAsync(id); - - Assert.Equal(AccountMergeState.Committed, back.State); - var stored = await rig.MergeAsync(id); - Assert.Equal("undo_not_reversible", stored.LastOutcome); - Assert.Null(stored.SealedProofs); - Assert.Equal(committed.GraceEndsUtc, stored.GraceEndsUtc); - Assert.IsType(await rig.StandingAsync(folded)); - - rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromMinutes(1)); - await rig.InScopeAsync(async sp => - { - await sp.GetRequiredService().AdvanceDueAsync(rig.Clock.Now, default); - return await sp.GetRequiredService().FinalizeDueAsync(rig.Clock.Now, default); - }); - Assert.Equal(AccountMergeState.Final, (await rig.MergeAsync(id)).State); - } - - [Fact] - public async Task Undo_is_requested_only_inside_the_grace_only_by_the_survivor_and_only_from_Committed() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Weak(survivor, "twitch"))); - Assert.IsType(await RequestUndoAsync(rig, Guid.NewGuid(), survivor, rig.Weak(survivor, "twitch"))); - await rig.AdvanceAsync(id); - - Assert.IsType(await RequestUndoAsync(rig, id, folded, rig.Weak(folded, "discord"))); - Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Weak(folded, "discord"))); - Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(id)).State); - - var proof = rig.Weak(survivor, "twitch"); - rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromSeconds(1)); - Assert.IsType(await RequestUndoAsync(rig, id, survivor, proof)); // Committed, but the grace ended - await rig.InScopeAsync(sp => sp.GetRequiredService().FinalizeDueAsync(rig.Clock.Now, default)); - Assert.IsType(await RequestUndoAsync(rig, id, survivor, proof)); // Final - Assert.Equal(AccountMergeState.Final, (await rig.MergeAsync(id)).State); - } - - [Fact] - public async Task A_suspended_folded_account_into_a_memberless_survivor_confirms_on_the_digest_the_member_saw_and_commits() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - await rig.InScopeAsync(async sp => - { - var db = sp.GetRequiredService(); - db.Memberships.Remove(await db.Memberships.SingleAsync(x => x.UserAccountId == survivor.Id)); // the chat tier holds no membership - (await db.Memberships.SingleAsync(x => x.UserAccountId == folded.Id)).Status = MembershipStatus.Suspended; - await db.SaveChangesAsync(); - return 0; - }); - - // The member is shown a plan and confirms it: the same unchanged world must show the same digest. - Assert.Equal(await rig.DigestAsync(survivor, folded), await rig.DigestAsync(survivor, folded)); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - - Assert.Equal(AccountMergeState.Committed, (await rig.AdvanceAsync(id)).State); - var carried = await rig.InScopeAsync(sp => sp.GetRequiredService().Memberships.SingleAsync(x => x.UserAccountId == survivor.Id)); - Assert.Equal(MembershipStatus.Suspended, carried.Status); - } - - [Fact] - public async Task Undo_is_refused_at_the_exact_instant_the_grace_ends_and_allowed_a_second_before() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - await rig.AdvanceAsync(id); - var ends = (await rig.MergeAsync(id)).GraceEndsUtc!.Value; - - rig.Clock.Advance(ends - rig.Clock.Now); - Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Weak(survivor, "twitch"))); - rig.Clock.Advance(TimeSpan.FromSeconds(-1)); - Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Weak(survivor, "twitch"))); - } - - [Fact] - public void The_sealed_proofs_record_prints_no_bearer() - { - var seal = typeof(AccountMergeSaga).GetNestedType("ProofSeal", System.Reflection.BindingFlags.NonPublic)!; - var instance = Activator.CreateInstance(seal, new List { "bearer-folded-secret" }, "bearer-survivor-secret")!; - - var text = instance.ToString()!; - - Assert.DoesNotContain("secret", text); - } - - [Fact] - public async Task An_unknown_answer_to_the_reversal_is_replayed_under_the_same_reverse_id_even_past_the_grace() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - await rig.AdvanceAsync(id); - Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Moved(survivor, folded, "discord"))); - rig.Moves.MoveApplyThenFail = HttpStatusCode.BadGateway; - - Assert.Equal(AccountMergeState.UndoRequested, (await rig.AdvanceAsync(id)).State); - rig.Moves.MoveApplyThenFail = null; - rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromDays(1)); - await rig.AdvanceDueAsync(); - - Assert.Equal(AccountMergeState.Undone, (await rig.MergeAsync(id)).State); - var seen = (await rig.SeenMoveIdsAsync()).Skip(1).ToArray(); - Assert.Equal(2, seen.Length); - Assert.Single(seen.Distinct()); - Assert.Equal(2, rig.Moves.Stored.Count); - } - - // ---- the wiring ---- - - [Fact] - public void The_host_registers_exactly_one_merge_loop_in_production_and_the_saga_beside_the_ledger() - { - var program = File.ReadAllText(Path.Combine(RepoRoot(), "src", "Bifrost.Web", "Program.cs")); - Assert.Single(System.Text.RegularExpressions.Regex.Matches(program, @"AddHostedService<.*Merge")); - Assert.Contains("AddScoped", program); - } - - private static string RepoRoot() - { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "Bifrost.slnx"))) - { - dir = dir.Parent; - } - - return dir?.FullName ?? throw new InvalidOperationException("repo root not found"); - } -} diff --git a/tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs b/tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs deleted file mode 100644 index 5337eb8..0000000 --- a/tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System.Net; -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Tests.Support; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using static Bifrost.Web.Tests.AccountMergeSagaTests; -using static Bifrost.Web.Tests.AccountMergeSettleTests; - -namespace Bifrost.Web.Tests; - -/// The operator's page for stuck merges, from browser sessions of the real host: admin only, the stored move id shown as the confirmation, results by closed code. -public sealed class AccountMergeSettlePageTests -{ - private const string Url = "/App/Merges"; - - private sealed class World : IDisposable - { - public Rig Rig { get; } = new(realSessions: true); - - public Party Admin { get; private set; } = null!; - - public string AdminSession { get; private set; } = string.Empty; - - public string MemberSession { get; private set; } = string.Empty; - - public Stuck Forward { get; private set; } = null!; - - public static async Task Make() - { - var world = new World(); - var rig = world.Rig; - world.Admin = await rig.AccountAsync("operator", "github"); - var member = await rig.AccountAsync("member", "github"); - await rig.InScopeAsync(async sp => - { - var db = sp.GetRequiredService(); - var membership = await db.Memberships.SingleAsync(x => x.UserAccountId == world.Admin.Id); - membership.IsPlatformAdmin = true; - await db.SaveChangesAsync(); - return 0; - }); - world.AdminSession = await rig.Host.SignInSessionAsync(world.Admin.HeimdallId); - world.MemberSession = await rig.Host.SignInSessionAsync(member.HeimdallId); - world.Forward = await ConfirmedStuckAsync(rig, AccountMergeSaga.ReceiptMismatch); - return world; - } - - public void Dispose() => Rig.Dispose(); - - public Task<(HttpResponseMessage Response, string Html)> Get(string session, string query = "") => MergePage.GetAsync(Rig.Host, session, query, Url); - - public async Task Post(string session, string handler, string mergeId, string moveId, MergePage.Antiforgery? token = null) => - await MergePage.PostAsync(Rig.Host, session, token ?? await MergePage.TokenAsync(Rig.Host, session, HeimdallHost.LinkedAccountsUrl), handler, - new Dictionary { ["mergeId"] = mergeId, ["moveId"] = moveId }, Url); - } - - private static bool Refused(HttpResponseMessage response) => - response.StatusCode == HttpStatusCode.Forbidden || (response.StatusCode == HttpStatusCode.Redirect && (response.Headers.Location?.OriginalString.Contains("/Membership/Status?ReturnUrl=", StringComparison.Ordinal) ?? false)); - - [Fact] - public async Task A_member_who_is_not_a_platform_admin_is_refused_on_the_listing_and_on_both_posts_and_nothing_changes() - { - using var w = await World.Make(); - var merge = await w.Rig.MergeAsync(w.Forward.Id); - var requests = w.Rig.Moves.Requests.Count; - - var (get, html) = await w.Get(w.MemberSession); - Assert.True(Refused(get), $"listing gave {(int)get.StatusCode} {MergePage.Location(get)}"); - Assert.DoesNotContain(merge.HeimdallMoveId!, html); - Assert.True(Refused(await w.Post(w.MemberSession, "FailForward", w.Forward.Id.ToString(), merge.HeimdallMoveId!))); - Assert.True(Refused(await w.Post(w.MemberSession, "AbandonUndo", w.Forward.Id.ToString(), merge.HeimdallMoveId!))); - - var after = await w.Rig.MergeAsync(w.Forward.Id); - Assert.Equal(AccountMergeState.Confirmed, after.State); - Assert.Equal(AccountMergeSaga.ReceiptMismatch, after.LastOutcome); - Assert.Equal(requests, w.Rig.Moves.Requests.Count); - } - - [Fact] - public async Task The_listing_shows_stuck_merges_with_their_stored_move_id_and_no_Heimdall_account_or_provider_user_id() - { - using var w = await World.Make(); - var stuck = w.Forward; - var merge = await w.Rig.MergeAsync(stuck.Id); - // Heimdall unreachable for a long time: listed, though only the three stuck outcomes can be ended. - var slow = await ConfirmedStuckAsync(w.Rig, AccountMergeSaga.MoveIdConflict); - var slowMerge = await w.Rig.MergeAsync(slow.Id); - var waiting = await ConfirmedStuckAsync(w.Rig, "transport"); - await EditMerge(w.Rig, waiting.Id, x => x.Attempts = 8); - var healthy = await ConfirmedStuckAsync(w.Rig, "confirmed"); // one waiting for its first replay: not stuck - await EditMerge(w.Rig, healthy.Id, x => x.Attempts = 1); - var undo = await UndoStuckAsync(w.Rig); - var undoMerge = await w.Rig.MergeAsync(undo.Id); - - var (response, html) = await w.Get(w.AdminSession); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains(stuck.Id.ToString(), html); - Assert.Contains(merge.HeimdallMoveId!, html); - Assert.Contains(slow.Id.ToString(), html); - Assert.Contains(slowMerge.HeimdallMoveId!, html); - Assert.Contains(waiting.Id.ToString(), html); - Assert.Contains(undo.Id.ToString(), html); - Assert.Contains(undoMerge.HeimdallReverseMoveId!, html); - Assert.DoesNotContain(undoMerge.HeimdallMoveId!, html); // the leg in flight is the reversal - Assert.DoesNotContain(healthy.Id.ToString(), html); - foreach (var party in new[] { stuck.Survivor, stuck.Folded, slow.Survivor, slow.Folded, undo.Survivor, undo.Folded }) - { - Assert.DoesNotContain(party.HeimdallId, html); - Assert.DoesNotContain(party.Id.ToString(), html); - Assert.DoesNotContain(party.Logins.Values.First(), html); - } - } - - [Fact] - public async Task A_platform_admin_ends_a_stuck_leg_by_typing_its_move_id_and_a_wrong_one_changes_nothing() - { - using var w = await World.Make(); - var merge = await w.Rig.MergeAsync(w.Forward.Id); - var token = await MergePage.TokenAsync(w.Rig.Host, w.AdminSession, Url); - var requests = w.Rig.Moves.Requests.Count; - - var wrong = await w.Post(w.AdminSession, "FailForward", w.Forward.Id.ToString(), "0123456789abcdef0123456789abcdef", token); - Assert.Equal(Url + "?result=wrong_move_id", MergePage.Location(wrong)); - Assert.Equal(AccountMergeState.Confirmed, (await w.Rig.MergeAsync(w.Forward.Id)).State); - - var otherLeg = await w.Post(w.AdminSession, "AbandonUndo", w.Forward.Id.ToString(), merge.HeimdallMoveId!, token); - Assert.Equal(Url + "?result=not_stuck", MergePage.Location(otherLeg)); - - var done = await w.Post(w.AdminSession, "FailForward", w.Forward.Id.ToString(), merge.HeimdallMoveId!, token); - Assert.Equal(Url + "?result=settled", MergePage.Location(done)); - var after = await w.Rig.MergeAsync(w.Forward.Id); - Assert.Equal(AccountMergeState.Failed, after.State); - await w.Rig.InScopeAsync(async sp => - { - var audit = await sp.GetRequiredService().AuditEvents.AsNoTracking().SingleAsync(x => x.EntityId == w.Forward.Id.ToString()); - Assert.Equal(w.Admin.Id, audit.ActorUserAccountId); - return 0; - }); - Assert.Equal(requests, w.Rig.Moves.Requests.Count); // the page calls no Heimdall - - var (_, html) = await w.Get(w.AdminSession, "?result=settled"); - Assert.DoesNotContain(w.Forward.Id.ToString(), html); // no longer stuck, so no longer listed - } - - [Fact] - public async Task A_platform_admin_gives_up_a_stuck_undo_by_typing_the_reverse_move_id() - { - using var w = await World.Make(); - var undo = await UndoStuckAsync(w.Rig); - var merge = await w.Rig.MergeAsync(undo.Id); - - var done = await w.Post(w.AdminSession, "AbandonUndo", undo.Id.ToString(), merge.HeimdallReverseMoveId!, await MergePage.TokenAsync(w.Rig.Host, w.AdminSession, Url)); - - Assert.Equal(Url + "?result=settled", MergePage.Location(done)); - Assert.Equal(AccountMergeState.Committed, (await w.Rig.MergeAsync(undo.Id)).State); - } -} diff --git a/tests/Bifrost.Web.Tests/AccountMergeSettleTests.cs b/tests/Bifrost.Web.Tests/AccountMergeSettleTests.cs deleted file mode 100644 index 839cc60..0000000 --- a/tests/Bifrost.Web.Tests/AccountMergeSettleTests.cs +++ /dev/null @@ -1,292 +0,0 @@ -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Heimdall; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Tests.Support; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging.Abstractions; -using static Bifrost.Web.Tests.AccountMergeSagaTests; - -namespace Bifrost.Web.Tests; - -/// -/// The operator's settle of a stuck merge (ruling merge-stuck-end-only-typed-id): two ends, FailForward and AbandonUndo, only from a -/// stuck leg and only with the leg's stored move id typed back, one audit row, never an adopt. The saga rig of AccountMergeSagaTests. -/// -public sealed class AccountMergeSettleTests -{ - private static readonly Guid Operator = Guid.NewGuid(); - - internal sealed record Stuck(Guid Id, Party Survivor, Party Folded); - - /// A Confirmed merge that is stuck on : the two the saga records itself are reached through the real step, the third is the stored Unknown reason. - internal static async Task ConfirmedStuckAsync(Rig rig, string outcome) - { - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - switch (outcome) - { - case AccountMergeSaga.ReceiptMismatch: - await Edit(rig, x => x.UserAccounts.Single(a => a.Id == survivor.Id).HeimdallAccountId = HeimdallShapes.NewAccountId()); - await rig.AdvanceAsync(id); - break; - case AccountMergeSaga.ProofsUnreadable: - await EditMerge(rig, id, x => x.SealedProofs = "CfDJ8-not-a-protected-payload"); - await rig.AdvanceAsync(id); - break; - default: - await EditMerge(rig, id, x => { x.LastOutcome = outcome; x.Attempts = 3; x.NextAttemptUtc = rig.Clock.Now.AddMinutes(5); }); - break; - } - - Assert.Equal(outcome, (await rig.MergeAsync(id)).LastOutcome); - return new Stuck(id, survivor, folded); - } - - /// A merge in UndoRequested whose reversal got a receipt for another account. - internal static async Task UndoStuckAsync(Rig rig) - { - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - await rig.AdvanceAsync(id); - var undo = await rig.InScopeAsync(sp => sp.GetRequiredService().RequestUndoAsync(id, survivor.Id, [rig.Moved(survivor, folded, "discord")], default)); - Assert.IsType(undo); - await Edit(rig, x => x.UserAccounts.Single(a => a.Id == folded.Id).HeimdallAccountId = HeimdallShapes.NewAccountId()); - await rig.AdvanceAsync(id); - var stuck = await rig.MergeAsync(id); - Assert.Equal(AccountMergeState.UndoRequested, stuck.State); - Assert.Equal(AccountMergeSaga.ReceiptMismatch, stuck.LastOutcome); - return new Stuck(id, survivor, folded); - } - - private static Task Edit(Rig rig, Action change) => rig.InScopeAsync(async sp => - { - var db = sp.GetRequiredService(); - change(db); - await db.SaveChangesAsync(); - return 0; - }); - - internal static Task EditMerge(Rig rig, Guid id, Action change) => Edit(rig, db => change(db.AccountMerges.Single(x => x.Id == id))); - - private static Task SettleAsync(Rig rig, Guid id, SettleChoice choice, string? typed) => - rig.InScopeAsync(sp => sp.GetRequiredService().SettleStuckAsync(id, choice, typed!, Operator, default)); - - private static Task> AuditAsync(Rig rig, Guid id) => - rig.InScopeAsync(sp => sp.GetRequiredService().AuditEvents.AsNoTracking().Where(x => x.EntityId == id.ToString()).ToListAsync()); - - // ---- FailForward ---- - - [Theory] - [InlineData("receipt_mismatch")] - [InlineData("proofs_unreadable")] - [InlineData("move_id_conflict")] - public async Task FailForward_ends_a_stuck_Confirmed_merge_as_Failed_with_the_proofs_wiped_the_folded_account_free_and_one_audit_row(string outcome) - { - using var rig = new Rig(); - var stuck = await ConfirmedStuckAsync(rig, outcome); - Assert.IsType(await rig.StandingAsync(stuck.Folded)); - var moveId = (await rig.MergeAsync(stuck.Id)).HeimdallMoveId!; - - Assert.IsType(await SettleAsync(rig, stuck.Id, SettleChoice.FailForward, moveId)); - - var merge = await rig.MergeAsync(stuck.Id); - Assert.Equal(AccountMergeState.Failed, merge.State); - Assert.Equal(AccountMergeSaga.OperatorFailed, merge.FailureCode); - Assert.Equal(rig.Clock.Now, merge.FailedUtc); - Assert.Null(merge.SealedProofs); - Assert.Null(merge.NextAttemptUtc); - Assert.Null(await rig.StandingAsync(stuck.Folded)); - Assert.Null(await rig.StandingAsync(stuck.Survivor)); - Assert.Empty(await rig.JournalAsync(stuck.Id)); - Assert.Equal(0, await rig.AdvanceDueAsync()); // the sweeper does not pick a settled merge up again - var audit = Assert.Single(await AuditAsync(rig, stuck.Id)); - Assert.Equal("merge.settled", audit.Action); - Assert.Equal(Operator, audit.ActorUserAccountId); - Assert.Contains("FailForward", audit.Detail); - // The row names the choice and the merge: nothing of either side. - Assert.DoesNotContain(stuck.Survivor.HeimdallId, audit.Detail); - Assert.DoesNotContain(stuck.Folded.HeimdallId, audit.Detail); - Assert.DoesNotContain(moveId, audit.Detail); - Assert.DoesNotContain(stuck.Survivor.Id.ToString(), audit.Detail); - Assert.DoesNotContain(stuck.Folded.Id.ToString(), audit.Detail); - } - - [Fact] - public async Task A_settled_merge_can_be_confirmed_again_for_the_same_pair() - { - using var rig = new Rig(); - var stuck = await ConfirmedStuckAsync(rig, AccountMergeSaga.ReceiptMismatch); - await EditHeimdallBack(rig, stuck); - Assert.IsType(await SettleAsync(rig, stuck.Id, SettleChoice.FailForward, (await rig.MergeAsync(stuck.Id)).HeimdallMoveId)); - - Assert.IsType(await rig.ConfirmAsync(stuck.Survivor, stuck.Folded, rig.Weak(stuck.Survivor, "twitch"), rig.Weak(stuck.Folded, "discord"))); - } - - private static Task EditHeimdallBack(Rig rig, Stuck stuck) => - Edit(rig, db => db.UserAccounts.Single(x => x.Id == stuck.Survivor.Id).HeimdallAccountId = stuck.Survivor.HeimdallId); - - // ---- AbandonUndo ---- - - [Fact] - public async Task AbandonUndo_returns_a_stuck_UndoRequested_merge_to_Committed_with_the_grace_the_proofs_wiped_and_one_audit_row() - { - using var rig = new Rig(); - var stuck = await UndoStuckAsync(rig); - var before = await rig.MergeAsync(stuck.Id); - - Assert.IsType(await SettleAsync(rig, stuck.Id, SettleChoice.AbandonUndo, before.HeimdallReverseMoveId)); - - var merge = await rig.MergeAsync(stuck.Id); - Assert.Equal(AccountMergeState.Committed, merge.State); - Assert.Equal(AccountMergeSaga.UndoOperatorAbandoned, merge.LastOutcome); - Assert.Null(merge.SealedProofs); - Assert.Null(merge.NextAttemptUtc); - Assert.Equal(before.CommittedUtc, merge.CommittedUtc); - Assert.Equal(before.GraceEndsUtc, merge.GraceEndsUtc); - Assert.IsType(await rig.StandingAsync(stuck.Folded)); - Assert.Equal(0, await rig.AdvanceDueAsync()); - var audit = Assert.Single(await AuditAsync(rig, stuck.Id)); - Assert.Equal("merge.settled", audit.Action); - Assert.Contains("AbandonUndo", audit.Detail); - Assert.DoesNotContain(before.HeimdallReverseMoveId!, audit.Detail); - - rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromMinutes(1)); - await rig.InScopeAsync(sp => sp.GetRequiredService().FinalizeDueAsync(rig.Clock.Now, default)); - Assert.Equal(AccountMergeState.Final, (await rig.MergeAsync(stuck.Id)).State); - } - - // ---- refusals write nothing ---- - - [Fact] - public async Task A_merge_in_any_other_state_or_with_another_LastOutcome_is_NotStuck_and_nothing_is_written() - { - using var rig = new Rig(); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - var moveId = (await rig.MergeAsync(id)).HeimdallMoveId!; - - // Confirmed and healthy ("confirmed"), then waiting on Heimdall ("transport"): not stuck. - Assert.IsType(await SettleAsync(rig, id, SettleChoice.FailForward, moveId)); - await EditMerge(rig, id, x => { x.LastOutcome = "transport"; x.Attempts = 9; }); - Assert.IsType(await SettleAsync(rig, id, SettleChoice.FailForward, moveId)); - var snapshot = await rig.MergeAsync(id); - Assert.Equal(AccountMergeState.Confirmed, snapshot.State); - Assert.NotNull(snapshot.SealedProofs); - - // A stuck outcome does not make the other leg's choice valid. - await EditMerge(rig, id, x => x.LastOutcome = AccountMergeSaga.ReceiptMismatch); - Assert.IsType(await SettleAsync(rig, id, SettleChoice.AbandonUndo, moveId)); - - // Heimdall answered Moved: HeimdallMoved and Committed are never settleable, whatever LastOutcome says. - foreach (var state in new[] { AccountMergeState.HeimdallMoved, AccountMergeState.Committed, AccountMergeState.HeimdallReversed, AccountMergeState.Undone, AccountMergeState.Final, AccountMergeState.Failed }) - { - await EditMerge(rig, id, x => { x.State = state; x.LastOutcome = AccountMergeSaga.ReceiptMismatch; }); - Assert.IsType(await SettleAsync(rig, id, SettleChoice.FailForward, moveId)); - Assert.IsType(await SettleAsync(rig, id, SettleChoice.AbandonUndo, moveId)); - Assert.Equal(state, (await rig.MergeAsync(id)).State); - } - - Assert.IsType(await SettleAsync(rig, Guid.NewGuid(), SettleChoice.FailForward, moveId)); - Assert.Empty(await AuditAsync(rig, id)); - } - - [Fact] - public async Task A_move_id_that_is_not_the_stored_one_of_the_leg_is_WrongMoveId_and_nothing_is_written() - { - using var rig = new Rig(); - var stuck = await ConfirmedStuckAsync(rig, AccountMergeSaga.ReceiptMismatch); - var merge = await rig.MergeAsync(stuck.Id); - - foreach (var typed in new[] { "", " ", merge.HeimdallMoveId!.ToUpperInvariant(), merge.HeimdallMoveId + " ", merge.HeimdallMoveId![..31], stuck.Id.ToString("N"), Guid.NewGuid().ToString("N") }) - { - Assert.IsType(await SettleAsync(rig, stuck.Id, SettleChoice.FailForward, typed)); - } - - Assert.IsType(await SettleAsync(rig, stuck.Id, SettleChoice.FailForward, null)); - var after = await rig.MergeAsync(stuck.Id); - Assert.Equal(AccountMergeState.Confirmed, after.State); - Assert.Equal(AccountMergeSaga.ReceiptMismatch, after.LastOutcome); - Assert.Empty(await AuditAsync(rig, stuck.Id)); - } - - [Fact] - public async Task The_undo_leg_is_confirmed_by_the_reverse_move_id_not_the_forward_one() - { - using var rig = new Rig(); - var stuck = await UndoStuckAsync(rig); - var merge = await rig.MergeAsync(stuck.Id); - - Assert.IsType(await SettleAsync(rig, stuck.Id, SettleChoice.AbandonUndo, merge.HeimdallMoveId)); - - Assert.Equal(AccountMergeState.UndoRequested, (await rig.MergeAsync(stuck.Id)).State); - Assert.Empty(await AuditAsync(rig, stuck.Id)); - } - - // ---- the race ---- - - [Fact] - public async Task A_settle_that_races_AdvanceAsync_and_loses_on_the_State_token_changes_nothing() - { - using var rig = new Rig(); - // Heimdall answered move_id_conflict, so the sweeper keeps replaying: the day its proofs verify, the replay lands. - var stuck = await ConfirmedStuckAsync(rig, AccountMergeSaga.MoveIdConflict); - await EditMerge(rig, stuck.Id, x => x.NextAttemptUtc = null); - var moveId = (await rig.MergeAsync(stuck.Id)).HeimdallMoveId!; - var raced = false; - rig.Host.Fault.When = db => - { - if (raced || !db.ChangeTracker.Entries().Any(x => x.Entity.State == AccountMergeState.Failed)) - { - return false; - } - - raced = true; // the settle has staged Failed and is about to save: the step function moves and commits first - Task.Run(() => rig.AdvanceAsync(stuck.Id)).GetAwaiter().GetResult(); - return false; - }; - - var outcome = await SettleAsync(rig, stuck.Id, SettleChoice.FailForward, moveId); - rig.Host.Fault.When = null; - - Assert.True(raced); - Assert.IsType(outcome); - Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(stuck.Id)).State); - Assert.Empty((await rig.MergeAsync(stuck.Id)).FailureCode); - // The audit row rides in the same SaveChanges as the transition, so a real database drops both; the in-memory provider - // applies entries one by one and cannot show that half. - Assert.IsType(await rig.StandingAsync(stuck.Folded)); - } - - // ---- proof bearers are swept by the existing tick ---- - - [Fact] - public async Task The_sweeper_tick_drops_a_bearer_past_its_lifetime_with_no_page_access() - { - using var rig = new Rig(); - var proofs = rig.Host.Services.GetRequiredService(); - var actor = Guid.NewGuid(); - var proof = new MergeProof("BEARER-CANARY", HeimdallShapes.NewAccountId(), "discord"); - Assert.Equal(PutOutcome.Stored, proofs.Put(actor, MergeSide.Self, proof, Guid.NewGuid(), [])); - rig.Clock.Advance(MergeProofs.ProofLifetime + AccountMergeSweeper.Tick); - Assert.Equal(1, HeldActors(proofs)); // nobody has touched it since - - var sweeper = new AccountMergeSweeper(rig.Host.Services.GetRequiredService(), rig.Clock, NullLogger.Instance); - await sweeper.StartAsync(default); - var deadline = DateTime.UtcNow.AddSeconds(10); - while (DateTime.UtcNow < deadline && HeldActors(proofs) > 0) - { - await Task.Delay(50); - } - - await sweeper.StopAsync(default); - Assert.Equal(0, HeldActors(proofs)); - } - - private static int HeldActors(MergeProofs proofs) => - ((System.Collections.IDictionary)typeof(MergeProofs).GetField("_held", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(proofs)!).Count; -} diff --git a/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs b/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs deleted file mode 100644 index c856c8f..0000000 --- a/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System.Net; -using System.Text; -using Bifrost.Web.Tests.Support; - -namespace Bifrost.Web.Tests; - -/// -/// The fake mover is the spec the client is tested against, so it must refuse what Heimdall 4fe367a refuses, with the same status and code, in the -/// same order (app.ts moveIdentitiesRoute and its schema, identity-move.ts decideMove). Each case sends a raw body to the fake. -/// -public sealed class FakeHeimdallMoverTests -{ - private static string Id() => "move-" + Guid.NewGuid().ToString("N"); - - private static string Account() => HeimdallShapes.NewAccountId(); - - private static async Task<(HttpStatusCode Status, string Error)> Post(HeimdallHost host, string json) - { - using var client = new HttpClient(host.Heimdall, disposeHandler: false) { BaseAddress = new Uri("https://heimdall.test") }; - client.DefaultRequestHeaders.Add("x-heimdall-app-secret", HeimdallHost.AppSecret); - using var response = await client.PostAsync("/v1/apps/bifrost/identity-moves", new StringContent(json, Encoding.UTF8, "application/json")); - var body = await response.Content.ReadAsStringAsync(); - var error = System.Text.Json.JsonDocument.Parse(body).RootElement.TryGetProperty("error", out var e) ? e.GetString()! : ""; - return (response.StatusCode, error); - } - - private static string Move(string moveId, string[] from, string? to = null, string[]? ids = null, string? reverses = null) => - System.Text.Json.JsonSerializer.Serialize(new Dictionary - { - ["moveId"] = moveId, - ["fromProofs"] = from, - ["toProof"] = to, - ["identityIds"] = ids, - ["reversesMoveId"] = reverses - }.Where(x => x.Value is not null).ToDictionary()); - - [Fact] - public async Task A_body_the_routes_schema_rejects_is_a_400_and_moves_nothing() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (s, d) = (Account(), Account()); - var login = moves.AddLogin(s, "discord"); - moves.AddLogin(d, "twitch"); - var forward = Id(); - Assert.Equal(HttpStatusCode.OK, (await Post(host, Move(forward, [moves.Issue(s, login, "bifrost-passkey")], moves.Issue(d)))).Status); - var (s2, d2) = (Account(), Account()); - var login2 = moves.AddLogin(s2, "patreon"); - moves.AddLogin(d2, "twitch"); - var strong = () => moves.Issue(s2, login2, "bifrost-passkey"); - - var bad = new[] - { - Move(Id(), [moves.Issue(d)], moves.Issue(s), reverses: forward), - Move(Id(), [strong()]), - Move(Id(), [strong()], reverses: "x"), - Move(Id(), [strong()], moves.Issue(d2), [login2, login2]), - Move(Id(), [""], "x"), - Move(Id(), [strong()], "x", [""]), - Move(Id(), [strong()], "x", []), - Move(Id(), [moves.Issue(d)], ids: [login], reverses: forward), - Move(Id(), [], "x"), - Move(Id(), Enumerable.Repeat("p", 9).ToArray(), "x"), - Move(Id(), [new string('p', 8193)], "x"), - Move("short", [strong()], "x"), - Move(Id() + "\n", [strong()], "x"), - Move(new string('a', 65), [strong()], "x"), - Move(Id(), [strong()], reverses: Id() + "\n"), - """{"moveId":"move-0123456789abcdef","fromProofs":"p","toProof":"x"}""", - "[]" - }; - foreach (var json in bad) - { - Assert.Equal((HttpStatusCode.BadRequest, "invalid_request"), await Post(host, json)); - } - - Assert.Single(moves.Stored); - Assert.Single(moves.Logins[s2]); - } - - [Fact] - public async Task A_source_holding_no_login_is_404_identity_not_found_not_an_empty_receipt() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (s, d) = (Account(), Account()); - moves.AddLogin(d, "twitch"); - - var answer = await Post(host, Move(Id(), [moves.Issue(s, Guid.NewGuid().ToString(), "bifrost-passkey")], moves.Issue(d))); - - Assert.Equal((HttpStatusCode.NotFound, "identity_not_found"), answer); - } - - [Fact] - public async Task An_unheld_login_is_404_before_coverage_is_judged() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (s, d) = (Account(), Account()); - var login = moves.AddLogin(s, "discord"); - moves.AddLogin(d, "twitch"); - - var answer = await Post(host, Move(Id(), [moves.Issue(s, login)], moves.Issue(d), [login, Guid.NewGuid().ToString()])); - - Assert.Equal((HttpStatusCode.NotFound, "identity_not_found"), answer); - } - - [Fact] - public async Task A_proof_that_covers_no_login_at_all_is_403_identity_not_proved_before_the_store_looks() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (s, d) = (Account(), Account()); - moves.AddLogin(d, "twitch"); - - // No auth_identity_id and no passkey: nothing is covered, even though the source holds no login either. - Assert.Equal((HttpStatusCode.Forbidden, "identity_not_proved"), await Post(host, Move(Id(), [moves.Issue(s)], moves.Issue(d)))); - } - - [Fact] - public async Task A_future_dated_proof_proves_nothing() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (s, d) = (Account(), Account()); - var login = moves.AddLogin(s, "discord"); - moves.AddLogin(d, "twitch"); - - Assert.Equal((HttpStatusCode.Forbidden, "proof_stale"), await Post(host, Move(Id(), [moves.Issue(s, login, authAgo: -60)], moves.Issue(d)))); - } - - [Fact] - public async Task A_replay_whose_proofs_are_not_signed_for_the_stored_accounts_is_409_move_id_conflict_not_proof_invalid() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (s, d) = (Account(), Account()); - var login = moves.AddLogin(s, "discord"); - moves.AddLogin(d, "twitch"); - var id = Id(); - var to = moves.Issue(d); - Assert.Equal(HttpStatusCode.OK, (await Post(host, Move(id, [moves.Issue(s, login)], to))).Status); - - Assert.Equal((HttpStatusCode.Conflict, "move_id_conflict"), await Post(host, Move(id, ["forged-bearer"], to))); - Assert.Equal((HttpStatusCode.Conflict, "move_id_conflict"), await Post(host, Move(id, [moves.Issue(d)], to))); - Assert.Equal((HttpStatusCode.Conflict, "move_id_conflict"), await Post(host, Move(id, [moves.Issue(s)], reverses: Id()))); - Assert.Equal(HttpStatusCode.OK, (await Post(host, Move(id, [moves.Issue(s)], to))).Status); - } - - [Fact] - public async Task A_reversal_by_the_wrong_account_or_of_a_reversed_move_is_409_not_reversible_in_Heimdalls_order() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (s, d, other) = (Account(), Account(), Account()); - var login = moves.AddLogin(s, "discord"); - moves.AddLogin(d, "twitch"); - moves.AddLogin(other, "google"); - var forward = Id(); - await Post(host, Move(forward, [moves.Issue(s, login, "bifrost-passkey")], moves.Issue(d))); - - // The wrong account proves the reversal: not_reversible only after its proof was judged live. - Assert.Equal((HttpStatusCode.Forbidden, "proof_invalid"), await Post(host, Move(Id(), ["unknown"], reverses: forward))); - Assert.Equal((HttpStatusCode.Conflict, "not_reversible"), await Post(host, Move(Id(), [moves.Issue(other, stepUpMethod: "bifrost-passkey")], reverses: forward))); - Assert.Equal((HttpStatusCode.OK, ""), await Post(host, Move(Id(), [moves.Issue(d, login, "bifrost-passkey")], reverses: forward))); - Assert.Equal((HttpStatusCode.Conflict, "not_reversible"), await Post(host, Move(Id(), [moves.Issue(d, stepUpMethod: "bifrost-passkey")], reverses: forward))); - } -} diff --git a/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs b/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs deleted file mode 100644 index 1e4cc01..0000000 --- a/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs +++ /dev/null @@ -1,728 +0,0 @@ -using System.Net; -using System.Text; -using System.Text.Json; -using Bifrost.Web.Configuration; -using Bifrost.Web.Features.Heimdall; -using Bifrost.Web.Tests.Support; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging.Abstractions; -using Microsoft.Extensions.Options; -using Moved = Bifrost.Web.Features.Heimdall.HeimdallMoveOutcome.Moved; -using Refused = Bifrost.Web.Features.Heimdall.HeimdallMoveOutcome.Refused; -using Unknown = Bifrost.Web.Features.Heimdall.HeimdallMoveOutcome.Unknown; - -namespace Bifrost.Web.Tests; - -/// -/// Bifrost's client for Heimdall's identity-move route, from the caller's side, against the fake Heimdall's account model, which answers -/// as Heimdall 4fe367a's service contract does. Moved and Refused are definitive; anything else is Unknown and is healed by replaying the same moveId. -/// -public sealed class HeimdallIdentityMoveClientTests -{ - private const string Passkey = "bifrost-passkey"; - private const string EmailCode = "bifrost-email-code"; - - private static string NewMoveId() => "move-" + Guid.NewGuid().ToString("N"); - - private static string NewAccount() => HeimdallShapes.NewAccountId(); - - private static HeimdallIdentityMoveClient ClientOf(HeimdallHost host) => host.Services.GetRequiredService(); - - private static Task Move(HeimdallHost host, HeimdallMoveRequest request) => - ClientOf(host).MoveAsync(request, CancellationToken.None); - - private static HeimdallMoveReceipt Receipt(HeimdallMoveOutcome outcome) => Assert.IsType(outcome).Receipt; - - /// An account holding these providers, one login each, in order. - private static (string Account, string[] Ids) AccountWith(FakeMoves moves, params string[] providers) - { - var account = NewAccount(); - return (account, providers.Select(p => moves.AddLogin(account, p)).ToArray()); - } - - /// The usual forward move of everything: a passkey proof of the source and a weak proof of the destination. - private static HeimdallMoveRequest Forward(FakeMoves moves, string source, string destination, string? destinationLogin = null, string[]? ids = null) => - new(NewMoveId(), [moves.Issue(source, stepUpMethod: Passkey)], moves.Issue(destination, destinationLogin), ids); - - // ---- the forward move and its receipt ---- - - [Fact] - public async Task A_forward_move_with_one_weak_proof_per_login_answers_the_receipt_under_the_app_secret_and_names_no_account() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (source, ids) = AccountWith(moves, "discord", "patreon"); - var (destination, destinationIds) = AccountWith(moves, "twitch"); - var request = new HeimdallMoveRequest( - NewMoveId(), [moves.Issue(source, ids[0]), moves.Issue(source, ids[1])], moves.Issue(destination, destinationIds[0])); - - var receipt = Receipt(await Move(host, request)); - - Assert.Equal(new HeimdallMoveReceipt(request.MoveId, destination, ids, HeimdallProofTier.Weak, HeimdallProofTier.Weak, null), receipt with { MovedIdentityIds = ids }); - Assert.Equal(ids, receipt.MovedIdentityIds); - Assert.Equal(["twitch", "discord", "patreon"], moves.Logins[destination].Select(x => x.Provider)); - Assert.Empty(moves.Logins[source]); - var sent = Assert.Single(moves.Requests); - Assert.Equal(HeimdallHost.AppSecret, sent.Secret); - Assert.Null(sent.Authorization); - Assert.DoesNotContain(source, sent.Body); - Assert.DoesNotContain(destination, sent.Body); - var names = JsonDocument.Parse(sent.Body).RootElement.EnumerateObject().Select(x => x.Name).Order().ToArray(); - Assert.Equal(["fromProofs", "moveId", "toProof"], names); - } - - [Fact] - public async Task A_proof_through_one_login_moves_only_that_login_and_only_an_asserted_passkey_speaks_for_the_account() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (destination, _) = AccountWith(moves, "twitch"); - - // Discord proves Discord; Patreon, and so the whole account, is not proved by it. - var (a, aIds) = AccountWith(moves, "discord", "patreon"); - Assert.Equal(new Refused(HeimdallMoveRefusal.IdentityNotProved), - await Move(host, new(NewMoveId(), [moves.Issue(a, aIds[0])], moves.Issue(destination), aIds[1..]))); - Assert.Equal(new Refused(HeimdallMoveRefusal.IdentityNotProved), - await Move(host, new(NewMoveId(), [moves.Issue(a, aIds[0])], moves.Issue(destination)))); - Assert.Equal(2, moves.Logins[a].Count); - - // An email code proves an inbox: strong, fresh, and still only its own login. - Assert.Equal(new Refused(HeimdallMoveRefusal.IdentityNotProved), - await Move(host, new(NewMoveId(), [moves.Issue(a, aIds[0], EmailCode)], moves.Issue(destination)))); - Assert.Equal(new Refused(HeimdallMoveRefusal.IdentityNotProved), - await Move(host, new(NewMoveId(), [moves.Issue(a, aIds[0], EmailCode)], moves.Issue(destination), aIds[1..]))); - Assert.Equal(2, moves.Logins[a].Count); - - // The same proof does move the one login it came through. - Assert.Equal([aIds[0]], Receipt(await Move(host, new(NewMoveId(), [moves.Issue(a, aIds[0], EmailCode)], moves.Issue(destination), aIds[..1]))).MovedIdentityIds); - (destination, _) = AccountWith(moves, "twitch"); - - // An asserted passkey moves everything. - var (b, bIds) = AccountWith(moves, "discord", "patreon", "google"); - var all = Receipt(await Move(host, Forward(moves, b, destination))); - Assert.Equal(bIds, all.MovedIdentityIds); - Assert.Equal(HeimdallProofTier.Strong, all.ProofFrom); - } - - [Fact] - public async Task A_proof_by_a_stale_weak_sign_in_or_step_up_is_refused_with_its_side_at_the_window_edge() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (destination, _) = AccountWith(moves, "twitch"); - - HeimdallMoveRequest Weak(string source, string login, int ago, int toAgo = 0) => - new(NewMoveId(), [moves.Issue(source, login, authAgo: ago)], moves.Issue(destination, authAgo: toAgo)); - - var (a, a1) = AccountWith(moves, "discord"); - Assert.Equal(new Refused(HeimdallMoveRefusal.ProofStale, HeimdallProofSide.From), await Move(host, Weak(a, a1[0], 301))); - Assert.Equal(new Refused(HeimdallMoveRefusal.ProofStale, HeimdallProofSide.To), await Move(host, Weak(a, a1[0], 0, 301))); - Assert.Equal(HeimdallProofTier.Weak, Receipt(await Move(host, Weak(a, a1[0], 300))).ProofFrom); - - var (b, _) = AccountWith(moves, "patreon"); - Assert.Equal(new Refused(HeimdallMoveRefusal.ProofStale, HeimdallProofSide.From), - await Move(host, new(NewMoveId(), [moves.Issue(b, stepUpMethod: Passkey, authAgo: 601, stepUpAgo: 601)], moves.Issue(destination)))); - Assert.Equal(HeimdallProofTier.Strong, - Receipt(await Move(host, new(NewMoveId(), [moves.Issue(b, stepUpMethod: Passkey, authAgo: 600, stepUpAgo: 600)], moves.Issue(destination)))).ProofFrom); - } - - // ---- replay ---- - - [Fact] - public async Task A_replayed_move_id_answers_the_first_receipt_after_the_sources_sessions_were_revoked_and_the_tokens_expired() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (source, ids) = AccountWith(moves, "discord", "patreon"); - var (destination, _) = AccountWith(moves, "twitch"); - var request = Forward(moves, source, destination); - var first = Receipt(await Move(host, request)); - Assert.True(moves.IsRevoked(request.FromProofs[0])); - host.Clock.Advance(TimeSpan.FromHours(2)); - - var again = Receipt(await Move(host, request)); - - Assert.Equal(first.AccountId, again.AccountId); - Assert.Equal(ids, again.MovedIdentityIds); - Assert.Equal(first.ProofFrom, again.ProofFrom); - Assert.Single(moves.Stored); - Assert.Equal(2, moves.Requests.Count); - } - - [Fact] - public async Task A_replay_with_different_identity_ids_answers_the_first_receipt_and_moves_nothing_more() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (source, ids) = AccountWith(moves, "discord", "patreon"); - var (destination, _) = AccountWith(moves, "twitch"); - var proofs = new[] { moves.Issue(source, stepUpMethod: Passkey) }; - var toProof = moves.Issue(destination); - var moveId = NewMoveId(); - - var first = Receipt(await Move(host, new(moveId, proofs, toProof, ids[..1]))); - var again = Receipt(await Move(host, new(moveId, proofs, toProof, ids))); - - Assert.Equal([ids[0]], first.MovedIdentityIds); - Assert.Equal([ids[0]], again.MovedIdentityIds); - Assert.Equal([ids[1]], moves.Logins[source].Select(x => x.Id)); - } - - [Fact] - public async Task A_move_whose_answer_was_lost_heals_by_replaying_the_same_request() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (source, ids) = AccountWith(moves, "discord"); - var (destination, _) = AccountWith(moves, "twitch"); - var request = Forward(moves, source, destination); - - moves.MoveApplyThenFail = HttpStatusCode.InternalServerError; - Assert.IsType(await Move(host, request)); - Assert.Single(moves.Stored); - moves.MoveApplyThenFail = HttpStatusCode.OK; - Assert.IsType(await Move(host, request)); - - moves.MoveApplyThenFail = null; - var healed = Receipt(await Move(host, request)); - Assert.Equal(destination, healed.AccountId); - Assert.Equal(ids, healed.MovedIdentityIds); - Assert.Single(moves.Stored); - } - - // ---- reversal ---- - - [Fact] - public async Task A_reversal_moves_back_exactly_the_logins_the_forward_move_carried_once() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (source, ids) = AccountWith(moves, "discord", "patreon"); - var (destination, destinationIds) = AccountWith(moves, "twitch"); - var forward = Forward(moves, source, destination, ids: ids[..1]); - Receipt(await Move(host, forward)); - Assert.Equal(["twitch", "discord"], moves.Logins[destination].Select(x => x.Provider)); - - // The destination's bearer proves a login it holds; the carried one is proved by its own sign-in. - var undo = new HeimdallMoveRequest(NewMoveId(), [moves.Issue(destination, ids[0])], ReversesMoveId: forward.MoveId); - var receipt = Receipt(await Move(host, undo)); - - Assert.Equal(source, receipt.AccountId); - Assert.Equal([ids[0]], receipt.MovedIdentityIds); - Assert.Equal(forward.MoveId, receipt.ReversesMoveId); - Assert.Null(receipt.ProofTo); - Assert.Equal([destinationIds[0]], moves.Logins[destination].Select(x => x.Id)); - Assert.Equal(ids.Order(), moves.Logins[source].Select(x => x.Id).Order()); - - Assert.Equal(new Refused(HeimdallMoveRefusal.NotReversible), - await Move(host, new(NewMoveId(), [moves.Issue(destination, destinationIds[0], Passkey)], ReversesMoveId: forward.MoveId))); - Assert.Equal(new Refused(HeimdallMoveRefusal.NotReversible), - await Move(host, new(NewMoveId(), [moves.Issue(source, ids[0], Passkey)], ReversesMoveId: undo.MoveId))); - } - - // ---- refusals ---- - - [Fact] - public async Task Each_contract_refusal_code_maps_to_its_member_and_only_provider_conflict_carries_a_provider() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - - // not_allowed_for_app - var (s0, _) = AccountWith(moves, "discord"); - var (d0, _) = AccountWith(moves, "twitch"); - moves.Granted = false; - Assert.Equal(new Refused(HeimdallMoveRefusal.NotAllowedForApp), await Move(host, Forward(moves, s0, d0))); - moves.Granted = true; - - // proof_invalid: unknown, revoked, foreign audience (from side); a lapsed destination proof (to side) - Assert.Equal(new Refused(HeimdallMoveRefusal.ProofInvalid, HeimdallProofSide.From), - await Move(host, new(NewMoveId(), ["no-such-bearer"], moves.Issue(d0)))); - Assert.Equal(new Refused(HeimdallMoveRefusal.ProofInvalid, HeimdallProofSide.From), - await Move(host, new(NewMoveId(), [moves.Issue(s0, stepUpMethod: Passkey, aud: "someone-else")], moves.Issue(d0)))); - Assert.Equal(new Refused(HeimdallMoveRefusal.ProofInvalid, HeimdallProofSide.To), - await Move(host, new(NewMoveId(), [moves.Issue(s0, stepUpMethod: Passkey)], "no-such-bearer"))); - var (other, _) = AccountWith(moves, "google"); - Assert.Equal(new Refused(HeimdallMoveRefusal.ProofInvalid, HeimdallProofSide.From), - await Move(host, new(NewMoveId(), [moves.Issue(s0, stepUpMethod: Passkey), moves.Issue(other, stepUpMethod: Passkey)], moves.Issue(d0)))); - - // same_account - Assert.Equal(new Refused(HeimdallMoveRefusal.SameAccount), - await Move(host, new(NewMoveId(), [moves.Issue(s0, stepUpMethod: Passkey)], moves.Issue(s0)))); - - // identity_not_found: the proof is a passkey, the login is nobody's - Assert.Equal(new Refused(HeimdallMoveRefusal.IdentityNotFound), - await Move(host, Forward(moves, s0, d0, ids: [Guid.NewGuid().ToString()]))); - - // provider_conflict: the destination already holds a Discord login - var (s1, _) = AccountWith(moves, "discord"); - var (d1, _) = AccountWith(moves, "discord"); - Assert.Equal(new Refused(HeimdallMoveRefusal.ProviderConflict, Provider: "discord"), await Move(host, Forward(moves, s1, d1))); - - // move_id_conflict is not a refusal: a committed move answers it when its proofs no longer verify, so the caller keeps its proofs. - var (s2, _) = AccountWith(moves, "patreon"); - var (d2, _) = AccountWith(moves, "twitch"); - var used = Forward(moves, s2, d2); - Receipt(await Move(host, used)); - var (s3, _) = AccountWith(moves, "patreon"); - Assert.Equal(new Unknown("move_id_conflict"), - await Move(host, new(used.MoveId, [moves.Issue(s3, stepUpMethod: Passkey)], moves.Issue(d2)))); - Assert.Equal(new Unknown("move_id_conflict"), - await Move(host, new(used.MoveId, ["forged-bearer"], used.ToProof))); - - // already_moved: s2 now holds nothing and an unreversed move left it - Assert.Equal(new Refused(HeimdallMoveRefusal.AlreadyMoved), await Move(host, Forward(moves, s2, d0))); - Assert.Equal(new Refused(HeimdallMoveRefusal.AlreadyMoved), await Move(host, Forward(moves, s3, s2))); - - // not_reversible: a move that never happened - Assert.Equal(new Refused(HeimdallMoveRefusal.NotReversible), - await Move(host, new(NewMoveId(), [moves.Issue(d2, stepUpMethod: Passkey)], ReversesMoveId: NewMoveId()))); - } - - [Fact] - public async Task A_wrong_app_secret_is_refused_as_app_auth_required() - { - using var host = new HeimdallHost(appSecret: "not-the-secret"); - var moves = host.Heimdall.Moves; - var (source, _) = AccountWith(moves, "discord"); - var (destination, _) = AccountWith(moves, "twitch"); - - Assert.Equal(new Refused(HeimdallMoveRefusal.AppAuthRequired), await Move(host, Forward(moves, source, destination))); - Assert.Empty(moves.Stored); - } - - [Fact] - public async Task A_400_carrying_Heimdalls_invalid_request_code_is_RequestInvalid_a_definitive_refusal_that_moves_nothing() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (source, _) = AccountWith(moves, "discord"); - var (destination, _) = AccountWith(moves, "twitch"); - moves.MoveStatus = HttpStatusCode.BadRequest; - - Assert.Equal(new Refused(HeimdallMoveRefusal.RequestInvalid), await Move(host, Forward(moves, source, destination))); - Assert.Empty(moves.Stored); - } - - [Theory] - [InlineData(HttpStatusCode.NotFound, "404 Not Found")] - [InlineData(HttpStatusCode.NotFound, "")] - [InlineData(HttpStatusCode.BadRequest, "400 Bad Requestnginx")] - [InlineData(HttpStatusCode.BadRequest, "")] - [InlineData(HttpStatusCode.BadRequest, """{"statusCode":400,"error":"Bad Request","message":"x"}""")] - [InlineData(HttpStatusCode.BadRequest, """{"message":"no error field"}""")] - [InlineData(HttpStatusCode.Conflict, """{"error":"invalid_request"}""")] - [InlineData(HttpStatusCode.RequestEntityTooLarge, """{"error":"invalid_request"}""")] // Heimdall's own 413 for a body over its limit; the client's rule is exactly 400 - [InlineData(HttpStatusCode.UnsupportedMediaType, """{"error":"invalid_request"}""")] - [InlineData(HttpStatusCode.RequestTimeout, "")] - [InlineData(HttpStatusCode.RequestTimeout, """{"error":"request_timeout"}""")] - [InlineData(HttpStatusCode.Gone, "")] - [InlineData(HttpStatusCode.UnavailableForLegalReasons, "")] - [InlineData(HttpStatusCode.Unauthorized, """{"error":"weird_code"}""")] - [InlineData(HttpStatusCode.Forbidden, """{"message":"no error field"}""")] - [InlineData((HttpStatusCode)418, """{"error":"app_auth_required_sort_of"}""")] - public async Task A_4xx_without_one_of_Heimdalls_move_codes_is_Unknown_because_it_proves_nothing_was_applied_no_more_than_a_gateway_does( - HttpStatusCode status, string body) - { - Assert.IsType(await Answered(body, Plain, status)); - } - - [Fact] - public async Task A_404_with_no_body_from_the_route_is_Unknown_not_identity_not_found() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (source, _) = AccountWith(moves, "discord"); - var (destination, _) = AccountWith(moves, "twitch"); - moves.MoveStatus = HttpStatusCode.NotFound; - - Assert.IsType(await Move(host, Forward(moves, source, destination))); - } - - [Fact] - public async Task An_exception_of_any_kind_from_the_pipeline_is_Unknown_and_only_the_callers_cancellation_propagates() - { - Exception[] thrown = - [ - new InvalidOperationException("handler"), new ObjectDisposedException("connection"), - new System.Security.Authentication.AuthenticationException("tls"), new InvalidDataException("zip"), new UriFormatException("uri"), - new HttpRequestException("down"), new IOException("reset"), new TaskCanceledException("deadline") - ]; - foreach (var error in thrown) - { - var client = new HeimdallIdentityMoveClient( - new HttpClient(new Throwing(error)) { BaseAddress = new Uri("https://heimdall.test") }, - Options.Create(new HeimdallOptions()), NullLogger.Instance); - - Assert.IsType(await client.MoveAsync(Plain, CancellationToken.None)); - } - } - - private sealed class Throwing(Exception error) : HttpMessageHandler - { - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => throw error; - } - - // ---- unknown outcomes ---- - - [Theory] - [InlineData(HttpStatusCode.InternalServerError)] - [InlineData(HttpStatusCode.ServiceUnavailable)] - [InlineData(HttpStatusCode.TooManyRequests)] - [InlineData(HttpStatusCode.Found)] - public async Task A_5xx_a_429_or_any_other_status_is_Unknown_never_a_refusal(HttpStatusCode status) - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (source, _) = AccountWith(moves, "discord"); - var (destination, _) = AccountWith(moves, "twitch"); - moves.MoveStatus = status; - - Assert.IsType(await Move(host, Forward(moves, source, destination))); - } - - [Fact] - public async Task A_timeout_a_transport_error_and_garbage_with_a_200_are_Unknown_while_the_callers_own_cancellation_propagates() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var (source, _) = AccountWith(moves, "discord"); - var (destination, _) = AccountWith(moves, "twitch"); - var request = Forward(moves, source, destination); - - moves.MoveDown = new TaskCanceledException("the client timed out"); - Assert.IsType(await Move(host, request)); - moves.MoveDown = new HttpRequestException("Heimdall is down"); - Assert.IsType(await Move(host, request)); - moves.MoveDown = null; - moves.MoveApplyThenFail = HttpStatusCode.OK; - Assert.IsType(await Move(host, request)); - moves.MoveApplyThenFail = null; - - using var cancelled = new CancellationTokenSource(); - await cancelled.CancelAsync(); - await Assert.ThrowsAnyAsync(() => ClientOf(host).MoveAsync(request, cancelled.Token)); - } - - private sealed class Stub(Func content, HttpStatusCode status = HttpStatusCode.OK) : HttpMessageHandler - { - public Stub(string json, HttpStatusCode status = HttpStatusCode.OK) - : this(() => new StringContent(json, Encoding.UTF8, "application/json"), status) - { - } - - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => - Task.FromResult(new HttpResponseMessage(status) { Content = content() }); - } - - /// A body that serves a prefix and then stalls, resets, or streams endless filler. - private sealed class Body(string prefix, bool reset = false, long endless = 0) : Stream - { - private readonly byte[] _prefix = Encoding.UTF8.GetBytes(prefix); - - public long Served { get; private set; } - - public override bool CanRead => true; - - public override bool CanSeek => false; - - public override bool CanWrite => false; - - public override long Length => throw new NotSupportedException(); - - public override long Position { get => Served; set => throw new NotSupportedException(); } - - public override void Flush() - { - } - - public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); - - public override void SetLength(long value) => throw new NotSupportedException(); - - public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); - - public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(); - - public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) - { - if (Served < _prefix.Length) - { - var n = (int)Math.Min(buffer.Length, _prefix.Length - Served); - _prefix.AsMemory((int)Served, n).CopyTo(buffer); - Served += n; - return n; - } - - if (endless > 0 && Served < _prefix.Length + endless) - { - var n = (int)Math.Min(buffer.Length, _prefix.Length + endless - Served); - buffer.Span[..n].Fill((byte)'a'); - Served += n; - return n; - } - - if (reset) - { - throw new IOException("connection reset mid-body"); - } - - await Task.Delay(Timeout.Infinite, cancellationToken); - return 0; - } - } - - private static HeimdallIdentityMoveClient Client(HttpMessageHandler handler, TimeSpan? timeout = null) => - new(new HttpClient(handler) { BaseAddress = new Uri("https://heimdall.test"), Timeout = timeout ?? TimeSpan.FromSeconds(30) }, - Options.Create(new HeimdallOptions()), NullLogger.Instance); - - private static Task Answered(string json, HeimdallMoveRequest request, HttpStatusCode status = HttpStatusCode.OK) => - Client(new Stub(json, status)).MoveAsync(request, CancellationToken.None); - - private static readonly HeimdallMoveRequest Plain = new("move-0123456789abcdef", ["p"], "q"); - - [Fact] - public async Task A_200_that_is_not_a_whole_receipt_for_this_request_is_Unknown() - { - var id = Guid.NewGuid().ToString(); - var forward = new HeimdallMoveRequest("move-0123456789abcdef", ["p"], "q"); - var reversal = new HeimdallMoveRequest("move-0123456789abcdef", ["p"], ReversesMoveId: "move-fedcba9876543210"); - string Body(string moveId = "move-0123456789abcdef", string? reverses = null, string proof = """{"from":"weak","to":"weak"}""", string ids = "\"" + "ID" + "\"") => - $$"""{"moveId":"{{moveId}}","accountId":"acct","movedIdentityIds":[{{ids.Replace("ID", id)}}],"proof":{{proof}}{{(reverses is null ? "" : $",\"reversesMoveId\":\"{reverses}\"")}}}"""; - - // The well formed shapes are accepted, so each refusal below is about its one flaw. - Assert.IsType(await Answered(Body(), forward)); - Assert.IsType(await Answered(Body(ids: "\"not-a-guid-but-an-id\""), forward)); - Assert.IsType(await Answered(Body("move-0123456789abcdef", "move-fedcba9876543210", """{"from":"strong","to":null}"""), reversal)); - - Assert.IsType(await Answered(Body("move-someoneelse12345"), forward)); - Assert.IsType(await Answered(Body(reverses: "move-fedcba9876543210"), forward)); - Assert.IsType(await Answered(Body(), reversal)); - Assert.IsType(await Answered(Body("move-0123456789abcdef", "move-other0123456789", """{"from":"strong","to":null}"""), reversal)); - Assert.IsType(await Answered(Body("move-0123456789abcdef", "move-fedcba9876543210", """{"from":"strong","to":"weak"}"""), reversal)); - Assert.IsType(await Answered(Body(proof: """{"from":"strong","to":null}"""), forward)); - Assert.IsType(await Answered(Body(proof: """{"from":"maybe","to":"weak"}"""), forward)); - Assert.IsType(await Answered(Body(ids: ""), forward)); - Assert.IsType(await Answered(Body(ids: "123"), forward)); - Assert.IsType(await Answered("""{"moveId":"move-0123456789abcdef"}""", forward)); - Assert.IsType(await Answered("[]", forward)); - } - - // ---- the closed body ---- - - [Fact] - public async Task A_request_that_breaks_the_contracts_body_throws_before_any_request_reaches_Heimdall() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var good = NewMoveId(); - var proofs = new[] { "p" }; - var broken = new HeimdallMoveRequest[] - { - new(good, proofs, "t", ReversesMoveId: NewMoveId()), - new(good, proofs), - new(good, Enumerable.Repeat("p", 9).ToArray(), "t"), - new(good, [], "t"), - new("short", proofs, "t"), - new("bad move id with spaces", proofs, "t"), - new(good, proofs, ReversesMoveId: "short"), - new(good, proofs, IdentityIds: ["i"], ReversesMoveId: NewMoveId()), - new(good, proofs, "t", []), - new(good, proofs, "t", Enumerable.Repeat("i", 33).ToArray()), - new(good, proofs, "t", ["i", "j", "i"]), - new(good, [new string('p', HeimdallIdentityMoveClient.MaxProofLength + 1)], "t"), - new(good, proofs, new string('p', HeimdallIdentityMoveClient.MaxProofLength + 1)), - new(good, [""], "t"), - new(good + "\n", proofs, "t"), - new(good, proofs, ReversesMoveId: good + "\n"), - new("move-0123456789abcdef\n", proofs, "t"), - new(new string('a', 65), proofs, "t"), - new(new string('a', 15), proofs, "t"), - new(good, proofs, ReversesMoveId: new string('a', 65)) - }; - - foreach (var request in broken) - { - await Assert.ThrowsAsync(() => Move(host, request)); - } - - Assert.Empty(moves.Requests); - } - - // ---- the wire: bounds, deadline, redirects, secrets ---- - - [Fact] - public async Task A_body_that_stalls_after_the_headers_is_Unknown_within_the_clients_deadline_for_a_receipt_and_a_refusal() - { - foreach (var (status, prefix) in new[] { (HttpStatusCode.OK, """{"moveId":"move-0123456789abcdef","""), (HttpStatusCode.Conflict, """{"error":"pro""") }) - { - var client = Client(new Stub(() => new StreamContent(new Body(prefix)), status), TimeSpan.FromMilliseconds(500)); - var task = client.MoveAsync(Plain, CancellationToken.None); - Assert.Same(task, await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(10)))); - Assert.IsType(await task); - } - } - - [Fact] - public async Task A_connection_reset_while_reading_the_body_is_Unknown_not_an_exception() - { - var client = Client(new Stub(() => new StreamContent(new Body("""{"moveId":"move-0123456789abcdef",""", reset: true)))); - - Assert.IsType(await client.MoveAsync(Plain, CancellationToken.None)); - } - - [Fact] - public async Task A_receipt_body_past_64_KiB_is_refused_unread_as_Unknown() - { - var body = new Body("""{"moveId":"move-0123456789abcdef","accountId":" """, endless: 64L * 1024 * 1024); - var client = Client(new Stub(() => new StreamContent(body))); - - Assert.IsType(await client.MoveAsync(Plain, CancellationToken.None)); - Assert.True(body.Served < 1024 * 1024, $"read {body.Served} bytes"); - } - - [Fact] - public async Task Refusal_qualifiers_are_kept_only_for_the_codes_that_carry_them() - { - Assert.Equal(new Refused(HeimdallMoveRefusal.SameAccount), - await Answered("""{"error":"same_account","proof":"from","provider":"discord"}""", Plain, HttpStatusCode.Conflict)); - Assert.Equal(new Refused(HeimdallMoveRefusal.AlreadyMoved), - await Answered("""{"error":"already_moved","proof":"to"}""", Plain, HttpStatusCode.Conflict)); - Assert.Equal(new Refused(HeimdallMoveRefusal.ProviderConflict, Provider: "discord"), - await Answered("""{"error":"provider_conflict","proof":"to","provider":"discord"}""", Plain, HttpStatusCode.Conflict)); - Assert.Equal(new Refused(HeimdallMoveRefusal.ProofStale, HeimdallProofSide.To), - await Answered("""{"error":"proof_stale","proof":"to","provider":"discord"}""", Plain, HttpStatusCode.Forbidden)); - Assert.Equal(new Refused(HeimdallMoveRefusal.ProofInvalid), - await Answered("""{"error":"proof_invalid","proof":"sideways"}""", Plain, HttpStatusCode.Forbidden)); - } - - [Fact] - public async Task The_largest_legal_request_is_sent_and_moves_what_it_names() - { - using var host = new HeimdallHost(); - var moves = host.Heimdall.Moves; - var source = NewAccount(); - var ids = Enumerable.Range(0, 32).Select(_ => moves.AddLogin(source, "discord")).ToArray(); - var (destination, _) = AccountWith(moves, "twitch"); - var proofs = Enumerable.Range(0, 8).Select(_ => moves.Issue(source, stepUpMethod: Passkey)).ToArray(); - - var longest = new string('m', 64); - var receipt = Receipt(await Move(host, new(longest, proofs, moves.Issue(destination), ids))); - Assert.Equal(longest, receipt.MoveId); - - Assert.Equal(ids, receipt.MovedIdentityIds); - Assert.Equal(8, JsonDocument.Parse(moves.Requests[0].Body).RootElement.GetProperty("fromProofs").GetArrayLength()); - } - - [Fact] - public void A_request_does_not_print_its_proofs() - { - var request = new HeimdallMoveRequest("move-0123456789abcdef", ["FROM-BEARER-SECRET"], "TO-BEARER-SECRET"); - - Assert.DoesNotContain("BEARER-SECRET", request.ToString()); - Assert.Contains("move-0123456789abcdef", request.ToString()); - } - - private static ServiceProvider RealRegistration(string baseUrl) - { - var services = new ServiceCollection(); - services.AddLogging(); - services.AddSingleton(Options.Create(new HeimdallOptions { BaseUrl = baseUrl, AppSecret = "APP-SECRET-VALUE" })); - services.AddHeimdallIdentityMoveClient(); - return services.BuildServiceProvider(); - } - - [Fact] - public void The_registered_client_carries_the_app_secret_and_the_15_second_deadline() - { - using var provider = RealRegistration("https://heimdall.test"); - var http = provider.GetRequiredService().CreateClient(nameof(HeimdallIdentityMoveClient)); - - Assert.Equal(TimeSpan.FromSeconds(15), http.Timeout); - Assert.Equal(new Uri("https://heimdall.test"), http.BaseAddress); - Assert.Equal("APP-SECRET-VALUE", Assert.Single(http.DefaultRequestHeaders.GetValues(HeimdallAuthService.AppSecretHeader))); - } - - [Theory] - [InlineData(307)] - [InlineData(302)] - public async Task A_redirect_is_Unknown_and_nothing_reaches_the_other_origin(int code) - { - static int FreePort() - { - var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); - listener.Start(); - var port = ((IPEndPoint)listener.LocalEndpoint).Port; - listener.Stop(); - return port; - } - - int first = FreePort(), second = FreePort(); - using var origin = new HttpListener(); - origin.Prefixes.Add($"http://127.0.0.1:{first}/"); - origin.Start(); - using var other = new HttpListener(); - other.Prefixes.Add($"http://127.0.0.1:{second}/"); - other.Start(); - var redirected = Task.Run(async () => - { - var context = await origin.GetContextAsync(); - context.Response.StatusCode = code; - context.Response.RedirectLocation = $"http://127.0.0.1:{second}/steal"; - context.Response.Close(); - }); - var stolen = new List(); - _ = Task.Run(async () => - { - try - { - var context = await other.GetContextAsync(); - stolen.Add(context.Request.Headers["x-heimdall-app-secret"] + new StreamReader(context.Request.InputStream).ReadToEnd()); - var forged = Encoding.UTF8.GetBytes($$$"""{"moveId":"move-0123456789abcdef","accountId":"attacker","movedIdentityIds":["{{{Guid.NewGuid()}}}"],"proof":{"from":"weak","to":"weak"}}"""); - context.Response.StatusCode = 200; - await context.Response.OutputStream.WriteAsync(forged); - context.Response.Close(); - } - catch (HttpListenerException) - { - } - catch (ObjectDisposedException) - { - } - }); - using var provider = RealRegistration($"http://127.0.0.1:{first}"); - - var outcome = await provider.GetRequiredService() - .MoveAsync(new("move-0123456789abcdef", ["FROM-BEARER"], "TO-BEARER"), CancellationToken.None); - await redirected; - await Task.Delay(300); - - Assert.IsType(outcome); - Assert.Empty(stolen); - } - - // ---- what the logs hold ---- - - [Fact] - public async Task With_http_trace_logging_on_no_log_line_holds_a_bearer_the_secret_an_identity_id_or_an_account_id() - { - using var host = new HeimdallHost(traceHttp: true); - var moves = host.Heimdall.Moves; - var (source, ids) = AccountWith(moves, "discord", "patreon"); - var (destination, _) = AccountWith(moves, "twitch"); - var request = Forward(moves, source, destination); - Receipt(await Move(host, request)); - Assert.IsType(await Move(host, Forward(moves, source, destination))); - - var logs = string.Join('\n', host.Logs.Lines); - Assert.Contains("Heimdall identity move: Moved", logs); - Assert.Contains("Heimdall identity move: Refused", logs); - Assert.Contains("identity-moves", logs); - // Only the secret and bearer headers are redacted: an ordinary header's value is logged, so the shared redaction is what is in force. - Assert.Contains("application/json", logs); - foreach (var secret in new[] { HeimdallHost.AppSecret, source, destination, request.FromProofs[0], request.ToProof!, request.MoveId }.Concat(ids)) - { - Assert.DoesNotContain(secret, logs); - } - } -} diff --git a/tests/Bifrost.Web.Tests/MergeAccountsPageTests.cs b/tests/Bifrost.Web.Tests/MergeAccountsPageTests.cs deleted file mode 100644 index 8210b8b..0000000 --- a/tests/Bifrost.Web.Tests/MergeAccountsPageTests.cs +++ /dev/null @@ -1,574 +0,0 @@ -using System.Net; -using System.Text.RegularExpressions; -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Heimdall; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Features.Shared; -using Bifrost.Web.Tests.Support; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using static Bifrost.Web.Tests.AccountMergeSagaTests; - -namespace Bifrost.Web.Tests; - -/// -/// The merge page from the member's side: browser sessions of the real host over the saga rig and the fake Heimdall. Stages derive -/// from the proofs held; the other account is unnamed until both proofs exist; consent is two boxes and the saga's Confirmed row. -/// -public sealed class MergeAccountsPageTests -{ - private const string Url = MergePage.AccountsUrl; - private const string OtherName = "banks-2d7c"; - - private static string Enc(string text) => System.Text.Encodings.Web.HtmlEncoder.Default.Encode(text); - - private sealed class World : IDisposable - { - public Rig Rig { get; private init; } = null!; - - public Party Me { get; private init; } = null!; - - public Party Other { get; private init; } = null!; - - public string Session { get; private init; } = string.Empty; - - /// The name the account carries after signing in (a sign-in refreshes it from Heimdall). - public string MyName { get; private init; } = string.Empty; - - public MergePage.Antiforgery? Token { get; private set; } - - public HeimdallHost Host => Rig.Host; - - public List Surface { get; } = []; - - public List Bearers { get; } = []; - - public MergeProofs Proofs => Host.Services.GetRequiredService(); - - public static async Task Make(bool enabled = true, string[]? otherProviders = null) - { - var rig = new Rig(realSessions: true, accountMerge: enabled); - var me = await rig.AccountAsync("quill-9f3a", "discord"); - var other = await rig.AccountAsync(OtherName, otherProviders ?? ["patreon", "google"]); - var session = await rig.Host.SignInSessionAsync(me.HeimdallId, "discord"); - var myName = await rig.InScopeAsync(async sp => (await sp.GetRequiredService().UserAccounts.AsNoTracking().SingleAsync(x => x.Id == me.Id)).DisplayName); - var world = new World { Rig = rig, Me = me, Other = other, Session = session, MyName = myName }; - if (enabled) - { - world.Token = await MergePage.TokenAsync(rig.Host, session, Url); - } - - return world; - } - - public void Dispose() => Rig.Dispose(); - - public async Task<(HttpResponseMessage Response, string Html)> Get(string query = "", string? session = null) - { - var (response, html) = await MergePage.GetAsync(Host, session ?? Session, query, Url); - Surface.Add(html + "\n" + MergePage.Location(response)); - return (response, html); - } - - public async Task Page(string query = "") - { - var (response, html) = await Get(query); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - return html; - } - - public async Task Post(string handler, params (string, string)[] form) - { - var response = await MergePage.PostAsync(Host, Session, Token!, handler, form.ToDictionary(x => x.Item1, x => x.Item2), Url); - Surface.Add(MergePage.Location(response) + "\n" + string.Join('\n', response.Headers.Select(x => x.Key + string.Concat(x.Value)))); - return response; - } - - /// One fresh sign-in of through its login of , started by the page's own button and finished as Heimdall's return does. - public async Task Prove(string handler, Party proved, string provider) - { - var before = Host.Heimdall.StartBodies.Count; - var started = await Post(handler, ("via", provider), ("keep", handler == "ProveRemaining" ? "self" : string.Empty)); - Assert.Equal(HttpStatusCode.Redirect, started.StatusCode); - var attempt = Host.AttemptFrom(started, before); - Assert.NotEmpty(attempt.Nonce); - - Host.Heimdall.Identities.Clear(); - foreach (var (name, id) in proved.Logins) - { - Host.Heimdall.AddIdentity(name, id: id); - } - - var bearer = Host.Token(proved.HeimdallId); - Rig.Moves.Issue(proved.HeimdallId, proved.Logins[provider], bearer: bearer); - Bearers.Add(bearer); - var done = await Host.PostCompleteAsync( - new Dictionary { ["attempt"] = attempt.Nonce, ["code"] = Host.CodeFor(attempt, proved.HeimdallId, bearer, provider: provider) }, - $"{BifrostCookies.Session}={Session}; {attempt.CookieName}={attempt.Cookie}"); - Surface.Add(MergePage.Location(done)); - Assert.Equal(Url + "?result=merge_proof_recorded", MergePage.Location(done)); - } - - public Task ProveSelf(string provider = "discord") => Prove("ProveSelf", Me, provider); - - public Task ProveOther(string provider) => Prove("ProveOther", Other, provider); - - /// Both accounts proved in full, so either can be kept. - public async Task ProveAll() - { - await ProveSelf(); - await ProveOther("patreon"); - await ProveOther("google"); - } - - public static string DigestIn(string html) => Regex.Match(html, "name=\"digest\"[^>]*value=\"([0-9a-f]{64})\"").Groups[1].Value; - - public Task Confirm(string keep, string digest, bool self = true, bool other = true) - { - var form = new List<(string, string)> { ("keep", keep), ("digest", digest) }; - if (self) - { - form.Add(("consentSelf", "true")); - } - - if (other) - { - form.Add(("consentOther", "true")); - } - - return Post("Confirm", [.. form]); - } - } - - private static string Where(string keep, string code) => $"{Url}?keep={keep}&merge={code}"; - - // ---- the flag and the gates ---- - - [Fact] - public async Task Disabled_the_page_is_404_and_Linked_accounts_renders_no_link() - { - using var w = await World.Make(enabled: false); - - var (response, _) = await w.Get(); - var (_, linked) = await w.Host.GetLinkedAccountsAsync(w.Session); - - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - Assert.DoesNotContain("Merge two accounts", linked); - Assert.DoesNotContain("MergeAccounts", linked); - } - - [Fact] - public async Task Enabled_Linked_accounts_links_to_the_page() - { - using var w = await World.Make(); - - var (_, linked) = await w.Host.GetLinkedAccountsAsync(w.Session); - - Assert.Contains("Merge two accounts", linked); - Assert.Contains(Url, linked); - } - - [Fact] - public async Task A_frozen_account_is_forbidden_the_page() - { - using var w = await World.Make(); - await w.Rig.ConfirmedAsync(w.Me, w.Other, w.Rig.Weak(w.Me, "discord"), w.Rig.Weak(w.Other, "patreon"), w.Rig.Weak(w.Other, "google")); - var folded = await w.Host.SignInSessionAsync(w.Other.HeimdallId, "patreon"); - - var (response, _) = await w.Get(session: folded); - - AssertRefused(response); - } - - /// Forbid answers 403 or sends the browser to the access-denied page; either way the page is not served. - private static void AssertRefused(HttpResponseMessage response) => - Assert.True(response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.Found, response.StatusCode.ToString()); - - // ---- stages derive from the proofs held ---- - - [Fact] - public async Task With_no_proof_the_page_asks_for_both_and_says_nothing_is_named_until_both_exist() - { - using var w = await World.Make(); - - var page = await w.Page(); - - Assert.Contains("ProveSelf", page); - Assert.Contains("ProveOther", page); - Assert.Contains("nothing is named until both", page); - Assert.DoesNotContain("Keep this account", page); - } - - [Fact] - public async Task Nothing_about_the_other_account_appears_before_its_proof_is_stored() - { - using var w = await World.Make(); - await w.ProveSelf(); - - var onlySelf = await w.Page(); - var onlySelfKept = await w.Page("?keep=other"); - - Assert.DoesNotContain(OtherName, onlySelf + onlySelfKept); - Assert.DoesNotContain(w.Other.HeimdallId, onlySelf + onlySelfKept); - Assert.DoesNotContain(w.Other.Id.ToString(), onlySelf + onlySelfKept); - Assert.DoesNotContain("Keep this account", onlySelf); - } - - [Fact] - public async Task The_other_proof_alone_names_neither_account() - { - using var w = await World.Make(); - await w.ProveOther("patreon"); - - var page = await w.Page(); - - Assert.DoesNotContain(OtherName, page); - Assert.DoesNotContain("Keep this account", page); - } - - [Fact] - public async Task Both_proofs_name_both_accounts_by_display_name_and_offer_each_survivor() - { - using var w = await World.Make(); - await w.ProveSelf(); - await w.ProveOther("patreon"); - - var page = await w.Page(); - - Assert.Contains(w.MyName, page); - Assert.Contains(OtherName, page); - Assert.Contains("Keep this account", page); - Assert.Contains("Keep the other account", page); - Assert.Contains("keep=self", page); - Assert.Contains("keep=other", page); - Assert.DoesNotContain(w.Other.HeimdallId, page); - Assert.DoesNotContain(w.Other.Id.ToString(), page); - } - - [Fact] - public async Task The_folded_sides_unproved_logins_are_asked_one_sign_in_each_and_the_kept_side_needs_none() - { - using var w = await World.Make(); - await w.ProveSelf(); - await w.ProveOther("patreon"); - - var keepSelf = await w.Page("?keep=self"); - var keepOther = await w.Page("?keep=other"); - - Assert.Contains("ProveRemaining", keepSelf); - Assert.Contains("Google", keepSelf); - Assert.DoesNotContain("name=\"digest\"", keepSelf); - Assert.DoesNotContain("ProveRemaining", keepOther); - Assert.Matches("name=\"digest\"", keepOther); - - await w.Prove("ProveRemaining", w.Other, "google"); - Assert.Matches("name=\"digest\"", await w.Page("?keep=self")); - } - - [Fact] - public async Task Proofs_older_than_their_lifetime_fall_out_and_the_page_asks_again() - { - using var w = await World.Make(); - await w.ProveAll(); - Assert.Matches("name=\"digest\"", await w.Page("?keep=other")); - - w.Rig.Clock.Advance(MergeProofs.ProofLifetime + TimeSpan.FromSeconds(1)); - var page = await w.Page("?keep=other"); - - Assert.Contains("ProveSelf", page); - Assert.DoesNotContain("name=\"digest\"", page); - Assert.DoesNotContain(OtherName, page); - } - - // ---- the preview and the digest ---- - - [Fact] - public async Task The_two_directions_preview_with_different_digests_and_a_stale_one_is_PreviewStale_and_keeps_the_proofs() - { - using var w = await World.Make(); - await w.ProveAll(); - var keepSelf = World.DigestIn(await w.Page("?keep=self")); - var keepOther = World.DigestIn(await w.Page("?keep=other")); - Assert.NotEqual(keepSelf, keepOther); - Assert.Equal(await w.Rig.DigestAsync(w.Me, w.Other), keepSelf); - Assert.Equal(await w.Rig.DigestAsync(w.Other, w.Me), keepOther); - - var response = await w.Confirm("self", keepOther); - - Assert.Equal(Where("self", "preview_stale"), MergePage.Location(response)); - Assert.Equal(0, await w.Rig.MergeCountAsync()); - Assert.NotNull(w.Proofs.Snapshot(w.Me.Id).Self); - Assert.NotNull(w.Proofs.Snapshot(w.Me.Id).Other); - Assert.Contains(Enc(MergeWording.Confirm("preview_stale")), await w.Page("?keep=self&merge=preview_stale")); - } - - [Fact] - public async Task A_change_after_the_member_looked_makes_the_digest_stale() - { - using var w = await World.Make(); - await w.ProveAll(); - var seen = World.DigestIn(await w.Page("?keep=self")); - var motion = await w.Rig.MotionAsync(w.Me); - await w.Rig.VoteAsync(motion, w.Other, VoteChoice.For); - - var response = await w.Confirm("self", seen); - - Assert.Equal(Where("self", "preview_stale"), MergePage.Location(response)); - Assert.Equal(0, await w.Rig.MergeCountAsync()); - } - - [Fact] - public async Task The_preview_shows_the_plans_counts_and_the_static_statements_and_never_the_digests_inputs() - { - using var w = await World.Make(); - var motion = await w.Rig.MotionAsync(w.Me); - await w.Rig.VoteAsync(motion, w.Other, VoteChoice.For); - await w.ProveAll(); - - var page = await w.Page("?keep=self"); - - Assert.Contains("1 open vote ", page); - foreach (var statement in MergePreview.Statements) - { - Assert.Contains(Enc(statement), page); - } - } - - [Fact] - public async Task A_blocked_pair_shows_the_blocks_words_and_no_confirm_form() - { - using var w = await World.Make(); - var third = await w.Rig.AccountAsync("third-77aa", "discord"); - await w.Rig.ConfirmedAsync(third, w.Other, w.Rig.Weak(third, "discord"), w.Rig.Weak(w.Other, "patreon"), w.Rig.Weak(w.Other, "google")); - await w.ProveAll(); - - var page = await w.Page("?keep=other"); - - Assert.Contains(Enc(MergePreview.Block("merge_in_flight")), page); - Assert.DoesNotContain("consentSelf", page); - } - - [Theory] - [InlineData("self")] - [InlineData("other")] - public async Task Two_accounts_holding_a_login_of_one_provider_are_blocked_before_consent_and_the_block_names_only_the_provider(string keep) - { - using var w = await World.Make(otherProviders: ["discord", "patreon"]); - await w.ProveSelf(); - await w.ProveOther("discord"); - await w.ProveOther("patreon"); - - var page = await w.Page($"?keep={keep}"); - - Assert.Contains("Both accounts hold a Discord login", page); - Assert.DoesNotContain("consentSelf", page); - Assert.DoesNotContain("name=\"digest\"", page); - Assert.DoesNotContain("ProveRemaining", page); - var words = Regex.Match(page, "Both accounts hold a[^<]*").Value; - Assert.DoesNotContain(OtherName, words); - Assert.DoesNotContain(w.MyName, words); - Assert.DoesNotContain(w.Other.HeimdallId, words); - } - - [Fact] - public async Task A_confirm_for_accounts_holding_one_providers_login_is_Blocked_writes_nothing_and_keeps_the_proofs() - { - using var w = await World.Make(otherProviders: ["discord", "patreon"]); - await w.ProveSelf(); - await w.ProveOther("discord"); - await w.ProveOther("patreon"); - var digest = await w.Rig.DigestAsync(w.Me, w.Other); - - var response = await w.Confirm("self", digest); - - Assert.Equal(Where("self", "blocked"), MergePage.Location(response)); - Assert.Equal(0, await w.Rig.MergeCountAsync()); - Assert.NotNull(w.Proofs.Snapshot(w.Me.Id).Self); - Assert.NotNull(w.Proofs.Snapshot(w.Me.Id).Other); - Assert.Empty(w.Rig.Moves.Requests); - } - - // ---- confirm ---- - - [Fact] - public async Task Confirm_with_only_the_self_proof_does_not_reach_the_saga() - { - using var w = await World.Make(); - await w.ProveSelf(); - var digest = await w.Rig.DigestAsync(w.Me, w.Other); - - var response = await w.Confirm("self", digest); - - Assert.Equal(Where("self", "proofs_needed"), MergePage.Location(response)); - Assert.Equal(0, await w.Rig.MergeCountAsync()); - Assert.Empty(w.Rig.Moves.Requests); - } - - [Fact] - public async Task Confirm_with_the_folded_sides_logins_not_all_proved_does_not_reach_the_saga() - { - using var w = await World.Make(); - await w.ProveSelf(); - await w.ProveOther("patreon"); - var digest = await w.Rig.DigestAsync(w.Me, w.Other); - - var response = await w.Confirm("self", digest); - - Assert.Equal(Where("self", "proofs_needed"), MergePage.Location(response)); - Assert.Equal(0, await w.Rig.MergeCountAsync()); - } - - [Theory] - [InlineData(false, false)] - [InlineData(true, false)] - [InlineData(false, true)] - public async Task Confirm_without_both_consent_boxes_writes_nothing_and_keeps_the_proofs(bool self, bool other) - { - using var w = await World.Make(); - await w.ProveAll(); - var digest = World.DigestIn(await w.Page("?keep=other")); - - var response = await w.Confirm("other", digest, self, other); - - Assert.Equal(Where("other", "consent_needed"), MergePage.Location(response)); - Assert.Equal(0, await w.Rig.MergeCountAsync()); - Assert.NotNull(w.Proofs.Snapshot(w.Me.Id).Other); - } - - [Fact] - public async Task A_confirm_that_is_not_self_or_other_is_BadChoice() - { - using var w = await World.Make(); - await w.ProveAll(); - - var response = await w.Confirm("both", "x"); - - Assert.Equal(Url + "?merge=bad_choice", MergePage.Location(response)); - Assert.Equal(0, await w.Rig.MergeCountAsync()); - } - - [Fact] - public async Task A_blocked_confirm_is_Blocked_and_keeps_the_proofs() - { - using var w = await World.Make(); - await w.ProveAll(); - var digest = World.DigestIn(await w.Page("?keep=other")); - var third = await w.Rig.AccountAsync("third-77aa", "discord"); - await w.Rig.ConfirmedAsync(third, w.Other, w.Rig.Weak(third, "discord"), w.Rig.Weak(w.Other, "patreon"), w.Rig.Weak(w.Other, "google")); - var merges = await w.Rig.MergeCountAsync(); - - var response = await w.Confirm("other", digest); - - Assert.Equal(Where("other", "blocked"), MergePage.Location(response)); - Assert.Equal(merges, await w.Rig.MergeCountAsync()); - Assert.NotNull(w.Proofs.Snapshot(w.Me.Id).Self); - } - - [Fact] - public async Task A_proof_of_a_Heimdall_account_the_member_account_no_longer_has_is_ProofAccountMismatch_and_keeps_the_proofs() - { - using var w = await World.Make(); - await w.ProveAll(); - var digest = World.DigestIn(await w.Page("?keep=other")); - await w.Rig.InScopeAsync(async sp => - { - var db = sp.GetRequiredService(); - (await db.UserAccounts.SingleAsync(x => x.Id == w.Me.Id)).HeimdallAccountId = HeimdallShapes.NewAccountId(); - return await db.SaveChangesAsync(); - }); - - var response = await w.Confirm("other", digest); - - Assert.Equal(Where("other", "proof_account_mismatch"), MergePage.Location(response)); - Assert.Equal(0, await w.Rig.MergeCountAsync()); - Assert.NotNull(w.Proofs.Snapshot(w.Me.Id).Other); - } - - [Theory] - [InlineData("self")] - [InlineData("other")] - public async Task A_confirm_in_either_direction_leaves_one_row_with_the_typed_consent_columns_sealed_proofs_and_spent_proofs(string keep) - { - using var w = await World.Make(); - await w.ProveAll(); - var digest = World.DigestIn(await w.Page("?keep=" + keep)); - - var response = await w.Confirm(keep, digest); - - Assert.Equal(MergePage.Url, MergePage.Location(response)); - var survivor = keep == "self" ? w.Me : w.Other; - var merge = Assert.Single(await w.Rig.InScopeAsync(sp => sp.GetRequiredService().AccountMerges.AsNoTracking().ToListAsync())); - Assert.Equal(AccountMergeState.Committed, merge.State); - Assert.Equal(survivor.Id, merge.SurvivorUserAccountId); - Assert.Equal(w.Me.Id, merge.ConfirmedByUserAccountId); - Assert.Equal(digest, merge.PreviewDigest); - Assert.Null(merge.SealedProofs); // spent by the move that landed - if (keep == "self") - { - Assert.Equal("discord", merge.SurvivorProofProvider); - Assert.Equal("google,patreon", merge.FoldedProofProviders); - } - else - { - Assert.Contains(merge.SurvivorProofProvider, new[] { "patreon", "google" }); - Assert.Equal("discord", merge.FoldedProofProviders); - } - - Assert.Equal(new MergeProofsView(null, null), w.Proofs.Snapshot(w.Me.Id)); - } - - [Fact] - public async Task A_confirm_while_Heimdall_is_unreachable_still_lands_on_Merge_status_with_the_row_Confirmed_and_the_proofs_sealed() - { - using var w = await World.Make(); - await w.ProveAll(); - var digest = World.DigestIn(await w.Page("?keep=self")); - w.Rig.Moves.MoveDown = new HttpRequestException("down"); - - var response = await w.Confirm("self", digest); - - Assert.Equal(MergePage.Url, MergePage.Location(response)); - var merge = Assert.Single(await w.Rig.InScopeAsync(sp => sp.GetRequiredService().AccountMerges.AsNoTracking().ToListAsync())); - Assert.Equal(AccountMergeState.Confirmed, merge.State); - Assert.NotNull(merge.SealedProofs); - Assert.Equal(new MergeProofsView(null, null), w.Proofs.Snapshot(w.Me.Id)); - } - - [Fact] - public async Task The_whole_flow_by_sign_ins_ends_on_the_survivors_status_with_a_notice_and_the_folded_cookie_has_no_actor() - { - using var w = await World.Make(); - var foldedSession = await w.Host.SignInSessionAsync(w.Other.HeimdallId, "patreon"); - await w.ProveSelf(); - await w.ProveOther("patreon"); - await w.Prove("ProveRemaining", w.Other, "google"); - var digest = World.DigestIn(await w.Page("?keep=self")); - - var response = await w.Confirm("self", digest); - - Assert.Equal(MergePage.Url, MergePage.Location(response)); - var (_, status) = await MergePage.GetAsync(w.Host, w.Session); - Assert.Contains(Enc(MergeWording.State(AccountMergeState.Committed)), status); - Assert.Contains("Undo window ends", status); - Assert.Contains("can still be undone", status); - var (foldedResponse, _) = await w.Host.GetLinkedAccountsAsync(foldedSession); - AssertRefused(foldedResponse); - - var everything = string.Join('\n', w.Surface) + status; - Assert.All(w.Bearers, bearer => Assert.DoesNotContain(bearer, everything)); - Assert.DoesNotContain(w.Other.HeimdallId, everything); - } - - [Fact] - public async Task Proving_without_naming_a_provider_starts_nothing_and_comes_back_with_the_error_code() - { - using var w = await World.Make(); - var started = w.Host.Heimdall.StartBodies.Count; - - var response = await w.Post("ProveOther"); - - Assert.Equal(Url + "?result=error", MergePage.Location(response)); - Assert.Equal(started, w.Host.Heimdall.StartBodies.Count); - } -} diff --git a/tests/Bifrost.Web.Tests/MergeNoticeAuthTests.cs b/tests/Bifrost.Web.Tests/MergeNoticeAuthTests.cs deleted file mode 100644 index 71f9e85..0000000 --- a/tests/Bifrost.Web.Tests/MergeNoticeAuthTests.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System.Net; -using System.Text; -using Bifrost.Web.Data; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using static Bifrost.Web.Tests.AccountMergeSagaTests; - -namespace Bifrost.Web.Tests; - -/// Who may pull merge notices: the chat host's own bearer and nobody else, whatever else the request carries (the test host signs every request in as an admin). -public sealed class MergeNoticeAuthTests -{ - private const string Token = "chat-notices-test-token-0123456789"; - private const string Get = "/api/merge-notices/chat"; - private const string Ack = "/api/merge-notices/chat/ack"; - - private static HttpRequestMessage Request(HttpMethod method, string url, string? authorization, string? body = null) - { - var request = new HttpRequestMessage(method, url); - if (authorization is not null) - { - request.Headers.TryAddWithoutValidation("Authorization", authorization); - } - - if (body is not null) - { - request.Content = new StringContent(body, Encoding.UTF8, "application/json"); - } - - return request; - } - - private static string AckBody(Guid id) => $"{{\"merge_id\":\"{id}\",\"type\":\"merged\"}}"; - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task With_no_token_configured_both_routes_are_404_even_for_a_bearer_that_looks_right(string? token) - { - using var rig = new Rig(chatNoticesToken: token); - using var client = rig.Host.NewClient(); - - foreach (var authorization in new[] { null, "Bearer " + Token, "Bearer " }) - { - using var read = await client.SendAsync(Request(HttpMethod.Get, Get, authorization)); - using var ack = await client.SendAsync(Request(HttpMethod.Post, Ack, authorization, AckBody(Guid.NewGuid()))); - Assert.Equal(HttpStatusCode.NotFound, read.StatusCode); - Assert.Equal(HttpStatusCode.NotFound, ack.StatusCode); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("Bearer")] - [InlineData("Bearer ")] - [InlineData("Bearer wrong-wrong-wrong-wrong-wrong-wrong")] - [InlineData("Bearer chat-notices-test-token-012345678")] // one short - [InlineData("Bearer chat-notices-test-token-01234567890")] // one long - [InlineData("Bearer c")] - [InlineData("chat-notices-test-token-0123456789")] - [InlineData("Basic chat-notices-test-token-0123456789")] - [InlineData("Bearer chat-notices-test-token-0123456789, Bearer other")] - public async Task A_missing_wrong_short_or_long_token_is_401_with_no_body_on_both_routes_and_acks_nothing(string? authorization) - { - using var rig = new Rig(chatNoticesToken: Token); - var (merge, _, _) = await Committed(rig); - using var client = rig.Host.NewClient(); - - using var read = await client.SendAsync(Request(HttpMethod.Get, Get, authorization)); - using var ack = await client.SendAsync(Request(HttpMethod.Post, Ack, authorization, AckBody(merge))); - - foreach (var response in new[] { read, ack }) - { - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Empty(await response.Content.ReadAsStringAsync()); - Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); - } - - Assert.Equal(0, await rig.InScopeAsync(async sp => await sp.GetRequiredService().AccountMergeNoticeAcks.CountAsync())); - } - - [Fact] - public async Task A_token_in_the_query_or_a_cookie_is_not_a_bearer() - { - using var rig = new Rig(chatNoticesToken: Token); - using var client = rig.Host.NewClient(); - - using var query = await client.SendAsync(Request(HttpMethod.Get, $"{Get}?token={Token}&access_token={Token}", null)); - using var cookie = Request(HttpMethod.Get, Get, null); - cookie.Headers.Add("Cookie", $"token={Token}"); - using var withCookie = await client.SendAsync(cookie); - - Assert.Equal(HttpStatusCode.Unauthorized, query.StatusCode); - Assert.Equal(HttpStatusCode.Unauthorized, withCookie.StatusCode); - } - - [Fact] - public async Task The_right_token_reads_and_acks_with_no_store_and_no_cors_or_cookie() - { - using var rig = new Rig(chatNoticesToken: Token); - var (merge, _, _) = await Committed(rig); - using var client = rig.Host.NewClient(); - - using var read = await client.SendAsync(Request(HttpMethod.Get, Get, "Bearer " + Token)); - using var ack = await client.SendAsync(Request(HttpMethod.Post, Ack, "Bearer " + Token, AckBody(merge))); - - Assert.Equal(HttpStatusCode.OK, read.StatusCode); - Assert.Equal(HttpStatusCode.NoContent, ack.StatusCode); - foreach (var response in new[] { read, ack }) - { - Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); - Assert.False(response.Headers.Contains("Access-Control-Allow-Origin")); - Assert.False(response.Headers.Contains("Set-Cookie")); - } - - Assert.Contains("application/json", read.Content.Headers.ContentType?.ToString()); - } - - internal static async Task<(Guid Merge, Party Survivor, Party Folded)> Committed(Rig rig) - { - var survivor = await rig.AccountAsync("survivor", "twitch"); - var folded = await rig.AccountAsync("folded", "discord"); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")); - Assert.Equal(Bifrost.Web.Domain.AccountMergeState.Committed, (await rig.AdvanceAsync(id)).State); - return (id, survivor, folded); - } -} diff --git a/tests/Bifrost.Web.Tests/MergeNoticeFeedTests.cs b/tests/Bifrost.Web.Tests/MergeNoticeFeedTests.cs deleted file mode 100644 index 4577583..0000000 --- a/tests/Bifrost.Web.Tests/MergeNoticeFeedTests.cs +++ /dev/null @@ -1,341 +0,0 @@ -using System.Net; -using System.Text; -using System.Text.Json; -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Membership; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using static Bifrost.Web.Tests.AccountMergeSagaTests; - -namespace Bifrost.Web.Tests; - -/// -/// The merge notice feed from the chat host's side: pulled over HTTP with the bearer, acked over HTTP, against merges the saga rig made; -/// bounds and the unique ack key from the feed itself over seeded rows. Notices are derived from the merge row: no stored status. -/// -public sealed class MergeNoticeFeedTests(MergePostgres postgres) : IClassFixture -{ - private const string Token = "chat-notices-test-token-0123456789"; - - private static readonly string[] PayloadKeys = - ["type", "merge_id", "occurred_at", "grace_ends_at", "old_subject", "new_subject", "old_preferred_username", "new_preferred_username"]; - - private static async Task PullAsync(Rig rig, string query = "") - { - using var client = rig.Host.NewClient(); - using var request = new HttpRequestMessage(HttpMethod.Get, "/api/merge-notices/chat" + query); - request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + Token); - using var response = await client.SendAsync(request); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.EnumerateArray().Select(x => x.Clone()).ToArray(); - } - - private static async Task AckAsync(Rig rig, Guid merge, string type) - { - using var client = rig.Host.NewClient(); - using var request = new HttpRequestMessage(HttpMethod.Post, "/api/merge-notices/chat/ack") - { - Content = new StringContent($"{{\"merge_id\":\"{merge}\",\"type\":\"{type}\"}}", Encoding.UTF8, "application/json") - }; - request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + Token); - using var response = await client.SendAsync(request); - return response.StatusCode; - } - - private static string[] Types(JsonElement[] notices) => [.. notices.Select(x => x.GetProperty("type").GetString()!)]; - - private static Task<(Guid Merge, Party Survivor, Party Folded)> CommittedAsync(Rig rig) => MergeNoticeAuthTests.Committed(rig); - - private static async Task FinalizeAsync(Rig rig) - { - rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromMinutes(1)); - await rig.InScopeAsync(async sp => await sp.GetRequiredService().FinalizeDueAsync(rig.Clock.Now, default)); - } - - // ---- what a notice says ---- - - [Fact] - public async Task A_committed_merge_yields_one_merged_notice_with_exactly_the_documented_keys_and_nothing_that_names_a_person() - { - using var rig = new Rig(chatNoticesToken: Token); - var (merge, survivor, folded) = await CommittedAsync(rig); - var committed = await rig.MergeAsync(merge); - - var notice = Assert.Single(await PullAsync(rig)); - - Assert.Equal(PayloadKeys.Order(), notice.EnumerateObject().Select(x => x.Name).Order()); - Assert.Equal("merged", notice.GetProperty("type").GetString()); - Assert.Equal(merge.ToString("D"), notice.GetProperty("merge_id").GetString()); - Assert.Equal(committed.CommittedUtc, notice.GetProperty("occurred_at").GetDateTimeOffset()); - Assert.Equal(committed.GraceEndsUtc, notice.GetProperty("grace_ends_at").GetDateTimeOffset()); - Assert.Equal(folded.Id.ToString("D"), notice.GetProperty("old_subject").GetString()); - Assert.Equal(survivor.Id.ToString("D"), notice.GetProperty("new_subject").GetString()); - Assert.Equal("folded", notice.GetProperty("old_preferred_username").GetString()); - Assert.Equal("survivor", notice.GetProperty("new_preferred_username").GetString()); - Assert.DoesNotContain(folded.HeimdallId, notice.GetRawText()); - Assert.DoesNotContain(survivor.HeimdallId, notice.GetRawText()); - } - - [Fact] - public async Task An_undone_merge_yields_merged_then_undone_and_each_is_acked_alone() - { - using var rig = new Rig(chatNoticesToken: Token); - var (merge, survivor, folded) = await CommittedAsync(rig); - rig.Clock.Advance(TimeSpan.FromHours(1)); - Assert.IsType(await rig.InScopeAsync(sp => - sp.GetRequiredService().RequestUndoAsync(merge, survivor.Id, [rig.Moved(survivor, folded, "discord")], default))); - Assert.Equal(AccountMergeState.Undone, (await rig.AdvanceAsync(merge)).State); - var stored = await rig.MergeAsync(merge); - - var notices = await PullAsync(rig); - - Assert.Equal(["merged", "undone"], Types(notices)); - Assert.Equal(stored.UndoneUtc, notices[1].GetProperty("occurred_at").GetDateTimeOffset()); - Assert.Equal(stored.GraceEndsUtc, notices[1].GetProperty("grace_ends_at").GetDateTimeOffset()); - Assert.Equal(HttpStatusCode.NoContent, await AckAsync(rig, merge, "merged")); - Assert.Equal(["undone"], Types(await PullAsync(rig))); - } - - [Fact] - public async Task A_finalized_merge_yields_merged_then_final() - { - using var rig = new Rig(chatNoticesToken: Token); - var (merge, _, _) = await CommittedAsync(rig); - await FinalizeAsync(rig); - var stored = await rig.MergeAsync(merge); - Assert.Equal(AccountMergeState.Final, stored.State); - - var notices = await PullAsync(rig); - - Assert.Equal(["merged", "final"], Types(notices)); - Assert.Equal(stored.FinalizedUtc, notices[1].GetProperty("occurred_at").GetDateTimeOffset()); - } - - [Fact] - public async Task A_confirmed_a_frozen_and_a_failed_merge_yield_nothing() - { - using var rig = new Rig(chatNoticesToken: Token); - var survivor = await rig.AccountAsync("survivor", "twitch"); - var frozen = await rig.AccountAsync("frozen", "discord"); - var stale = await rig.AccountAsync("stale", "patreon"); - var confirmed = await rig.ConfirmedAsync(survivor, frozen, rig.Weak(survivor, "twitch"), rig.Weak(frozen, "discord")); - Assert.Equal(AccountMergeState.Confirmed, (await rig.MergeAsync(confirmed)).State); - Assert.IsType(await rig.StandingAsync(frozen)); - Assert.Empty(await PullAsync(rig)); - - var other = await rig.AccountAsync("other", "twitch2"); - var failing = await rig.ConfirmedAsync(other, stale, rig.Weak(other, "twitch2"), rig.Weak(stale, "patreon")); - rig.Clock.Advance(TimeSpan.FromSeconds(400)); - Assert.Equal(AccountMergeState.Failed, (await rig.AdvanceAsync(failing)).State); - - // The first merge is still Confirmed and the second Failed: neither committed, neither is told. - Assert.Empty(await PullAsync(rig)); - } - - // ---- ack ---- - - [Fact] - public async Task An_ack_is_idempotent_and_the_notice_is_gone_from_the_next_read() - { - using var rig = new Rig(chatNoticesToken: Token); - var (merge, _, _) = await CommittedAsync(rig); - Assert.Single(await PullAsync(rig)); - - Assert.Equal(HttpStatusCode.NoContent, await AckAsync(rig, merge, "merged")); - Assert.Equal(HttpStatusCode.NoContent, await AckAsync(rig, merge, "merged")); - - Assert.Empty(await PullAsync(rig)); - Assert.Equal(1, await rig.InScopeAsync(async sp => await sp.GetRequiredService().AccountMergeNoticeAcks.CountAsync())); - } - - [Fact] - public async Task An_ack_of_a_notice_the_feed_would_not_emit_is_refused_and_stores_nothing() - { - using var rig = new Rig(chatNoticesToken: Token); - var (merge, _, _) = await CommittedAsync(rig); // merged only: not undone, not final - - Assert.Equal(HttpStatusCode.NotFound, await AckAsync(rig, merge, "undone")); - Assert.Equal(HttpStatusCode.NotFound, await AckAsync(rig, merge, "final")); - Assert.Equal(HttpStatusCode.NotFound, await AckAsync(rig, Guid.NewGuid(), "merged")); - Assert.Equal(HttpStatusCode.BadRequest, await AckAsync(rig, merge, "created")); - Assert.Equal(HttpStatusCode.BadRequest, await AckAsync(rig, merge, "Merged")); - - Assert.Equal(0, await rig.InScopeAsync(async sp => await sp.GetRequiredService().AccountMergeNoticeAcks.CountAsync())); - Assert.Single(await PullAsync(rig)); - } - - [Fact] - public async Task A_malformed_ack_body_is_400_and_stores_nothing() - { - using var rig = new Rig(chatNoticesToken: Token); - await CommittedAsync(rig); - using var client = rig.Host.NewClient(); - foreach (var body in new[] { "", "not json", "{}", "{\"merge_id\":\"nope\",\"type\":\"merged\"}", "{\"type\":\"merged\"}", "[]" }) - { - using var request = new HttpRequestMessage(HttpMethod.Post, "/api/merge-notices/chat/ack") { Content = new StringContent(body, Encoding.UTF8, "application/json") }; - request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + Token); - using var response = await client.SendAsync(request); - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - } - - Assert.Equal(0, await rig.InScopeAsync(async sp => await sp.GetRequiredService().AccountMergeNoticeAcks.CountAsync())); - } - - // ---- order, bounds, after: the feed over seeded rows ---- - - private static readonly DateTimeOffset T0 = AccountMergeLedgerTests.T0; - - private static async Task<(AccountMergeLedgerTests.World World, UserAccount Survivor, UserAccount Folded)> SeededAsync(Func> merges, string? postgres = null) - { - var world = postgres is null ? new AccountMergeLedgerTests.World() : AccountMergeLedgerTests.World.OnPostgres(postgres); - await using (var migrate = world.Db()) - { - if (postgres is not null) - { - await migrate.Database.MigrateAsync(); - } - } - - var survivor = await world.AccountAsync("survivor"); - var folded = await world.AccountAsync("folded"); - await using var db = world.Db(); - db.AccountMerges.AddRange(merges(survivor.Id, folded.Id)); - await db.SaveChangesAsync(); - return (world, survivor, folded); - } - - private static AccountMerge Committed(Guid survivor, Guid folded, DateTimeOffset at, Guid? id = null) => new() - { - Id = id ?? Guid.NewGuid(), State = AccountMergeState.Committed, SurvivorUserAccountId = survivor, FoldedUserAccountId = folded, - CreatedUtc = at, CommittedUtc = at, GraceEndsUtc = at + AccountMergeLedger.Grace - }; - - private static MergeNoticeFeed Feed(BifrostDbContext db) => new(db, TimeProvider.System); - - [Fact] - public async Task Notices_come_ordered_by_occurred_at_then_merge_id_then_kind_and_after_keeps_only_later_ones() - { - var low = new Guid("00000000-0000-0000-0000-000000000001"); - var high = new Guid("00000000-0000-0000-0000-000000000002"); - var (world, _, _) = await SeededAsync((s, f) => - [ - Committed(s, f, T0.AddHours(3), high), - Committed(s, f, T0.AddHours(3), low), - Committed(s, f, T0.AddHours(1), Guid.NewGuid()) - ]); - await using var db = world.Db(); - - var all = await Feed(db).ReadAsync(AccountMergeNoticeTarget.Chat, null, null, default); - var later = await Feed(db).ReadAsync(AccountMergeNoticeTarget.Chat, T0.AddHours(1), null, default); - - Assert.Equal([T0.AddHours(1), T0.AddHours(3), T0.AddHours(3)], all.Select(x => x.OccurredAt)); - Assert.Equal([low, high], all.Skip(1).Select(x => x.MergeId)); - Assert.Equal([low, high], later.Select(x => x.MergeId)); - } - - [Fact] - public async Task A_merge_that_is_undone_and_one_that_is_final_order_their_two_notices_by_their_own_times() - { - var (world, _, _) = await SeededAsync((s, f) => - { - var undone = Committed(s, f, T0); - undone.State = AccountMergeState.Undone; - undone.UndoneUtc = T0.AddHours(5); - var final = Committed(s, f, T0.AddHours(1)); - final.State = AccountMergeState.Final; - final.FinalizedUtc = T0.AddHours(2); - return [undone, final]; - }); - await using var db = world.Db(); - - var kinds = (await Feed(db).ReadAsync(AccountMergeNoticeTarget.Chat, null, null, default)).Select(x => x.Kind); - - Assert.Equal([AccountMergeNoticeKind.Merged, AccountMergeNoticeKind.Merged, AccountMergeNoticeKind.Final, AccountMergeNoticeKind.Undone], kinds); - } - - [Theory] - [InlineData(null, 50)] - [InlineData(0, 50)] - [InlineData(-5, 50)] - [InlineData(3, 3)] - [InlineData(200, 200)] - [InlineData(100000, 200)] - public async Task The_limit_is_bounded_default_fifty_maximum_two_hundred(int? asked, int expected) - { - var (world, _, _) = await SeededAsync((s, f) => Enumerable.Range(0, 230).Select(i => Committed(s, f, T0.AddMinutes(i)))); - await using var db = world.Db(); - - var read = await Feed(db).ReadAsync(AccountMergeNoticeTarget.Chat, null, asked, default); - - Assert.Equal(expected, read.Count); - Assert.Equal(T0.AddMinutes(expected - 1), read[^1].OccurredAt); // the oldest first, cut at the limit - } - - [Fact] - public async Task The_feed_writes_no_merge_row_only_acks() - { - var (world, _, _) = await SeededAsync((s, f) => [Committed(s, f, T0)]); - await using var db = world.Db(); - var before = await db.AccountMerges.AsNoTracking().SingleAsync(); - var feed = Feed(db); - - await feed.ReadAsync(AccountMergeNoticeTarget.Chat, null, null, default); - Assert.True(await feed.AckAsync(AccountMergeNoticeTarget.Chat, before.Id, AccountMergeNoticeKind.Merged, default)); - Assert.True(await feed.AckAsync(AccountMergeNoticeTarget.Chat, before.Id, AccountMergeNoticeKind.Merged, default)); - Assert.False(await feed.AckAsync(AccountMergeNoticeTarget.Chat, before.Id, AccountMergeNoticeKind.Final, default)); - - await using var fresh = world.Db(); - var after = await fresh.AccountMerges.AsNoTracking().SingleAsync(); - Assert.Equal(System.Text.Json.JsonSerializer.Serialize(before), System.Text.Json.JsonSerializer.Serialize(after)); - Assert.Equal(1, await fresh.AccountMergeNoticeAcks.CountAsync()); - } - - // ---- the unique key, on a real database ---- - - [PostgresFact] - public async Task Two_concurrent_acks_of_one_notice_both_succeed_and_leave_one_row() - { - var name = $"bifrost_notices_{Guid.NewGuid():N}"; - var admin = Environment.GetEnvironmentVariable(PostgresGate.Variable)!; - await using (var connection = new Npgsql.NpgsqlConnection(admin)) - { - await connection.OpenAsync(); - await using var create = new Npgsql.NpgsqlCommand($"CREATE DATABASE \"{name}\"", connection); - await create.ExecuteNonQueryAsync(); - } - - try - { - var (world, _, _) = await SeededAsync((s, f) => [Committed(s, f, T0)], new Npgsql.NpgsqlConnectionStringBuilder(admin) { Database = name }.ConnectionString); - Guid id; - await using (var read = world.Db()) - { - id = (await read.AccountMerges.SingleAsync()).Id; - } - - for (var round = 0; round < 5; round++) // a fresh race each round - { - const AccountMergeNoticeKind kind = AccountMergeNoticeKind.Merged; - var results = await Task.WhenAll(Enumerable.Range(0, 6).Select(async _ => - { - await using var db = world.Db(); - return await Feed(db).AckAsync(AccountMergeNoticeTarget.Chat, id, kind, default); - })); - Assert.All(results, Assert.True); - } - - await using var check = world.Db(); - Assert.Equal(1, await check.AccountMergeNoticeAcks.CountAsync()); - Assert.Empty(await Feed(check).ReadAsync(AccountMergeNoticeTarget.Chat, null, null, default)); - } - finally - { - Npgsql.NpgsqlConnection.ClearAllPools(); - await using var connection = new Npgsql.NpgsqlConnection(admin); - await connection.OpenAsync(); - await using var drop = new Npgsql.NpgsqlCommand($"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)", connection); - await drop.ExecuteNonQueryAsync(); - } - } -} diff --git a/tests/Bifrost.Web.Tests/MergePreviewTests.cs b/tests/Bifrost.Web.Tests/MergePreviewTests.cs deleted file mode 100644 index 3e9d8c8..0000000 --- a/tests/Bifrost.Web.Tests/MergePreviewTests.cs +++ /dev/null @@ -1,106 +0,0 @@ -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Membership; - -namespace Bifrost.Web.Tests; - -/// The wording of a merge plan: closed vocabulary, counts from the plan's entries, the statements a member must always see. -public sealed class MergePreviewTests -{ - private static readonly string[] BlockCodes = - [ - "same_account", "account_missing", "mind_account", "native_account", "merge_in_flight", - "survivor_is_folded", "already_folded", "folded_is_survivor", "sealed_ballot_pending" - ]; - - private static MergePlanEntry Entry(AccountMergeEntryKind kind, AccountMergeEntryAction action) => new(kind, action, Guid.NewGuid()); - - private static MergePlan Plan(IEnumerable entries, IReadOnlyDictionary? left = null) => - new([], [.. entries], left ?? new Dictionary()); - - [Fact] - public void The_provider_conflict_names_the_providers_and_says_to_prove_that_side_again_after_unlinking() - { - // The conflict is read from the login list held with the proofs, which unlinking does not change until the member proves again. - var words = MergePreview.ProviderConflict(["Discord", "Twitch"]); - - Assert.Contains("Discord and Twitch", words); - Assert.Contains("Unlink", words); - Assert.Contains("prove that account again", words); - } - - [Fact] - public void Every_block_code_has_its_own_words_and_none_names_an_account() - { - var words = BlockCodes.Select(MergePreview.Block).ToList(); - - Assert.All(words, x => Assert.NotEmpty(x)); - Assert.Equal(BlockCodes.Length, words.Distinct().Count()); - Assert.All(words, x => Assert.DoesNotContain("@", x)); - Assert.NotEmpty(MergePreview.Block("a code nobody wrote")); - Assert.DoesNotContain("a code nobody wrote", MergePreview.Block("a code nobody wrote")); - } - - [Fact] - public void The_counts_come_from_the_plans_entries_by_kind_and_action() - { - var plan = Plan( - [ - .. Enumerable.Range(0, 3).Select(_ => Entry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided)), - Entry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved), - .. Enumerable.Range(0, 2).Select(_ => Entry(AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Voided)), - Entry(AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed), - Entry(AccountMergeEntryKind.Standing, AccountMergeEntryAction.Suspended), - .. Enumerable.Range(0, 4).Select(_ => Entry(AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved)) - ], - new Dictionary { ["ConsentReceipts"] = 5, ["PasskeyCredentials"] = 1, ["LedgerEntries"] = 0 }); - - var text = string.Join('\n', MergePreview.Lines(plan)); - - Assert.Contains("3 open votes", text); - Assert.Contains("1 open vote ", text); - Assert.Contains("2 appraisals", text); - Assert.Contains("membership", text); - Assert.Contains("suspended", text); - Assert.Contains("4 patron events", text); - Assert.Contains("5 consent records", text); - Assert.Contains("1 passkey ", text); - Assert.DoesNotContain("0 ledger", text); - - Assert.Contains("2 open votes", string.Join('\n', MergePreview.Lines(Plan( - Enumerable.Range(0, 2).Select(_ => Entry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided)))))); - } - - [Theory] - [InlineData("chat id")] - [InlineData("consent again")] - [InlineData("StreamPixels")] - [InlineData("Roles and admin")] - [InlineData("one vote per motion")] - [InlineData("7 days")] - [InlineData("ordinary sign-ins")] - [InlineData("Merge status")] - public void The_statements_always_carry_what_a_merge_cannot_carry_over(string statement) - { - Assert.Contains(MergePreview.Statements, x => x.Contains(statement, StringComparison.Ordinal)); - } - - [Fact] - public void The_statements_promise_no_passkey_because_no_page_offers_one() - { - Assert.DoesNotContain(MergePreview.Statements, x => x.Contains("passkey", StringComparison.OrdinalIgnoreCase)); - } - - [Theory] - [InlineData("blocked")] - [InlineData("preview_stale")] - [InlineData("not_party")] - [InlineData("proof_account_mismatch")] - [InlineData("proofs_needed")] - [InlineData("consent_needed")] - [InlineData("bad_choice")] - public void Every_refusal_the_page_can_answer_has_closed_words(string code) - { - Assert.NotEmpty(MergeWording.Confirm(code)); - Assert.Empty(MergeWording.Confirm("not a code")); - } -} diff --git a/tests/Bifrost.Web.Tests/MergeProofCompletionTests.cs b/tests/Bifrost.Web.Tests/MergeProofCompletionTests.cs deleted file mode 100644 index 704b037..0000000 --- a/tests/Bifrost.Web.Tests/MergeProofCompletionTests.cs +++ /dev/null @@ -1,230 +0,0 @@ -using System.Net; -using System.Text.Json; -using Bifrost.Web.Features.Heimdall; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Features.Shared; -using Bifrost.Web.Tests.Support; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Extensions.DependencyInjection; - -namespace Bifrost.Web.Tests; - -/// -/// The two merge-proof sign-ins from the browser's side, against a fake Heimdall: a fresh sign-in as the account signed in here (Self) -/// or as a second account (Other), each held in and nowhere else. No page starts them yet, so the tests start -/// them through the service and finish them as the browser does, by posting the completion code with the attempt cookie. -/// -public sealed class MergeProofCompletionTests -{ - private const string Page = "/Membership/MergeStandIn"; - private const string Callback = "https://localhost"; - - private sealed record Member(string Account, string Session, Guid UserAccountId); - - private static async Task SignedIn(HeimdallHost host) - { - var account = HeimdallShapes.NewAccountId(); - var session = await host.SignInSessionAsync(account); - return new Member(account, session, (await host.Account(account))!.Id); - } - - private static async Task Begin(HeimdallHost host, Member session, MergeSide side, string via = "discord") - { - var auth = host.Services.GetRequiredService(); - var started = side == MergeSide.Self - ? await auth.StartMergeProveSelfAsync(session.Account, via, Page, Callback, [], CancellationToken.None) - : await auth.StartMergeProveOtherAsync(session.Account, via, Page, Callback, [], CancellationToken.None); - var returnTo = JsonDocument.Parse(host.Heimdall.StartBodies[^1]).RootElement.GetProperty("returnTo").GetString()!; - var nonce = QueryHelpers.ParseQuery(new Uri(returnTo).Query)["attempt"].ToString(); - return new StartedAttempt(nonce, started.CookieName, started.CookieValue, returnTo, new HttpResponseMessage()); - } - - private static async Task Finish( - HeimdallHost host, Member session, StartedAttempt attempt, string provedAccount, string token, string provider = "discord", string? sessionOverride = null) - { - var code = host.CodeFor(attempt, provedAccount, token, provider: provider); - return await host.PostCompleteAsync( - new Dictionary { ["attempt"] = attempt.Nonce, ["code"] = code }, - $"{BifrostCookies.Session}={sessionOverride ?? session.Session}; {attempt.CookieName}={attempt.Cookie}"); - } - - private static string? Location(HttpResponseMessage response) => response.Headers.Location?.OriginalString; - - private static MergeProofs Proofs(HeimdallHost host) => host.Services.GetRequiredService(); - - private static void SetList(HeimdallHost host, params string[] providers) - { - host.Heimdall.Identities.Clear(); - foreach (var provider in providers) - { - host.Heimdall.AddIdentity(provider, "Name of " + provider); - } - } - - [Theory] - [InlineData(MergeSide.Self)] - [InlineData(MergeSide.Other)] - public async Task A_completion_through_another_provider_than_the_attempts_records_no_proof(MergeSide side) - { - using var host = new HeimdallHost(realSessions: true); - var me = await SignedIn(host); - var other = await SignedIn(host); - SetList(host, "discord", "patreon"); - var proved = side == MergeSide.Self ? me : other; - var attempt = await Begin(host, me, side, via: "discord"); - - var done = await Finish(host, me, attempt, proved.Account, host.Token(proved.Account), provider: "patreon"); - - Assert.NotEqual(Page + "?result=merge_proof_recorded", Location(done)); - var held = Proofs(host).Snapshot(me.UserAccountId); - Assert.Null(held.Self); - Assert.Null(held.Other); - } - - [Fact] - public async Task A_self_proof_for_the_signed_in_account_is_held_and_the_browser_goes_back_with_a_closed_code() - { - using var host = new HeimdallHost(realSessions: true); - var me = await SignedIn(host); - SetList(host, "discord", "patreon"); - var bearer = host.Token(me.Account); - - var done = await Finish(host, me, await Begin(host, me, MergeSide.Self), me.Account, bearer); - - Assert.Equal(Page + "?result=merge_proof_recorded", Location(done)); - var view = Assert.IsType(Proofs(host).Snapshot(me.UserAccountId).Self); - Assert.Equal(me.UserAccountId, view.UserAccountId); - Assert.Equal(["discord"], view.ProvedProviders); - Assert.Equal(["discord", "patreon"], view.LoginProviders.Order().ToArray()); - Assert.Equal($"Bearer {bearer}", Assert.Single(host.Heimdall.ListAuthorizations)); - var surface = Location(done) + string.Join('\n', done.Headers.Select(x => x.Key + string.Concat(x.Value))); - Assert.DoesNotContain(bearer, surface); - Assert.DoesNotContain(me.Account, surface); - Assert.DoesNotContain(bearer, string.Join('\n', host.Logs.Lines)); - } - - [Fact] - public async Task A_self_proof_of_a_different_account_is_refused_and_stores_nothing() - { - using var host = new HeimdallHost(realSessions: true); - var me = await SignedIn(host); - var someoneElse = HeimdallShapes.NewAccountId(); - SetList(host, "discord"); - - var done = await Finish(host, me, await Begin(host, me, MergeSide.Self), someoneElse, host.Token(someoneElse)); - - Assert.Equal(Page + "?result=error", Location(done)); - Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId)); - Assert.Empty(host.Heimdall.ListAuthorizations); - } - - [Fact] - public async Task An_other_proof_of_the_sessions_own_account_is_MergeSameAccount_and_stores_nothing() - { - using var host = new HeimdallHost(realSessions: true); - var me = await SignedIn(host); - SetList(host, "discord"); - - var done = await Finish(host, me, await Begin(host, me, MergeSide.Other), me.Account, host.Token(me.Account)); - - Assert.Equal(Page + "?result=merge_same_account", Location(done)); - Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId)); - Assert.Empty(host.Heimdall.ListAuthorizations); - } - - [Fact] - public async Task An_other_proof_for_a_Heimdall_account_without_a_member_account_is_MergeNoAccount_and_the_bearer_is_dropped() - { - using var host = new HeimdallHost(realSessions: true); - var me = await SignedIn(host); - var stranger = HeimdallShapes.NewAccountId(); - SetList(host, "patreon"); - - var done = await Finish(host, me, await Begin(host, me, MergeSide.Other, "patreon"), stranger, host.Token(stranger), "patreon"); - - Assert.Equal(Page + "?result=merge_no_account", Location(done)); - Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId)); - Assert.Empty(host.Heimdall.ListAuthorizations); - Assert.Null(await host.Account(stranger)); - } - - [Fact] - public async Task Both_sides_proved_give_the_actor_the_bearers_that_were_redeemed() - { - using var host = new HeimdallHost(realSessions: true); - var me = await SignedIn(host); - var them = await SignedIn(host); - SetList(host, "discord"); - var mine = host.Token(me.Account); - await Finish(host, me, await Begin(host, me, MergeSide.Self), me.Account, mine); - SetList(host, "patreon"); - var theirs = host.Token(them.Account); - - var done = await Finish(host, me, await Begin(host, me, MergeSide.Other, "patreon"), them.Account, theirs, "patreon"); - - Assert.Equal(Page + "?result=merge_proof_recorded", Location(done)); - var ready = Assert.IsType(Proofs(host).Peek(me.UserAccountId, MergeSide.Self)); - Assert.Equal((mine, me.Account, "discord"), (ready.Survivor.AccessToken, ready.Survivor.HeimdallAccountId, ready.Survivor.Provider)); - var folded = Assert.Single(ready.Folded); - Assert.Equal((theirs, them.Account, "patreon"), (folded.AccessToken, folded.HeimdallAccountId, folded.Provider)); - var view = Assert.IsType(Proofs(host).Snapshot(me.UserAccountId).Other); - Assert.Equal(them.UserAccountId, view.UserAccountId); - } - - [Fact] - public async Task A_list_Heimdall_does_not_give_stores_nothing() - { - using var host = new HeimdallHost(realSessions: true); - var me = await SignedIn(host); - SetList(host, "discord"); - host.Heimdall.ListStatus = HttpStatusCode.InternalServerError; - - var done = await Finish(host, me, await Begin(host, me, MergeSide.Self), me.Account, host.Token(me.Account)); - - Assert.Equal(Page + "?result=error", Location(done)); - Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId)); - } - - [Fact] - public async Task A_side_holding_two_logins_of_one_provider_is_MergeLoginsAmbiguous_and_stores_nothing() - { - using var host = new HeimdallHost(realSessions: true); - var me = await SignedIn(host); - SetList(host, "discord", "discord"); - - var done = await Finish(host, me, await Begin(host, me, MergeSide.Self), me.Account, host.Token(me.Account)); - - Assert.Equal(Page + "?result=merge_logins_ambiguous", Location(done)); - Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId)); - } - - [Fact] - public async Task A_completion_in_another_browsers_session_holds_nothing() - { - using var host = new HeimdallHost(realSessions: true); - var me = await SignedIn(host); - var them = await SignedIn(host); - SetList(host, "discord"); - - var done = await Finish(host, me, await Begin(host, me, MergeSide.Self), me.Account, host.Token(me.Account), sessionOverride: them.Session); - - Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId)); - Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(them.UserAccountId)); - Assert.Empty(host.Heimdall.ListAuthorizations); - Assert.Equal(Page + "?result=error", Location(done)); - } - - [Fact] - public async Task A_merge_proof_starts_only_through_a_provider_the_member_names() - { - using var host = new HeimdallHost(realSessions: true); - var me = await SignedIn(host); - var auth = host.Services.GetRequiredService(); - var before = host.Heimdall.StartBodies.Count; - - await Assert.ThrowsAsync(() => auth.StartMergeProveSelfAsync(me.Account, null, Page, Callback, [], CancellationToken.None)); - await Assert.ThrowsAsync(() => auth.StartMergeProveOtherAsync(me.Account, "github", Page, Callback, [], CancellationToken.None)); - - Assert.Equal(before, host.Heimdall.StartBodies.Count); - } -} diff --git a/tests/Bifrost.Web.Tests/MergeProofsTests.cs b/tests/Bifrost.Web.Tests/MergeProofsTests.cs deleted file mode 100644 index 5c28e48..0000000 --- a/tests/Bifrost.Web.Tests/MergeProofsTests.cs +++ /dev/null @@ -1,243 +0,0 @@ -using Bifrost.Web.Features.Heimdall; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Tests.Support; - -namespace Bifrost.Web.Tests; - -/// The in-memory holder of merge proofs: per actor, expiring, never consuming, bearer-free in every view. -public sealed class MergeProofsTests -{ - private const string Secret = "BEARER-CANARY"; - - private readonly TestClock _clock = new(); - private readonly MergeProofs _proofs; - private readonly Guid _actor = Guid.NewGuid(); - private readonly Guid _self = Guid.NewGuid(); - private readonly Guid _other = Guid.NewGuid(); - private readonly string _selfAccount = HeimdallShapes.NewAccountId(); - private readonly string _otherAccount = HeimdallShapes.NewAccountId(); - - public MergeProofsTests() => _proofs = new MergeProofs(_clock); - - private static LinkedIdentitySummary Login(string provider) => new(Guid.NewGuid().ToString(), provider, "Name of " + provider, null); - - private MergeProof Proof(string account, string provider, string? token = null) => new(token ?? Secret + provider, account, provider); - - private PutOutcome PutSelf(string provider, params LinkedIdentitySummary[] logins) => - _proofs.Put(_actor, MergeSide.Self, Proof(_selfAccount, provider), _self, logins); - - private PutOutcome PutOther(string provider, params LinkedIdentitySummary[] logins) => - _proofs.Put(_actor, MergeSide.Other, Proof(_otherAccount, provider), _other, logins); - - [Fact] - public void Peek_gives_one_actor_their_own_proofs_and_never_consumes() - { - var selfLogin = Login("discord"); - var otherLogin = Login("patreon"); - Assert.Equal(PutOutcome.Stored, PutSelf("discord", selfLogin)); - Assert.Equal(PutOutcome.Stored, PutOther("patreon", otherLogin)); - - var first = Assert.IsType(_proofs.Peek(_actor, MergeSide.Self)); - var second = Assert.IsType(_proofs.Peek(_actor, MergeSide.Self)); - - Assert.Equal("discord", first.Survivor.Provider); - Assert.Equal("patreon", Assert.Single(first.Folded).Provider); - Assert.Equal(first.Survivor, second.Survivor); - Assert.Equal(first.Folded, second.Folded); - Assert.IsType(_proofs.Peek(Guid.NewGuid(), MergeSide.Self)); - Assert.Null(_proofs.Snapshot(Guid.NewGuid()).Self); - Assert.Null(_proofs.Snapshot(Guid.NewGuid()).Other); - } - - [Fact] - public void Peek_runs_both_ways_the_survivor_is_chosen_by_the_caller() - { - PutSelf("discord", Login("discord")); - PutOther("patreon", Login("patreon")); - - var ready = Assert.IsType(_proofs.Peek(_actor, MergeSide.Other)); - - Assert.Equal(_otherAccount, ready.Survivor.HeimdallAccountId); - Assert.Equal(_selfAccount, Assert.Single(ready.Folded).HeimdallAccountId); - } - - [Fact] - public void Clear_removes_both_sides_and_only_that_actors() - { - PutSelf("discord", Login("discord")); - PutOther("patreon", Login("patreon")); - var stranger = Guid.NewGuid(); - _proofs.Put(stranger, MergeSide.Self, Proof(_selfAccount, "discord"), _self, [Login("discord")]); - - _proofs.Clear(_actor); - - Assert.IsType(_proofs.Peek(_actor, MergeSide.Self)); - Assert.Equal(new MergeProofsView(null, null), _proofs.Snapshot(_actor)); - Assert.NotNull(_proofs.Snapshot(stranger).Self); - } - - [Theory] - [InlineData(269, true)] - [InlineData(270, false)] - [InlineData(271, false)] - public void A_proof_lives_270_seconds_from_its_redeem(int seconds, bool alive) - { - PutSelf("discord", Login("discord")); - PutOther("patreon", Login("patreon")); - - _clock.Advance(TimeSpan.FromSeconds(seconds)); - - Assert.Equal(alive, _proofs.Peek(_actor, MergeSide.Self) is PeekResult.Ready); - Assert.Equal(alive, _proofs.Snapshot(_actor).Self is not null); - } - - [Fact] - public void One_lapsed_proof_costs_only_that_provider_and_a_newer_proof_replaces_the_older() - { - var discord = Login("discord"); - var patreon = Login("patreon"); - PutSelf("twitch", Login("twitch")); - PutOther("discord", discord, patreon); - _clock.Advance(TimeSpan.FromSeconds(200)); - PutOther("patreon", discord, patreon); - _clock.Advance(TimeSpan.FromSeconds(100)); // the discord proof is 300 s old, the patreon one 100 s - - var self = PutSelf("twitch", Login("twitch")); // keeps the self side alive - var unproved = Assert.IsType(_proofs.Peek(_actor, MergeSide.Self)); - - Assert.Equal(PutOutcome.Stored, self); - Assert.Equal(["discord"], unproved.Providers); - - PutOther("discord", discord, patreon); - var ready = Assert.IsType(_proofs.Peek(_actor, MergeSide.Self)); - Assert.Equal(["discord", "patreon"], ready.Folded.Select(x => x.Provider).Order().ToArray()); - var replacedAt = Assert.IsType(_proofs.Snapshot(_actor).Other); - Assert.Equal(["discord", "patreon"], replacedAt.ProvedProviders.Order().ToArray()); - } - - [Fact] - public void A_login_list_with_two_logins_of_one_provider_is_refused_and_stores_nothing() - { - var outcome = PutOther("discord", Login("discord"), Login("discord")); - - Assert.Equal(PutOutcome.AmbiguousLogins, outcome); - Assert.Null(_proofs.Snapshot(_actor).Other); - } - - [Fact] - public void A_folded_side_with_an_unproved_provider_names_providers_and_nothing_else() - { - PutSelf("discord", Login("discord")); - PutOther("patreon", Login("patreon"), Login("twitch"), Login("google")); - - var unproved = Assert.IsType(_proofs.Peek(_actor, MergeSide.Self)); - - Assert.Equal(["google", "twitch"], unproved.Providers.Order().ToArray()); - Assert.DoesNotContain(Secret, unproved.ToString()); - } - - [Fact] - public void A_proof_for_another_account_on_a_side_replaces_the_side_and_the_old_proofs_are_not_mixed_in() - { - PutOther("patreon", Login("patreon"), Login("twitch")); - var someoneElse = Guid.NewGuid(); - var elsewhere = HeimdallShapes.NewAccountId(); - - _proofs.Put(_actor, MergeSide.Other, Proof(elsewhere, "twitch"), someoneElse, [Login("twitch")]); - - var view = Assert.IsType(_proofs.Snapshot(_actor).Other); - Assert.Equal(someoneElse, view.UserAccountId); - Assert.Equal(["twitch"], view.ProvedProviders); - } - - [Fact] - public void A_side_holds_at_most_eight_proofs() - { - var providers = Enumerable.Range(0, MergeProofs.MaxProofsPerSide + 1).Select(x => "p" + x).ToArray(); - var logins = providers.Select(Login).ToArray(); - - var outcomes = providers.Select(p => PutOther(p, logins)).ToArray(); - - Assert.All(outcomes.Take(MergeProofs.MaxProofsPerSide), x => Assert.Equal(PutOutcome.Stored, x)); - Assert.Equal(PutOutcome.TooManyProofs, outcomes[^1]); - Assert.Equal(MergeProofs.MaxProofsPerSide, _proofs.Snapshot(_actor).Other!.ProvedProviders.Count); - } - - [Fact] - public void Undo_needs_every_moved_login_proved_and_returns_only_the_selfs_proofs() - { - var discord = Login("discord"); - var patreon = Login("patreon"); - var twitch = Login("twitch"); - PutSelf("discord", discord, patreon, twitch); - PutOther("twitch", Login("twitch")); - - var missing = Assert.IsType(_proofs.PeekUndo(_actor, [discord.Id, patreon.Id])); - PutSelf("patreon", discord, patreon, twitch); - var ready = Assert.IsType(_proofs.PeekUndo(_actor, [discord.Id, patreon.Id])); - - Assert.Equal(["patreon"], missing.Providers); - Assert.Equal(["discord", "patreon"], ready.Proofs.Select(x => x.Provider).Order().ToArray()); - Assert.All(ready.Proofs, x => Assert.Equal(_selfAccount, x.HeimdallAccountId)); - Assert.IsType(_proofs.PeekUndo(_actor, [discord.Id, Guid.NewGuid().ToString()])); - Assert.IsType(_proofs.PeekUndo(Guid.NewGuid(), [discord.Id])); - } - - [Fact] - public void No_view_or_printed_result_holds_a_bearer() - { - PutSelf("discord", Login("discord")); - PutOther("patreon", Login("patreon")); - var ready = _proofs.Peek(_actor, MergeSide.Self); - - var printed = string.Join('\n', _proofs.Snapshot(_actor), ready, ready is PeekResult.Ready r ? r.Survivor : null, _proofs.PeekUndo(_actor, ["x"])); - - Assert.DoesNotContain(Secret, printed); - Assert.DoesNotContain(_selfAccount, printed); - Assert.DoesNotContain(_otherAccount, printed); - } - - /// Actors with anything in memory: pruning drops a side with no proof and an actor with no side. - private int HeldProofs() => - ((System.Collections.IDictionary)typeof(MergeProofs).GetField("_held", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(_proofs)!) - .Count; - - [Fact] - public void An_expired_bearer_is_dropped_by_any_later_access_even_one_for_another_actor() - { - PutSelf("discord", Login("discord")); - Assert.Equal(1, HeldProofs()); - _clock.Advance(MergeProofs.ProofLifetime + TimeSpan.FromSeconds(1)); - - _proofs.Clear(Guid.NewGuid()); - - Assert.Equal(0, HeldProofs()); - } - - [Fact] - public void PruneExpired_drops_an_expired_bearer_with_no_other_access_and_keeps_a_live_one() - { - PutSelf("discord", Login("discord")); - _clock.Advance(MergeProofs.ProofLifetime); - _proofs.PruneExpired(); - Assert.Equal(0, HeldProofs()); - - PutSelf("discord", Login("discord")); - _clock.Advance(MergeProofs.ProofLifetime - TimeSpan.FromSeconds(1)); - _proofs.PruneExpired(); - Assert.Equal(1, HeldProofs()); - } - - [Fact] - public void Two_sides_holding_a_login_of_one_provider_are_a_conflict_named_by_provider_only_in_both_directions() - { - PutSelf("discord", Login("discord"), Login("twitch")); - PutOther("patreon", Login("patreon"), Login("discord"), Login("twitch")); - - foreach (var survivor in new[] { MergeSide.Self, MergeSide.Other }) - { - var conflict = Assert.IsType(_proofs.Peek(_actor, survivor)); - Assert.Equal(["discord", "twitch"], conflict.Providers); - } - } -} diff --git a/tests/Bifrost.Web.Tests/MergeStatusTests.cs b/tests/Bifrost.Web.Tests/MergeStatusTests.cs deleted file mode 100644 index 780c151..0000000 --- a/tests/Bifrost.Web.Tests/MergeStatusTests.cs +++ /dev/null @@ -1,222 +0,0 @@ -using System.Net; -using System.Text.RegularExpressions; -using Bifrost.Web.Data; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Membership; -using Bifrost.Web.Tests.Support; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using static Bifrost.Web.Tests.AccountMergeSagaTests; - -namespace Bifrost.Web.Tests; - -/// -/// What the merge pages show each member, from browser sessions of the real host over the saga rig: the notice in the layout and the -/// page itself, for the survivor inside the grace, for a frozen or folded account, and for everyone else (nothing). -/// -public sealed class MergeStatusTests -{ - private static string Enc(string text) => System.Text.Encodings.Web.HtmlEncoder.Default.Encode(text); - - private static int Notices(string html) => Regex.Matches(html, "class=\"merge-notice\"").Count; - - private sealed record World(Rig Rig, Party Survivor, Party Folded, Party Stranger, string SurvivorSession, string FoldedSession, string StrangerSession, Guid MergeId); - - private static async Task Open(string[]? foldedLogins = null) - { - var rig = new Rig(realSessions: true); - var survivor = await rig.AccountAsync("quill-9f3a", "twitch"); - var folded = await rig.AccountAsync("banks-2d7c", foldedLogins ?? ["discord"]); - var stranger = await rig.AccountAsync("stranger-51e0", "twitch"); - // Sessions exist before the merge, as a member's browser does. - var sessions = new[] { survivor, folded, stranger }; - var cookies = new List(); - foreach (var who in sessions) - { - cookies.Add(await rig.Host.SignInSessionAsync(who.HeimdallId)); - } - - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), [.. (foldedLogins ?? ["discord"]).Select(x => rig.Weak(folded, x))]); - return new World(rig, survivor, folded, stranger, cookies[0], cookies[1], cookies[2], id); - } - - private static async Task Committed(string[]? foldedLogins = null) - { - var world = await Open(foldedLogins); - Assert.Equal(AccountMergeState.Committed, (await world.Rig.AdvanceAsync(world.MergeId)).State); - return world; - } - - private static async Task Html(World world, string session, string url = MergePage.Url) - { - using var client = world.Rig.Host.NewClient(); - using var request = new HttpRequestMessage(HttpMethod.Get, url); - request.Headers.Add("Cookie", $"{Bifrost.Web.Features.Shared.BifrostCookies.Session}={session}"); - using var response = await client.SendAsync(request); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - return await response.Content.ReadAsStringAsync(); - } - - private static async Task Edit(World world, Action change) - { - using var scope = world.Rig.Host.Services.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - var merge = await db.AccountMerges.SingleAsync(x => x.Id == world.MergeId); - change(merge); - await db.SaveChangesAsync(); - } - - [Fact] - public async Task The_survivor_sees_days_left_and_the_weak_note_on_the_page_and_one_notice_in_the_layout() - { - var w = await Committed(); - using var rig = w.Rig; - rig.Clock.Advance(TimeSpan.FromDays(2)); - var merge = await rig.MergeAsync(w.MergeId); - - var page = await Html(w, w.SurvivorSession); - - Assert.Contains(Enc(MergeWording.DaysLeft(5)), page); - Assert.Contains(Enc(MergeWording.TierNote("weak", merge.GraceEndsUtc!.Value)), page); - Assert.DoesNotContain(Enc(MergeWording.TierNote("strong", merge.GraceEndsUtc!.Value)), page); - Assert.Contains(Enc(MergeWording.State(AccountMergeState.Committed)), page); - Assert.Equal(1, Notices(page)); - Assert.Contains(Enc(MergeWording.SurvivorNotice(5)), page); - Assert.Equal(1, Notices(await Html(w, w.SurvivorSession, "/Membership/Status"))); - } - - [Fact] - public async Task Past_the_grace_and_before_the_sweeper_there_is_no_notice_and_no_undo_offer() - { - var w = await Committed(); - using var rig = w.Rig; - var inside = await Html(w, w.SurvivorSession); - Assert.Equal(1, Notices(inside)); - Assert.Contains("To undo, sign in again", inside); - - rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromHours(1)); - Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(w.MergeId)).State); - var late = await Html(w, w.SurvivorSession); - - Assert.Equal(0, Notices(late)); - Assert.DoesNotContain("To undo, sign in again", late); - Assert.DoesNotContain("Undo this merge", late); - Assert.DoesNotContain("ProveForUndo", late); - Assert.DoesNotContain("can still be undone", late); - } - - [Fact] - public async Task Once_the_undo_is_requested_no_page_says_the_merge_can_still_be_undone() - { - var w = await Committed(); - using var rig = w.Rig; - await Edit(w, x => x.State = AccountMergeState.UndoRequested); - - var page = await Html(w, w.SurvivorSession); - - Assert.Equal(1, Notices(page)); - Assert.DoesNotContain("can still be undone", page); - Assert.DoesNotContain("can still undo", page); - Assert.Contains("Undo requested", page); - Assert.DoesNotContain("To undo, sign in again", page); - } - - [Fact] - public async Task A_strong_proof_merge_says_so_in_its_own_words() - { - var w = await Committed(); - using var rig = w.Rig; - await Edit(w, x => x.ProofFromTier = "strong"); - var merge = await rig.MergeAsync(w.MergeId); - - var page = await Html(w, w.SurvivorSession); - - Assert.NotEqual(MergeWording.TierNote("weak", merge.GraceEndsUtc!.Value), MergeWording.TierNote("strong", merge.GraceEndsUtc!.Value)); - Assert.Contains(Enc(MergeWording.TierNote("strong", merge.GraceEndsUtc!.Value)), page); - } - - [Fact] - public async Task No_notice_for_a_merge_that_is_Final_Undone_or_Failed_and_none_for_another_member() - { - var w = await Committed(); - using var rig = w.Rig; - Assert.Equal(1, Notices(await Html(w, w.SurvivorSession))); - Assert.Equal(0, Notices(await Html(w, w.StrangerSession))); - Assert.DoesNotContain(Enc(MergeWording.State(AccountMergeState.Committed)), await Html(w, w.StrangerSession)); - - rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromHours(1)); - await rig.InScopeAsync(sp => sp.GetRequiredService().FinalizeDueAsync(rig.Clock.Now, default)); - var final = await Html(w, w.SurvivorSession); - Assert.Equal(AccountMergeState.Final, (await rig.MergeAsync(w.MergeId)).State); - Assert.Equal(0, Notices(final)); - Assert.Contains("/Membership/MergeStatus", await Html(w, w.SurvivorSession, "/Membership/Status")); - Assert.DoesNotContain("/Membership/MergeStatus", await Html(w, w.StrangerSession, "/Membership/Status")); - Assert.Contains(Enc(MergeWording.State(AccountMergeState.Final)), final); - - foreach (var state in new[] { AccountMergeState.Undone, AccountMergeState.Failed }) - { - await Edit(w, x => { x.State = state; x.FinalizedUtc = null; }); - var page = await Html(w, w.SurvivorSession); - Assert.Equal(0, Notices(page)); - Assert.Contains(Enc(MergeWording.State(state)), page); - } - } - - [Theory] - [InlineData(AccountMergeState.Undone)] - [InlineData(AccountMergeState.Failed)] - [InlineData(AccountMergeState.Final)] - public async Task A_merge_that_ended_has_no_notice_even_with_its_grace_date_still_ahead(AccountMergeState state) - { - var w = await Committed(); - using var rig = w.Rig; - await Edit(w, x => x.State = state); - - var page = await Html(w, w.SurvivorSession); - - Assert.Equal(0, Notices(page)); - Assert.Contains(Enc(MergeWording.State(state)), page); - } - - [Fact] - public async Task A_failed_merge_says_why_in_closed_words_and_never_echoes_the_stored_text() - { - var w = await Committed(); - using var rig = w.Rig; - await Edit(w, x => { x.State = AccountMergeState.Failed; x.FailureCode = "proof_stale"; x.LastOutcome = "HEIMDALL FREE TEXT"; }); - - var page = await Html(w, w.SurvivorSession); - - Assert.Contains(Enc(MergeWording.Failure("proof_stale")!), page); - Assert.Contains(Enc(MergeWording.Outcome("HEIMDALL FREE TEXT")!), page); - Assert.DoesNotContain("HEIMDALL FREE TEXT", page); - Assert.DoesNotContain("proof_stale", page); - } - - [Fact] - public async Task A_frozen_account_reaches_the_page_and_is_told_the_merge_is_in_progress() - { - var w = await Open(); - using var rig = w.Rig; - - var page = await Html(w, w.FoldedSession); - - Assert.Equal(1, Notices(page)); - Assert.Contains(Enc(MergeWording.FrozenNotice()), page); - Assert.Contains(Enc(MergeWording.State(AccountMergeState.Confirmed)), page); - } - - [Fact] - public async Task A_folded_account_reaches_the_page_is_told_when_it_was_merged_and_cannot_undo() - { - var w = await Committed(); - using var rig = w.Rig; - var merge = await rig.MergeAsync(w.MergeId); - - var page = await Html(w, w.FoldedSession); - - Assert.Equal(1, Notices(page)); - Assert.Contains(Enc(MergeWording.FoldedNotice(merge.CommittedUtc!.Value)), page); - Assert.DoesNotContain(" -/// The merge status page's undo from the person's side: browser sessions of the real host over the saga rig and the fake Heimdall's -/// account model. The folded person signs in through a login the merge moved and is the survivor there. -/// -public sealed class MergeUndoPageTests -{ - private const string Callback = "https://localhost"; - - /// The Heimdall account that holds a login now, by the fake's own model of where a move left it. - private static string OwnerOf(Rig rig, string loginId) => - rig.Moves.Logins.Single(x => x.Value.Any(l => l.Id == loginId)).Key; - - private sealed class World(Rig rig, Party survivor, Party folded, Guid mergeId) : IDisposable - { - public Rig Rig { get; } = rig; - - public Party Survivor { get; } = survivor; - - public Party Folded { get; } = folded; - - public Guid MergeId { get; } = mergeId; - - public HeimdallHost Host => Rig.Host; - - /// Everything a response put on the wire: bodies, Location, Set-Cookie. The privacy test reads it at the end. - public List Surface { get; } = []; - - /// Every bearer the test redeemed; none may appear on the surface. - public List Bearers { get; } = []; - - public void Dispose() => Rig.Dispose(); - - public async Task SignInThrough(string provider) => await Host.SignInSessionAsync(OwnerOf(Rig, Folded.Logins[provider]), provider); - - public async Task<(MergePage.Antiforgery Token, HttpResponseMessage Response)> Post(string session, MergePage.Antiforgery? token, string handler, params (string, string)[] form) - { - token ??= await MergePage.TokenAsync(Host, session); - var response = await MergePage.PostAsync(Host, session, token, handler, form.ToDictionary(x => x.Item1, x => x.Item2)); - Record(response, string.Empty); - return (token, response); - } - - public void Record(HttpResponseMessage response, string body) => - Surface.Add(body + "\n" + MergePage.Location(response) + "\n" + string.Join('\n', response.Headers.Select(x => x.Key + string.Concat(x.Value)))); - - public async Task Page(string session, string query = "") - { - var (response, html) = await MergePage.GetAsync(Host, session, query); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Record(response, html); - return html; - } - - public IReadOnlyList MovedIds(AccountMerge merge) => JsonSerializer.Deserialize(merge.MovedIdentityIds!)!; - - /// One fresh sign-in of the survivor's account through a moved login of , as the page's button and Heimdall's return do. - public async Task Prove(string session, MergePage.Antiforgery token, string provider) - { - var merge = await Rig.MergeAsync(MergeId); - var before = Host.Heimdall.StartBodies.Count; - var (_, started) = await Post(session, token, "ProveForUndo", ("via", provider)); - Assert.Equal(HttpStatusCode.Redirect, started.StatusCode); - var attempt = Host.AttemptFrom(started, before); - Assert.NotEmpty(attempt.Nonce); - - Host.Heimdall.Identities.Clear(); - Host.Heimdall.AddIdentity("twitch", id: Survivor.Logins["twitch"]); - foreach (var moved in MovedIds(merge)) - { - Host.Heimdall.AddIdentity(Rig.Moves.Logins.Values.SelectMany(x => x).Single(x => x.Id == moved).Provider, id: moved); - } - - var bearer = Host.Token(Survivor.HeimdallId); - Rig.Moves.Issue(Survivor.HeimdallId, Folded.Logins[provider], bearer: bearer); - Bearers.Add(bearer); - var done = await Host.PostCompleteAsync( - new Dictionary { ["attempt"] = attempt.Nonce, ["code"] = Host.CodeFor(attempt, Survivor.HeimdallId, bearer, provider: provider) }, - $"{Bifrost.Web.Features.Shared.BifrostCookies.Session}={session}; {attempt.CookieName}={attempt.Cookie}"); - Record(done, string.Empty); - Assert.Equal(MergePage.Url + "?result=merge_proof_recorded", MergePage.Location(done)); - } - } - - private static async Task Committed(params string[] foldedLogins) - { - var rig = new Rig(realSessions: true); - var survivor = await rig.AccountAsync("quill-9f3a", "twitch"); - var folded = await rig.AccountAsync("banks-2d7c", foldedLogins); - var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), [.. foldedLogins.Select(x => rig.Weak(folded, x))]); - Assert.Equal(AccountMergeState.Committed, (await rig.AdvanceAsync(id)).State); - return new World(rig, survivor, folded, id); - } - - private static string Undo(World w, string code) => $"{MergePage.Url}?undo={code}"; - - [Fact] - public async Task A_sign_in_through_a_login_the_merge_moved_lands_on_the_survivors_account_not_the_folded_one() - { - using var w = await Committed("discord"); - - // Heimdall answers a sign-in through the moved login with the account that holds the login now. - var landedOn = OwnerOf(w.Rig, w.Folded.Logins["discord"]); - Assert.Equal(w.Survivor.HeimdallId, landedOn); - var session = await w.Host.SignInSessionAsync(landedOn, "discord"); - - // The survivor acts (the folded account would be refused on this page: its actor has no account). - var (response, _) = await w.Host.GetLinkedAccountsAsync(session); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } - - [Fact] - public async Task Undo_needs_a_fresh_proof_of_every_moved_login_and_the_missing_provider_is_named() - { - using var w = await Committed("discord", "patreon"); - var session = await w.SignInThrough("discord"); - var token = await MergePage.TokenAsync(w.Host, session); - - await w.Prove(session, token, "discord"); - var page = await w.Page(session); - Assert.Contains("Patreon", page); - var asked = w.Rig.Moves.Requests.Count; - - var (_, refused) = await w.Post(session, token, "Undo", ("mergeId", w.MergeId.ToString())); - - Assert.Equal(Undo(w, "logins_unproved"), MergePage.Location(refused)); - Assert.Equal(asked, w.Rig.Moves.Requests.Count); - var merge = await w.Rig.MergeAsync(w.MergeId); - Assert.Equal(AccountMergeState.Committed, merge.State); - Assert.Null(merge.UndoRequestedUtc); - Assert.Contains(Enc(MergeWording.Undo("logins_unproved")), await w.Page(session, "?undo=logins_unproved")); - } - - [Fact] - public async Task The_folded_person_proves_every_moved_login_and_the_undo_runs_once_to_Undone_and_spends_the_proofs() - { - using var w = await Committed("discord", "patreon"); - var session = await w.SignInThrough("patreon"); - var token = await MergePage.TokenAsync(w.Host, session); - await w.Prove(session, token, "discord"); - await w.Prove(session, token, "patreon"); - var asked = w.Rig.Moves.Requests.Count; - - var (_, done) = await w.Post(session, token, "Undo", ("mergeId", w.MergeId.ToString())); - - Assert.Equal(Undo(w, "requested"), MergePage.Location(done)); - Assert.Equal(AccountMergeState.Undone, (await w.Rig.MergeAsync(w.MergeId)).State); - Assert.Equal(asked + 1, w.Rig.Moves.Requests.Count); - Assert.Equal(new MergeProofsView(null, null), w.Host.Services.GetRequiredService().Snapshot(w.Survivor.Id)); - - // A replay has no proofs left and starts nothing. - var (_, replay) = await w.Post(session, token, "Undo", ("mergeId", w.MergeId.ToString())); - Assert.NotEqual(Undo(w, "requested"), MergePage.Location(replay)); - Assert.Equal(asked + 1, w.Rig.Moves.Requests.Count); - } - - [Fact] - public async Task Another_member_posting_the_survivors_undo_is_NotSurvivor_and_the_saga_is_never_asked() - { - using var w = await Committed("discord"); - var other = await w.Rig.AccountAsync("other-survivor-77c1", "twitch"); - var otherFolded = await w.Rig.AccountAsync("other-folded-08ab", "patreon"); - var otherMerge = await w.Rig.ConfirmedAsync(other, otherFolded, w.Rig.Weak(other, "twitch"), w.Rig.Weak(otherFolded, "patreon")); - await w.Rig.AdvanceAsync(otherMerge); - var session = await w.Host.SignInSessionAsync(other.HeimdallId); - var asked = w.Rig.Moves.Requests.Count; - - var (_, response) = await w.Post(session, null, "Undo", ("mergeId", w.MergeId.ToString())); - - Assert.Equal(Undo(w, "not_survivor"), MergePage.Location(response)); - Assert.Equal(asked, w.Rig.Moves.Requests.Count); - var merge = await w.Rig.MergeAsync(w.MergeId); - Assert.Equal(AccountMergeState.Committed, merge.State); - Assert.Null(merge.UndoRequestedUtc); - } - - [Fact] - public async Task A_post_after_the_grace_ended_is_GraceOver_with_live_proofs_and_nothing_is_requested() - { - using var w = await Committed("discord"); - var session = await w.SignInThrough("discord"); - var token = await MergePage.TokenAsync(w.Host, session); - w.Rig.Clock.Advance(AccountMergeLedger.Grace - TimeSpan.FromSeconds(60)); - await w.Prove(session, token, "discord"); - w.Rig.Clock.Advance(TimeSpan.FromSeconds(61)); - var asked = w.Rig.Moves.Requests.Count; - - var (_, response) = await w.Post(session, token, "Undo", ("mergeId", w.MergeId.ToString())); - - Assert.Equal(Undo(w, "grace_over"), MergePage.Location(response)); - Assert.Equal(asked, w.Rig.Moves.Requests.Count); - Assert.Equal(AccountMergeState.Committed, (await w.Rig.MergeAsync(w.MergeId)).State); - } - - [Fact] - public async Task A_reversal_Heimdall_refuses_returns_the_merge_to_Committed_and_the_page_words_the_refusal() - { - using var w = await Committed("discord"); - var session = await w.SignInThrough("discord"); - var token = await MergePage.TokenAsync(w.Host, session); - await w.Prove(session, token, "discord"); - w.Rig.Moves.MoveStatus = HttpStatusCode.BadRequest; - - var (_, response) = await w.Post(session, token, "Undo", ("mergeId", w.MergeId.ToString())); - - Assert.Equal(Undo(w, "requested"), MergePage.Location(response)); - var merge = await w.Rig.MergeAsync(w.MergeId); - Assert.Equal(AccountMergeState.Committed, merge.State); - Assert.StartsWith("undo_", merge.LastOutcome); - Assert.Contains(Enc(MergeWording.Outcome(merge.LastOutcome)!), await w.Page(session)); - } - - [Fact] - public async Task No_response_cookie_or_redirect_of_the_merge_pages_carries_an_account_id_name_or_bearer() - { - using var w = await Committed("discord", "patreon"); - var session = await w.SignInThrough("discord"); - var token = await MergePage.TokenAsync(w.Host, session); - await w.Page(session); - await w.Prove(session, token, "discord"); - await w.Prove(session, token, "patreon"); - await w.Page(session); - await w.Post(session, token, "Undo", ("mergeId", w.MergeId.ToString())); - await w.Page(session, "?undo=requested"); - - var everything = string.Join('\n', w.Surface); - var secrets = new List { "quill-9f3a", "banks-2d7c", w.Survivor.HeimdallId, w.Folded.HeimdallId }; - foreach (var id in new[] { w.Survivor.Id, w.Folded.Id }) - { - secrets.AddRange([id.ToString(), id.ToString("N")]); - } - - secrets.AddRange(w.Survivor.Logins.Values); - secrets.AddRange(w.Folded.Logins.Values); - secrets.AddRange(w.Bearers); - Assert.Equal(2, w.Bearers.Count); - Assert.All(secrets, x => Assert.DoesNotContain(x, everything)); - Assert.DoesNotContain("PUID-CANARY", everything); - Assert.DoesNotContain("username-canary", everything); - } - - private static string Enc(string text) => System.Text.Encodings.Web.HtmlEncoder.Default.Encode(text); -} diff --git a/tests/Bifrost.Web.Tests/MergeWordingTests.cs b/tests/Bifrost.Web.Tests/MergeWordingTests.cs deleted file mode 100644 index 6f63e89..0000000 --- a/tests/Bifrost.Web.Tests/MergeWordingTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System.Text.RegularExpressions; -using Bifrost.Web.Domain; -using Bifrost.Web.Features.Heimdall; -using Bifrost.Web.Features.Membership; - -namespace Bifrost.Web.Tests; - -/// The merge pages' words are a closed set: every state, refusal code and outcome the saga can store has one, and nothing the store holds is echoed. -public sealed class MergeWordingTests -{ - private static string Snake(HeimdallMoveRefusal code) => - code == HeimdallMoveRefusal.RequestInvalid ? "invalid_request" : Regex.Replace(code.ToString(), "(?().Select(MergeWording.State).ToArray(); - Assert.All(words, x => Assert.NotEmpty(x)); - Assert.Equal(words.Length, words.Distinct().Count()); - } - - [Fact] - public void Every_refusal_Heimdall_can_give_has_words_and_the_code_itself_is_not_one_of_them() - { - foreach (var code in Enum.GetValues().Select(Snake)) - { - var words = MergeWording.Failure(code); - Assert.False(string.IsNullOrWhiteSpace(words), code); - Assert.DoesNotContain(code, words!); - Assert.False(string.IsNullOrWhiteSpace(MergeWording.Outcome("undo_" + code)), code); - } - } - - [Theory] - [InlineData("confirmed")] - [InlineData("moved")] - [InlineData("refused")] - [InlineData("undo_requested")] - [InlineData("receipt_mismatch")] - [InlineData("proofs_unreadable")] - [InlineData("transport")] - [InlineData("move_id_conflict")] - [InlineData("malformed or mismatched receipt")] - public void Every_outcome_the_saga_stores_has_words(string outcome) => Assert.False(string.IsNullOrWhiteSpace(MergeWording.Outcome(outcome)), outcome); - - [Theory] - [InlineData("operator_failed", "ended")] - [InlineData("undo_operator_abandoned", "merge stands")] - public void An_operators_settle_has_its_own_words_not_the_retry_line(string outcome, string says) - { - var words = MergeWording.Outcome(outcome); - - Assert.Contains(says, words); - Assert.DoesNotContain("try again", words); - } - - [Theory] - [InlineData("HTTP 502")] - [InlineData("HEIMDALL FREE TEXT")] - [InlineData("undo_made_up_code")] - public void An_outcome_the_wording_does_not_know_is_a_generic_line_that_does_not_echo_it(string outcome) - { - var words = MergeWording.Outcome(outcome); - Assert.False(string.IsNullOrWhiteSpace(words)); - Assert.DoesNotContain(outcome, words!); - Assert.Null(MergeWording.Failure(outcome)); - } - - [Fact] - public void Every_undo_answer_has_distinct_words_and_a_closed_code() - { - UndoOutcome[] all = [new UndoOutcome.Requested(), new UndoOutcome.NotCommitted(), new UndoOutcome.GraceOver(), new UndoOutcome.NotSurvivor(), new UndoOutcome.ProofAccountMismatch()]; - var codes = all.Select(MergeWording.UndoCode).Append("logins_unproved").ToArray(); - Assert.Equal(6, codes.Distinct().Count()); - Assert.All(codes, x => Assert.False(string.IsNullOrWhiteSpace(MergeWording.Undo(x)), x)); - Assert.True(string.IsNullOrEmpty(MergeWording.Undo("anything else"))); - } -} diff --git a/tests/Bifrost.Web.Tests/Support/FakeMoves.cs b/tests/Bifrost.Web.Tests/Support/FakeMoves.cs deleted file mode 100644 index f1b7abd..0000000 --- a/tests/Bifrost.Web.Tests/Support/FakeMoves.cs +++ /dev/null @@ -1,381 +0,0 @@ -using System.Net; -using System.Text; -using System.Text.Json; - -namespace Bifrost.Web.Tests.Support; - -/// One login of a fake account. -public sealed record MoveLogin(string Id, string Provider); - -/// A move Heimdall stored: the forward move or its reversal, with the receipt it answered byte for byte. -public sealed class StoredMove(string moveId, string from, string to, string? reversesMoveId, IReadOnlyList carried, string receipt) -{ - public string MoveId { get; } = moveId; - - public string From { get; } = from; - - public string To { get; } = to; - - public string? ReversesMoveId { get; } = reversesMoveId; - - public IReadOnlyList Carried { get; } = carried; - - public string Receipt { get; } = receipt; - - public bool Reversed { get; set; } -} - -/// -/// The fake Heimdall's account model for identity moves, and the route over it: POST /v1/apps/bifrost/identity-moves as Heimdall's -/// moveIdentitiesRoute and decideMove answer it (docs/service-contract.md at 4fe367a). It owns per-account logins, a registry of the -/// bearers it issued (token to claims), revoked sessions and stored moves. Nothing else of the fake reads these yet; the linked -/// accounts list can read later so one model answers both routes. -/// -public sealed class FakeMoves(Func now) -{ - private const string App = "bifrost"; - private const int WeakSeconds = 300; - private const int StrongSeconds = 600; - private const int Lifetime = 900; - - private sealed record Claims(string Account, string Sid, string Aud, long AuthAt, string? AuthIdentityId, long? StepUpAt, string? StepUpMethod, long Exp); - - private readonly Dictionary _tokens = new(StringComparer.Ordinal); - private readonly HashSet _revoked = new(StringComparer.Ordinal); - private readonly Dictionary _moves = new(StringComparer.Ordinal); - - public Dictionary> Logins { get; } = new(StringComparer.Ordinal); - - public IReadOnlyCollection Stored => _moves.Values; - - /// Every request that reached the route: the app secret header, the Authorization header and the raw body. - public List<(string? Secret, string? Authorization, string Body)> Requests { get; } = []; - - /// When false the app's profile lacks identityMoves, so the route answers 403 not_allowed_for_app. - public bool Granted { get; set; } = true; - - /// When set, the route answers this status after the schema check, bypassing the fake's own rules (nothing is applied). - public HttpStatusCode? MoveStatus { get; set; } - - /// When set, a move that passes every rule is applied and then answered with this status (200 answers a body that is not JSON): a lost answer. - public HttpStatusCode? MoveApplyThenFail { get; set; } - - /// When set, the route throws it instead of answering, as an unreachable or timed-out Heimdall does. - public Exception? MoveDown { get; set; } - - public string AddLogin(string account, string provider, string? id = null) - { - id ??= Guid.NewGuid().ToString(); - if (!Logins.TryGetValue(account, out var list)) - { - Logins[account] = list = []; - } - - list.Add(new MoveLogin(id, provider)); - return id; - } - - /// - /// Issues a live bearer of for the bifrost app. A weak proof is a sign-in through - /// at before now ( registers a token another fake minted, such as the sign-in's JWT, so one string is a proof at both); a step-up () adds step_up_at at before now. - /// - public string Issue(string account, string? authIdentityId = null, string? stepUpMethod = null, int authAgo = 0, int? stepUpAgo = null, string aud = App, string? bearer = null) - { - var at = now().ToUnixTimeSeconds(); - var token = bearer ?? "bearer-" + Guid.NewGuid().ToString("N"); - _tokens[token] = new Claims( - account, Guid.NewGuid().ToString(), aud, at - authAgo, authIdentityId, - stepUpMethod is null ? null : at - (stepUpAgo ?? 0), stepUpMethod, at + Lifetime); - return token; - } - - public bool IsRevoked(string token) => _revoked.Contains(_tokens[token].Sid); - - /// Heimdall serializes a move by its id; so does the fake, because concurrent callers (the saga tests that race two advances) share its dictionaries. - public HttpResponseMessage Route(HttpRequestMessage request, string body, string? requiredSecret) - { - lock (_moves) - { - return RouteLocked(request, body, requiredSecret); - } - } - - private HttpResponseMessage RouteLocked(HttpRequestMessage request, string body, string? requiredSecret) - { - var secret = request.Headers.TryGetValues("x-heimdall-app-secret", out var values) ? values.Single() : null; - Requests.Add((secret, request.Headers.Authorization?.ToString(), body)); - if (MoveDown is not null) - { - throw MoveDown; - } - - if (Parse(body) is not { } move) - { - return Json(HttpStatusCode.BadRequest, """{"error":"invalid_request","detail":"body: must match the schema"}"""); - } - - if (MoveStatus is { } forced) - { - return forced == HttpStatusCode.NotFound - ? new HttpResponseMessage(forced) - : Json(forced, forced == HttpStatusCode.BadRequest - ? """{"error":"invalid_request","detail":"body: must match the schema"}""" - : """{"error":"server_error","detail":"HEIMDALL FREE TEXT"}"""); - } - - if (secret != requiredSecret) - { - return Refuse(HttpStatusCode.Unauthorized, "app_auth_required"); - } - - if (!Granted) - { - return Refuse(HttpStatusCode.Forbidden, "not_allowed_for_app"); - } - - var applied = Decide(move); - if (applied.Refusal is { } refusal || MoveApplyThenFail is not { } lost) - { - return applied.Refusal ?? Ok(applied.Receipt!); - } - - return lost == HttpStatusCode.OK ? Json(HttpStatusCode.OK, "not json {") : Json(lost, """{"error":"server_error","detail":"HEIMDALL FREE TEXT"}"""); - } - - private sealed record Move(string MoveId, string[] FromProofs, string? ToProof, string[]? IdentityIds, string? ReversesMoveId); - - private static readonly System.Text.RegularExpressions.Regex MoveIdShape = new(@"^[A-Za-z0-9_-]{16,64}\z"); - - /// - /// Heimdall's route schema (app.ts, the identity-moves route): moveId pattern, 1 to 8 fromProofs of 1 to 8192 chars, toProof, 1 to 32 - /// unique non-empty identityIds, reversesMoveId pattern; and oneOf: a forward move has toProof and no reversesMoveId, a reversal has - /// reversesMoveId and neither toProof nor identityIds. Unknown properties are stripped. Anything else is a 400. - /// - private static Move? Parse(string body) - { - try - { - var root = JsonDocument.Parse(body).RootElement; - if (root.ValueKind != JsonValueKind.Object) - { - return null; - } - - var bad = false; - string? Text(string name, int min, int max, bool pattern) - { - if (!root.TryGetProperty(name, out var v)) - { - return null; - } - - if (v.ValueKind != JsonValueKind.String || v.GetString() is not { } t || t.Length < min || t.Length > max || (pattern && !MoveIdShape.IsMatch(t))) - { - bad = true; - return null; - } - - return t; - } - - string[]? List(string name, int max, int maxLength, bool unique) - { - if (!root.TryGetProperty(name, out var v)) - { - return null; - } - - if (v.ValueKind != JsonValueKind.Array || v.GetArrayLength() is 0 || v.GetArrayLength() > max - || v.EnumerateArray().Any(x => x.ValueKind != JsonValueKind.String || x.GetString() is not { Length: > 0 } t || t.Length > maxLength)) - { - bad = true; - return null; - } - - var items = v.EnumerateArray().Select(x => x.GetString()!).ToArray(); - bad |= unique && items.Distinct().Count() != items.Length; - return items; - } - - var id = Text("moveId", 16, 64, true); - var from = List("fromProofs", 8, 8192, false); - var to = Text("toProof", 1, 8192, false); - var ids = List("identityIds", 32, int.MaxValue, true); - var reverses = Text("reversesMoveId", 16, 64, true); - var forward = to is not null && reverses is null; - var reversal = reverses is not null && to is null && ids is null; - return bad || id is null || from is null || !(forward || reversal) ? null : new Move(id, from, to, ids, reverses); - } - catch (JsonException) - { - return null; - } - } - - /// moveIdentitiesRoute then decideMove at 4fe367a, in their order; each comment names the check. - private (HttpResponseMessage? Refusal, string? Receipt) Decide(Move move) - { - var at = now().ToUnixTimeSeconds(); - var reversal = move.ReversesMoveId is not null; - - // Replay: the stored move answers before any proof is judged live; proofs need only be signed for the stored accounts. - if (_moves.TryGetValue(move.MoveId, out var stored)) - { - var same = move.ReversesMoveId == stored.ReversesMoveId - && move.FromProofs.All(x => Known(x)?.Account == stored.From) - && (reversal ? move.ToProof is null : Known(move.ToProof!)?.Account == stored.To); - return same ? (null, stored.Receipt) : (Refuse(HttpStatusCode.Conflict, "move_id_conflict"), null); - } - - StoredMove? forward = null; - if (reversal && !(_moves.TryGetValue(move.ReversesMoveId!, out forward) && forward.ReversesMoveId is null)) - { - return (Refuse(HttpStatusCode.Conflict, "not_reversible"), null); - } - - var from = new List(); - foreach (var token in move.FromProofs) - { - if (Live(token) is not { } claims) - { - return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "from"), null); - } - - from.Add(claims); - } - - var source = from[0].Account; - if (from.Any(x => x.Account != source)) - { - return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "from"), null); - } - - Claims? to = null; - if (!reversal && (to = Live(move.ToProof!)) is null) - { - return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "to"), null); - } - - if (reversal && source != forward!.To) - { - return (Refuse(HttpStatusCode.Conflict, "not_reversible"), null); - } - - var destination = to?.Account ?? forward!.From; - if (source == destination) - { - return (Refuse(HttpStatusCode.Conflict, "same_account"), null); - } - - if (from.Any(x => Tier(x, at) is null)) - { - return (Refuse(HttpStatusCode.Forbidden, "proof_stale", proof: "from"), null); - } - - if (to is not null && Tier(to, at) is null) - { - return (Refuse(HttpStatusCode.Forbidden, "proof_stale", proof: "to"), null); - } - - // proofCovers: a strong passkey proof speaks for the account, else the login the sign-in came through, else nothing. - var coverage = from.Select(x => Tier(x, at) == "strong" && x.StepUpMethod == "bifrost-passkey" ? "account" : x.AuthIdentityId).ToArray(); - if (coverage.All(x => x is null)) - { - return (Refuse(HttpStatusCode.Forbidden, "identity_not_proved"), null); - } - - // decideMove: reversal or alias, the logins chosen (held ones only), coverage of them, then the destination's providers. - var held = Logins.GetValueOrDefault(source) ?? []; - if (reversal) - { - if (forward!.Reversed || forward.Carried.Any(id => held.All(x => x.Id != id))) - { - return (Refuse(HttpStatusCode.Conflict, "not_reversible"), null); - } - } - else if (IsAlias(source) || IsAlias(destination)) - { - return (Refuse(HttpStatusCode.Conflict, "already_moved"), null); - } - - var wanted = reversal ? forward!.Carried : move.IdentityIds; - if (wanted is not null && wanted.Any(id => held.All(x => x.Id != id))) - { - return (Refuse(HttpStatusCode.NotFound, "identity_not_found"), null); - } - - var moving = held.Where(x => wanted is null || wanted.Contains(x.Id)).ToList(); - if (moving.Count == 0) - { - return (Refuse(HttpStatusCode.NotFound, "identity_not_found"), null); - } - - if (!coverage.Contains("account") && moving.Any(x => !coverage.Contains(x.Id))) - { - return (Refuse(HttpStatusCode.Forbidden, "identity_not_proved"), null); - } - - var there = Logins.GetValueOrDefault(destination) ?? []; - if (moving.FirstOrDefault(x => there.Any(y => y.Provider == x.Provider)) is { } clash) - { - return (Refuse(HttpStatusCode.Conflict, "provider_conflict", provider: clash.Provider), null); - } - - // The move: re-home, revoke the source's sessions, store the receipt. - held.RemoveAll(moving.Contains); - Logins[destination] = [.. there, .. moving]; - foreach (var claims in _tokens.Values.Where(x => x.Account == source)) - { - _revoked.Add(claims.Sid); - } - - var strong = from.Any(x => Tier(x, at) == "strong"); - var receipt = new Dictionary - { - ["moveId"] = move.MoveId, - ["accountId"] = destination, - ["movedIdentityIds"] = moving.Select(x => x.Id).ToArray(), - ["proof"] = new Dictionary { ["from"] = strong ? "strong" : "weak", ["to"] = to is null ? null : Tier(to, at) } - }; - if (move.ReversesMoveId is not null) - { - receipt["reversesMoveId"] = move.ReversesMoveId; - } - - var json = JsonSerializer.Serialize(receipt); - _moves[move.MoveId] = new StoredMove(move.MoveId, source, destination, move.ReversesMoveId, moving.Select(x => x.Id).ToArray(), json); - if (forward is not null) - { - forward.Reversed = true; - } - - return (null, json); - } - - private bool IsAlias(string account) => - (Logins.GetValueOrDefault(account)?.Count ?? 0) == 0 && _moves.Values.Any(x => x.From == account && x.ReversesMoveId is null && !x.Reversed); - - private Claims? Known(string token) => _tokens.TryGetValue(token, out var claims) && claims.Aud == App ? claims : null; - - private Claims? Live(string token) => - Known(token) is { } claims && !_revoked.Contains(claims.Sid) && claims.Exp > now().ToUnixTimeSeconds() ? claims : null; - - /// proofTier: strong inside 600 s of step_up_at, else weak inside 300 s of auth_at; a future-dated claim proves nothing. - private static string? Tier(Claims claims, long at) => - claims.StepUpAt is { } stepUp && stepUp <= at && at - stepUp <= StrongSeconds ? "strong" - : claims.AuthAt <= at && at - claims.AuthAt <= WeakSeconds ? "weak" : null; - - private static HttpResponseMessage Json(HttpStatusCode status, string json) => - new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; - - private static HttpResponseMessage Ok(string receipt) - { - var response = Json(HttpStatusCode.OK, receipt); - response.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue { NoStore = true }; - return response; - } - - private static HttpResponseMessage Refuse(HttpStatusCode status, string error, string? proof = null, string? provider = null) => - Json(status, JsonSerializer.Serialize(new Dictionary { ["error"] = error, ["proof"] = proof, ["provider"] = provider } - .Where(x => x.Value is not null).ToDictionary())); -} diff --git a/tests/Bifrost.Web.Tests/Support/FaultOnSave.cs b/tests/Bifrost.Web.Tests/Support/FaultOnSave.cs deleted file mode 100644 index 3d27f15..0000000 --- a/tests/Bifrost.Web.Tests/Support/FaultOnSave.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Diagnostics; - -namespace Bifrost.Web.Tests.Support; - -/// -/// Armed by a test, it throws on the save its predicate picks and lets every other save through: a crash between two writes (the -/// SaveChangesInterceptor seam of AccountMergeLedgerTests). The host's contexts all carry it, so a crash in the saga's own scope is real. -/// -public sealed class FaultOnSave : SaveChangesInterceptor -{ - public Func? When { get; set; } - - public override ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) => - When is { } when && when(eventData.Context!) ? throw new InvalidOperationException("injected save failure") : ValueTask.FromResult(result); -} diff --git a/tests/Bifrost.Web.Tests/Support/MergePageKit.cs b/tests/Bifrost.Web.Tests/Support/MergePageKit.cs deleted file mode 100644 index 64ca4e1..0000000 --- a/tests/Bifrost.Web.Tests/Support/MergePageKit.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Text.RegularExpressions; -using Bifrost.Web.Features.Shared; -using Bifrost.Web.Tests.Support; - -namespace Bifrost.Web.Tests.Support; - -/// The merge status page as a browser uses it: a GET with the session, a POST with the antiforgery pair the page itself handed out. -internal static class MergePage -{ - public const string Url = "/Membership/MergeStatus"; - - public const string AccountsUrl = "/Membership/MergeAccounts"; - - public sealed record Antiforgery(string Token, string Cookie); - - public static async Task<(HttpResponseMessage Response, string Html)> GetAsync(HeimdallHost host, string session, string query = "", string url = Url) - { - using var client = host.NewClient(); - using var request = new HttpRequestMessage(HttpMethod.Get, url + query); - request.Headers.Add("Cookie", $"{BifrostCookies.Session}={session}"); - var response = await client.SendAsync(request); - return (response, await response.Content.ReadAsStringAsync()); - } - - /// The antiforgery pair from a page of this member that carries a form. - public static async Task TokenAsync(HeimdallHost host, string session, string url = Url) - { - var (response, html) = await GetAsync(host, session, "", url); - var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value; - Assert.NotEmpty(token); - return new Antiforgery(token, HeimdallHost.CookieValue(response, BifrostCookies.Antiforgery)!); - } - - public static async Task PostAsync( - HeimdallHost host, string session, Antiforgery antiforgery, string handler, IDictionary form, string url = Url) - { - using var client = host.NewClient(); - var fields = new Dictionary(form) { ["__RequestVerificationToken"] = antiforgery.Token }; - using var request = new HttpRequestMessage(HttpMethod.Post, $"{url}?handler={handler}") { Content = new FormUrlEncodedContent(fields) }; - request.Headers.Add("Cookie", $"{BifrostCookies.Session}={session}; {BifrostCookies.Antiforgery}={antiforgery.Cookie}"); - return await client.SendAsync(request); - } - - public static string? Location(HttpResponseMessage response) => response.Headers.Location?.OriginalString; -}