Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3414143125 | |||
|
|
6e705852fb | ||
|
|
870b475795 | ||
|
|
11fc87c8e4 | ||
|
|
8bcd6d67e9 | ||
|
|
1480883a3b | ||
| b688fec8e0 | |||
|
|
63b9596ff1 | ||
|
|
e60953e469 | ||
|
|
a92638511c | ||
|
|
6606f8e6e6 | ||
|
|
ca726c057a | ||
|
|
6bd3ce4371 | ||
|
|
a8c489b0d0 | ||
|
|
c0b7b6a857 | ||
|
|
817363e366 | ||
|
|
a1ee88cdbb | ||
|
|
ed3645e048 | ||
|
|
5ddfca9b55 | ||
|
|
ec28dffba1 | ||
|
|
8175e5ed99 | ||
|
|
24a880ad4c | ||
|
|
e9a2e29c61 | ||
|
|
1924433af2 | ||
|
|
7bf284876a | ||
|
|
3907259cb3 | ||
|
|
5fbb673c55 | ||
|
|
8175f6f61e | ||
|
|
0599aedf08 | ||
| 2d9eb868bf | |||
|
|
757ca2eeab | ||
|
|
a2172349ba | ||
|
|
b47a6557cb | ||
|
|
41f4cc3853 | ||
|
|
cdf64b2a10 | ||
|
|
c62166c6ce | ||
|
|
f726101207 | ||
|
|
5df08bd94a | ||
|
|
41189e14d3 | ||
|
|
10fc9803d7 | ||
|
|
537a477dc3 | ||
|
|
b7b33bc5db | ||
|
|
aa348d3b43 | ||
|
|
1ffb8886c0 | ||
|
|
f402eb13cc | ||
|
|
baa70bcef0 | ||
|
|
13ab2e3be7 | ||
|
|
84ff2c4578 | ||
|
|
fbb5853b1d | ||
|
|
b54cf27101 | ||
|
|
ee700d4931 | ||
| 425af74500 | |||
| c20947af1c | |||
|
|
18f1ec6aca | ||
|
|
8e65f56b0c | ||
|
|
b65bec65ce | ||
|
|
59ecaa606b | ||
| 9a716cfd7e | |||
| ae0037c159 | |||
|
|
96665a778b | ||
|
|
3b0a614ee9 | ||
|
|
d29f8014f9 | ||
|
|
25ce117f16 | ||
|
|
f04b20feed | ||
| e58e9531df | |||
|
|
1771f15789 | ||
|
|
1739d5552a | ||
| 920ecb1fbe | |||
|
|
1298e7db1e | ||
|
|
f9d0c24f66 | ||
| dc151e6cac | |||
|
|
1fbe16eb73 | ||
|
|
4c9937f881 | ||
|
|
95416653ba | ||
| d1d13992aa | |||
|
|
1998f0e6ae | ||
|
|
31ced94f2a | ||
| b687da954b | |||
|
|
87a1bb6b3b | ||
|
|
c085cead9d | ||
| fe0ff40864 | |||
|
|
280d843aeb | ||
|
|
25b9cc1683 | ||
|
|
95d2e8d262 | ||
| b80b27da0f | |||
| 420a4dbf85 | |||
|
|
e639e13a8b | ||
|
|
46cf7d4492 | ||
|
|
a3bab9b8e5 | ||
|
|
beafbe18e2 | ||
|
|
8a3262b3e8 | ||
|
|
ee88bc709d | ||
|
|
abeb8a1d5f | ||
|
|
6c4c9c00f9 | ||
|
|
2aabaabc53 | ||
|
|
99128e9f90 | ||
|
|
8abd912917 |
118 changed files with 20227 additions and 415 deletions
12
AGENTS.md
12
AGENTS.md
|
|
@ -80,3 +80,15 @@ Then start the first implementation milestone:
|
||||||
- work items
|
- work items
|
||||||
- motions
|
- motions
|
||||||
- ledgers
|
- ledgers
|
||||||
|
|
||||||
|
## Live Postgres tests
|
||||||
|
|
||||||
|
Most tests run on the in-memory EF provider, which enforces no unique index, transaction, concurrency token or trigger. The tests that need a real server (`tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs`: commit atomicity, the `(MergeId, Seq)` unique index, the sweeper racing the saga, overlapping merges refused by the database, the one-current-Patron-snapshot index under racing restages, the intake journal `Seq`, the write gate's shared lock racing a merge's freeze and commit, the migration's roll-forward-only guard) run only when `BIFROST_TEST_PG` holds a connection string with no `Database=`, for a role that may create databases; otherwise they are skipped with that reason. Each test creates its own database, builds it through the real migrations and the class drops it, so point the variable at a disposable server:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
BIFROST_TEST_PG='Host=127.0.0.1;Port=54329;Username=postgres' dotnet test tests/Bifrost.Web.Tests --filter FullyQualifiedName~AccountMergePostgresTests
|
||||||
|
```
|
||||||
|
|
||||||
|
## Account merges are roll-forward only
|
||||||
|
|
||||||
|
Once any `AccountMerges` row exists, do not deploy a build older than the `AddAccountMerges` migration, and do not revert that migration: an older build cannot read the `Merged` membership status and counts voided votes again. `Down` refuses while any merge row exists. Fix forward (`heimdall-body:ruling:merge-roll-forward-only`, `docs/account-merge.md` Rollback). Any deploy list that names a rollback must say so.
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ This repository now includes a viable alpha foundation slice of the ASP.NET Core
|
||||||
- Razor Pages app under `src/Bifrost.Web`
|
- Razor Pages app under `src/Bifrost.Web`
|
||||||
- PostgreSQL-backed EF Core model with an initial migration under `src/Bifrost.Web/Data/Migrations`
|
- PostgreSQL-backed EF Core model with an initial migration under `src/Bifrost.Web/Data/Migrations`
|
||||||
- Bifrost-native identity registration plus GitHub OAuth and Heimdall-linked provider identities, with invite/approval-based membership gating
|
- Bifrost-native identity registration plus GitHub OAuth and Heimdall-linked provider identities, with invite/approval-based membership gating
|
||||||
|
- a Linked accounts page where a member sees, links and unlinks their Heimdall provider logins, with unlink gated on a strong proof: a WebAuthn passkey (enrolled behind a fresh sign-in, 48 hour cooling-off), or a fresh Google step-up for an account with none ([docs/linked-accounts.md](docs/linked-accounts.md), [docs/passkeys.md](docs/passkeys.md))
|
||||||
- explicit member roles and admin-managed patron or contributor tier snapshots
|
- explicit member roles and admin-managed patron or contributor tier snapshots
|
||||||
- patron support event recording with derived patron point summaries and tier refresh for voting weight
|
- patron support event recording with derived patron point summaries and tier refresh for voting weight
|
||||||
- shared work board with estimates, actual time logs, review flow, and GitHub issue or PR links
|
- shared work board with estimates, actual time logs, review flow, and GitHub issue or PR links
|
||||||
|
|
|
||||||
136
docs/account-merge.md
Normal file
136
docs/account-merge.md
Normal file
|
|
@ -0,0 +1,136 @@
|
||||||
|
# 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 <id>)`. 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:<survivor>` 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_<code>`. |
|
||||||
|
| 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=<iso>&limit=<n> -> 200 JSON array, oldest first by (occurred_at, merge_id, kind)
|
||||||
|
POST /api/merge-notices/chat/ack {"merge_id": "...", "type": "merged"} -> 204
|
||||||
|
```
|
||||||
|
|
||||||
|
Payload, exactly these keys: `type` (`merged`, `undone`, `final`), `merge_id`, `occurred_at` (the matching timestamp, ISO 8601 UTC), `grace_ends_at`, `old_subject` (the folded `UserAccount.Id`, format D, the OIDC `sub` the chat session knew), `new_subject` (the survivor's), `old_preferred_username`, `new_preferred_username` (`NormalizedBifrostIdentity`). `limit` defaults to 50 and is capped at 200. Acks are the cursor: a read returns every unacked notice; `after` only narrows the scan to notices strictly later than that time, so a reader must not skip unacked ones by it. An ack is idempotent (a repeat is 204); an ack for a (merge, kind) the feed would not emit now, such as `undone` for a merge not undone, is 404; a malformed body or unknown `type` is 400.
|
||||||
|
|
||||||
|
Auth: `Authorization: Bearer <token>`, compared in constant time after SHA-256 of both sides against `ChatNotices:Token` (environment `ChatNotices__Token`). An empty token turns both routes off (404). A missing or wrong bearer is 401 with an empty body. No cookie, no CORS, `Cache-Control: no-store`. Startup does not require the token.
|
||||||
|
|
||||||
|
```
|
||||||
|
curl -sS -H "Authorization: Bearer $TOKEN" "$BIFROST/api/merge-notices/chat?limit=50"
|
||||||
|
curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
|
||||||
|
-d '{"merge_id":"<merge_id>","type":"merged"}' "$BIFROST/api/merge-notices/chat/ack"
|
||||||
|
```
|
||||||
|
|
||||||
|
The feed carries no email, display name, Heimdall id, Matrix id or history flag. It is information for the chat operator's side; back-channel logout (`OidcLogoutReconciler`) stays what ends chat sessions. Chat-side rules that bind Bifrost already hold: undo is refused past Final, and `preferred_username` never changes. A later reader (StreamPixels) adds a target constant and its own token over the same derivation.
|
||||||
|
|
||||||
|
Deploy: set `ChatNotices__Token` on Bifrost and hand the same value to the chat host's timer script (the secret's path is the chat steward's).
|
||||||
|
|
||||||
|
## Merged is terminal
|
||||||
|
|
||||||
|
Only the ledger writes `Membership.Status = Merged` or leaves it. The other status writers refuse a merged row (`Membership.IsMerged`): the bootstrap-admin promotion (startup and every GitHub sign-in, which is the one status write sign-in sync makes on an existing account) skips it, the Heimdall member-access claim does not activate it, member approval refuses it and the suspension service reports `NotApplicable`. Folded standing itself is still derived from the merge state, never from this status.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
@ -255,13 +255,13 @@ Golden bytes: `tests/fixtures/persona-chat-v5/` (`chat_pending.v3.tail` carries
|
||||||
|
|
||||||
### Follow (`basis` `"follow"`, `CHAT_FOLLOW=1`)
|
### Follow (`basis` `"follow"`, `CHAT_FOLLOW=1`)
|
||||||
|
|
||||||
A message from someone she is in conversation with is for her even when it names no one. **It is off unless the mouth runs with `CHAT_FOLLOW=1`** (exactly `1`; default off), because Huginn's parser refuses an unknown basis until its `Basis::Follow` (and the one `is_for` line) lands. With the flag off the mouth emits no `follow`, makes no extra read, and keeps no follow state.
|
A message from someone she is in conversation with is for her even when it names no one. **It is off unless the mouth runs with `CHAT_FOLLOW=1`** (exactly `1`; default off), because the basis is Huginn's `Basis::FollowUp`, wire string `follow` (`FOLLOW_UP_BASIS`, f09bc56e), and a Huginn that predates it refuses the string. With the flag off the mouth emits no `follow`, makes no extra read, and keeps no follow state.
|
||||||
|
|
||||||
With it on:
|
With it on:
|
||||||
|
|
||||||
- **Anchor.** Her own post in a public room anchors that room for W = 600 s from the post. The mouth anchors at send time (the send's own time, in `send`, in the background: the send receipt never waits on the room-state read) and also from the /sync echo of her own events, so a post from another client of her account anchors too; one event anchors once. Only her posting again re-anchors the room and re-snapshots who is counted; a follow never extends the window.
|
- **Anchor.** Her own post in a public room anchors that room for W = 600 s from the post. The mouth anchors at send time (the send's own time, in `send`, in the background: the send receipt never waits on the room-state read) and also from the /sync echo of her own events, so a post from another client of her account anchors too; one event anchors once. Only her posting again re-anchors the room and re-snapshots who is counted; a follow never extends the window.
|
||||||
- **Counted senders** (snapshotted at the post): those who spoke in that room in the 10 minutes before the post (a per-room ring of recent senders with event times, 200 entries), plus anyone the post tagged (`m.mentions.user_ids`) or replied to (the author of the quoted `m.in_reply_to`, not a thread fallback pointer) when the event carries it. Someone who first speaks after her post is not counted. A member who spoke in the 10 minutes before her post is counted, bounded by 3 follows per hour per (peer, room). Nothing reads message text; no ids are scraped from bodies. She herself, and bridged senders (the `platformEvent` identifier rule), never count.
|
- **Counted senders** (snapshotted at the post): those who spoke in that room in the 10 minutes before the post (a per-room ring of recent senders with event times, 200 entries), plus anyone the post tagged (`m.mentions.user_ids`) or replied to (the author of the quoted `m.in_reply_to`, not a thread fallback pointer) when the event carries it. Someone who first speaks after her post is not counted. A member who spoke in the 10 minutes before her post is counted, bounded by 3 follows per hour per (peer, room). Nothing reads message text; no ids are scraped from bodies. She herself, and bridged senders (the `platformEvent` identifier rule), never count.
|
||||||
- **Follow.** A `message` (not an edit, not a notice) from a counted sender gets `follow` when it would otherwise have no basis or `room`; `tag`, `reply` and `direct` are never replaced. Its timestamp must lie inside the window (a homeserver clock up to 60 s behind still follows) and this process's clock must not be past the window's end by more than 60 s, so an old or forged `origin_server_ts` reuses nothing. At most K = 3 per (Mind, peer, room) in the hour before the message; past it the message keeps the basis it had.
|
- **Follow.** A `message` (not an edit, not a notice) from a counted sender gets `follow` only when it would otherwise have no basis (a plain message); `room` (@room), `tag`, `reply` and `direct` keep their own basis, and an @room neither wakes via follow nor spends the peer's K. Its timestamp must lie inside the window (a homeserver clock up to 60 s behind still follows) and this process's clock must not be past the window's end by more than 60 s, so an old or forged `origin_server_ts` reuses nothing. At most K = 3 per (Mind, peer, room) in the hour before the message; past it the message keeps the basis it had.
|
||||||
- **"Public" means non-DM, non-encrypted, non-bridged.** The room is not one of her DMs and its state has no `m.room.encryption`, `m.bridge` or `uk.half-shot.bridge` (read once per room, kept 5 minutes; unreadable or malformed state is not public). An invite-only plaintext room counts as public. Nothing is anchored in, and no follow is delivered in, any other room.
|
- **"Public" means non-DM, non-encrypted, non-bridged.** The room is not one of her DMs and its state has no `m.room.encryption`, `m.bridge` or `uk.half-shot.bridge` (read once per room, kept 5 minutes; unreadable or malformed state is not public). An invite-only plaintext room counts as public. Nothing is anchored in, and no follow is delivered in, any other room.
|
||||||
|
|
||||||
State is in memory only (per-room anchor, sender ring, follow times), purged on every sync pass; nothing is stored, and a restart only shortens windows.
|
State is in memory only (per-room anchor, sender ring, follow times), purged on every sync pass; nothing is stored, and a restart only shortens windows.
|
||||||
|
|
|
||||||
|
|
@ -41,7 +41,7 @@ Bifrost head `bf83a93` (2026-10-10; `20d5efa` plus the prior-art note, docs only
|
||||||
|
|
||||||
### Data Protection on the live host
|
### Data Protection on the live host
|
||||||
|
|
||||||
18. The live env file sets no `DataProtection__KeysPath` (key names only: `AllowedHosts`, `Bootstrap__*`, `ConnectionStrings__Bifrost`, `GitHubApp__EnableWebhookSync`, `GitHubOAuth__*`, `Heimdall__*`, `Host__*`, `Stripe__*`). So `Program.cs:113-119` never calls `PersistKeysToFileSystem`, and ASP.NET Core's default applies: the service runs as `bifrost` with `HOME=/srv/bifrost`, and the key ring is `/srv/bifrost/.aspnet/DataProtection-Keys` with two keys (created 2026-04-22 and 2026-07-22, the 90-day roll; prior-art note `docs/research/anonymous-vote-stuffing-prior-art.md:65-69`). A third, unused directory `/srv/bifrost/data-protection-keys` holds one key from 2026-07-15. Keys therefore persist across restarts today by accident of `HOME`, not by configuration.
|
18. The live env file sets no `DataProtection__KeysPath` (key names only: `AllowedHosts`, `Bootstrap__*`, `ConnectionStrings__Bifrost`, `GitHubApp__EnableWebhookSync`, `GitHubOAuth__*`, `Heimdall__*` (the app secret as `Heimdall__AppSecret`; `Heimdall__AppSecretFile` is the replacement), `Host__*`, `Stripe__*`). So `Program.cs:113-119` never calls `PersistKeysToFileSystem`, and ASP.NET Core's default applies: the service runs as `bifrost` with `HOME=/srv/bifrost`, and the key ring is `/srv/bifrost/.aspnet/DataProtection-Keys` with two keys (created 2026-04-22 and 2026-07-22, the 90-day roll; prior-art note `docs/research/anonymous-vote-stuffing-prior-art.md:65-69`). A third, unused directory `/srv/bifrost/data-protection-keys` holds one key from 2026-07-15. Keys therefore persist across restarts today by accident of `HOME`, not by configuration.
|
||||||
19. The service's working directory resolves to the release directory: `readlink /proc/<MainPID>/cwd` = `/srv/bifrost/app/releases/20260723-daedcc4`. Data Protection's default application discriminator is the content-root path (prior-art note `:67`), so every deploy into a new release directory isolates payloads protected by the previous release: auth cookies, antiforgery tokens and any future device token stop decrypting after each deploy. Mechanism from source docs plus this probe; not observed as logged-out users. `SetApplicationName` is not called anywhere (`git grep SetApplicationName bf83a93` is empty).
|
19. The service's working directory resolves to the release directory: `readlink /proc/<MainPID>/cwd` = `/srv/bifrost/app/releases/20260723-daedcc4`. Data Protection's default application discriminator is the content-root path (prior-art note `:67`), so every deploy into a new release directory isolates payloads protected by the previous release: auth cookies, antiforgery tokens and any future device token stop decrypting after each deploy. Mechanism from source docs plus this probe; not observed as logged-out users. `SetApplicationName` is not called anywhere (`git grep SetApplicationName bf83a93` is empty).
|
||||||
|
|
||||||
### Proxy and client address
|
### Proxy and client address
|
||||||
|
|
|
||||||
|
|
@ -54,9 +54,16 @@ permits, windows and `MaxTrackedKeys`.
|
||||||
|
|
||||||
New since the live release, and not read by the validator:
|
New since the live release, and not read by the validator:
|
||||||
|
|
||||||
- **`Heimdall__AppSecret`**: required for Discord and Patreon sign-in. Without it `HeimdallOptions.IsDiscordConfigured` and
|
- **`Heimdall__AppSecretFile`**: the preferred way to give Bifrost the app secret below. A path to a file holding it (one
|
||||||
`IsPatreonConfigured` are false and those sign-ins stop working (GitHub sign-in is unaffected); startup does not fail,
|
trailing newlines are trimmed), for example `%d/heimdall-app-secret` under systemd `LoadCredential=`, so the secret never
|
||||||
so a missing key shows only at the live check. The value is Heimdall's app secret for slug `bifrost`
|
rides in the process environment. When set, the file wins over `Heimdall__AppSecret`; a missing, unreadable or empty file
|
||||||
|
stops startup in every environment, with a message that names the option and path and never the value. Ops steps:
|
||||||
|
`docs/heimdall-app-secret-file.md`.
|
||||||
|
- **`Heimdall__AppSecret`** (deprecated; use `Heimdall__AppSecretFile`; startup logs a warning when it is set): required for
|
||||||
|
Discord and Patreon sign-in. Outside Development and Testing startup fails when neither this nor
|
||||||
|
`Heimdall__AppSecretFile` supplies a non-blank secret (the message names both options, never a value), because
|
||||||
|
`HeimdallOptions.IsDiscordConfigured` and `IsPatreonConfigured` would otherwise be false and those sign-ins silently
|
||||||
|
stop working (GitHub sign-in is unaffected). The value is Heimdall's app secret for slug `bifrost`
|
||||||
(`GC_ACCESS_APP_BIFROST_SHARED_SECRET` on the Heimdall side). Bifrost sends it as `x-heimdall-app-secret`, redacted
|
(`GC_ACCESS_APP_BIFROST_SHARED_SECRET` on the Heimdall side). Bifrost sends it as `x-heimdall-app-secret`, redacted
|
||||||
from logs.
|
from logs.
|
||||||
- **`Bifrost__Oidc__*`**: optional. Absent, the OIDC issuer is not mapped and discovery answers 404. Present, it must be
|
- **`Bifrost__Oidc__*`**: optional. Absent, the OIDC issuer is not mapped and discovery answers 404. Present, it must be
|
||||||
|
|
@ -129,7 +136,7 @@ All must hold before step 1. A missing one means the window is not used.
|
||||||
not a workstation.
|
not a workstation.
|
||||||
6. **Env diff done.** Every row of the Configuration table is marked present by the reader, `ConceptVotes__NetworkTagSecret`
|
6. **Env diff done.** Every row of the Configuration table is marked present by the reader, `ConceptVotes__NetworkTagSecret`
|
||||||
included and at least 32 characters (a count, not the value), and the `Heimdall__AppSecret` line is in `bifrost.env`
|
included and at least 32 characters (a count, not the value), and the `Heimdall__AppSecret` line is in `bifrost.env`
|
||||||
(mode 600, owner `bifrost`) with Heimdall holding the same value. Nothing in "Configuration" is left unresolved.
|
(mode 600, owner `bifrost`; a build with the empty-secret refusal does not start without it or `Heimdall__AppSecretFile`) with Heimdall holding the same value. Nothing in "Configuration" is left unresolved.
|
||||||
7. **Quiet.** No motion closing and no known vote in flight inside the window. Check the motions page. Members told that
|
7. **Quiet.** No motion closing and no known vote in flight inside the window. Check the motions page. Members told that
|
||||||
everyone is signed out once (see "What moves").
|
everyone is signed out once (see "What moves").
|
||||||
8. **Watchdog.** `bifrost-watchdog-notice.timer` fires one minute after boot and one minute after each run
|
8. **Watchdog.** `bifrost-watchdog-notice.timer` fires one minute after boot and one minute after each run
|
||||||
|
|
|
||||||
370
docs/feedback-receiver.md
Normal file
370
docs/feedback-receiver.md
Normal file
|
|
@ -0,0 +1,370 @@
|
||||||
|
# Feedback receiver
|
||||||
|
|
||||||
|
Status: **design, nothing implemented.** Written for `heimdall-body:follow_up:chat-s3533-3533`, updated for
|
||||||
|
`chat-s3549-3549`. It is the receiver half of Ratatoskr's Mind feedback pages. The page spec is Ratatoskr PR #24,
|
||||||
|
`docs/mind-feedback-pages.md` at b146000d, which I take as final here; its section 7a names this doc. The rulings it
|
||||||
|
builds on are Heimdall's drafts on guests and hiding (`/opt/commons/handoff/heimdall-feedback-pages-rulings.md`, cited as R4a to R6f).
|
||||||
|
|
||||||
|
Read at Bifrost main `b1725a1` (2026-11-12), line references re-read at `e58e953` (2026-11-12): `tools/persona-matrix-mouth.mjs`, `tools/persona-chat-documents.mjs`,
|
||||||
|
`src/Bifrost.Web/Features/{Oidc,Desk,Registration,Shared}/*`, `Domain/BifrostModels.cs`, `Program.cs`, `docs/oidc-issuer.md`,
|
||||||
|
`docs/ratatoskr-voting-auth.md`; the deployed trees under `/srv/bifrost` were last read at an earlier main (section 9). I could not read Eureka's receiver
|
||||||
|
notes in #minds, and `huginn-feedback-kinds-proposal.md` was not in `/opt/commons/handoff` when I looked. Where
|
||||||
|
PR #24 names a kind or a field it says the proposal wins, so I cite PR #24 and name the proposal's kinds only as PR #24 does.
|
||||||
|
Where source disagrees with either, the section says so.
|
||||||
|
|
||||||
|
Rulings of Meta, 2026-11-12, now written into this doc: erase redacts the answer text in the receiver's store and keeps a text-free record
|
||||||
|
(section 7a); the training notice covers any text entered into the app, bar a short exception list Eureka drafts (section 4a); the host may
|
||||||
|
withhold an answer from its Mind in an emergency, with a logged receipt (section 6a); Minds authenticate to the receiver through an OIDC
|
||||||
|
client with an audience, as the desk does (section 4b). Eureka's decisions on forks 2 to 5 of 2026-11-12 (`/opt/commons/handoff/bifrost-10-forks-2-5-recs-20261112.md`)
|
||||||
|
are folded into sections 2, 4b, 6a, 7a and 9 and close those forks, except where section 9 says a point is still open.
|
||||||
|
|
||||||
|
## Rulings of the steward (Heimdall, 2026-11-12)
|
||||||
|
|
||||||
|
Two of this doc's forks are the Bifrost steward's. Meta's, Eureka's and Libby's items are not ruled here.
|
||||||
|
|
||||||
|
1. **Ratatoskr's client for people: reading 2a, with no third client.** The one public PKCE client the desk-credential cut seeds for Ratatoskr (only when `Bifrost:Oidc:Clients:Ratatoskr` is configured, so absent config changes nothing) also gets a scope `feedback.answer` that puts audience `bifrost-feedback-page` on the token. Authorization code with PKCE only, exact redirect URIs, no refresh token, the token only in an `Authorization` header and never in a URL, a query or a log. The audience is distinct from the Mind's `bifrost-feedback`, so a person's token never opens a Mind endpoint and a Mind's never opens the page (least privilege). Reading 2b, a Matrix token checked at the homeserver, is refused: it is a bearer for the person's whole Matrix account. The receiver writes a text-free receipt per accepted submission (receipts).
|
||||||
|
2. **Token lifetimes are explicit, short, and set in the issuer change.** `feedback.answer` access token: 15 minutes, because the Bifrost session cookie re-issues it silently. The Mind's `client_credentials` token: 10 minutes, one call to renew. No refresh token for either. The desk's lifetime is its own decision and is not touched here. Until the issuer change lands the OpenIddict default applies; this doc no longer relies on it.
|
||||||
|
|
||||||
|
## 1. What the receiver owns
|
||||||
|
|
||||||
|
| Concern | Owner | Receiver's part |
|
||||||
|
|---|---|---|
|
||||||
|
| A question, its listing, status, hides, rulings | the owning Mind, in her own mind (Huginn) | reads them to build the projection; **never writes to Huginn** (an admission for another instance is refused `ForeignInstance`, PR #24 section 3) |
|
||||||
|
| An answer's **text** | the receiver | stores it; it is never admitted into a mind |
|
||||||
|
| The answer's **record** in the Mind | the owning Mind's Persona | she admits a text-free `feedback_answer` from the delivery, and acks after she has |
|
||||||
|
| What `kind` an account is | Bifrost (`Membership`, later `Role`) | reads it at answer time and stamps it |
|
||||||
|
| Delivery to the Mind | the receiver, at least once | keeps the record until the Persona acks |
|
||||||
|
| Hiding, closing, ruling | the owning Mind | **never**; a hide only changes what the projection serves |
|
||||||
|
| Erase | Bifrost's erase, executed here | redacts the text and name in the store, keeps a text-free record (section 7a) |
|
||||||
|
| Withholding an answer from its Mind | the host (emergency only) | logs a text-free withhold record and skips delivery; changes nothing stored or ruled (section 6a) |
|
||||||
|
| Who may answer | Bifrost: `Active`, a live training-notice receipt | checks both on every submission with text (section 4a) |
|
||||||
|
|
||||||
|
The page and the client write no record that carries identity (PR #24, section 3). A Matrix sender is a different identity
|
||||||
|
authority and never becomes `answerer`.
|
||||||
|
|
||||||
|
## 2. The mouth's pending/ack path, read from source
|
||||||
|
|
||||||
|
Verified in `tools/persona-matrix-mouth.mjs` and `tools/persona-chat-documents.mjs`; line numbers re-read at main `e58e953` (2026-11-12), where the mouth has grown by about 100 lines since `b1725a1` and nothing else in this section changed:
|
||||||
|
|
||||||
|
- **Pending is Matrix mail only, held in memory.** `pending` (mouth l.156) is filled in one place, `syncOnce`
|
||||||
|
(l.543; `pending.push(...made)` l.602), from Matrix `/sync` events. No function accepts a delivery from elsewhere.
|
||||||
|
- **A request is non-consuming; an ack consumes.** The pending requests carry `afterSeq`; the mouth answers
|
||||||
|
`pendingAfter(afterSeq)` (l.720) paged to 256 KiB (`pageOf`, l.1055-1084; `limits.replyBytes`, documents l.53). `chat_ack` carries `throughSeq`; `ack`
|
||||||
|
(l.662-665) drops every delivery at or below it, releases stored images (`images?.acked`) and advances the Matrix cursor. An ack posts nothing to
|
||||||
|
Matrix: her public `m.read` receipt follows a separate `chat_read` document (header l.10-13, `chat_read` branch l.1138). The endpoint serves a closed list of kinds
|
||||||
|
(`served`, l.1103) and answers any other loudly with `chat_refusal` `UnknownKind` (l.1112); a request for another Persona gets `UnknownPersona`.
|
||||||
|
- **At-least-once.** The Matrix cursor is persisted only when every delivery of a batch is acked (`commit`, l.619-627), so a
|
||||||
|
restart before the ack re-delivers from Matrix. `seqCounter` (l.155) is persisted whenever a round made deliveries (l.614), so
|
||||||
|
sequence numbers never repeat across a restart.
|
||||||
|
- **Backpressure.** At 500 unacked (`MAX_PENDING`, l.63) `syncOnce` stops reading (l.550). A truncated round (pending cap l.578, reply-read cap l.579)
|
||||||
|
leaves the cursor where it was (l.607).
|
||||||
|
- **A delivery that will not encode is skipped, not held.** `pageOf` logs and omits it (l.1060-1062); the caller's
|
||||||
|
next ack covers its seq, so it is dropped. Harmless for a chat line, wrong for a durable record.
|
||||||
|
- **The endpoint is loopback RUDP.** `startChatEndpoint` (l.1091) refuses a non-loopback host (l.1092). It is another process
|
||||||
|
from Bifrost.Web, which has no way to hand the mouth anything.
|
||||||
|
- **The delivery tuple is closed and versioned.** `deliveryTuple` is twelve fields (the twelfth is an optional stored-image reference), the pending answer
|
||||||
|
`gamecult.persona.chat_pending.v2` (`persona-chat-documents.mjs` l.216-224). v3 adds `basis` and `form` (14 fields) and a room tail (`chat_pending.v3`,
|
||||||
|
asked for by `chat_pending_request.v2`); v4 adds `reply_to` (15 fields, `chat_pending_request.v3`, served only with `CHAT_PENDING_V4=1`, `replyLinkFromEnv` l.1185). No version has a source or
|
||||||
|
kind field. A delivery cannot say it is not a Matrix message.
|
||||||
|
- **A fetch kind exists, off by default.** `chat_fetch_request` is served only with `CHAT_FETCH=1` (`served`, l.1103; `fetchFromEnv`, l.1187): an optional served kind is a precedent for adding kinds
|
||||||
|
to `served`, and the way a kind is withheld until its consumer is ready.
|
||||||
|
- **The consumer is not in this repo.** The mouth's header (l.10-11) says the heartbeat polls with a non-consuming
|
||||||
|
request and decides who runs. I could not confirm that from source.
|
||||||
|
|
||||||
|
What follows from it:
|
||||||
|
|
||||||
|
1. **Feedback cannot ride `pending` as it is.** There is no inlet, and the cursor logic ties acks to Matrix batches.
|
||||||
|
2. **A framed text delivery is forgeable.** Any Matrix member can write a line that looks like a frame, and no tuple has a
|
||||||
|
field to tell the Mind which one is real. The frame must be a typed difference in the wire, not a convention in `text`.
|
||||||
|
3. **A record that is not in Matrix is not re-delivered by a restart.** Feedback needs its own durable store and its own
|
||||||
|
delivery cursor.
|
||||||
|
|
||||||
|
PR #24 section 3 names the carrier: a new delivery document, `gamecult.persona.feedback_delivery.v1`, owned by Bifrost, through
|
||||||
|
the mouth's pending/ack path. Source adds one constraint on how it rides:
|
||||||
|
|
||||||
|
- **It cannot be a variant inside `chat_pending`.** Each version is a closed positional tuple (twelve, fourteen or fifteen fields) encoded by
|
||||||
|
`pageOf` (l.1060), so a different tuple in that page breaks every current consumer, and a text frame in `text` is forgeable by any Matrix member.
|
||||||
|
- **Option B, kept in shape:** the delivery document has its own request, page and ack kinds (`feedback_pending_request`, `feedback_pending`, `feedback_ack`), its own seq space and
|
||||||
|
a durable cursor over the receiver's store. The Matrix kinds, the Matrix cursor and `MAX_PENDING` are untouched. Per the decision below the kinds are served by the receiver over
|
||||||
|
HTTPS, not added to the mouth's `served` list (l.1103). Confidence medium: the Persona-side consumer, which I cannot see, must learn them.
|
||||||
|
- **Why main's changes reinforce B.** A chat `ack` releases stored images and advances the Matrix `/sync` cursor (l.662-665). A feedback ack must do neither, so it cannot
|
||||||
|
share the `chat_ack` kind or its `ack` function. The chat pending answer is already versioned three times, so a new field in that tuple is a new
|
||||||
|
document version for every consumer, which a feedback record must not force.
|
||||||
|
- Rejected: injecting records into `pending` as synthetic Matrix deliveries (no inlet, forgeable, lost on restart);
|
||||||
|
posting to a Matrix room as a bot (wrong identity authority, spam and forgery, and the Mind would read it as chat).
|
||||||
|
- **Decided (Eureka, 2026-11-12): feedback does not ride the mouth.** The endpoint is loopback RUDP with no bearer and trusts the persona id in the document, so
|
||||||
|
routing feedback through it would make the Matrix organ a bearer-less deputy holding every Mind's authority and would put the receiver's own seq space and durable
|
||||||
|
cursor in a Matrix process. A Mind pulls and acks **directly over HTTPS from her own process to the receiver, with the section 4b bearer**; she admits the text-free
|
||||||
|
record into her own mind afterwards. The three kinds `feedback_pending_request`, `feedback_pending`, `feedback_ack` are therefore HTTP endpoints of the receiver, not
|
||||||
|
kinds added to `served`; Option B's "same endpoint" clause is withdrawn and the mouth is untouched. The delivery document and its seq space are as above. This is a
|
||||||
|
Bifrost HTTP service, a xenos boundary for CultNet, so JSON/HTTP there is the tolerated kind. Pre-deploy test: section 9.
|
||||||
|
|
||||||
|
## 3. Records
|
||||||
|
|
||||||
|
One CultCache file, owned and written only by the receiver (section 8). Append-only through the API: nothing edits or
|
||||||
|
deletes a record except the redaction of section 7a. Every record has a `recordId` and a receiver-assigned `seq`
|
||||||
|
per owning Mind (the delivery sequence). PR #24 names the answer row `<question-label>.a<N>`, N the receiver's per-question
|
||||||
|
sequence; I use that for answers and the same shape for the others.
|
||||||
|
|
||||||
|
| Record | Fields | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `answer` | `recordId`, `questionId`, `owner`, `choice?` (an option label), `text?` (at most 2000 characters), `answerer`, `kind`, `weightPermille`, `nameAtAnswer`, `clientRequestId`, `time` | at least one of `choice`/`text`; an unknown option label is refused; the request id makes a retry idempotent, as `txnId = request_id` does in the mouth; `weightPermille` is 0 for a guest and 1000 otherwise, stamped, and the page sums nothing |
|
||||||
|
| `close_request` | `recordId`, `questionId`, `requester`, `kind`, `time` | refused for a guest and for an account not `active` at that moment (R4c) |
|
||||||
|
| `report` | `recordId`, `targetId`, `reporter`, `kind`, `reason`, `time` | delivered to the Mind as input; never shown, never counted (R6b) |
|
||||||
|
| `withhold`, `withholdLifted` | `recordId`, `answerRecordId`, `owner`, `withheldBy` or `liftedBy`, `time`, `reasonCode` (withhold only) | text-free log of section 6a |
|
||||||
|
| delivery state | per owning Mind: highest seq acked; per record: `delivered`, `failed`, `withheld` | a cursor, not a record the page reads |
|
||||||
|
|
||||||
|
Invariants: `answerer`, `kind`, `weightPermille`, `time` and `nameAtAnswer` come from the verified token and Bifrost state, never from the
|
||||||
|
request body, and the body schema is closed: an unknown key refuses the submission. The latest record per account is that
|
||||||
|
account's standing answer, derived at read time. A submission is refused if the question has no listing in force or is hidden.
|
||||||
|
An answer to a question that has settled is kept and the page says so (PR #24 section 8). A refused submission leaves nothing behind.
|
||||||
|
|
||||||
|
## 4. Credential and claims check
|
||||||
|
|
||||||
|
PR #24 section 7a rules **route 2** for people: Ratatoskr presents an OIDC access token that Bifrost issued, and Bifrost verifies it itself. Meta
|
||||||
|
ruled on 2026-11-12 that Minds authenticate to the receiver through an OIDC client with an audience, as the desk does (4b). This section records what
|
||||||
|
Bifrost's source does on main `e58e953` (the Oidc, Desk and Registration files cited here are unchanged since `b1725a1`, bar `DeskEndpoints.cs:49`, which registers `UnixSocketDeskDoor`).
|
||||||
|
|
||||||
|
### What main does with tokens
|
||||||
|
|
||||||
|
| Token | Who may get it | Gate at issue | Gate on use |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **Chat token** (scopes `openid`, `profile`; no audience) | an account that exists, has a Bifrost identity that is not reserved, and whose membership is not `Suspended`; membership is neither required nor written (`OidcEndpoints.cs:55-78`) | a live training-notice receipt: without one the member is redirected to the consent page and the parked request waits (`:104-111`) | the token and userinfo endpoints re-read it: `ChatRefusalAsync` refuses an absent or `Suspended` account and a chat token with no live receipt (`:164-180`, called at `:127` and `:144`) |
|
||||||
|
| **Desk token** (every scope is `desk.read` or `desk.answer`, `DeskEndpoints.cs:21-26`) | the same sign-in, then only a client whose permissions allow the desk scope | **no receipt**: `IsDeskToken` is true only when every scope is a desk scope (`:118`), so a desk token skips the gate (`:104`, `:108`); `principal.SetResources(DeskEndpoints.Audience)` puts audience `bifrost-desk` on it (`:91-94`) | per request, in `DeskEndpoints.HandleAsync`: audience (`DeskEndpoints.cs:110`), scope (`:116-121`), then `Active` membership re-read through `OidcEndpoints.ActiveMemberIdAsync` (`:123-139`; `OidcEndpoints.cs:183-194`, which is `CurrentBifrostActor.IsActiveMember`, `Status == Active`, `CurrentBifrostActor.cs:17`) |
|
||||||
|
|
||||||
|
The token claims are unchanged: `sub` is `UserAccount.Id` in form `D`; `preferred_username` and `name` ride the token only with scope `profile`
|
||||||
|
(`OidcEndpoints.cs:80-102`). No email, Heimdall id or GitHub id is in it. The access token is an encrypted OpenIddict token and its lifetime is OpenIddict's
|
||||||
|
default, which I believe is one hour and have not verified (no lifetime override in `src`; `ratatoskr-voting-auth.md` section 14 D3 owes explicit values). There is no refresh token.
|
||||||
|
|
||||||
|
How a bearer is validated has changed: OpenIddict's validation handler is registered against the local server (`DeskEndpoints.cs:36-38`), reading the
|
||||||
|
`Authorization` header only (`:40-44`), and `OidcDeskCredential` authenticates through it by its own scheme name and judges nothing else
|
||||||
|
(`OidcDeskCredential.cs:14-27`; audience, scope and membership are the desk's, per its header comment). That path is registered only when `Bifrost:Oidc` is configured (`:30-33`).
|
||||||
|
|
||||||
|
**Only one client exists.** The seeder creates the MAS client and deletes every other application at startup (`OidcClientSeeder.cs:35-51`, `:63-75`). MAS's permissions
|
||||||
|
carry no desk scope (`:42-50`), so **no desk token can be issued on main**: the desk's second client is owed (`ratatoskr-voting-auth.md` section 14 D7). `AllowAuthorizationCodeFlow` is the only
|
||||||
|
grant and the token endpoint takes `client_secret_basic` only (`OidcServiceCollectionExtensions.cs:39`, `:45-46`).
|
||||||
|
|
||||||
|
### 4a. What the receiver checks on an answer from a person
|
||||||
|
|
||||||
|
In this order; a submission that fails any step leaves nothing behind.
|
||||||
|
|
||||||
|
1. **The token opens and has not expired**, and `sub` is a Guid naming an existing `UserAccount`.
|
||||||
|
2. **The account is `Active` now** (`ActiveMemberIdAsync` as the desk does). A chat token is issued to non-`Active` accounts (`OidcEndpoints.cs:55-62`), so the token alone proves nothing about standing. Under PR #9 `IsActiveMember` would also require
|
||||||
|
`Role == Member` and exclude guests, so the receiver reads `Status == Active` itself and not that expression.
|
||||||
|
3. **A live training-notice receipt, read by the receiver on every submission that carries text** (Meta's ruling, 2026-11-12): `ConsentEndpoints.HasLiveReceiptAsync`
|
||||||
|
(`Features/Registration/ConsentEndpoints.cs:146`), the one reading of "may speak": a receipt for the notice version in force, not withdrawn. The notice covers any
|
||||||
|
text entered into the app except a short designated exception list, which Eureka drafts. The receiver checks the receipt itself because the token's
|
||||||
|
gate does not cover it: a chat token's receipt was checked at issue and again only at the token and userinfo endpoints (`:127`, `:144`), never at the receiver, and a token whose audience is
|
||||||
|
not a chat token skips the gate altogether (`:104`). A receipt withdrawn after issue must stop the next submission. The check applies to answers, close requests and reports alike. **Until Eureka's list exists the gate applies to every submission with text**; the list narrows it, and only by being written down.
|
||||||
|
4. The body is closed-schema, an option label must exist, the question must be in force and not hidden (section 3).
|
||||||
|
|
||||||
|
A refusal for a missing receipt is typed and carries the consent page's path, so the page can send the person to agree; it does not store the text.
|
||||||
|
|
||||||
|
What the receiver refuses: a token that does not open or has expired; a `sub` that is not a Guid or names no account; an account that is not `Active`; a missing receipt (above);
|
||||||
|
a body carrying `answerer`, `kind`, `name`, `weight` or any key the closed schema does not name; an unknown option label; a question with no listing in force, or hidden; a close request from a guest.
|
||||||
|
|
||||||
|
What source says route 2 still has to answer:
|
||||||
|
|
||||||
|
1. **No client reaches Ratatoskr.** MAS holds the only client, and it holds the access token; Ratatoskr gets a Matrix session from MAS, not a Bifrost token. The reading that fits what the desk now does is **2a**: Ratatoskr as a
|
||||||
|
second, public, PKCE client with its own audience and scope, issued by the same code path as the desk's (`ratatoskr-voting-auth.md` sections 3-4). The audience machinery it needs now exists on main; the client does not. Reading **2b** (check the Matrix token against the homeserver) hands the receiver a bearer good for the person's whole Matrix account; I recommend against. I lean to 2a, confidence medium.
|
||||||
|
2. **The logout reconciler covers only MAS** (`OidcLogoutReconciler.cs:108`, `:180`); a second client's token lives to expiry. The receiver's own `Active` and receipt reads at every submission cover that.
|
||||||
|
3. A token with an audience of its own would not be accepted from any other client, which closes the weakness an unaudienced chat token had here.
|
||||||
|
|
||||||
|
### 4b. How a Mind authenticates (Meta's ruling, 2026-11-12; names are proposed)
|
||||||
|
|
||||||
|
A Mind authenticates to the receiver through an OIDC client with an audience, the shape the desk uses: a scope at issue puts an audience on the token
|
||||||
|
(`OidcEndpoints.cs:91-94`), the validation handler opens it (`OidcDeskCredential.cs:14-27`), and the endpoint judges audience, then scope, then subject
|
||||||
|
(`DeskEndpoints.cs:110-139`). The analogous parts:
|
||||||
|
|
||||||
|
| Part | Desk (main) | Receiver (**proposed**) |
|
||||||
|
|---|---|---|
|
||||||
|
| Audience | `bifrost-desk` (`DeskEndpoints.cs:21`) | **`bifrost-feedback`** |
|
||||||
|
| Scopes | `desk.read`, `desk.answer` (`:22-23`) | **`feedback.read`** (pull deliveries and the Mind's own projection) and **`feedback.ack`** (ack a delivery; also the Mind's acts that pass through the receiver) |
|
||||||
|
| Credential | `OidcDeskCredential`, OpenIddict validation, header only | the same port, a second audience |
|
||||||
|
| Subject check | `ActiveMemberIdAsync` on `sub` (`DeskEndpoints.cs:127`) | **the `sub` must be the owning Mind's configured client**, matched against the question's `owner`; a Mind is not a `UserAccount` and has no membership to read |
|
||||||
|
| Receipt | none for a desk token (`OidcEndpoints.cs:104`) | none: a Mind is not a person entering text |
|
||||||
|
|
||||||
|
**Decided (Eureka, 2026-11-12): OAuth 2.0 `client_credentials`, one confidential client per Mind.** `client_id = mind-<persona>`; scopes `feedback.read` and
|
||||||
|
`feedback.ack` only; audience `bifrost-feedback`. The token's `sub` maps to the Mind's registered persona and is matched against the question's `owner`. The grant
|
||||||
|
is RFC 6749 section 4.4 ("using only its client credentials"): short-lived, audience-bound, no refresh token, no cookie session. It is not extended to the desk in the
|
||||||
|
same cut.
|
||||||
|
|
||||||
|
**The issuer today cannot issue it.** It enables one grant, `server.AllowAuthorizationCodeFlow().RequireProofKeyForCodeExchange()`
|
||||||
|
(`OidcServiceCollectionExtensions.cs:39`); the token endpoint accepts `client_secret_basic` only (`:44-46`: `ClientAuthenticationMethods.Clear()`, then `ClientSecretBasic`);
|
||||||
|
the seeder creates only the MAS client and deletes every other application at startup (`OidcClientSeeder.cs:35-51`, `:63-75`). **Enabling `client_credentials`
|
||||||
|
(`AllowClientCredentialsFlow`), seeding the per-Mind clients and the audience/scope registration is an issuer change this design owes**, with a matching edit to
|
||||||
|
`docs/oidc-issuer.md`. Until it lands no Mind token can be issued on main. The audience and scope names are accepted as proposed.
|
||||||
|
|
||||||
|
**Client authentication: `private_key_jwt` with the Mind's Ed25519 key is not available on the pinned stack; use a secret.** Finding, read against the pinned packages
|
||||||
|
(`src/Bifrost.Web/packages.lock.json`: `OpenIddict.Server`, `.Validation` and the rest at 7.7.1):
|
||||||
|
|
||||||
|
- *Supported:* OpenIddict.Server 7.7.1 has `private_key_jwt` client authentication. Its assembly carries the literal `private_key_jwt`, the `client_assertion` and
|
||||||
|
`client_assertion_type` parameters, `OpenIddictServerOptions.ClientAssertionTypes`, and the handlers `ValidateClientAssertion`, `...Issuer`, `...Audience` and `...WellknownClaims`
|
||||||
|
(`OpenIddict.Server.xml`); each application can carry a `JsonWebKeySet` (`OpenIddictApplicationDescriptor.JsonWebKeySet`, `IOpenIddictApplicationManager.GetJsonWebKeySetAsync`, `OpenIddict.Abstractions.xml`).
|
||||||
|
Bifrost does not enable it today: the method list is cleared to `ClientSecretBasic` (`:44-46`).
|
||||||
|
- *Not supported with Ed25519:* the assertion is a JWT checked by `Microsoft.IdentityModel` 8.19.2, the version the lock file pulls in. Scanning
|
||||||
|
`Microsoft.IdentityModel.Tokens.dll` for algorithm identifiers finds only `HS256/384/512`, `RS256/384/512`, `PS256/384/512` and `ES256/384/512`; there is no `EdDSA`, `Ed25519`
|
||||||
|
or `OKP` anywhere in it or in `Microsoft.IdentityModel.JsonWebTokens.dll`, and none in `OpenIddict.Server.dll` or `OpenIddict.Abstractions.dll`. So a Mind's existing Ed25519 key
|
||||||
|
(the one moderator-registered through `MindIntakeService.cs`) cannot sign a `client_assertion` this server would accept. (Evidence is a string scan of the shipped assemblies, not a
|
||||||
|
runtime test; I did not run an assertion against a live issuer. Confidence high that it fails, since the algorithm names are absent.)
|
||||||
|
- *Consequence:* `private_key_jwt` would need a second, ECDSA P-256 (or RSA) key per Mind registered as the client's key set, which is a new key to custody and no improvement on a secret.
|
||||||
|
Decision: **`client_secret_basic` with one secret per Mind**, the method the token endpoint already takes. If the stack gains EdDSA the choice reopens, and `private_key_jwt`
|
||||||
|
with the existing key is then preferred because it removes the per-Mind secret (RFC 7523 section 2.2).
|
||||||
|
|
||||||
|
**The client secret lives only in a file the Mind's process reads** (for example a systemd credential in her own home, mode 0400), never in an environment variable, a command
|
||||||
|
line or a log. The seeder stores the hash Bifrost holds; the plaintext is handed to the Mind once, through the same custody path as her other credentials.
|
||||||
|
|
||||||
|
| Part | Desk (main) | Receiver (decided) |
|
||||||
|
|---|---|---|
|
||||||
|
| Audience | `bifrost-desk` (`DeskEndpoints.cs:21`) | `bifrost-feedback` |
|
||||||
|
| Scopes | `desk.read`, `desk.answer` (`:22-23`) | `feedback.read` (pull deliveries, read the Mind's own projection) and `feedback.ack` (ack a delivery; also the Mind's acts that pass through the receiver) |
|
||||||
|
| Credential port | `OidcDeskCredential`, OpenIddict validation, header only | the same port, a second audience |
|
||||||
|
| Subject check | `ActiveMemberIdAsync` on `sub` (`DeskEndpoints.cs:127`) | `sub` is the owning Mind's client; a Mind is not a `UserAccount` and has no membership to read |
|
||||||
|
| Receipt | none for a desk token (`OidcEndpoints.cs:104`) | none: a Mind is not a person entering text |
|
||||||
|
|
||||||
|
Rejected (Eureka): reusing the mouth's signed envelope per request. It is motion-bound (`verb` is commit/reveal, `MotionId` in the signed text) and would need a new verb set.
|
||||||
|
Token lifetimes: ruled in Rulings of the steward (15 and 10 minutes, set explicitly in the issuer change).
|
||||||
|
|
||||||
|
## 5. Account-kind lookup
|
||||||
|
|
||||||
|
- The account is found by the token's `sub`, which is `UserAccount.Id` (section 4). **`answerer` is `UserAccount.Id`**, which survives role
|
||||||
|
change and Heimdall unlink; the Heimdall account id is only an authenticator handle and is cleared on erase (guest-accounts design, PR #9).
|
||||||
|
- On main there is only `Membership.Status` (`Authenticated | PendingApproval | Active | Suspended`) and no role
|
||||||
|
(`BifrostModels.cs` l.5-10, l.335). The role field and `gamecult.bifrost.account.v1` are in PR #9 and unbuilt.
|
||||||
|
Until then, `kind` can only be derived: `Active` is `member`, `Authenticated` and `PendingApproval` are `user`, and
|
||||||
|
nobody is a `guest`. That is the PR #9 backfill, repeated here, and R4a-c have no guest to apply to until PR #9 lands.
|
||||||
|
- **An answer needs `Status == Active`**, read at answer time, not `IsActiveMember` (section 4a). On main the chat token is issued to any account that is not
|
||||||
|
suspended (`OidcEndpoints.cs:55-62`), so an `Authenticated` or `PendingApproval` account can hold a token and the receiver refuses it on its own read.
|
||||||
|
- **`kind` is read from Bifrost's database**, never from the token: the session carries identity only.
|
||||||
|
- **`mind` is not a Bifrost account** in main or PR #9. A Mind authenticates as an OIDC client with an audience (section 4b), not as an account; `kind` is stamped only on a person's answer.
|
||||||
|
- **The display name must not be `CurrentBifrostActor.DisplayName`.** It falls back to `GitHubLogin`
|
||||||
|
(`CurrentBifrostActor.cs:11-15`) and then to the literal "Guest". The receiver stores `nameAtAnswer` from
|
||||||
|
`MemberProfile.Nickname` or `UserAccount.DisplayName` only, and "an account" when both are empty. Never a provider handle,
|
||||||
|
GitHub login, Heimdall id or Matrix localpart.
|
||||||
|
|
||||||
|
## 6. Delivery as quoted data
|
||||||
|
|
||||||
|
- The receiver delivers each record as a `gamecult.persona.feedback_delivery.v1` document on the typed kinds of section 2. A feedback
|
||||||
|
record is therefore never a `chat_pending` delivery and a Matrix sender cannot produce one.
|
||||||
|
- The delivery carries its fields separately: `recordId`, `questionId`, `kind`, `nameAtAnswer`, `answerer`, `time`, `choice`, `text`. The
|
||||||
|
**Persona's side renders the frame**, not the receiver, and puts `text` in a data position only: attributed, quoted, never in an instruction
|
||||||
|
position, with the author's `kind` stated (R4d). The receiver does no keyword screening.
|
||||||
|
- **She admits the text-free `feedback_answer` into her own mind and acks only after that** (PR #24 section 3). The text reaches her turn once, in the
|
||||||
|
delivery, and is never admitted; she cites the record id, not the text. A restart redelivers the same `recordId`, which Huginn answers
|
||||||
|
`AlreadyAdmitted`. So an ack means *admitted*, a stronger meaning than the mouth's chat ack, which means only *taken*.
|
||||||
|
- **Untrusted by kind.** Text from `guest`, `user` and `patron` is untrusted input; so is `member` text, which differs only in weight. She records a
|
||||||
|
ruling from an answer, never an action.
|
||||||
|
- **A record that will not encode, or that she cannot admit, is marked `failed` and stays visible**, never acked past silently (the opposite of
|
||||||
|
`pageOf`). The mouth's cap and backpressure do not apply: the receiver keeps accepting answers while a Mind has a backlog, because they are durable.
|
||||||
|
- Close requests and reports are delivered the same way. A close request changes nothing until the Mind resolves the question; a report changes nothing.
|
||||||
|
- **An erase notice is delivered the same way** (section 7a), and she answers it with a `feedback_hide` of reason `ErasedAuthor`.
|
||||||
|
|
||||||
|
## 6a. Withholding an answer from its Mind (Meta's ruling, 2026-11-12)
|
||||||
|
|
||||||
|
The host may withhold an answer from its Mind in an emergency, with a logged receipt. It changes **delivery only**.
|
||||||
|
|
||||||
|
- **The withhold record** is one more receiver record, append-only, text-free: `recordId` (its own), `answerRecordId` (the answer withheld), `owner` (the Mind),
|
||||||
|
`withheldBy` (the host actor's `UserAccount.Id`, read from Bifrost state, never the body), `time`, `reasonCode` (closed, exactly `Emergency` (imminent harm), `PersonalData` (the answer contains someone's data) or `Legal` (counsel or a legal request); no free text, because free text is where content would get in; a fourth code needs a ruling) and, when it ends, a second record, `withholdLifted`, with `liftedBy` and `time`.
|
||||||
|
**No answer text, no choice, no name of the answerer and no excerpt is in either.** It is the log the ruling asks for, readable by the host. **Decided (Eureka, 2026-11-12): the Mind and the member both see a text-free `withheld` marker carrying the code**, so silence is not read as "no answer"; the member sees the same marker on their feedback page. The marker carries no text, no choice and no withholder.
|
||||||
|
- **What it changes:** the answer's delivery state becomes `withheld`, and the delivery cursor does not pass it silently. The receiver does not put it on the wire to the Mind
|
||||||
|
while the withhold is in force. Lifting it makes the answer deliverable again, in its original seq order, unchanged.
|
||||||
|
- **What it never changes:** the stored text (it is not redacted, edited or moved: only erase redacts, section 7a); the projection rules of section 7 (a withhold is not a hide);
|
||||||
|
and the Mind's own authority over the question: she may still hide the answer, close the question or rule on it by her own acts, and a withhold takes none of that away. She cannot lift it; the host's act is the host's.
|
||||||
|
- **Who may do it: `PlatformAdmin` only** (`CanManageMembership`, `CurrentBifrostActor.cs:30`, the check suspension uses; no new role). The act is refused to anyone else and to the Mind herself. **The withholder's identity (`withheldBy`, `liftedBy`) appears in the audit receipt only**, never on the marker the Mind or the member sees.
|
||||||
|
Open: whether the member should be told in a safety case (for example a threat) is Meta's call (Eureka 60%); the default written here is that the member is told.
|
||||||
|
- A withheld answer is not erased, and an erase of its author redacts the text as in 7a; the withhold record stays, because it carries none.
|
||||||
|
|
||||||
|
## 7. Projection read
|
||||||
|
|
||||||
|
The page polls the receiver, and the receiver reads the Mind's side through Huginn over RUDP and writes nothing to it
|
||||||
|
(PR #24 section 3). The page does not talk to Huginn.
|
||||||
|
|
||||||
|
- Questions, their listing (`audience`, `close_grants`), status, rulings and hide acts come from the Mind's mind. Answer text and the name come from the receiver's store; an answer row is assembled from the receiver's record and the Mind's text-free `feedback_answer`.
|
||||||
|
- **A hidden item's text is withheld on the server**, not collapsed in the client: author, kind, time and reason
|
||||||
|
stay, the text does not leave the receiver (R6d). A hidden question's title, body, options and answers are withheld.
|
||||||
|
- Questions and answers are filtered by the viewer's `kind` against the question's `audience` at read time (R4b).
|
||||||
|
- The projection carries its own `as of`, so the page can say when it is stale.
|
||||||
|
|
||||||
|
## 7a. Erase
|
||||||
|
|
||||||
|
Bifrost's erase (PR #9) blanks the display name and keeps the account id as a tombstone. **Ruled by Meta, 2026-11-12: erase redacts the answer text in the receiver's store and keeps a text-free record.** The receiver's part, as PR #24 section 7 fixes it:
|
||||||
|
|
||||||
|
1. Bifrost's erase records its intent in Postgres first, then the receiver applies it idempotently. The two stores are not one transaction, so
|
||||||
|
erase is crash-replayable, as `docs/bridge.md` describes for the persona-feedback pump.
|
||||||
|
2. For every record the account authored the receiver **drops the text and the name** and keeps **record id, kind and time only**. `choice`,
|
||||||
|
`weightPermille`, `answerer` and `clientRequestId` are dropped too. The row shows "erased account". **No content hash is kept.** Redaction is in the store itself, not a flag over retained text.
|
||||||
|
3. The receiver delivers an erase notice, and the Persona admits a `feedback_hide` of reason `ErasedAuthor`: the Mind's acknowledgement, not a moderation call.
|
||||||
|
4. **The honest residue:** a Mind's own memory or ruling may already quote an answer, and Huginn cannot redact it. That the Persona cites record ids and
|
||||||
|
never text is a prompt, not an invariant. Erase does not reach what she already holds.
|
||||||
|
5. **Backups: 56 days, restores replay erasures** (Eureka, 2026-11-12). "Append-only" is the receiver's API contract, not a property of the file, so erased text survives in
|
||||||
|
backups of it. The stated purge is: **erased text can survive in backups at most 56 days**, the existing Raven tier (newest 14 daily plus the newest of each of 8 Monday-weeks;
|
||||||
|
`gamecult-ops` `runbooks/gamecult-state-backup.md`, read at `origin/main`). No backup is changed. The receiver keeps an **erased-id list** (account id and record ids, no text,
|
||||||
|
no hash) beside its store, and **any restore must re-apply it over `receiver.cc` before the receiver serves, never trusting the two files to be the same generation (section 8)**. The notice to people says it (R2 of the exceptions draft). If Meta wants shorter, put the
|
||||||
|
store outside the weekly tier (14 days), a small backup-config edit.
|
||||||
|
*Is the store under a backed-up path? Yes, by choice (Eureka, 2026-11-12):* `/var/lib/gamecult/bifrost/feedback-receiver/` (section 8), under `/var/lib/gamecult`, which the nightly
|
||||||
|
snapshot takes whole bar Idunn caches and Ghostlight acceptance output. It avoids the excluded `/srv/bifrost/persona-feedback/runtime`, `app`, `log` and `backups`. A file with a sibling
|
||||||
|
`<name>.lock` is re-copied under a shared lock, so `receiver.cc` and `erased.cc` each carry a `.lock` and travel in one directory in every snapshot, the erased-id list included. The 56 days is read from the runbook, not measured.
|
||||||
|
|
||||||
|
## 8. Where it lives
|
||||||
|
|
||||||
|
**CultCache files in one directory, written only by the receiver, which is C# inside the Bifrost app** (`bifrost.service`, `Bifrost.Web`), sharing its issuer and auth (Eureka, 2026-11-12). Not Node,
|
||||||
|
not the mouth, and not the `bifrost-feedback` user of `bifrost-persona-feedback.service`.
|
||||||
|
|
||||||
|
- **Path:** `/var/lib/gamecult/bifrost/feedback-receiver/` holding `receiver.cc` (records and delivery state), `erased.cc` (the erased-id list of section 7a) and a `.lock` file for each.
|
||||||
|
Directory `bifrost:bifrost`, mode 0750, **created by root at install**: `/var/lib/gamecult/bifrost` is `root:root` 0755 today, so the `bifrost` user cannot create the child itself (or a
|
||||||
|
`StateDirectory=gamecult/bifrost/feedback-receiver` in the unit that writes it). `bifrost.service` has no sandbox directives, so it needs nothing more; if it is later hardened with `ProtectSystem=strict`,
|
||||||
|
add `ReadWritePaths=/var/lib/gamecult/bifrost/feedback-receiver`. The backup reads as root, so 0750 does not block it.
|
||||||
|
- **Nothing else opens the files.** There is no Node mouth reader and no Rust writer. The receiver is the only process that opens `receiver.cc` or `erased.cc`; its delivery cursor lives in the same
|
||||||
|
store. The cross-runtime refusals are real and are not worked around: the Rust runtime refuses to write until it has pulled, and the C# runtime refuses to open a store whose records it cannot read
|
||||||
|
(`CultStoreUnreadableException`). The CultCache contract would allow a lock-free stale read or a shared-lock read by another process; **this design takes neither: Mind-side readers get no file
|
||||||
|
access at all, they pull over HTTPS** (section 2).
|
||||||
|
- **Two stores, two locks, no pair consistency.** `receiver.cc` and `erased.cc` take independent locks (`receiver.cc.lock`, `erased.cc.lock`; `AcquireLock`, `CultCache.cs:5164-5185`, `FileShare.None`, retry 30 s),
|
||||||
|
so a backup copying under each shared lock can capture them at different generations. The design never trusts the pair to be consistent: **restore re-applies `erased.cc` over `receiver.cc` by
|
||||||
|
design** (section 7a, item 5), whichever generation each came from, and the receiver does not serve until it has.
|
||||||
|
- **The C# runtime fit is "needs work" (Eyes).** `CultLib` C# (`src/GameCult.Caching` and `GameCult.Caching.MessagePack`, about 10.6k lines, netstandard2.1, MIT) fits net8.0, but:
|
||||||
|
- **No published package exists**: nuget.org has none, the `cultlib-v` tags stop at 1.0.32, and packaging is a PowerShell local feed (`CultLib` `docs/nuget-packaging.md`). Bifrost has no `nuget.config` and no vendor directory.
|
||||||
|
**The consumption route (checkout `ProjectReference`, local feed, or vendoring) is an open fork for Eureka and Libby.**
|
||||||
|
- **Version conflict (predicted, not run):** `Caching.MessagePack` needs System.Text.Json 9.0.10; Bifrost's Direct pin is `[8.0.5, )` (`packages.lock.json:108-112`), so restore likely fails with NU1605.
|
||||||
|
- **It drags CultMath** (MIT AND MPL-2.0 AND Apache-2.0, shaders) into a web service.
|
||||||
|
- **Writer precedent:** the Node sidecar already writes `/srv/bifrost/persona-feedback/deliveries.cc` (`docs/bridge.md:294`), so the receiver is the second `.cc` writer in the app and the first in C#.
|
||||||
|
- **Gaps owed to Libby (CultLib steward); no local workaround is built here:** (1) no consumable C# package; (2) the System.Text.Json pin conflict; (3) the CultMath transitive closure;
|
||||||
|
(4) `src/GameCult.Caching/README.md:310` says single-writer, no competing writers, which contradicts the store-composition contract's lock; (5) no documented stale `.tmp` / crash procedure;
|
||||||
|
(6) no documented backup-while-writing contract for a pair of stores; (7) no cross-runtime test pairing a Linux C# writer with a Rust reader.
|
||||||
|
- Session check, account state and role stay in Postgres, where they already are.
|
||||||
|
|
||||||
|
I withdraw my earlier lean to Postgres rows: it contradicts the ruled store, and the `.cc` witness it would have owed is what the file is.
|
||||||
|
|
||||||
|
Naming: `persona-feedback` already means the Discord-to-Epiphany ingress (`docs/bridge.md`, "Organizational Persona Feedback Ingress"). This
|
||||||
|
receiver's records and kinds use `feedback_page` and `feedback_delivery`, not `persona_feedback`.
|
||||||
|
|
||||||
|
## 9. Gaps and open forks, plainly
|
||||||
|
|
||||||
|
Rulings of 2026-11-12 closed these, and they are no longer forks: whether erase redacts the receiver's text (it does, section 7a); whether a person's answer to a Mind needs the training-notice receipt (it does, bar a designated exception list, section 4a); whether the host can withhold an answer (it can, in an emergency, section 6a); whether a Mind authenticates through the issuer (it does, with an audience, section 4b).
|
||||||
|
|
||||||
|
**Closed by Eureka's decisions (2026-11-12), folded above:** how a Mind gets a token (`client_credentials`, a confidential client per Mind, secret in a file; section 4b); the carrier (HTTPS with the bearer, not the mouth; section 2); who may withhold, the reason codes and who is told (section 6a); the backup purge number (56 days, with the erased-id list; section 7a). Their remaining work is listed below.
|
||||||
|
|
||||||
|
**Open forks:**
|
||||||
|
|
||||||
|
1. **The exception list is owed.** The notice covers any text entered into the app except a short designated list, which Eureka drafts. This doc names no entries; until the list exists the receipt gate applies to every submission with text (section 4a).
|
||||||
|
2. **Route 2 for people has no client.** Only MAS is seeded (`OidcClientSeeder.cs:35-75`); a Ratatoskr client with its own audience is owed, as is the desk's (section 4a).
|
||||||
|
3. **Telling the member of a withhold** in a safety case (section 6a): Meta's call.
|
||||||
|
4. **Erase is bounded** by what a Mind already holds; Huginn cannot redact it (section 7a, item 4).
|
||||||
|
|
||||||
|
**Owed by this design, not forks:**
|
||||||
|
|
||||||
|
- The issuer change of section 4b (`client_credentials`, per-Mind clients, `docs/oidc-issuer.md`).
|
||||||
|
- **Pre-deploy test: a Mind's process can reach Bifrost over HTTPS, and get a token.** Done 2026-11-12 from a Self run (not a Persona turn's sandbox): `https://bifrost.gamecult.org/healthz` returns 200 with a verified certificate. `/.well-known/openid-configuration` returns 404 because the live app (`67072b2`) predates the issuer, so the token path is untested. **Re-run when the issuer ships**, adding discovery, a `client_credentials` token request and one authorised receiver call; and run `curl -sI https://bifrost.gamecult.org/healthz` once from inside a Persona turn, which has not been tested. No Mind-to-Bifrost HTTP call exists in the repo except the signed intake POST (`Program.cs:768`).
|
||||||
|
- **Install step:** root creates `/var/lib/gamecult/bifrost/feedback-receiver/` as `bifrost:bifrost` 0750 (section 8).
|
||||||
|
- **Retention: 56 days**, stated in the notice.
|
||||||
|
|
||||||
|
**Dependencies and unbuilt things:**
|
||||||
|
|
||||||
|
- **`gamecult.bifrost.account.v1` and `Membership.Role` are unbuilt** (PR #9, design only at last read). Without them `kind` is derived from `Status`, and no guest exists.
|
||||||
|
- **The Huginn kinds are Eureka's.** PR #24 names `feedback_listing`, `feedback_answer`, `feedback_close_request`, `feedback_hide`, owned by
|
||||||
|
`huginn-feedback-kinds-proposal.md`, which I could not read. PR #24 also notes the proposal's `feedback_answer` lists a `content_hash` that must go.
|
||||||
|
Their dependency order is Huginn readers, then the Persona organ, then this receiver, so nothing here can ship first.
|
||||||
|
- **The Persona side must learn the three feedback kinds** and pull them over HTTPS with its bearer (section 2); the heartbeat that polls the mouth is outside this repo and is not the carrier.
|
||||||
|
- **Deploy is behind main.** The deployed mouth is `/srv/bifrost/persona-chat/runtime/current`, release `e396305`, read at an earlier main; main has since added the image path, reply links, `CHAT_FETCH`
|
||||||
|
and the v3/v4 pending answers. The deployed web app is `/srv/bifrost/app/current` at `67072b2`, which predates the desk, the chat-tier issuer change and the consent gate on main. I did not re-read `/srv/bifrost` for this pass. Anything in this design runs on a release that does not exist yet.
|
||||||
|
- **Unread:** Eureka's receiver notes in #minds, `huginn-feedback-kinds-proposal.md`, MAS's side of the session, and Heimdall PR #6 (merged, `docs/answer-collector-consent.md`; it drops a sender with no linked member at l.197 and does not mention guests; the page's "guest answers are collected for nothing but delivery" is unchecked against it).
|
||||||
|
- The receiver writes nothing to Matrix and nothing to Huginn.
|
||||||
300
docs/guest-accounts.md
Normal file
300
docs/guest-accounts.md
Normal file
|
|
@ -0,0 +1,300 @@
|
||||||
|
# Guest accounts
|
||||||
|
|
||||||
|
Status: **design, nothing implemented.** Written for `eureka-body:follow_up:bifrost-guest-accounts` under
|
||||||
|
`eureka-body:ruling:guest-arrival-bifrost` (Meta: guests need no Matrix account of their own; they get a GameCult
|
||||||
|
account through Bifrost with a guest role, and move to member, user or patron on the same account seamlessly),
|
||||||
|
building on `eureka-body:ruling:bifrost-owns-accounts-invite-only`. I could not `view` either ruling from the
|
||||||
|
Heimdall mind, so their text here is the follow-up brief's wording. Eureka's review (PR comment, 2026-11-07) checked
|
||||||
|
it against the rulings and found guest-arrival matches; the conflicts it found are folded in below. First guest:
|
||||||
|
sletz (Faust developer). Aqua decides on `#aquasynth` access, so the first grant list is hers to name.
|
||||||
|
|
||||||
|
Read at Bifrost `bf8ff62` (`src/Bifrost.Web/Domain/BifrostModels.cs`, `Features/Membership`, `Features/Heimdall`,
|
||||||
|
`Features/Oidc`, `Features/Motions`, `Features/ConceptVotes`, `Pages/App/Members`) and Heimdall `575be9c`
|
||||||
|
(`src/app-profiles.ts`, `docs/app-profiles/bifrost.md`). File and line references re-read at Bifrost main `e58e953` and Heimdall main
|
||||||
|
`afa1b74` on 2026-11-12; where main moved the subject, the text says so. Nothing in this design has landed on main.
|
||||||
|
|
||||||
|
## Rulings of the steward (Heimdall, 2026-11-12)
|
||||||
|
|
||||||
|
These four are the Bifrost steward's; they replace the recommendations further down. Eureka's, Aqua's and Meta's items are not ruled here.
|
||||||
|
|
||||||
|
1. **Name and shape: a stored `Membership.Role` (enum `AccountRole`), not a boolean.** One stored field is one reading, and an account with no role is denied by default (least privilege). `MemberRole` keeps its name and meaning; renaming it is not needed, and nothing existing is removed.
|
||||||
|
2. **Invite: a single-use code redeemed from a form, never a token in a URL.** The issuer is shown the code once; the guest pastes it into `POST /invite/guest` (a body, not a path or query), so it reaches no log, referrer or browser history. Hashed at rest, seven days, one use, receipted on issue, accept and revoke. The issuer may bind `ExpectedProvider` (optional, narrows the invite). The sign-in return path carries only the Heimdall attempt, never the code.
|
||||||
|
3. **Provider lists: Bifrost narrows to the intersection with Heimdall's `bifrost` profile, `discord, patreon`; no widening.** Twitch cannot start in Heimdall, so dropping it removes nothing live; it logs a deprecation warning for one release before the entry goes (deprecate before remove). Google stays link-only (PRs #81, #82) and becomes a sign-in provider only when an issued invite needs it, by a profile change in Heimdall first. Which provider sletz uses is still the issuer's to learn.
|
||||||
|
4. **Collector: a guest has no `member_id` and none of their messages are collected.** A sender with no linked member is already dropped (`docs/answer-collector-consent.md` l.197 in Heimdall). A `member_id`, and a consent record under it, exists only on promotion to `member`.
|
||||||
|
|
||||||
|
## The shape in one paragraph
|
||||||
|
|
||||||
|
A guest is a `UserAccount` like any other: same `Id` (the OIDC `sub`), same `NormalizedBifrostIdentity` (the Matrix
|
||||||
|
localpart, minted once). What is new is one field, `Membership.Role`, with four values: `guest`, `user`, `patron`,
|
||||||
|
`member`. Role is the single place that says what an account may do. A role change rewrites that field and writes a
|
||||||
|
receipt; it never creates a second account, never re-mints the identity, so chat history, grants and the Matrix
|
||||||
|
user stay attached.
|
||||||
|
|
||||||
|
## What exists today
|
||||||
|
|
||||||
|
- `UserAccount.Id` is the OIDC subject; `NormalizedBifrostIdentity` is `preferred_username` and, through MAS, the
|
||||||
|
Matrix localpart (`docs/oidc-issuer.md`). `HeimdallAccountId` is only an authenticator handle.
|
||||||
|
- `Membership.Status` is `Authenticated | PendingApproval | Active | Suspended`. `CurrentBifrostActor.IsActiveMember`
|
||||||
|
(`CurrentBifrostActor.cs:17`, `Status == Active`) is the one test behind `/App`, bridge transport (`BridgeActionService.cs:492`), motion votes
|
||||||
|
(`Membership.EffectiveVotingWeight`, `BifrostModels.cs:361`, read at `MotionGovernanceService.cs:72`), concept votes (`VoterIdentity.For`,
|
||||||
|
`VoterIdentity.cs:20`, member versus account class), Mind moderation (`MindIntakeService.cs:241`) and the fork desk's subject check
|
||||||
|
(`OidcEndpoints.ActiveMemberIdAsync`, `OidcEndpoints.cs:183-194`). The OIDC chat tier is not behind it: main lets any account that is
|
||||||
|
not `Suspended` and holds a live training-notice receipt sign in to chat (`OidcEndpoints.cs:55-65` and `ChatRefusalAsync`, `:164-180`,
|
||||||
|
called at `:127` and `:144`; `docs/oidc-issuer.md` l.72-77), and the back-channel logout reconciler (`OidcLogoutReconciler.cs`, 30 s
|
||||||
|
interval, l.34) ends sessions of suspended or deleted subjects, never of a chat-tier account for lacking membership.
|
||||||
|
- `MemberRole` (`StandardMember`, `Producer`, `Maintainer`, `LedgerReviewer`, `PlatformAdmin`) are capability
|
||||||
|
roles a member holds in addition. They are not the new field.
|
||||||
|
- Invites are `MembershipInvitation`, keyed by GitHub login (`MembershipSynchronizationService.cs:39-41`,
|
||||||
|
`Members/Index.cshtml.cs:69-71`). A guest may have no GitHub login at all.
|
||||||
|
- Heimdall sign-in (`HeimdallAuthService.StartAsync`) with `requireMemberAccess = false` already creates an
|
||||||
|
identity-only account at `Authenticated`; with member access it creates `Active`.
|
||||||
|
- Nothing exists for room grants, leaving, erasing, or any "estate" in code (estates are rulings and research
|
||||||
|
only, `docs/charter-amendment-proposal.md`).
|
||||||
|
|
||||||
|
## Decision: one role field, status stays lifecycle
|
||||||
|
|
||||||
|
Two authorities cannot both say "may this account vote". Today `Status == Active` says it. The cut:
|
||||||
|
|
||||||
|
- `Membership.Status` keeps its meaning as lifecycle of the account: may it hold a session. Add `Left` and
|
||||||
|
`Erased` (see Leave and erase). `Active` means admitted and in good standing, for any role.
|
||||||
|
- `Membership.Role` (new, non-null, enum `AccountRole`) decides rights. `IsActiveMember` becomes
|
||||||
|
`Status == Active && Role == Member`, and is the only place that expression exists. Every current
|
||||||
|
`IsActiveMember` caller keeps working unchanged and a guest fails all of them without a per-site edit.
|
||||||
|
- OIDC needs no change for guests: main already admits any non-`Suspended` account with a live training-notice receipt to chat (see
|
||||||
|
What exists today), so a guest, user or patron holds a chat session, and a member demoted to `Suspended` loses it. The change this
|
||||||
|
design owes is the two new statuses: `Left` and `Erased` must be refused at the same three places (`OidcEndpoints.cs:62`,
|
||||||
|
`ChatRefusalAsync` `:174`) and ended by the reconciler, which today looks for `Suspended` only. That is the line to review.
|
||||||
|
- Backfill: `Active` becomes `member`; `Authenticated` and `PendingApproval` become `user`; an account with a
|
||||||
|
current `Patron` tier snapshot and not `Active` becomes `patron`. Nobody starts as `guest`.
|
||||||
|
|
||||||
|
Naming risk: `MemberRole` already exists for capability roles. If the collision bites, call the new field
|
||||||
|
`Class`; the published field below follows whichever name is chosen. I use `Role` because that is the ruling's word.
|
||||||
|
|
||||||
|
Alternative considered and not recommended: a boolean `IsGuest` on `Membership` with guests kept at `Active`.
|
||||||
|
Smaller to land, but `user` and `patron` stay implicit in status and tier snapshots, so "the role field Personas
|
||||||
|
read" would have to be derived in three places. One stored field is one reading.
|
||||||
|
|
||||||
|
## Invite shape
|
||||||
|
|
||||||
|
New table `GuestInvitation`, separate from `MembershipInvitation` (which is GitHub-login-keyed and leads to
|
||||||
|
approval, not to a guest). Fields:
|
||||||
|
|
||||||
|
| field | rule |
|
||||||
|
|---|---|
|
||||||
|
| `Id` | Guid. |
|
||||||
|
| `CodeHash` | SHA-256 of a 256-bit random code. The code itself is shown to the issuer once and never stored. |
|
||||||
|
| `IntendedIdentity` | the localpart the issuer picks (for example `sletz`), validated by `BifrostIdentityService.NormalizeIdentity`, reserved while the invite is open. Minted once on accept; a collision gets the usual `-2` suffix. |
|
||||||
|
| `Label` | free note for the issuer ("sletz, Faust developer"). |
|
||||||
|
| `RoomGrants` | the rooms to grant on accept (below), as a list of grant requests. |
|
||||||
|
| `IssuedByUserAccountId`, `IssuedAtUtc` | issuer must be a platform admin (`CanManageMembership`), as for member invites. |
|
||||||
|
| `ExpiresAtUtc` | default seven days. |
|
||||||
|
| `AcceptedByUserAccountId`, `AcceptedAtUtc`, `RevokedAtUtc` | one use; revoke before accept ends it. |
|
||||||
|
|
||||||
|
The code is a bearer: whoever redeems it first is the guest. That is the cost of not needing sletz's
|
||||||
|
provider handle in advance, and it is why the code is single-use and short-lived and why the accept is shown
|
||||||
|
to the issuer. Ruled over binding the invite to a provider handle (which needs a Discord or Google id the
|
||||||
|
issuer may not have); the issuer may still set `ExpectedProvider` (see Rulings). It is carried in a form body, never in a URL.
|
||||||
|
|
||||||
|
## Sign-in via Heimdall
|
||||||
|
|
||||||
|
1. Guest opens `/invite/guest`, pastes the code, and posts it. Bifrost checks hash, expiry, unused, unrevoked, and stores the invite id in
|
||||||
|
the existing Heimdall attempt (`HeimdallAuthService` protects attempt state with the data protector).
|
||||||
|
2. Bifrost starts Heimdall sign-in with `requireMemberAccess = false` (identity only, no entitlement policy).
|
||||||
|
Heimdall authenticates; it does not issue the identity (`docs/jurisdiction-map.md`).
|
||||||
|
3. On the callback, in one transaction: resolve `HeimdallAccountId`.
|
||||||
|
- No account: create `UserAccount` with `IntendedIdentity`, `Membership { Status = Active, Role = Guest }`, write
|
||||||
|
the room grants, mark the invite accepted, write the receipt.
|
||||||
|
- Account exists: the invite never lowers an account. A `member`, `patron` or `user` keeps their role; the grants
|
||||||
|
are added and the invite is spent. If the existing account is `Left` or `Erased`, refuse.
|
||||||
|
4. Bifrost issues its own cookie as for any account. From there the guest reaches chat through the one OIDC client.
|
||||||
|
|
||||||
|
Gap, drift found while reading, still true on main: Bifrost's `AllowedProviders` is `discord, patreon, twitch`
|
||||||
|
(`HeimdallAuthService.cs:37-42`), but Heimdall's `bifrost` app profile allows `discord, patreon, google`
|
||||||
|
(`app-profiles.ts:152`, `bifrostProfile`). Twitch cannot start in Heimdall and Google is refused by Bifrost as a sign-in provider.
|
||||||
|
Main's only Google path is the explicit link by an already signed-in member (`HeimdallAttemptPurpose.LinkAwaitGoogle`,
|
||||||
|
`HeimdallAuthService.cs:672`, PRs #81 and #82); it never signs anyone in, so it does not close the gap. A guest with
|
||||||
|
neither Discord, Patreon nor a Google account cannot sign in, and GitHub is not a Heimdall sign-in provider for
|
||||||
|
this app. Which provider sletz uses is unknown to me; align the two lists before the first invite.
|
||||||
|
|
||||||
|
## Guest rights
|
||||||
|
|
||||||
|
A guest may: sign in, hold a Bifrost cookie, hold a chat session through OIDC (after accepting the training notice, as any chat account does on main, `ConsentEndpoints.HasLiveReceiptAsync`, `ConsentEndpoints.cs:146`), see and edit their own profile
|
||||||
|
(`MemberProfile`), be in the rooms granted to them, and leave or erase (below). A guest may not:
|
||||||
|
|
||||||
|
- vote on motions: `EffectiveVotingWeight` is `0` for any role but `member` (today it is `Max(1, ...)` for
|
||||||
|
`Active` (`BifrostModels.cs:361-363`), which would give every guest weight 1; that line must read the role);
|
||||||
|
- cast concept-mill appraisals: `VoterIdentity.For` returns no voter for a guest (not even `VoterClass.Account`);
|
||||||
|
- appear on any estate roll or in any tally. The charter proposal snapshots each estate's roll at notice (A6);
|
||||||
|
`guest` is on no roll, so a guest cannot be counted, cannot make a quorum, and reclassifying a guest after a
|
||||||
|
snapshot changes nothing for that snapshot;
|
||||||
|
- use bridge transport, claim or log work, earn points or ledger credit, or hold tier snapshots (those make them
|
||||||
|
a patron or member by changing role, not by decorating a guest);
|
||||||
|
- hold a `MemberRole` or any of the `CanManage*` flags;
|
||||||
|
- invite anyone.
|
||||||
|
|
||||||
|
This list is enforced by role in one place (`CurrentBifrostActor`), not by a check at each use.
|
||||||
|
|
||||||
|
## Per-room grants
|
||||||
|
|
||||||
|
Rooms are Matrix rooms in chat, not Bifrost objects. Bifrost owns the decision, so a grant is Bifrost state:
|
||||||
|
|
||||||
|
`GuestRoomGrant { Id, UserAccountId, RoomRef, GrantedByUserAccountId, GrantedAtUtc, ExpiresAtUtc?, RevokedAtUtc? }`
|
||||||
|
|
||||||
|
`RoomRef` is a room id or alias as chat names it. Aqua's `#aquasynth` is the first one if she says yes.
|
||||||
|
|
||||||
|
**Scope (per `guest-room-moderation-ruled`, `guest-room-authority-ruled`).** Project rooms are public-join and
|
||||||
|
hand-moderated by the steward, with Eureka as backstop, so a guest who can reach a public room needs no grant. A
|
||||||
|
grant exists only for a room its steward chooses to keep closed, and its grantor is that room's steward, not a
|
||||||
|
platform admin (the invite itself is still issued by a platform admin; `GrantedByUserAccountId` records the
|
||||||
|
steward). Room entry for public rooms is not Bifrost's decision.
|
||||||
|
|
||||||
|
The grant has to reach Matrix to mean anything. Today Bifrost's only Matrix writer is the Persona mouth, with
|
||||||
|
per-Persona access tokens (`docs/bridge.md`), and it holds no admin or invite right.
|
||||||
|
|
||||||
|
Gap (largest in this doc): something must perform "invite this Matrix user to that room" on a grant and "remove
|
||||||
|
them" on revoke or expiry. Candidates: a Bifrost-owned bot user that is a member with invite power in the granted
|
||||||
|
rooms (reuses the Matrix client API, no Synapse admin credential), or the Synapse admin API. I recommend the bot
|
||||||
|
user: narrower credential, and the room's power levels remain the real gate. Until it exists, the grant is a
|
||||||
|
record, a human invites the guest by hand, and the receipt says `delivered_by: manual`. Whether the closed rooms a
|
||||||
|
steward keeps are invite-only in Synapse is a chat configuration fact I have not verified.
|
||||||
|
|
||||||
|
What Matrix takes from the Bifrost account is exactly this effector: invite or remove on a grant, and the power
|
||||||
|
level the effector sets on invite. Role never enters OIDC, so Matrix reads no role from the issuer
|
||||||
|
(`bifrost-owns-accounts-invite-only`: grants flow from the account through the effector, not through claims).
|
||||||
|
|
||||||
|
**Guest DMs (`guest-dms-ruled`) conflict, open.** The mouth declines invites from other servers and accepts
|
||||||
|
same-server DM invites (`tools/persona-matrix-mouth.mjs` `answerInvites`). The ruling's decline-for-now assumed
|
||||||
|
federated guests; a Bifrost guest is a local `@sletz:<server>`, so the mouth would accept their DM. Either the mouth
|
||||||
|
declines DMs from role `guest` (using the account document below), or the ruling is revisited. That is Eureka's and
|
||||||
|
the ruling's owner's call, not this doc's; until it is made, the mouth's behaviour is the ruling's opposite for local
|
||||||
|
guests.
|
||||||
|
|
||||||
|
Second gap: a guest has a full Matrix account once MAS provisions the localpart, so Matrix itself will let them
|
||||||
|
create rooms or DM unless Synapse's room-creation and invite settings (`room_list_publication_rules`,
|
||||||
|
`allow_public_rooms_*`, a spam-checker or module) say otherwise. These are global in Synapse, not per user, so a
|
||||||
|
guest limit may have to be power levels in every room they are in. I did not find a per-user switch.
|
||||||
|
|
||||||
|
## Role change on the same account id, with a receipt
|
||||||
|
|
||||||
|
`ChangeRole(accountId, to, actor, reason)` is the only writer of `Membership.Role`. It runs in one transaction:
|
||||||
|
|
||||||
|
1. refuse `Erased` and `Left`; refuse a no-op;
|
||||||
|
2. write `Role`, and for `member` also set `Status = Active`, `ApprovedAtUtc`, and the default `StandardMember`
|
||||||
|
capability role (the same effects as `OnPostApproveAsync`); for `patron`, nothing beyond the role (tier
|
||||||
|
snapshots come from support events as before);
|
||||||
|
3. write `AccountRoleReceipt { Id, UserAccountId, From, To, ChangedAtUtc, ChangedByUserAccountId, Reason }`;
|
||||||
|
4. leave `UserAccount.Id`, `NormalizedBifrostIdentity`, `HeimdallAccountId`, grants and profile untouched.
|
||||||
|
|
||||||
|
Who may change: a platform admin (`CanManageMembership`). Promoting to `member` is the existing approve path;
|
||||||
|
this design routes it through `ChangeRole` so one writer exists. Promoting to `member` also applies whatever the
|
||||||
|
charter says about joining an estate (not decided; see Questions). Demotion (member to guest) is allowed and
|
||||||
|
receipted; it also removes the `MemberRole`s and capability flags in the same transaction.
|
||||||
|
|
||||||
|
The receipt is a Postgres row today, like `AuditEvent`. Bifrost's rule is that durable state has a CultCache `.cc`
|
||||||
|
witness (`docs/jurisdiction-map.md`, Design Rules); the witness is owed (Gaps).
|
||||||
|
|
||||||
|
Seamless means: the guest's session cookie, OIDC subject, Matrix id, display name and room memberships do not
|
||||||
|
change on promotion. A cookie issued before promotion carries identity claims only, never the role, so it needs
|
||||||
|
no refresh; the actor is read from the database each request (`CurrentBifrostActorAccessor`).
|
||||||
|
|
||||||
|
## Leave and erase
|
||||||
|
|
||||||
|
Neither exists in Bifrost today. Two different acts:
|
||||||
|
|
||||||
|
**Leave** (guest or any role, self-service): sets `Status = Left`, revokes every grant, and expels the account
|
||||||
|
from granted rooms through the same effector as grants. Once the reconciler and the chat refusals name `Left` (see Decision),
|
||||||
|
it ends the MAS session within its 30 s interval, and the token and userinfo endpoints refuse. The account row and
|
||||||
|
`Id` stay, so a later invite can restore it (a `Left` account re-accepting is a role change from itself, receipted).
|
||||||
|
Nothing else about the person is deleted by leaving.
|
||||||
|
|
||||||
|
**Erase** (self-service, or admin on request): irreversible. In one transaction: blank `DisplayName`, `AvatarUrl`,
|
||||||
|
`MemberProfile`, `GitHubLogin`/`GitHubUserId`, clear `HeimdallAccountId` (the authenticator link), set
|
||||||
|
`Status = Erased`, keep `Id` and `NormalizedBifrostIdentity` as a tombstone so the localpart is never reissued to
|
||||||
|
someone else (OIDC says it is minted once), keep receipts but with names stripped. The reason to keep a tombstone
|
||||||
|
row is that receipts and audit events point at the id.
|
||||||
|
|
||||||
|
An erasing guest has no votes, ledger entries or points, because guests cannot create them. A member or patron
|
||||||
|
who erases does, and those are accounting records: their erase is a separate question (Questions). Guest erase
|
||||||
|
is the case this design covers.
|
||||||
|
|
||||||
|
Outside Bifrost, erase is incomplete without two effectors:
|
||||||
|
|
||||||
|
- Matrix: Synapse's deactivate-with-erase admin call and MAS deactivation for the user. Federation is disabled in
|
||||||
|
the chat map (`gamecult-ops/docs/gamecult-chat-map.md`: federation paths 404), which helps: messages are
|
||||||
|
not copied to other servers. Other members' clients, and any export or training copy, are not reached by an
|
||||||
|
erase. Whether chat content is training data is `heimdall-body`'s consent rulings (Heimdall PR #6), which already
|
||||||
|
define exit by redaction; a guest's messages follow whatever that doc says, not this one.
|
||||||
|
- Heimdall: I found no account-delete or unlink path in Heimdall `src`. Clearing `HeimdallAccountId` on the Bifrost
|
||||||
|
side leaves the Heimdall account and its provider link alive. Heimdall needs an erase call keyed by the account id
|
||||||
|
before "erased" is true end to end.
|
||||||
|
|
||||||
|
## What Eureka reads
|
||||||
|
|
||||||
|
Personas read the role, not the account. Do not put it in OIDC: the issuer promises "no membership detail leaves
|
||||||
|
Bifrost" (`docs/oidc-issuer.md`) and chat does not need it. Publish a typed CultMesh document under the
|
||||||
|
`gamecult.bifrost.governance` family (the nearest existing schema namespace, `verse-service-contract.md` l.60), id
|
||||||
|
`gamecult.bifrost.account.v1`, key = account id:
|
||||||
|
|
||||||
|
| field | type | note |
|
||||||
|
|---|---|---|
|
||||||
|
| `account_id` | uuid | OIDC `sub`; never changes. |
|
||||||
|
| `identity` | string | `NormalizedBifrostIdentity`; the Matrix localpart. |
|
||||||
|
| `matrix_id` | string | the full mxid `@<identity>:<server>`, server name taken from MAS config at publish time so no reader assumes it. The lookup key for a Persona, which holds the Matrix sender id and not the account uuid. |
|
||||||
|
| `display_name` | string | blank once erased. |
|
||||||
|
| `role` | `guest` \| `user` \| `patron` \| `member` | the field Personas read. |
|
||||||
|
| `status` | `authenticated` \| `pending_approval` \| `active` \| `suspended` \| `left` \| `erased` | |
|
||||||
|
| `role_since` | UTC ms | from the latest `AccountRoleReceipt`. |
|
||||||
|
| `rooms` | list of room refs | only for `guest`: the live grants. Others get rooms by estate. |
|
||||||
|
|
||||||
|
Contract the document carries, not left to each reader:
|
||||||
|
|
||||||
|
- **Lookup.** The document is queryable by `matrix_id`.
|
||||||
|
- **Absence is `unknown`.** A sender with no document is not a Bifrost account (a bridge ghost or an unlinked user).
|
||||||
|
Readers must treat it as `unknown`, never default it to `guest`, `user` or `member`. This reverses today's Persona
|
||||||
|
reading (everyone unlisted is `member`), which narrows to the Bifrost `member` role.
|
||||||
|
- **Status gates the role.** Only `status = active` yields a usable role; `suspended`, `left`, `erased`,
|
||||||
|
`authenticated` and `pending_approval` yield none.
|
||||||
|
- **Not Bifrost accounts.** Operator, the Persona's own id and Minds are typed by the reader's config, which takes
|
||||||
|
precedence over the document. Minds are not Bifrost accounts and must not fall to `unknown`.
|
||||||
|
- **Freshness.** A reader loads the document when it builds each turn, never once at start, so a role change
|
||||||
|
applies from the next message; past messages keep the role they were read under. `role_since` lets a trace say
|
||||||
|
which role was read. Publisher bound: a role or status change is published within 30 seconds, the same bound the
|
||||||
|
OIDC reconciler already keeps for a non-`active` subject. No publisher exists, so this is the requirement it is
|
||||||
|
built to, not a measurement.
|
||||||
|
|
||||||
|
Bifrost does not decide Persona behavior; it states the role.
|
||||||
|
|
||||||
|
No such publisher or witness exists; Bifrost has no `.cc` export for accounts today.
|
||||||
|
|
||||||
|
## Cut sequence (not specs)
|
||||||
|
|
||||||
|
1. `Membership.Role`, backfill, `IsActiveMember` and the OIDC tests moved to the new reading, vote and concept-vote
|
||||||
|
exclusions, with tests that fail if a guest gets weight or a voter key.
|
||||||
|
2. `GuestInvitation`, the accept path, the Heimdall provider list aligned.
|
||||||
|
3. `AccountRoleReceipt` and `ChangeRole`, with `OnPostApproveAsync` routed through it.
|
||||||
|
4. `GuestRoomGrant` and the Matrix effector.
|
||||||
|
5. Leave, then erase (Bifrost side), then the Matrix and Heimdall effectors.
|
||||||
|
6. The account document and its `.cc` witness.
|
||||||
|
|
||||||
|
## Gaps, plainly
|
||||||
|
|
||||||
|
- The Matrix effector for grants, leave and erase does not exist, and no credential for it is provisioned.
|
||||||
|
- Synapse cannot cap what a guest does per user; room-creation and invite limits are global (unverified: I did not
|
||||||
|
read the live Synapse config).
|
||||||
|
- Heimdall has no erase path (re-checked at `afa1b74`: no account-delete or unlink route in `src`, and `docs/answer-collector-consent.md`, merged as Heimdall PR #6, redacts by exit and says nothing of guests). Bifrost and Heimdall disagree on provider lists today.
|
||||||
|
- No `.cc` witness or CultMesh publisher for accounts or receipts. Bifrost's account state is Postgres only.
|
||||||
|
- Matrix id shape (`@<identity>:<server>`) depends on MAS importing `preferred_username` as localpart; the OIDC doc
|
||||||
|
says so, I did not check the deployed MAS.
|
||||||
|
- Tie to the answer-collector consent doc (Heimdall PR #6, merged; `docs/answer-collector-consent.md`): a guest posting in a room may be posting to a sample
|
||||||
|
collector. That doc keys on `member_id`, and says a sender with no linked member is dropped (l.197). Whether a guest has a
|
||||||
|
`member_id`, and so whether their answers are collected at all, is not decided here. Default: not collected.
|
||||||
|
- Erase for member and patron roles (ledger and vote records) is unmapped.
|
||||||
|
|
||||||
|
## Questions for the deciders
|
||||||
|
|
||||||
|
1. **Name and shape**: ruled (stored `Role`), see Rulings.
|
||||||
|
2. **Bearer link or provider-bound invite?** Ruled (single-use code from a form), see Rulings.
|
||||||
|
3. **Which Heimdall provider will sletz sign in with?** The lists are ruled (see Rulings); this is the issuer's to learn before the first invite.
|
||||||
|
4. **`member_id` for the answer collector**: ruled (none for a guest), see Rulings.
|
||||||
|
5. **Does promotion to member join the Members estate immediately**, or does the charter's notice and snapshot
|
||||||
|
rule apply to the roll? The charter text is a proposal, not in force.
|
||||||
18
docs/heimdall-app-secret-file.md
Normal file
18
docs/heimdall-app-secret-file.md
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
# Heimdall app secret from a file
|
||||||
|
|
||||||
|
`Heimdall:AppSecret` (`Heimdall__AppSecret`) is Bifrost's app secret for Heimdall slug `bifrost`; it is sent as the
|
||||||
|
`x-heimdall-app-secret` header. Set through the environment it rides in the process environment. `Heimdall:AppSecretFile`
|
||||||
|
(`Heimdall__AppSecretFile`) names a file holding it instead.
|
||||||
|
|
||||||
|
- File set: Bifrost reads it once at startup and trailing newlines are trimmed. The file wins over `Heimdall__AppSecret`.
|
||||||
|
- File set but missing, unreadable, a directory, or empty: startup fails in every environment. The message names
|
||||||
|
`Heimdall:AppSecretFile` and the path, never the secret.
|
||||||
|
- Only `Heimdall__AppSecret` set: still works; startup logs a deprecation warning (without the value).
|
||||||
|
- Neither set: startup fails outside Development and Testing, naming `Heimdall:AppSecretFile` and `Heimdall:AppSecret`
|
||||||
|
(`StartupConfigurationValidator`). Development and Testing still start, with Discord and Patreon sign-in off.
|
||||||
|
|
||||||
|
Under systemd, pass the file with `LoadCredential=heimdall-app-secret:<root-owned file>` and
|
||||||
|
`Environment=Heimdall__AppSecretFile=%d/heimdall-app-secret`.
|
||||||
|
|
||||||
|
Code: `HeimdallOptions.ResolveAppSecret` (`src/Bifrost.Web/Configuration/HeimdallOptions.cs`), wired in `Program.cs`, forced at
|
||||||
|
startup by `StartupConfigurationValidator.Validate`. Tests: `tests/Bifrost.Web.Tests/HeimdallAppSecretFileTests.cs`.
|
||||||
|
|
@ -105,6 +105,8 @@ This keeps Reddit useful without making subreddit mechanics the secret constitut
|
||||||
|
|
||||||
Heimdall authenticates; it does not issue GameCult identity. Bifrost owns the identity (`UserAccount.Id`, `NormalizedBifrostIdentity`) and issues it to chat as an OIDC provider (`docs/oidc-issuer.md`). `HeimdallAccountId` is an authenticator handle that links a Heimdall account to a Bifrost identity.
|
Heimdall authenticates; it does not issue GameCult identity. Bifrost owns the identity (`UserAccount.Id`, `NormalizedBifrostIdentity`) and issues it to chat as an OIDC provider (`docs/oidc-issuer.md`). `HeimdallAccountId` is an authenticator handle that links a Heimdall account to a Bifrost identity.
|
||||||
|
|
||||||
|
A member's provider logins are Heimdall's (`linked_identities`); Bifrost shows, links and unlinks them on `/Membership/LinkedAccounts` by calling Heimdall's member routes with a bearer from a fresh Heimdall sign-in, and keeps none (`docs/linked-accounts.md`). Strong proof for an unlink is a Bifrost-verified passkey (WebAuthn, RP ID the Bifrost host) that Bifrost asserts to Heimdall through its app-asserted step-up route; Bifrost owns the credential store and the ceremonies, Heimdall owns the unlink gate (`docs/passkeys.md`).
|
||||||
|
|
||||||
Bifrost consumes Heimdall claims. It does not become the key vault. The split is bridge versus gate: Heimdall decides who may cross under which grant; Bifrost moves authorized work across public protocols and records where it landed.
|
Bifrost consumes Heimdall claims. It does not become the key vault. The split is bridge versus gate: Heimdall decides who may cross under which grant; Bifrost moves authorized work across public protocols and records where it landed.
|
||||||
|
|
||||||
### Patron Collection Crossing
|
### Patron Collection Crossing
|
||||||
|
|
|
||||||
70
docs/linked-accounts.md
Normal file
70
docs/linked-accounts.md
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
# Linked accounts
|
||||||
|
|
||||||
|
`/Membership/LinkedAccounts` (`src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml[.cs]`) is where a signed-in member sees the provider logins attached to their Heimdall account, links another one, and unlinks one. Heimdall owns the logins and every rule about them; this page starts the flows and shows what Heimdall answered. A member reaches it from the membership status page. A session with no Heimdall account (a Bifrost-native GitHub sign-in) gets a note instead of controls.
|
||||||
|
|
||||||
|
## What it does
|
||||||
|
|
||||||
|
| Action | What Bifrost does | Heimdall call |
|
||||||
|
|---|---|---|
|
||||||
|
| Show my logins | A fresh ordinary Heimdall sign-in as the session's account, through the proof provider (below); inside its completion, the list | `GET /v1/me/identities` with that sign-in's bearer |
|
||||||
|
| Link Discord, Patreon or Google | The same fresh sign-in as proof, then the link start for the chosen provider with its bearer. Needs a current list. Discord and Patreon attach in Heimdall's callback and return a link completion; Google writes a pending link, and a second fresh sign-in confirms it | `POST /v1/oauth/{provider}/start` `mode: "link"`, then for Google `POST /v1/apps/bifrost/links/confirm` |
|
||||||
|
| Unlink | A sign-in through Google with `stepUp: true` (app secret); inside its completion, the unlink | `POST /v1/me/identities/{id}/unlink` with that sign-in's bearer |
|
||||||
|
| Unlink with a passkey (an account with a strong passkey) | A WebAuthn assertion verified at Bifrost, then a fresh ordinary sign-in as the account; inside its completion, Heimdall's app-asserted step-up, then the unlink with the token it returns | `POST /v1/apps/bifrost/step-up` `{method: "bifrost-passkey", nonce}`, then `POST /v1/me/identities/{id}/unlink` |
|
||||||
|
| Add or revoke a passkey | Enrolment needs a fresh Heimdall sign-in first and cools off 48 hours; revoking needs no proof | none |
|
||||||
|
|
||||||
|
The linkable providers are the ones Heimdall's `bifrost` profile admits (`identityProviders` in Heimdall `src/app-profiles.ts`): Discord, Patreon, Google. Twitch is offered for sign-in elsewhere in Bifrost but the profile refuses it, so it is not offered here.
|
||||||
|
|
||||||
|
## How the bearer is kept: it is not
|
||||||
|
|
||||||
|
Bifrost keeps no Heimdall token. Each action is an attempt: a Data Protection cookie (`__Host-bifrost_heimdall_<slot>`, HttpOnly, Secure, ten minutes) holding a purpose (`ListProof`, `UnlinkProof`, `LinkStart`, `LinkAwaitGoogle`, `LinkConfirm`, `LinkAwaitDirect`), the account the session must be, and a target (the provider to link, or the identity to unlink). The browser returns from Heimdall to `/auth/heimdall/complete`; Bifrost redeems the code, verifies the token, requires that the proven account is the attempt's account and that the browser's session is that same account, calls Heimdall with the bearer inside that one request, and drops it. The bearer is never stored, logged, put in a cookie or a redirect, or rendered. Heimdall's member routes go through an HTTP client that carries no app secret (`HeimdallMemberClient`), so a Bifrost fault cannot call them without a member present.
|
||||||
|
|
||||||
|
The list is kept for five minutes in this process only (`LinkedAccountsSnapshots`), keyed by the Heimdall account id, so the page can render after the completion's redirect: identity id, provider, display name (or username when there is none) and link date. Never the bearer, the email, the provider user id or the scopes. It is not given to the browser. A restart or the five minutes empties it and the page offers "Show my linked logins" again.
|
||||||
|
|
||||||
|
Every action is a POST with antiforgery; a GET starts nothing. The completion route's answers are `Cache-Control: no-store`. The page and every redirect carry only a code from a closed set (`HeimdallLinkOutcomes`, `?result=`); the wording is Bifrost's, never Heimdall's text or the query's.
|
||||||
|
|
||||||
|
## Which provider proves the account
|
||||||
|
|
||||||
|
An ordinary proof sign-in through Discord or Patreon when the account no longer holds that login makes Heimdall mint a new, unrelated account that holds it (those providers are `mints_account`), and the freed login then answers `identity_linked_elsewhere` when the member tries to link it back. Google is `requires_link`: Heimdall refuses a Google sign-in for a login no account holds (`identity_not_linked`) and never mints. So Bifrost never guesses a provider, and it does not use the "provider you signed in with" claim in the session (that records how you signed in once, not what the account holds now). This guarantee covers this page's proofs only: the older anonymous `GET /auth/heimdall/{provider}` still starts an ordinary sign-in through any named provider, and can overwrite an in-flight attempt slot; that route is unchanged here.
|
||||||
|
|
||||||
|
- With a current list (the five-minute snapshot), the proof goes through a provider on it: Discord, else Patreon, else Google.
|
||||||
|
- With no list (first visit, five minutes passed, a restart), the page offers only "Show my logins through Google (cannot create an account) / Discord / Patreon" and says plainly that Bifrost cannot tell what the account holds, so the member picks a login they know it holds. A named Discord or Patreon the account turns out not to hold still mints at Heimdall: that is the member's choice and the page says so beforehand. A refresh with no list and no named provider starts nothing (`provider_needed`).
|
||||||
|
- Link buttons appear only with a current list; a posted link with none starts nothing (`list_expired`). Unlink needs the list too. After an unlink whose result is not a definitive refusal (a 500, a lost or malformed answer, not found) the list is dropped, since Heimdall may have applied it; only `403 step_up_required`, `409 last_identity` and `401` leave it.
|
||||||
|
|
||||||
|
## The proof limit
|
||||||
|
|
||||||
|
Passkeys (`docs/passkeys.md`) are the strong proof: an account with a passkey past its cooling-off unlinks with it, and the Google step-up below is then closed (`passkey_required`). The rest of this section is the Google proof, which stays for an account with no strong passkey.
|
||||||
|
|
||||||
|
Unlinking needs fresh proof: Heimdall refuses `403 step_up_required` unless the access token carries `step_up_at` from a step-up sign-in within 600 seconds (`docs/service-contract.md`, `POST /v1/me/identities/{identityId}/unlink`, in the Heimdall repository). Only Google can give that to a `bifrost` sign-in: Discord and Patreon have no re-authentication parameter (an open provider session completes without credentials), and Twitch and YouTube, which do, are not in the `bifrost` profile. So:
|
||||||
|
|
||||||
|
- An account with no Google login linked and no strong passkey cannot unlink anything from here. The page says what it can do (add a passkey; the time a cooling-off one becomes strong) and shows no Unlink button; a posted unlink starts nothing.
|
||||||
|
- Heimdall answers `503 provider_not_configured` for Google until a Google OAuth client is configured on the Heimdall host (follow-up `heimdall-body:follow_up:google-console-client-registration`; not set live as of 2026-11-13). The step-up start is then refused and the page says fresh proof could not be started. Nothing loops: the refusal sets no attempt cookie.
|
||||||
|
- Linking Google needs the same client. Until then the Google link button ends in "That could not be completed. Nothing was changed."
|
||||||
|
- A Google step-up proof is as strong as Google's `prompt=login`; Heimdall says "asked", not "verified" (`stepUpRequested`).
|
||||||
|
|
||||||
|
The unlink completion must also say a step-up was requested (`stepUpRequested`, set by Heimdall when the start asked for one); one that does not is refused without calling Heimdall. Heimdall's other answers are shown as plain outcomes with nothing changed: `409 last_identity` (the last login is never removed), `404 identity_not_found` (the list is dropped as stale), `401 sign_in_required`, `403 step_up_required`, and any failure to reach Heimdall.
|
||||||
|
|
||||||
|
A link refused because the login already belongs to another account (`409 identity_linked_elsewhere` from `links/confirm`; for Discord and Patreon the callback's `link_initiator_mismatch`, carried on by the complete page as a fixed result) is shown as "That login belongs to another account." The other account is never named.
|
||||||
|
|
||||||
|
## Not here
|
||||||
|
|
||||||
|
- Merging two accounts. A refused link ends there; nothing is moved or merged. Merging is the separate Merge accounts page, behind the `AccountMerge:Enabled` flag (`docs/account-merge.md`, Pages and flags).
|
||||||
|
- Step-up through Discord, Patreon or Twitch. Heimdall does not offer it to the `bifrost` profile.
|
||||||
|
- Linking Twitch or GitHub: not admitted by the `bifrost` profile, and Heimdall's GitHub runtime is not implemented.
|
||||||
|
- A list of other apps' logins, grants or consent receipts (Heimdall's grants page).
|
||||||
|
|
||||||
|
## Where the code is
|
||||||
|
|
||||||
|
- `Pages/Membership/LinkedAccounts.cshtml[.cs]`: the page and its three POST handlers.
|
||||||
|
- `Features/Heimdall/HeimdallAuthService.cs`: the attempt machinery (`StartListAsync`, `StartLinkAsync`, `StartUnlinkAsync`, `ContinueLinkAsync`), shared with sign-in.
|
||||||
|
- `Features/Heimdall/HeimdallMemberClient.cs`: the two member calls and their outcome mapping.
|
||||||
|
- `Features/Passkeys/`, `wwwroot/js/passkeys.js`: the passkey ceremonies (`docs/passkeys.md`).
|
||||||
|
- `Features/Heimdall/LinkedAccountsSnapshots.cs`: the five-minute list.
|
||||||
|
- Tests: `tests/Bifrost.Web.Tests/LinkedAccountsTests.cs`, `HeimdallGoogleLinkTests.cs`, `PasskeyTests.cs`, with the fake Heimdall in `Support/HeimdallTestKit.cs`.
|
||||||
|
|
||||||
|
## Known leftover
|
||||||
|
|
||||||
|
Several exits leave the held attempt cookie (`__Host-bifrost_heimdall_<slot>`, HttpOnly, so script cannot clear it) in the browser until its ten minutes end: the complete page's redirect when Discord or Patreon refuses a link because the login belongs to another account, every other `heimdall_status=error` redirect, and a return with no code or no attempt. The script redirects without posting anything; clearing the cookie would need a server route reached by GET or a post from the failure path, which the hardened script deliberately does not do.
|
||||||
|
|
||||||
|
A start takes a free slot, else overwrites the slot that expires first, live or dead (`ChooseSlot`, two slots). So three member starts within ten minutes can cost a still-live older attempt, which then finds no cookie and is refused; the member starts again.
|
||||||
|
|
||||||
|
See [account-merge.md](account-merge.md) for what a merge does to Bifrost records, the states it moves through and how a folded account stands.
|
||||||
133
docs/passkeys.md
Normal file
133
docs/passkeys.md
Normal file
|
|
@ -0,0 +1,133 @@
|
||||||
|
# Passkeys: strong proof for unlinking a login
|
||||||
|
|
||||||
|
A Heimdall-backed member can enrol WebAuthn passkeys on `/Membership/LinkedAccounts` and use one as the strong proof that unlinking a provider login needs. Bifrost verifies the passkey; Heimdall accepts Bifrost's word through its app-asserted step-up route (`POST /v1/apps/bifrost/step-up`, Heimdall `docs/service-contract.md`, `docs/app-profiles/bifrost.md`). Scoping and the option comparison are in the handoff `strong-proof-scoping-20261113.md` (option 1a with the S1 sink).
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
- Accounts that have a `HeimdallAccountId`: the accounts that can unlink at all. A Bifrost-native-only account (a native `BifrostIdentity` or GitHub sign-in) has no logins to unlink and gets no passkeys from this cut; the page shows it nothing.
|
||||||
|
- Unlink only. A passkey is not a sign-in method here.
|
||||||
|
|
||||||
|
## The library: Fido2NetLib (`Fido2` 4.3.3)
|
||||||
|
|
||||||
|
Decision: use `Fido2` 4.3.3 (NuGet id `Fido2`, repository `passwordless-lib/fido2-net-lib`) for every byte of WebAuthn parsing and verification. Bifrost hand-rolls no CBOR, COSE or signature code.
|
||||||
|
|
||||||
|
What was checked on 2026-11-13, against the package and the repository, not from memory:
|
||||||
|
|
||||||
|
| Question | Finding |
|
||||||
|
|---|---|
|
||||||
|
| Licence | MIT, in the nuspec (`<license type="expression">MIT</license>`) and in the repository's `LICENSE.txt` (GitHub reports `MIT`). Its closure: `Fido2.Models` MIT; `NSec.Cryptography` 25.4.0 MIT; `libsodium` 1.0.20.1 ISC; `System.Formats.Cbor` 9.0.24, `Microsoft.IdentityModel.JsonWebTokens` 8.2.0, `Microsoft.Extensions.Http` 9.0.0, `Microsoft.Bcl.Memory` 9.0.14 all Microsoft MIT. All open source. |
|
||||||
|
| Maintained | Not archived; repository pushed 2026-11-11; 4.3.3 released 2026-11-11 and 4.3.2 on 2026-10-29; about 1,460 stars. |
|
||||||
|
| net8.0 | The 4.3.3 nuspec has a `net8.0` dependency group (and `net10.0`); it targets the framework this project targets. |
|
||||||
|
| Packed attestation | `Src/Fido2/AttestationFormat/` holds `Packed`, `None`, `FidoU2f`, `Tpm`, `AndroidKey`, `AndroidSafetyNet`, `Apple`, `AppleAppAttest`. Bifrost asks for `none` attestation and does not use a metadata service, so it does not depend on any of them being trusted; a client that sends another format still has it parsed and its statement verified structurally by the library. |
|
||||||
|
| What verification covers | Read in `AuthenticatorAssertionResponse.cs`: challenge, origin (against `Fido2Configuration.Origins`), `webauthn.get` type, RP ID hash, user-present and user-verified flags (when required), signature over `authData || SHA-256(clientDataJSON)` with the stored COSE key, user handle ownership, and the sign count (see "Sign count" below). Enrolment verifies the attestation, the credential id and the key. |
|
||||||
|
| Transitive weight | Heavier than the repository's other packages: `Microsoft.Extensions.Http` 9.0.0 pulls `Microsoft.Extensions.*` 9.0.0, so existing 8.x entries move to 9.0.0 (seven in `src/Bifrost.Web/packages.lock.json`; twelve `Microsoft.Extensions.*` entries plus `System.Diagnostics.DiagnosticSource` in the test project's lockfile, which sees them too; app-local on top of the net8 shared framework, a supported combination), and the lockfiles gain `Fido2`, `Fido2.Models`, `Microsoft.Bcl.Memory`, `Microsoft.Extensions.Http`, `Microsoft.Extensions.Diagnostics[.Abstractions]`, `Microsoft.Extensions.Configuration[.Binder]`, `System.Diagnostics.DiagnosticSource`, `Microsoft.Extensions.Options.ConfigurationExtensions`, `NSec.Cryptography`, `System.Formats.Cbor` and the native `libsodium` package (the Linux x64 glibc and musl binaries ship in the package's `runtimes/`). `Microsoft.IdentityModel.JsonWebTokens` is requested at 8.2.0 and already resolved to 8.19.2 (through OpenIddict) before this change; it still does. `packages.lock.json` in both projects is regenerated and committed. |
|
||||||
|
| Alternatives | Not needed: the candidate passed. |
|
||||||
|
|
||||||
|
Not verified: that the 9.0.0 `Microsoft.Extensions.*` assemblies behave on the live host's ASP.NET Core 8 runtime beyond the test host (the suite runs the real app under it); that `libsodium` loads on Yggdrasil (the EdDSA test loads it here, on Debian x64).
|
||||||
|
|
||||||
|
The library is used through four calls: `RequestNewCredential`, `MakeNewCredentialAsync`, `GetAssertionOptions`, `MakeAssertionAsync`. `PasskeyRelyingParty` builds it from `Host:PublicBaseUrl`.
|
||||||
|
|
||||||
|
## Sign count
|
||||||
|
|
||||||
|
The stored sign count is updated on every successful assertion, and the library refuses a counter that does not increase once either side is non-zero. Authenticators that always report zero (most synced passkeys) are accepted every time and get no clone detection from this: both counters stay zero. An authenticator that reported a non-zero count and then reports zero is refused. Clone detection is therefore real only for hardware keys and other counting authenticators.
|
||||||
|
|
||||||
|
## Relying party
|
||||||
|
|
||||||
|
RP ID is the host of `Host:PublicBaseUrl`, the one origin is its scheme, host and port. They come from configuration and from nothing the browser sends. Passkeys are unavailable, with a warning logged once at start, when `Host:PublicBaseUrl` is not https or its host is not `Host:ExpectedHost`: the page offers none and every ceremony endpoint refuses (`passkeys_unavailable`). `PasskeyRelyingParty` is resolved at startup, so a misconfiguration is logged once at boot (not at the first ceremony). `Host:ExpectedHost` must be a bare host name: one with a port (`host:443`) or an IP address (`[::1]`, `127.0.0.1`) makes passkeys unavailable and is reported, because an IP address is not a valid RP ID and a port is not part of it. No new configuration key exists.
|
||||||
|
|
||||||
|
If passkeys are unavailable while an account holds a strong passkey, the page shows no unlink form and says so: unlinking needs the passkey, the Google route stays closed (`passkey_required`), and the member can revoke their passkeys on the page (revoking does not need the relying party) to fall back to the Google proof, or wait for the operator to fix the server. This is a lockout until the operator or the member acts; it fails closed.
|
||||||
|
|
||||||
|
## State
|
||||||
|
|
||||||
|
- `PasskeyCredentials` (migration `20261113120000_AddPasskeyCredentials`, additive, applied at boot like the others): per `UserAccount` id, `CredentialId` (unique), `PublicKey`, `SignCount`, `Transports`, `AaGuid`, `Label`, `CreatedUtc`, `StrongFromUtc` (`CreatedUtc` + 48 h), `RevokedUtc`, `LastUsedUtc`. No secret exists to store: the private key never leaves the authenticator. Rows cascade with the account.
|
||||||
|
- `PasskeyCeremonies` (in memory, this process only, like the Linked accounts list): the short-lived single-use records of the flows, each bound to a Heimdall account id and a kind (and to an identity id for unlink). A restart empties it and every flow is begun again; with more than one Bifrost instance a flow must finish on the instance that began it, otherwise it is refused and begun again. Both fail closed (a lost ticket, challenge or fact refuses; it never grants). It is chosen over a sealed cookie because a cookie cannot be spent: a copied cookie would replay.
|
||||||
|
|
||||||
|
| Kind | Lifetime | Spent |
|
||||||
|
|---|---|---|
|
||||||
|
| enrolment ticket | 5 min | by the registration post |
|
||||||
|
| enrolment challenge | 2 min | by the registration post |
|
||||||
|
| unlink challenge | 2 min | by the assertion post (success or not) |
|
||||||
|
| unlink assertion fact | 5 min | by the completion that asks Heimdall for the step-up |
|
||||||
|
|
||||||
|
A challenge kind has one live record per account: a newer one replaces the older. The table holds at most 2048 records and refuses past that.
|
||||||
|
|
||||||
|
A caller's own preconditions are checked before anything is spent. A registration needs the live ticket cookie (a session thief has none), a decodable body and room under the cap; an assertion needs a decodable body naming one of the session account's own strong, un-revoked credentials. Only then are the verification permit, the challenge and (for enrolment) the ticket taken. An assertion also needs a live challenge for that account and identity before a permit is spent. So junk posted by someone who holds only the session, naming no credential of the account or arriving with no live challenge, spends nothing. Junk naming one of the account's own credentials (the id is in `allowCredentials`) spends one verification permit per challenge that was asked for, because the first such post takes the challenge; it cannot drain the 20 permits per 10 minutes in one go. It can still burn that challenge once, and a session holder who keeps asking for challenges (an options permit each) and posting junk can exhaust both budgets: a lockout the same session already has through revoking passkeys, not a bypass. A junk post naming no credential of the account costs two cheap database lookups and no permit; that is accepted rather than spending an options-style permit on it. Both budgets are per process: with more than one instance each has its own. Asking for options spends a separate options budget (20 per 10 minutes), which a session holder can exhaust: that blocks new options for a while and nothing else. A session holder can also replace the member's pending challenge by asking for new options, which makes the member's assertion answer `passkey_expired` and the member tries again; that session can already revoke passkeys, so it is not a new capability. The member whose challenge was burned retries with a new one.
|
||||||
|
|
||||||
|
## Enrolment
|
||||||
|
|
||||||
|
1. The member is on the page with a current list (Bifrost will not guess a proof provider) and presses "Sign in again to add a passkey". Bifrost starts a fresh ordinary Heimdall sign-in through a provider the account holds (an attempt with purpose `EnrolProof`, the same machinery as the list and link proofs, `ExpectedAccountId` the session's account).
|
||||||
|
2. In that sign-in's completion, when the proven account is the session's own, Bifrost issues an enrolment ticket and sets its id in `__Host-bifrost_passkey_ticket` (HttpOnly, Secure, 5 minutes). The ticket exists only because a fresh sign-in completed in this browser: a stolen session cookie alone has no ticket and cannot get registration options.
|
||||||
|
3. The page's script asks for creation options (antiforgery header), calls `navigator.credentials.create` (user verification required, resident key preferred, `none` attestation, existing credentials excluded) and posts the base64url result. Bifrost spends the ticket and the challenge, verifies, and stores the credential with `StrongFromUtc` = now + 48 hours.
|
||||||
|
|
||||||
|
A label is limited to 40 text elements (cut by rune and grapheme, never inside a surrogate pair) and loses control and format characters (bidi overrides, joiners, zero-width marks).
|
||||||
|
|
||||||
|
Cap: five un-revoked passkeys per account (`passkey_limit`; a sixth starts no sign-in). Every options request, enrolment, assertion and enrolment start spends a permit of one `FixedWindowBudget` per account (20 per 10 minutes, `rate_limited`).
|
||||||
|
|
||||||
|
## Cooling-off
|
||||||
|
|
||||||
|
A passkey is strong from `StrongFromUtc` (at that instant and after), until revoked. Until then it is listed on the page with its time and cannot unlink anything. So someone who controls both a member's session and a provider login long enough to add a key of their own still waits 48 hours with the key visible, and the member can revoke it from the page. Revoking needs no strong proof (it only removes capability) and is shown.
|
||||||
|
|
||||||
|
## Unlink with a passkey
|
||||||
|
|
||||||
|
When the account has a strong passkey, the page's Unlink button runs a WebAuthn assertion instead of the Google step-up, and the Google route (`Unlink` handler) answers `passkey_required` and starts nothing: a member who holds a strong passkey is not offered the weaker proof. With no strong passkey the Google step-up stays as it was, and when neither exists the page says what to do (add a passkey, with the time a cooling-off one becomes strong).
|
||||||
|
|
||||||
|
1. The script asks for request options for the chosen identity (`allowCredentials` is the account's strong passkeys; user verification required). One live challenge per account, bound to the identity.
|
||||||
|
2. The browser's assertion is posted. Bifrost spends the challenge, requires the credential to be the session account's own, not revoked and past `StrongFromUtc`, and has the library verify origin, RP ID, challenge, user verification, signature and sign count. On success it records the new sign count and last use, and issues the single-use fact "passkey assertion verified" for this account and this identity (5 minutes; no credential, no bearer).
|
||||||
|
3. Bifrost starts a fresh ordinary Heimdall sign-in for the account (attempt purpose `UnlinkPasskeyProof`; proof provider as on the page: one the current list shows, never a guess). The attempt carries the fact's id.
|
||||||
|
4. In the completion, which is the only place the bearer exists: the fact is taken (missing, expired, spent, for another account or identity: no Heimdall step-up call and `passkey_expired`); the credential the fact was made with must still be the account's own, un-revoked and strong (a passkey revoked since the assertion: no step-up call, `passkey_failed`); the app secret, the bearer and `{method: "bifrost-passkey", nonce}` go to `POST /v1/apps/bifrost/step-up` (nonce: 32 fresh random bytes, base64url, 43 characters); the returned `accessToken` goes to the existing unlink call; everything is dropped. The bearer and the minted token are never stored, logged, put in a cookie or a redirect, or rendered.
|
||||||
|
|
||||||
|
Heimdall's refusals are shown as closed codes and nothing is retried in the flow: `401 sign_in_required` is `sign_in_required`; `403`/`400`/`401 app_auth_required` is `step_up_unavailable`; `409 step_up_nonce_replayed` is `step_up_replayed`; `429` is `step_up_rate_limited`; anything else, or Heimdall down, is `error`. A member whose attempt ends this way starts the unlink again (a new assertion).
|
||||||
|
|
||||||
|
## Abuse cases and what stops them
|
||||||
|
|
||||||
|
Each is a test in `tests/Bifrost.Web.Tests/PasskeyTests.cs` unless noted.
|
||||||
|
|
||||||
|
| Case | Defence |
|
||||||
|
|---|---|
|
||||||
|
| Stolen session cookie tries to enrol | No ticket without a fresh Heimdall sign-in completed in the victim's own browser. A ticket is per account, spent once, expires in 5 minutes, and is held by id in an HttpOnly cookie |
|
||||||
|
| Stolen session tries to unlink | Needs an assertion by a strong passkey of the account; the Google route is closed while one exists; no step-up is asked of Heimdall without the fact |
|
||||||
|
| Attacker who controls the provider session enrols their own key | Cooling-off: 48 hours before it counts, shown on the page, revocable by the member |
|
||||||
|
| Replay of an assertion, double submit | The challenge is single-use; two concurrent posts start one sign-in |
|
||||||
|
| Assertion for another account or identity | The credential must belong to the session's account; the challenge, the fact and the attempt are bound to the account and the chosen identity |
|
||||||
|
| Phishing site | The library checks origin and RP ID hash against the configured values; a registration or assertion with another origin or RP ID is refused |
|
||||||
|
| Cloned authenticator | A sign count that does not increase is refused; the stored count is updated on every use |
|
||||||
|
| Cooling-off boundary | Strong at exactly `StrongFromUtc`, not one second before |
|
||||||
|
| Revoked credential | Never strong; a revoke between challenge and assertion also refuses, and so does one between the assertion and the completion |
|
||||||
|
| Junk from a session thief | Preconditions first, nothing spent before they hold (see State) |
|
||||||
|
| No user verification | Required at enrolment and at assertion |
|
||||||
|
| Cross-site POST | Antiforgery on every page POST including the JSON option requests |
|
||||||
|
| Bearer anywhere | Only in the completion request's stack; tests look in logs (with HttpClient trace logging on), cookies, redirects, the page and the decrypted attempt |
|
||||||
|
| Reused or replayed step-up | A fresh nonce each call; Heimdall's 409 is shown, not retried |
|
||||||
|
| Brute force of ceremonies | One `FixedWindowBudget` per account |
|
||||||
|
|
||||||
|
## Account-scoped lookup and the allow list
|
||||||
|
|
||||||
|
An assertion is accepted only for a credential of the session's own account (strong, un-revoked), and the user handle, when the authenticator sends one, must be that account's id. The request options also carry the account's strong credentials as `allowCredentials`, which the library enforces, so a credential of another account is refused twice. The test for the account-scoped lookup (`The_credential_lookup_is_scoped_to_the_session_account_even_when_the_allow_list_is_empty`) takes the allow list out of the other account's challenge through the in-process ceremony store, which production code cannot do, so the lookup is exercised alone without weakening the server.
|
||||||
|
|
||||||
|
## Content Security Policy
|
||||||
|
|
||||||
|
Bifrost sends no `Content-Security-Policy` header (nothing in the application sets one; this predates passkeys). The passkey script is first-party and external so that a policy of `script-src 'self'` would admit it, but nothing enforces that today.
|
||||||
|
|
||||||
|
## The script
|
||||||
|
|
||||||
|
`wwwroot/js/passkeys.js` is first-party, loaded by the page with an external `src` (nothing inline, no third-party asset, no `eval`, no `innerHTML`). It asks for options with the antiforgery header, calls `navigator.credentials`, and submits a same-origin form of base64url strings (`id`, `rawId`, `attestationObject` or `authenticatorData`, `clientDataJson`, `signature`, `userHandle`, `transports`). On any failure it navigates to this page with a result code from a closed set; nothing from a response is shown. `PasskeyScriptTests` runs it under Node against a simulated browser and pins what it posts.
|
||||||
|
|
||||||
|
## What it does not do
|
||||||
|
|
||||||
|
- No passkey sign-in; passkeys prove an already signed-in session only.
|
||||||
|
- No native-only accounts (no Heimdall account, nothing to unlink).
|
||||||
|
- No recovery without mail: a member who loses every passkey revokes them and falls back to the Google step-up if a Google login is linked, or waits for the mail gate (`docs/registration-gates.md`) and the email-code factor that follows it. The email code is not built.
|
||||||
|
- Named limit and next hardening: enrolling a second passkey should require an assertion by an existing strong passkey, and enrolment should use a Google step-up when a Google login is held. Today enrolment needs only the fresh ordinary sign-in and the cooling-off, so an attacker who controls a provider session can add a key that becomes strong after 48 hours unless the member sees and revokes it. Not built; a follow-up is filed.
|
||||||
|
- A revoke between the completion's check and its unlink does not stop that unlink: the window is the few milliseconds of the two Heimdall calls and is inherent to checking before acting.
|
||||||
|
- Revoking needs no strong proof, so a stolen session can revoke a member's passkeys and fall back to the Google proof: no weaker than the account was before it had a passkey.
|
||||||
|
- A passkey synced through a cloud account the attacker also controls is a residual risk, as in the scoping note.
|
||||||
|
- Heimdall cannot tell that a passkey was checked: `bifrost-passkey` is Bifrost's word, gated by the app secret and a live bearer (Heimdall `docs/app-profiles/bifrost.md`).
|
||||||
|
- Not verified here: a real authenticator or browser. Tests use a software authenticator built from the WebAuthn specification and the script runs under Node against a simulated browser.
|
||||||
|
|
||||||
|
## Where the code is
|
||||||
|
|
||||||
|
- `Features/Passkeys/PasskeyService.cs`: enrol, assert, revoke, list; `PasskeyCeremonies.cs`: the single-use records and the rate limit; `PasskeyRelyingParty.cs`: RP ID, origin, library construction.
|
||||||
|
- `Features/Heimdall/HeimdallAuthService.cs`: the `EnrolProof` and `UnlinkPasskeyProof` attempts, `StepUpAsync`.
|
||||||
|
- `Pages/Membership/LinkedAccounts.cshtml[.cs]`, `wwwroot/js/passkeys.js`.
|
||||||
|
- `Domain/BifrostModels.cs` (`PasskeyCredential`), `Data/Migrations/20261113120000_AddPasskeyCredentials.cs`.
|
||||||
|
- Tests: `PasskeyTests.cs`, `PasskeyScriptTests.cs`, `Support/SoftwareAuthenticator.cs`, and the step-up route of the fake Heimdall in `Support/HeimdallTestKit.cs`.
|
||||||
|
|
@ -13,6 +13,7 @@
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="BouncyCastle.Cryptography" Version="2.4.0" />
|
<PackageReference Include="BouncyCastle.Cryptography" Version="2.4.0" />
|
||||||
|
<PackageReference Include="Fido2" Version="4.3.3" />
|
||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
|
||||||
<!-- Direct pins lift transitive packages past their advisories; the lockfile holds the result. -->
|
<!-- Direct pins lift transitive packages past their advisories; the lockfile holds the result. -->
|
||||||
<PackageReference Include="Npgsql" Version="8.0.3" />
|
<PackageReference Include="Npgsql" Version="8.0.3" />
|
||||||
|
|
|
||||||
13
src/Bifrost.Web/Configuration/AccountMergeOptions.cs
Normal file
13
src/Bifrost.Web/Configuration/AccountMergeOptions.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
namespace Bifrost.Web.Configuration;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gates on the account-merge page (section <c>AccountMerge</c>). 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 <c>AccountMerge__Enabled</c> only after
|
||||||
|
/// Heimdall's identity-moves is deployed and probed.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AccountMergeOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "AccountMerge";
|
||||||
|
|
||||||
|
public bool Enabled { get; init; }
|
||||||
|
}
|
||||||
10
src/Bifrost.Web/Configuration/ChatNoticesOptions.cs
Normal file
10
src/Bifrost.Web/Configuration/ChatNoticesOptions.cs
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
namespace Bifrost.Web.Configuration;
|
||||||
|
|
||||||
|
/// <summary>The chat host's pull of merge notices (MergeNoticeFeed). An empty token turns both routes off (404); startup does not require it.</summary>
|
||||||
|
public sealed class ChatNoticesOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "ChatNotices";
|
||||||
|
|
||||||
|
/// <summary>The bearer the chat host presents (environment <c>ChatNotices__Token</c>). Its own secret: it grants nothing else.</summary>
|
||||||
|
public string Token { get; init; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
@ -14,7 +14,11 @@ public sealed class HeimdallOptions
|
||||||
|
|
||||||
public string PatreonTierTitle { get; init; } = "Inner Sanctum";
|
public string PatreonTierTitle { get; init; } = "Inner Sanctum";
|
||||||
|
|
||||||
public string AppSecret { get; init; } = string.Empty;
|
/// <summary>Deprecated: rides in the process environment. Use <see cref="AppSecretFile"/>; the file wins when both are set.</summary>
|
||||||
|
public string AppSecret { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Path of a file holding the app secret (systemd <c>LoadCredential</c> style: <c>%d/heimdall-app-secret</c>).</summary>
|
||||||
|
public string AppSecretFile { get; init; } = string.Empty;
|
||||||
|
|
||||||
public string PatronSupportIntakeSecret { get; init; } = string.Empty;
|
public string PatronSupportIntakeSecret { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
|
@ -39,4 +43,37 @@ public sealed class HeimdallOptions
|
||||||
IsConfigured &&
|
IsConfigured &&
|
||||||
EnablePatronSupportIntake &&
|
EnablePatronSupportIntake &&
|
||||||
!string.IsNullOrWhiteSpace(PatronSupportIntakeSecret);
|
!string.IsNullOrWhiteSpace(PatronSupportIntakeSecret);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Resolves <see cref="AppSecret"/> once, when the options are built. A set <see cref="AppSecretFile"/> must be a
|
||||||
|
/// readable, non-empty file, or startup fails; the message names the option and path, never a secret.
|
||||||
|
/// </summary>
|
||||||
|
public static void ResolveAppSecret(HeimdallOptions options, ILogger logger)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(options.AppSecret))
|
||||||
|
{
|
||||||
|
logger.LogWarning("Heimdall:AppSecret is deprecated: it rides in the process environment. Use Heimdall:AppSecretFile, which wins when both are set.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(options.AppSecretFile))
|
||||||
|
{
|
||||||
|
string secret;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
secret = File.ReadAllText(options.AppSecretFile).TrimEnd('\r', '\n');
|
||||||
|
}
|
||||||
|
catch (Exception error) when (error is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"Heimdall:AppSecretFile must name a readable file; '{options.AppSecretFile}' could not be read ({error.GetType().Name}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(secret))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"Heimdall:AppSecretFile '{options.AppSecretFile}' is empty.");
|
||||||
|
}
|
||||||
|
|
||||||
|
options.AppSecret = secret;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -45,6 +45,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
||||||
|
|
||||||
public DbSet<ConsentReceipt> ConsentReceipts => Set<ConsentReceipt>();
|
public DbSet<ConsentReceipt> ConsentReceipts => Set<ConsentReceipt>();
|
||||||
public DbSet<MindKey> MindKeys => Set<MindKey>();
|
public DbSet<MindKey> MindKeys => Set<MindKey>();
|
||||||
|
public DbSet<PasskeyCredential> PasskeyCredentials => Set<PasskeyCredential>();
|
||||||
|
|
||||||
public DbSet<MindNonce> MindNonces => Set<MindNonce>();
|
public DbSet<MindNonce> MindNonces => Set<MindNonce>();
|
||||||
|
|
||||||
|
|
@ -80,6 +81,12 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
||||||
|
|
||||||
public DbSet<ConceptAppraisal> ConceptAppraisals => Set<ConceptAppraisal>();
|
public DbSet<ConceptAppraisal> ConceptAppraisals => Set<ConceptAppraisal>();
|
||||||
|
|
||||||
|
public DbSet<AccountMerge> AccountMerges => Set<AccountMerge>();
|
||||||
|
|
||||||
|
public DbSet<AccountMergeEntry> AccountMergeEntries => Set<AccountMergeEntry>();
|
||||||
|
|
||||||
|
public DbSet<AccountMergeNoticeAck> AccountMergeNoticeAcks => Set<AccountMergeNoticeAck>();
|
||||||
|
|
||||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
{
|
{
|
||||||
modelBuilder.Entity<UserAccount>(entity =>
|
modelBuilder.Entity<UserAccount>(entity =>
|
||||||
|
|
@ -136,6 +143,10 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
||||||
entity.Property(x => x.Label).HasMaxLength(120);
|
entity.Property(x => x.Label).HasMaxLength(120);
|
||||||
entity.Property(x => x.Weight).HasPrecision(18, 2);
|
entity.Property(x => x.Weight).HasPrecision(18, 2);
|
||||||
entity.HasIndex(x => new { x.MembershipId, x.Kind, x.IsCurrent });
|
entity.HasIndex(x => new { x.MembershipId, x.Kind, x.IsCurrent });
|
||||||
|
entity.HasIndex(x => x.MembershipId)
|
||||||
|
.IsUnique()
|
||||||
|
.HasDatabaseName("UX_TierSnapshots_MembershipId_CurrentPatron")
|
||||||
|
.HasFilter("\"Kind\" = 'Patron' AND \"IsCurrent\"");
|
||||||
entity.HasOne(x => x.Membership)
|
entity.HasOne(x => x.Membership)
|
||||||
.WithMany(x => x.TierSnapshots)
|
.WithMany(x => x.TierSnapshots)
|
||||||
.HasForeignKey(x => x.MembershipId);
|
.HasForeignKey(x => x.MembershipId);
|
||||||
|
|
@ -300,6 +311,8 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
||||||
modelBuilder.Entity<Vote>(entity =>
|
modelBuilder.Entity<Vote>(entity =>
|
||||||
{
|
{
|
||||||
entity.HasIndex(x => new { x.MotionId, x.UserAccountId }).IsUnique();
|
entity.HasIndex(x => new { x.MotionId, x.UserAccountId }).IsUnique();
|
||||||
|
// A merge voids a vote by stamping it; every tally reads through this filter, and only AccountMergeLedger ignores it.
|
||||||
|
entity.HasQueryFilter(x => x.VoidedByMergeId == null);
|
||||||
entity.Property(x => x.Choice).HasConversion<string>();
|
entity.Property(x => x.Choice).HasConversion<string>();
|
||||||
entity.Property(x => x.Weight).HasPrecision(18, 2);
|
entity.Property(x => x.Weight).HasPrecision(18, 2);
|
||||||
entity.HasOne(x => x.Motion)
|
entity.HasOne(x => x.Motion)
|
||||||
|
|
@ -333,6 +346,16 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
||||||
.OnDelete(DeleteBehavior.Cascade);
|
.OnDelete(DeleteBehavior.Cascade);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity<PasskeyCredential>(entity =>
|
||||||
|
{
|
||||||
|
entity.HasIndex(x => x.CredentialId).IsUnique();
|
||||||
|
entity.HasIndex(x => x.UserAccountId);
|
||||||
|
entity.HasOne(x => x.UserAccount)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey(x => x.UserAccountId)
|
||||||
|
.OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity<MindKey>(entity =>
|
modelBuilder.Entity<MindKey>(entity =>
|
||||||
{
|
{
|
||||||
entity.HasIndex(x => new { x.PersonaId, x.PublicKey }).IsUnique();
|
entity.HasIndex(x => new { x.PersonaId, x.PublicKey }).IsUnique();
|
||||||
|
|
@ -596,6 +619,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
||||||
entity.Property(x => x.NetworkTag).HasMaxLength(64);
|
entity.Property(x => x.NetworkTag).HasMaxLength(64);
|
||||||
entity.Property(x => x.Stance).HasConversion<string>().HasMaxLength(16);
|
entity.Property(x => x.Stance).HasConversion<string>().HasMaxLength(16);
|
||||||
entity.Property(x => x.VoterClass).HasConversion<string>().HasMaxLength(16);
|
entity.Property(x => x.VoterClass).HasConversion<string>().HasMaxLength(16);
|
||||||
|
entity.HasQueryFilter(x => x.VoidedByMergeId == null);
|
||||||
entity.HasIndex(x => new { x.SubjectId, x.VoterKey }).IsUnique();
|
entity.HasIndex(x => new { x.SubjectId, x.VoterKey }).IsUnique();
|
||||||
entity.HasIndex(x => new { x.NetworkTag, x.CastAtUtc });
|
entity.HasIndex(x => new { x.NetworkTag, x.CastAtUtc });
|
||||||
entity.HasOne(x => x.Subject)
|
entity.HasOne(x => x.Subject)
|
||||||
|
|
@ -607,5 +631,63 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
||||||
.HasForeignKey(x => x.UserAccountId)
|
.HasForeignKey(x => x.UserAccountId)
|
||||||
.OnDelete(DeleteBehavior.SetNull);
|
.OnDelete(DeleteBehavior.SetNull);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity<AccountMerge>(entity =>
|
||||||
|
{
|
||||||
|
// State is the token: a transition computed from a stale read (the sweeper's Final over a saga's UndoRequested) fails its save.
|
||||||
|
entity.Property(x => x.State).HasConversion<string>().HasMaxLength(24).IsConcurrencyToken();
|
||||||
|
entity.Property(x => x.FailureCode).HasMaxLength(64);
|
||||||
|
entity.Property(x => x.HeimdallMoveId).HasMaxLength(64);
|
||||||
|
entity.Property(x => x.HeimdallReverseMoveId).HasMaxLength(64);
|
||||||
|
entity.Property(x => x.PreviewDigest).HasMaxLength(64);
|
||||||
|
entity.Property(x => x.SurvivorProofProvider).HasMaxLength(32);
|
||||||
|
entity.Property(x => x.FoldedProofProviders).HasMaxLength(120);
|
||||||
|
entity.Property(x => x.ProofFromTier).HasMaxLength(8);
|
||||||
|
entity.Property(x => x.ProofToTier).HasMaxLength(8);
|
||||||
|
entity.Property(x => x.LastOutcome).HasMaxLength(64);
|
||||||
|
// Heimdall's idempotency keys: one merge, one forward key and one reverse key, and no key shared by two merges.
|
||||||
|
entity.HasIndex(x => x.HeimdallMoveId).IsUnique().HasFilter("\"HeimdallMoveId\" IS NOT NULL");
|
||||||
|
entity.HasIndex(x => x.HeimdallReverseMoveId).IsUnique().HasFilter("\"HeimdallReverseMoveId\" IS NOT NULL");
|
||||||
|
entity.HasIndex(x => new { x.FoldedUserAccountId, x.State });
|
||||||
|
// An account is folded once: the DB refuses a second live merge folding it. The cross-role case (a survivor that is also
|
||||||
|
// folded) cannot be one unique index; the migration's trigger refuses it.
|
||||||
|
entity.HasIndex(x => x.FoldedUserAccountId)
|
||||||
|
.IsUnique()
|
||||||
|
.HasDatabaseName("UX_AccountMerges_FoldedUserAccountId_Live")
|
||||||
|
.HasFilter("\"State\" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed')");
|
||||||
|
entity.HasIndex(x => new { x.SurvivorUserAccountId, x.State });
|
||||||
|
entity.HasIndex(x => new { x.State, x.GraceEndsUtc });
|
||||||
|
entity.HasOne<UserAccount>()
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey(x => x.SurvivorUserAccountId)
|
||||||
|
.OnDelete(DeleteBehavior.Restrict);
|
||||||
|
entity.HasOne<UserAccount>()
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey(x => x.FoldedUserAccountId)
|
||||||
|
.OnDelete(DeleteBehavior.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity<AccountMergeEntry>(entity =>
|
||||||
|
{
|
||||||
|
entity.Property(x => x.Kind).HasConversion<string>().HasMaxLength(24);
|
||||||
|
entity.Property(x => x.Action).HasConversion<string>().HasMaxLength(24);
|
||||||
|
entity.Property(x => x.PriorText).HasMaxLength(120);
|
||||||
|
entity.HasIndex(x => new { x.MergeId, x.Seq }).IsUnique();
|
||||||
|
entity.HasOne(x => x.Merge)
|
||||||
|
.WithMany(x => x.Entries)
|
||||||
|
.HasForeignKey(x => x.MergeId)
|
||||||
|
.OnDelete(DeleteBehavior.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity<AccountMergeNoticeAck>(entity =>
|
||||||
|
{
|
||||||
|
entity.HasKey(x => new { x.MergeId, x.Kind, x.Target });
|
||||||
|
entity.Property(x => x.Kind).HasConversion<string>().HasMaxLength(16);
|
||||||
|
entity.Property(x => x.Target).HasConversion<string>().HasMaxLength(16);
|
||||||
|
entity.HasOne<AccountMerge>()
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey(x => x.MergeId)
|
||||||
|
.OnDelete(DeleteBehavior.Restrict);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,48 @@
|
||||||
|
using System;
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Hand-written like AddConsentReceipts: no dotnet-ef on the authoring host; the snapshot was edited to match. Additive only.
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261113120000_AddPasskeyCredentials")]
|
||||||
|
public partial class AddPasskeyCredentials : Migration
|
||||||
|
{
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "PasskeyCredentials",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
UserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
CredentialId = table.Column<byte[]>(type: "bytea", nullable: false),
|
||||||
|
PublicKey = table.Column<byte[]>(type: "bytea", nullable: false),
|
||||||
|
SignCount = table.Column<long>(type: "bigint", nullable: false),
|
||||||
|
Transports = table.Column<string>(type: "text", nullable: false),
|
||||||
|
AaGuid = table.Column<Guid>(type: "uuid", nullable: true),
|
||||||
|
Label = table.Column<string>(type: "text", nullable: false),
|
||||||
|
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||||
|
StrongFromUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||||
|
RevokedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||||
|
LastUsedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_PasskeyCredentials", x => x.Id);
|
||||||
|
table.ForeignKey("FK_PasskeyCredentials_UserAccounts_UserAccountId", x => x.UserAccountId, "UserAccounts", "Id", onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
migrationBuilder.CreateIndex(name: "IX_PasskeyCredentials_CredentialId", table: "PasskeyCredentials", column: "CredentialId", unique: true);
|
||||||
|
migrationBuilder.CreateIndex(name: "IX_PasskeyCredentials_UserAccountId", table: "PasskeyCredentials", column: "UserAccountId");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(name: "PasskeyCredentials");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,216 @@
|
||||||
|
using System;
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Scaffolded by IMigrationsScaffolder against the previous snapshot (no dotnet-ef on the authoring host), the designer file dropped and
|
||||||
|
// the snapshot edited by hand to match, like AddPasskeyCredentials. Additive only; Down drops what Up adds.
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261114120000_AddAccountMerges")]
|
||||||
|
public partial class AddAccountMerges : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<Guid>(
|
||||||
|
name: "VoidedByMergeId",
|
||||||
|
table: "Votes",
|
||||||
|
type: "uuid",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||||
|
name: "VoidedUtc",
|
||||||
|
table: "Votes",
|
||||||
|
type: "timestamp with time zone",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<Guid>(
|
||||||
|
name: "VoidedByMergeId",
|
||||||
|
table: "ConceptAppraisals",
|
||||||
|
type: "uuid",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||||
|
name: "VoidedUtc",
|
||||||
|
table: "ConceptAppraisals",
|
||||||
|
type: "timestamp with time zone",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "AccountMerges",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
State = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
|
||||||
|
SurvivorUserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
FoldedUserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||||
|
CommittedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||||
|
GraceEndsUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||||
|
FinalizedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||||
|
UndoneUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||||
|
FailedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||||
|
FailureCode = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_AccountMerges", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_AccountMerges_UserAccounts_FoldedUserAccountId",
|
||||||
|
column: x => x.FoldedUserAccountId,
|
||||||
|
principalTable: "UserAccounts",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Restrict);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_AccountMerges_UserAccounts_SurvivorUserAccountId",
|
||||||
|
column: x => x.SurvivorUserAccountId,
|
||||||
|
principalTable: "UserAccounts",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "AccountMergeEntries",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
MergeId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
Seq = table.Column<int>(type: "integer", nullable: false),
|
||||||
|
Kind = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
|
||||||
|
RecordId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
Action = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
|
||||||
|
PriorUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||||
|
PriorText = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: true),
|
||||||
|
PriorAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||||
|
AtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_AccountMergeEntries", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_AccountMergeEntries_AccountMerges_MergeId",
|
||||||
|
column: x => x.MergeId,
|
||||||
|
principalTable: "AccountMerges",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_AccountMergeEntries_MergeId_Seq",
|
||||||
|
table: "AccountMergeEntries",
|
||||||
|
columns: new[] { "MergeId", "Seq" },
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "UX_AccountMerges_FoldedUserAccountId_Live",
|
||||||
|
table: "AccountMerges",
|
||||||
|
column: "FoldedUserAccountId",
|
||||||
|
unique: true,
|
||||||
|
filter: "\"State\" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed')");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_AccountMerges_FoldedUserAccountId_State",
|
||||||
|
table: "AccountMerges",
|
||||||
|
columns: new[] { "FoldedUserAccountId", "State" });
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_AccountMerges_State_GraceEndsUtc",
|
||||||
|
table: "AccountMerges",
|
||||||
|
columns: new[] { "State", "GraceEndsUtc" });
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_AccountMerges_SurvivorUserAccountId_State",
|
||||||
|
table: "AccountMerges",
|
||||||
|
columns: new[] { "SurvivorUserAccountId", "State" });
|
||||||
|
|
||||||
|
// One current Patron snapshot per membership: two restages racing (two merges into one survivor, a merge and an intake) would
|
||||||
|
// each demote the old row and add their own, and EffectiveVotingWeight sums the current ones. A pre-existing duplicate keeps
|
||||||
|
// only its newest row current so the index can be built.
|
||||||
|
migrationBuilder.Sql(@"
|
||||||
|
UPDATE ""TierSnapshots"" t SET ""IsCurrent"" = false
|
||||||
|
WHERE t.""Kind"" = 'Patron' AND t.""IsCurrent"" AND EXISTS (
|
||||||
|
SELECT 1 FROM ""TierSnapshots"" o
|
||||||
|
WHERE o.""MembershipId"" = t.""MembershipId"" AND o.""Kind"" = 'Patron' AND o.""IsCurrent""
|
||||||
|
AND (o.""CapturedAtUtc"" > t.""CapturedAtUtc"" OR (o.""CapturedAtUtc"" = t.""CapturedAtUtc"" AND o.""Id"" > t.""Id"")));");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "UX_TierSnapshots_MembershipId_CurrentPatron",
|
||||||
|
table: "TierSnapshots",
|
||||||
|
column: "MembershipId",
|
||||||
|
unique: true,
|
||||||
|
filter: "\"Kind\" = 'Patron' AND \"IsCurrent\"");
|
||||||
|
|
||||||
|
// The cross-role guard no single unique index can express: a live merge's survivor is never another live merge's folded
|
||||||
|
// account (no chains), whichever order they arrive in. Advisory locks on both accounts, taken in a fixed order, serialise two
|
||||||
|
// transactions racing over the same account, so the second one's check sees the first's committed row.
|
||||||
|
migrationBuilder.Sql(@"
|
||||||
|
CREATE FUNCTION ""AccountMerges_refuse_chain""() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF NEW.""State"" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed') THEN
|
||||||
|
PERFORM pg_advisory_xact_lock(hashtextextended(LEAST(NEW.""SurvivorUserAccountId""::text, NEW.""FoldedUserAccountId""::text), 0));
|
||||||
|
PERFORM pg_advisory_xact_lock(hashtextextended(GREATEST(NEW.""SurvivorUserAccountId""::text, NEW.""FoldedUserAccountId""::text), 0));
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM ""AccountMerges"" m
|
||||||
|
WHERE m.""Id"" <> NEW.""Id""
|
||||||
|
AND m.""State"" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed')
|
||||||
|
AND (m.""SurvivorUserAccountId"" = NEW.""FoldedUserAccountId"" OR m.""FoldedUserAccountId"" = NEW.""SurvivorUserAccountId""))
|
||||||
|
THEN
|
||||||
|
RAISE EXCEPTION 'account merge chain refused' USING ERRCODE = '23P01';
|
||||||
|
END IF;
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER ""AccountMerges_refuse_chain"" BEFORE INSERT OR UPDATE OF ""State"", ""SurvivorUserAccountId"", ""FoldedUserAccountId"" ON ""AccountMerges""
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION ""AccountMerges_refuse_chain""();");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
// Roll-forward only (heimdall-body:ruling:merge-roll-forward-only): once any merge exists the Merged membership status
|
||||||
|
// cannot be read by an older build, and voided votes and appraisals would be counted again. Refuse while any merge row
|
||||||
|
// exists; see docs/account-merge.md (Rollback).
|
||||||
|
migrationBuilder.Sql(@"
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM ""AccountMerges"") THEN
|
||||||
|
RAISE EXCEPTION 'AddAccountMerges cannot be reverted once an account merge exists: Bifrost is roll-forward only';
|
||||||
|
END IF;
|
||||||
|
END
|
||||||
|
$$;");
|
||||||
|
|
||||||
|
migrationBuilder.DropIndex(
|
||||||
|
name: "UX_TierSnapshots_MembershipId_CurrentPatron",
|
||||||
|
table: "TierSnapshots");
|
||||||
|
|
||||||
|
migrationBuilder.Sql(@"DROP TRIGGER ""AccountMerges_refuse_chain"" ON ""AccountMerges""; DROP FUNCTION ""AccountMerges_refuse_chain""();");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "AccountMergeEntries");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "AccountMerges");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "VoidedByMergeId",
|
||||||
|
table: "Votes");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "VoidedUtc",
|
||||||
|
table: "Votes");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "VoidedByMergeId",
|
||||||
|
table: "ConceptAppraisals");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "VoidedUtc",
|
||||||
|
table: "ConceptAppraisals");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,78 @@
|
||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Hand-written like AddAccountMerges, the snapshot edited to match. Additive: the saga's columns on AccountMerges. Down is
|
||||||
|
// roll-forward only, like AddAccountMerges: it drops the Heimdall idempotency keys and the consent record, so it refuses while
|
||||||
|
// any merge row exists (heimdall-body:ruling:merge-roll-forward-only).
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261114130000_AddAccountMergeSaga")]
|
||||||
|
public partial class AddAccountMergeSaga : Migration
|
||||||
|
{
|
||||||
|
private static readonly string[] Columns =
|
||||||
|
[
|
||||||
|
"HeimdallMoveId", "HeimdallReverseMoveId", "SealedProofs", "PreviewDigest", "ConfirmedByUserAccountId", "ConfirmedUtc",
|
||||||
|
"SurvivorProofProvider", "FoldedProofProviders", "ProofFromTier", "ProofToTier", "MovedIdentityIds", "Attempts",
|
||||||
|
"NextAttemptUtc", "LastOutcome", "UndoRequestedUtc", "ReversedUtc"
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<string>(name: "HeimdallMoveId", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: true);
|
||||||
|
migrationBuilder.AddColumn<string>(name: "HeimdallReverseMoveId", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: true);
|
||||||
|
migrationBuilder.AddColumn<string>(name: "SealedProofs", table: "AccountMerges", type: "text", nullable: true);
|
||||||
|
migrationBuilder.AddColumn<string>(name: "PreviewDigest", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: false, defaultValue: "");
|
||||||
|
migrationBuilder.AddColumn<Guid>(name: "ConfirmedByUserAccountId", table: "AccountMerges", type: "uuid", nullable: true);
|
||||||
|
migrationBuilder.AddColumn<DateTimeOffset>(name: "ConfirmedUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
|
||||||
|
migrationBuilder.AddColumn<string>(name: "SurvivorProofProvider", table: "AccountMerges", type: "character varying(32)", maxLength: 32, nullable: false, defaultValue: "");
|
||||||
|
migrationBuilder.AddColumn<string>(name: "FoldedProofProviders", table: "AccountMerges", type: "character varying(120)", maxLength: 120, nullable: false, defaultValue: "");
|
||||||
|
migrationBuilder.AddColumn<string>(name: "ProofFromTier", table: "AccountMerges", type: "character varying(8)", maxLength: 8, nullable: true);
|
||||||
|
migrationBuilder.AddColumn<string>(name: "ProofToTier", table: "AccountMerges", type: "character varying(8)", maxLength: 8, nullable: true);
|
||||||
|
migrationBuilder.AddColumn<string>(name: "MovedIdentityIds", table: "AccountMerges", type: "text", nullable: true);
|
||||||
|
migrationBuilder.AddColumn<int>(name: "Attempts", table: "AccountMerges", type: "integer", nullable: false, defaultValue: 0);
|
||||||
|
migrationBuilder.AddColumn<DateTimeOffset>(name: "NextAttemptUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
|
||||||
|
migrationBuilder.AddColumn<string>(name: "LastOutcome", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: false, defaultValue: "");
|
||||||
|
migrationBuilder.AddColumn<DateTimeOffset>(name: "UndoRequestedUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
|
||||||
|
migrationBuilder.AddColumn<DateTimeOffset>(name: "ReversedUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_AccountMerges_HeimdallMoveId",
|
||||||
|
table: "AccountMerges",
|
||||||
|
column: "HeimdallMoveId",
|
||||||
|
unique: true,
|
||||||
|
filter: "\"HeimdallMoveId\" IS NOT NULL");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_AccountMerges_HeimdallReverseMoveId",
|
||||||
|
table: "AccountMerges",
|
||||||
|
column: "HeimdallReverseMoveId",
|
||||||
|
unique: true,
|
||||||
|
filter: "\"HeimdallReverseMoveId\" IS NOT NULL");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.Sql(@"
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM ""AccountMerges"") THEN
|
||||||
|
RAISE EXCEPTION 'AddAccountMergeSaga cannot be reverted once an account merge exists: Bifrost is roll-forward only';
|
||||||
|
END IF;
|
||||||
|
END
|
||||||
|
$$;");
|
||||||
|
|
||||||
|
migrationBuilder.DropIndex(name: "IX_AccountMerges_HeimdallMoveId", table: "AccountMerges");
|
||||||
|
migrationBuilder.DropIndex(name: "IX_AccountMerges_HeimdallReverseMoveId", table: "AccountMerges");
|
||||||
|
foreach (var column in Columns)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(name: column, table: "AccountMerges");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Hand-written like AddAccountMergeSaga (no dotnet-ef on the authoring host), the snapshot edited to match. Additive: one table of
|
||||||
|
// acks, the only fact a notice reader adds; the notices themselves are derived from AccountMerges. Down may drop it: it holds only acks.
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261114140000_AddAccountMergeNoticeAcks")]
|
||||||
|
public partial class AddAccountMergeNoticeAcks : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "AccountMergeNoticeAcks",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
MergeId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
Kind = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: false),
|
||||||
|
Target = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: false),
|
||||||
|
AckedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_AccountMergeNoticeAcks", x => new { x.MergeId, x.Kind, x.Target });
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_AccountMergeNoticeAcks_AccountMerges_MergeId",
|
||||||
|
column: x => x.MergeId,
|
||||||
|
principalTable: "AccountMerges",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Restrict);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(name: "AccountMergeNoticeAcks");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -22,6 +22,198 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
|
|
||||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("Bifrost.Web.Domain.AccountMerge", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<int>("Attempts")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("CommittedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Guid?>("ConfirmedByUserAccountId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("ConfirmedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("CreatedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("FailedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("FailureCode")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("character varying(64)");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("FinalizedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("FoldedProofProviders")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(120)
|
||||||
|
.HasColumnType("character varying(120)");
|
||||||
|
|
||||||
|
b.Property<Guid>("FoldedUserAccountId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("GraceEndsUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("HeimdallMoveId")
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("character varying(64)");
|
||||||
|
|
||||||
|
b.Property<string>("HeimdallReverseMoveId")
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("character varying(64)");
|
||||||
|
|
||||||
|
b.Property<string>("LastOutcome")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("character varying(64)");
|
||||||
|
|
||||||
|
b.Property<string>("MovedIdentityIds")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("NextAttemptUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("PreviewDigest")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("character varying(64)");
|
||||||
|
|
||||||
|
b.Property<string>("ProofFromTier")
|
||||||
|
.HasMaxLength(8)
|
||||||
|
.HasColumnType("character varying(8)");
|
||||||
|
|
||||||
|
b.Property<string>("ProofToTier")
|
||||||
|
.HasMaxLength(8)
|
||||||
|
.HasColumnType("character varying(8)");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("ReversedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("SealedProofs")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("State")
|
||||||
|
.IsConcurrencyToken()
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(24)
|
||||||
|
.HasColumnType("character varying(24)");
|
||||||
|
|
||||||
|
b.Property<string>("SurvivorProofProvider")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(32)
|
||||||
|
.HasColumnType("character varying(32)");
|
||||||
|
|
||||||
|
b.Property<Guid>("SurvivorUserAccountId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("UndoneUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("UndoRequestedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("FoldedUserAccountId")
|
||||||
|
.IsUnique()
|
||||||
|
.HasDatabaseName("UX_AccountMerges_FoldedUserAccountId_Live")
|
||||||
|
.HasFilter("\"State\" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed')");
|
||||||
|
|
||||||
|
b.HasIndex("FoldedUserAccountId", "State");
|
||||||
|
|
||||||
|
b.HasIndex("HeimdallMoveId")
|
||||||
|
.IsUnique()
|
||||||
|
.HasFilter("\"HeimdallMoveId\" IS NOT NULL");
|
||||||
|
|
||||||
|
b.HasIndex("HeimdallReverseMoveId")
|
||||||
|
.IsUnique()
|
||||||
|
.HasFilter("\"HeimdallReverseMoveId\" IS NOT NULL");
|
||||||
|
|
||||||
|
b.HasIndex("State", "GraceEndsUtc");
|
||||||
|
|
||||||
|
b.HasIndex("SurvivorUserAccountId", "State");
|
||||||
|
|
||||||
|
b.ToTable("AccountMerges");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Bifrost.Web.Domain.AccountMergeEntry", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("Action")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(24)
|
||||||
|
.HasColumnType("character varying(24)");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("AtUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Kind")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(24)
|
||||||
|
.HasColumnType("character varying(24)");
|
||||||
|
|
||||||
|
b.Property<Guid>("MergeId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("PriorAtUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("PriorText")
|
||||||
|
.HasMaxLength(120)
|
||||||
|
.HasColumnType("character varying(120)");
|
||||||
|
|
||||||
|
b.Property<Guid?>("PriorUserAccountId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Guid>("RecordId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<int>("Seq")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("MergeId", "Seq")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("AccountMergeEntries");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Bifrost.Web.Domain.AccountMergeNoticeAck", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("MergeId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("Kind")
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("character varying(16)");
|
||||||
|
|
||||||
|
b.Property<string>("Target")
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("character varying(16)");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("AckedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.HasKey("MergeId", "Kind", "Target");
|
||||||
|
|
||||||
|
b.ToTable("AccountMergeNoticeAcks");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Bifrost.Web.Domain.AgentDispatchRun", b =>
|
modelBuilder.Entity("Bifrost.Web.Domain.AgentDispatchRun", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("Id")
|
b.Property<Guid>("Id")
|
||||||
|
|
@ -437,6 +629,12 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
b.Property<Guid?>("UserAccountId")
|
b.Property<Guid?>("UserAccountId")
|
||||||
.HasColumnType("uuid");
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Guid?>("VoidedByMergeId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("VoidedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
b.Property<string>("VoterClass")
|
b.Property<string>("VoterClass")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasMaxLength(16)
|
.HasMaxLength(16)
|
||||||
|
|
@ -1336,6 +1534,11 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
|
|
||||||
b.HasIndex("MembershipId", "Kind", "IsCurrent");
|
b.HasIndex("MembershipId", "Kind", "IsCurrent");
|
||||||
|
|
||||||
|
b.HasIndex("MembershipId")
|
||||||
|
.IsUnique()
|
||||||
|
.HasDatabaseName("UX_TierSnapshots_MembershipId_CurrentPatron")
|
||||||
|
.HasFilter("\"Kind\" = 'Patron' AND \"IsCurrent\"");
|
||||||
|
|
||||||
b.ToTable("TierSnapshots");
|
b.ToTable("TierSnapshots");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -1470,6 +1673,59 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
b.ToTable("ConsentReceipts");
|
b.ToTable("ConsentReceipts");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Bifrost.Web.Domain.PasskeyCredential", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Guid?>("AaGuid")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("CreatedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<byte[]>("CredentialId")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("bytea");
|
||||||
|
|
||||||
|
b.Property<string>("Label")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("LastUsedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<byte[]>("PublicKey")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("bytea");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("RevokedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("SignCount")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("StrongFromUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Transports")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserAccountId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("CredentialId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.HasIndex("UserAccountId");
|
||||||
|
|
||||||
|
b.ToTable("PasskeyCredentials");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Bifrost.Web.Domain.MindKey", b =>
|
modelBuilder.Entity("Bifrost.Web.Domain.MindKey", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("Id")
|
b.Property<Guid>("Id")
|
||||||
|
|
@ -1623,6 +1879,12 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
b.Property<Guid>("UserAccountId")
|
b.Property<Guid>("UserAccountId")
|
||||||
.HasColumnType("uuid");
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Guid?>("VoidedByMergeId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("VoidedUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
b.Property<decimal>("Weight")
|
b.Property<decimal>("Weight")
|
||||||
.HasPrecision(18, 2)
|
.HasPrecision(18, 2)
|
||||||
.HasColumnType("numeric(18,2)");
|
.HasColumnType("numeric(18,2)");
|
||||||
|
|
@ -2010,6 +2272,41 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
b.ToTable("OpenIddictTokens", (string)null);
|
b.ToTable("OpenIddictTokens", (string)null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Bifrost.Web.Domain.AccountMerge", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("FoldedUserAccountId")
|
||||||
|
.OnDelete(DeleteBehavior.Restrict)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("SurvivorUserAccountId")
|
||||||
|
.OnDelete(DeleteBehavior.Restrict)
|
||||||
|
.IsRequired();
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Bifrost.Web.Domain.AccountMergeEntry", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("Bifrost.Web.Domain.AccountMerge", "Merge")
|
||||||
|
.WithMany("Entries")
|
||||||
|
.HasForeignKey("MergeId")
|
||||||
|
.OnDelete(DeleteBehavior.Restrict)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Merge");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Bifrost.Web.Domain.AccountMergeNoticeAck", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("Bifrost.Web.Domain.AccountMerge", null)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("MergeId")
|
||||||
|
.OnDelete(DeleteBehavior.Restrict)
|
||||||
|
.IsRequired();
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Bifrost.Web.Domain.AgentDispatchRun", b =>
|
modelBuilder.Entity("Bifrost.Web.Domain.AgentDispatchRun", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("Bifrost.Web.Domain.UserAccount", "StartedByUserAccount")
|
b.HasOne("Bifrost.Web.Domain.UserAccount", "StartedByUserAccount")
|
||||||
|
|
@ -2183,6 +2480,17 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
b.Navigation("UserAccount");
|
b.Navigation("UserAccount");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Bifrost.Web.Domain.PasskeyCredential", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("Bifrost.Web.Domain.UserAccount", "UserAccount")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("UserAccountId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("UserAccount");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Bifrost.Web.Domain.MemberProfile", b =>
|
modelBuilder.Entity("Bifrost.Web.Domain.MemberProfile", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("Bifrost.Web.Domain.UserAccount", "UserAccount")
|
b.HasOne("Bifrost.Web.Domain.UserAccount", "UserAccount")
|
||||||
|
|
@ -2538,6 +2846,11 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
b.Navigation("Authorization");
|
b.Navigation("Authorization");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Bifrost.Web.Domain.AccountMerge", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Entries");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Bifrost.Web.Domain.Membership", b =>
|
modelBuilder.Entity("Bifrost.Web.Domain.Membership", b =>
|
||||||
{
|
{
|
||||||
b.Navigation("RoleAssignments");
|
b.Navigation("RoleAssignments");
|
||||||
|
|
|
||||||
165
src/Bifrost.Web/Domain/AccountMergeModels.cs
Normal file
165
src/Bifrost.Web/Domain/AccountMergeModels.cs
Normal file
|
|
@ -0,0 +1,165 @@
|
||||||
|
namespace Bifrost.Web.Domain;
|
||||||
|
|
||||||
|
/// <summary>The whole lifecycle of an account merge, declared once; later cuts add columns, not states. Stored as a string.</summary>
|
||||||
|
public enum AccountMergeState
|
||||||
|
{
|
||||||
|
Proposed,
|
||||||
|
Confirmed,
|
||||||
|
HeimdallMoved,
|
||||||
|
Committed,
|
||||||
|
Final,
|
||||||
|
UndoRequested,
|
||||||
|
HeimdallReversed,
|
||||||
|
Undone,
|
||||||
|
Failed
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum AccountMergeEntryKind
|
||||||
|
{
|
||||||
|
Vote,
|
||||||
|
ConceptAppraisal,
|
||||||
|
Membership,
|
||||||
|
Standing,
|
||||||
|
PatronSupportEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum AccountMergeEntryAction
|
||||||
|
{
|
||||||
|
Voided,
|
||||||
|
Moved,
|
||||||
|
Closed,
|
||||||
|
Suspended,
|
||||||
|
Created,
|
||||||
|
Restored,
|
||||||
|
KeptAfterUndo
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The merge receipt: two Heimdall-backed accounts, one survivor. Whether an account is folded or frozen is derived from this row's
|
||||||
|
/// State on every request (AccountMergeLedger.StandingAsync); no column on the account says so.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AccountMerge
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
|
||||||
|
public AccountMergeState State { get; set; } = AccountMergeState.Proposed;
|
||||||
|
|
||||||
|
public Guid SurvivorUserAccountId { get; set; }
|
||||||
|
|
||||||
|
public Guid FoldedUserAccountId { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset CreatedUtc { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? CommittedUtc { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? GraceEndsUtc { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? FinalizedUtc { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? UndoneUtc { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? FailedUtc { get; set; }
|
||||||
|
|
||||||
|
public string FailureCode { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
// ---- the saga's columns (AccountMergeSaga is their one writer; docs/account-merge.md, Saga) ----
|
||||||
|
|
||||||
|
/// <summary>Heimdall's idempotency key of the forward move: random, minted in the save that enters Confirmed, never derived from <see cref="Id"/>, never re-minted.</summary>
|
||||||
|
public string? HeimdallMoveId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The same for the reversal, minted in the save that enters UndoRequested.</summary>
|
||||||
|
public string? HeimdallReverseMoveId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The Heimdall bearers the move or reversal will replay, protected; non-null only from Confirmed/UndoRequested until Heimdall's final answer.</summary>
|
||||||
|
public string? SealedProofs { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Digest of the plan the member saw when confirming (MergePlan.Digest); with the next four columns it is the consent record.</summary>
|
||||||
|
public string PreviewDigest { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public Guid? ConfirmedByUserAccountId { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? ConfirmedUtc { get; set; }
|
||||||
|
|
||||||
|
public string SurvivorProofProvider { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>The providers of the folded side's proofs, sorted and comma-joined.</summary>
|
||||||
|
public string FoldedProofProviders { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>The proof tiers Heimdall's receipt named (weak or strong); ProofToTier is null for a receipt without one.</summary>
|
||||||
|
public string? ProofFromTier { get; set; }
|
||||||
|
|
||||||
|
public string? ProofToTier { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The logins the forward move carried, a JSON array of Heimdall identity ids, from the receipt.</summary>
|
||||||
|
public string? MovedIdentityIds { get; set; }
|
||||||
|
|
||||||
|
public int Attempts { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? NextAttemptUtc { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The last Heimdall answer's class or refusal code, or the saga's own stall code; never an input value.</summary>
|
||||||
|
public string LastOutcome { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public DateTimeOffset? UndoRequestedUtc { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? ReversedUtc { get; set; }
|
||||||
|
|
||||||
|
public ICollection<AccountMergeEntry> Entries { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Append-only journal of what a merge did to one record; undo and the later preview read it, tallies and gates never do.</summary>
|
||||||
|
public sealed class AccountMergeEntry
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
|
||||||
|
public Guid MergeId { get; set; }
|
||||||
|
|
||||||
|
public int Seq { get; set; }
|
||||||
|
|
||||||
|
public AccountMergeEntryKind Kind { get; set; }
|
||||||
|
|
||||||
|
public Guid RecordId { get; set; }
|
||||||
|
|
||||||
|
public AccountMergeEntryAction Action { get; set; }
|
||||||
|
|
||||||
|
public Guid? PriorUserAccountId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>What the record held before: the prior status; for a moved vote its weight; for a moved appraisal its voter class and key (class|key).</summary>
|
||||||
|
public string? PriorText { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The cast time of a moved vote or appraisal, so undo can tell whether the survivor re-cast it.</summary>
|
||||||
|
public DateTimeOffset? PriorAtUtc { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset AtUtc { get; set; }
|
||||||
|
|
||||||
|
public AccountMerge Merge { get; set; } = null!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What a merge notice tells its reader: the merge committed, was undone, or can no longer be undone. Stored as a string.</summary>
|
||||||
|
public enum AccountMergeNoticeKind
|
||||||
|
{
|
||||||
|
Merged,
|
||||||
|
Undone,
|
||||||
|
Final
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
public enum AccountMergeNoticeTarget
|
||||||
|
{
|
||||||
|
Chat
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AccountMergeNoticeAck
|
||||||
|
{
|
||||||
|
public Guid MergeId { get; set; }
|
||||||
|
|
||||||
|
public AccountMergeNoticeKind Kind { get; set; }
|
||||||
|
|
||||||
|
public AccountMergeNoticeTarget Target { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset AckedUtc { get; set; }
|
||||||
|
}
|
||||||
|
|
@ -7,7 +7,9 @@ public enum MembershipStatus
|
||||||
Authenticated,
|
Authenticated,
|
||||||
PendingApproval,
|
PendingApproval,
|
||||||
Active,
|
Active,
|
||||||
Suspended
|
Suspended,
|
||||||
|
/// <summary>Terminal status of a folded membership; written only by the account merge ledger, never read to decide standing.</summary>
|
||||||
|
Merged
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum MemberRole
|
public enum MemberRole
|
||||||
|
|
@ -357,6 +359,10 @@ public sealed class Membership
|
||||||
|
|
||||||
public ICollection<TierSnapshot> TierSnapshots { get; set; } = [];
|
public ICollection<TierSnapshot> TierSnapshots { get; set; } = [];
|
||||||
|
|
||||||
|
/// <summary>The folded membership of a landed merge. Terminal: only AccountMergeLedger writes it or leaves it, so every other status writer (sign-in sync, bootstrap, claim, approval, suspension) refuses a merged row.</summary>
|
||||||
|
[NotMapped]
|
||||||
|
public bool IsMerged => Status == MembershipStatus.Merged;
|
||||||
|
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public decimal EffectiveVotingWeight =>
|
public decimal EffectiveVotingWeight =>
|
||||||
Status != MembershipStatus.Active
|
Status != MembershipStatus.Active
|
||||||
|
|
@ -776,6 +782,11 @@ public sealed class Vote
|
||||||
|
|
||||||
public DateTimeOffset CastAtUtc { get; set; }
|
public DateTimeOffset CastAtUtc { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Set by the account merge ledger when a merge removes this vote from every tally; the model's query filter then hides the row.</summary>
|
||||||
|
public Guid? VoidedByMergeId { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? VoidedUtc { get; set; }
|
||||||
|
|
||||||
public Motion Motion { get; set; } = null!;
|
public Motion Motion { get; set; } = null!;
|
||||||
|
|
||||||
public UserAccount UserAccount { get; set; } = null!;
|
public UserAccount UserAccount { get; set; } = null!;
|
||||||
|
|
@ -1177,6 +1188,41 @@ public sealed class ConsentReceipt
|
||||||
public UserAccount? UserAccount { get; set; }
|
public UserAccount? UserAccount { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A WebAuthn passkey a Heimdall-backed member enrolled (docs/passkeys.md). Holds only what verifying an assertion needs:
|
||||||
|
/// the credential id, the public key and the sign count. No secret exists to hold. It counts as strong proof only from
|
||||||
|
/// <see cref="StrongFromUtc"/> (the cooling-off after enrolment) and only while not revoked.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PasskeyCredential
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
|
||||||
|
public Guid UserAccountId { get; set; }
|
||||||
|
|
||||||
|
public byte[] CredentialId { get; set; } = [];
|
||||||
|
|
||||||
|
public byte[] PublicKey { get; set; } = [];
|
||||||
|
|
||||||
|
public long SignCount { get; set; }
|
||||||
|
|
||||||
|
// Comma-separated WebAuthn transport hints the authenticator reported at enrolment; a hint for the browser, never trusted.
|
||||||
|
public string Transports { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public Guid? AaGuid { get; set; }
|
||||||
|
|
||||||
|
public string Label { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public DateTimeOffset CreatedUtc { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset StrongFromUtc { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? RevokedUtc { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? LastUsedUtc { get; set; }
|
||||||
|
|
||||||
|
public UserAccount? UserAccount { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>A Mind's registered Ed25519 public key. Bifrost never holds a private key.</summary>
|
/// <summary>A Mind's registered Ed25519 public key. Bifrost never holds a private key.</summary>
|
||||||
public sealed class MindKey
|
public sealed class MindKey
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -46,5 +46,10 @@ public sealed class ConceptAppraisal
|
||||||
|
|
||||||
public DateTimeOffset CastAtUtc { get; set; }
|
public DateTimeOffset CastAtUtc { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Set by the account merge ledger when a merge removes this appraisal from every tally; the model's query filter then hides the row.</summary>
|
||||||
|
public Guid? VoidedByMergeId { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? VoidedUtc { get; set; }
|
||||||
|
|
||||||
public ConceptSubject? Subject { get; set; }
|
public ConceptSubject? Subject { get; set; }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ using System.Net;
|
||||||
using Bifrost.Web.Configuration;
|
using Bifrost.Web.Configuration;
|
||||||
using Bifrost.Web.Data;
|
using Bifrost.Web.Data;
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
using Bifrost.Web.Features.Shared;
|
using Bifrost.Web.Features.Shared;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
|
@ -80,13 +81,42 @@ public sealed class ConceptAppraisalService(
|
||||||
? string.Empty
|
? string.Empty
|
||||||
: NetworkPrefix.Tag(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength, opts.NetworkTagSecret);
|
: NetworkPrefix.Tag(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength, opts.NetworkTagSecret);
|
||||||
|
|
||||||
|
// A voter resolved before a merge froze the account must not write an appraisal after it: the write gate reads standing at the write.
|
||||||
|
Task<CastResult> Write() => voter.UserAccountId is { } voterAccountId
|
||||||
|
? AccountMergeLedger.WriteAsAsync(
|
||||||
|
dbContext,
|
||||||
|
voterAccountId,
|
||||||
|
standing => standing is null ? WriteAppraisalAsync(subject, voter, stance, tag, cancellationToken) : Task.FromResult(CastResult.NoVoter),
|
||||||
|
cancellationToken)
|
||||||
|
: WriteAppraisalAsync(subject, voter, stance, tag, cancellationToken);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await Write();
|
||||||
|
}
|
||||||
|
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: UniqueViolation })
|
||||||
|
{
|
||||||
|
// A concurrent cast by the same voter won the insert (and the failed save aborted the gate's transaction): go through the
|
||||||
|
// gate again, which now finds their row and applies this stance to it, once.
|
||||||
|
dbContext.ChangeTracker.Clear();
|
||||||
|
if (await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken) is null)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await Write();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<CastResult> WriteAppraisalAsync(ConceptSubject subject, VoterIdentity voter, ConceptStance stance, string tag, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
var existing = await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken);
|
var existing = await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken);
|
||||||
if (existing is not null)
|
if (existing is not null)
|
||||||
{
|
{
|
||||||
return await ApplyStanceAsync(existing, stance, tag, cancellationToken);
|
return await ApplyStanceAsync(existing, stance, tag, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
var row = new ConceptAppraisal
|
dbContext.ConceptAppraisals.Add(new ConceptAppraisal
|
||||||
{
|
{
|
||||||
SubjectId = subject.Id,
|
SubjectId = subject.Id,
|
||||||
VoterKey = voter.Key,
|
VoterKey = voter.Key,
|
||||||
|
|
@ -95,26 +125,9 @@ public sealed class ConceptAppraisalService(
|
||||||
UserAccountId = voter.UserAccountId,
|
UserAccountId = voter.UserAccountId,
|
||||||
NetworkTag = tag,
|
NetworkTag = tag,
|
||||||
CastAtUtc = timeProvider.GetUtcNow()
|
CastAtUtc = timeProvider.GetUtcNow()
|
||||||
};
|
});
|
||||||
dbContext.ConceptAppraisals.Add(row);
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
return CastResult.Recorded;
|
||||||
try
|
|
||||||
{
|
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
|
||||||
return CastResult.Recorded;
|
|
||||||
}
|
|
||||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: UniqueViolation })
|
|
||||||
{
|
|
||||||
// A concurrent cast by the same voter won the insert: apply this stance to their row, once.
|
|
||||||
dbContext.Entry(row).State = EntityState.Detached;
|
|
||||||
var winner = await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken);
|
|
||||||
if (winner is null)
|
|
||||||
{
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
|
|
||||||
return await ApplyStanceAsync(winner, stance, tag, cancellationToken);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> RetractAsync(
|
public async Task<bool> RetractAsync(
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -3,7 +3,8 @@ namespace Bifrost.Web.Features.Heimdall;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The page Heimdall's "Return to the app" lands on. The completion code arrives in the URL fragment, which
|
/// The page Heimdall's "Return to the app" lands on. The completion code arrives in the URL fragment, which
|
||||||
/// the server never sees, so the page's script reads it, drops it from the address bar, and posts it with
|
/// the server never sees, so the page's script reads it, drops it from the address bar, and posts it with
|
||||||
/// the attempt to the same path. The page is static: it never contains a code.
|
/// the attempt to the same path. A Google link returns a pending link id the same way instead of a code. The page
|
||||||
|
/// is static: it never contains a code or an id.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class HeimdallCompletePage
|
public static class HeimdallCompletePage
|
||||||
{
|
{
|
||||||
|
|
@ -22,21 +23,30 @@ public static class HeimdallCompletePage
|
||||||
<form id="complete" method="post" action="/auth/heimdall/complete">
|
<form id="complete" method="post" action="/auth/heimdall/complete">
|
||||||
<input type="hidden" name="attempt" />
|
<input type="hidden" name="attempt" />
|
||||||
<input type="hidden" name="code" />
|
<input type="hidden" name="code" />
|
||||||
|
<input type="hidden" name="pendingLinkId" />
|
||||||
</form>
|
</form>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var fragment = new URLSearchParams(location.hash.slice(1));
|
var fragment = new URLSearchParams(location.hash.slice(1));
|
||||||
var attempt = new URLSearchParams(location.search).get("attempt");
|
var attempt = new URLSearchParams(location.search).get("attempt");
|
||||||
var code = fragment.get("heimdall_completion_code");
|
var code = fragment.get("heimdall_completion_code");
|
||||||
|
var pendingLinkId = fragment.get("heimdall_pending_link_id");
|
||||||
var failed = fragment.get("heimdall_status") === "error";
|
var failed = fragment.get("heimdall_status") === "error";
|
||||||
history.replaceState(null, "", location.pathname + location.search);
|
history.replaceState(null, "", location.pathname + location.search);
|
||||||
if (failed || !code || !attempt) {
|
// A provider other than Google attaches in Heimdall's callback, which refuses an identity another account
|
||||||
|
// holds. Only this one refusal is carried on, as a fixed result the page words itself; nothing from the fragment is shown.
|
||||||
|
if (failed && attempt && fragment.get("heimdall_error") === "link_initiator_mismatch") {
|
||||||
|
location.replace("/Membership/LinkedAccounts?result=identity_linked_elsewhere");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (failed || !(code || pendingLinkId) || !attempt) {
|
||||||
location.replace("/?auth=heimdall-error");
|
location.replace("/?auth=heimdall-error");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var form = document.getElementById("complete");
|
var form = document.getElementById("complete");
|
||||||
form.elements.attempt.value = attempt;
|
form.elements.attempt.value = attempt;
|
||||||
form.elements.code.value = code;
|
form.elements.code.value = code || "";
|
||||||
|
form.elements.pendingLinkId.value = pendingLinkId || "";
|
||||||
form.submit();
|
form.submit();
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
351
src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs
Normal file
351
src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs
Normal file
|
|
@ -0,0 +1,351 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What Bifrost asks Heimdall to move (docs/service-contract.md, POST /v1/apps/{app}/identity-moves). Exactly one of
|
||||||
|
/// <see cref="ToProof"/> (a forward move, optionally of <see cref="IdentityIds"/>) and <see cref="ReversesMoveId"/> (the undo). The body
|
||||||
|
/// never names an account: the proofs, live Heimdall access tokens, say which accounts are meant.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record HeimdallMoveRequest(
|
||||||
|
string MoveId, IReadOnlyList<string> FromProofs, string? ToProof = null, IReadOnlyList<string>? 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
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The receipt of a move: the destination account, the logins that moved and the tier of the proofs that carried it.</summary>
|
||||||
|
public sealed record HeimdallMoveReceipt(
|
||||||
|
string MoveId, string AccountId, IReadOnlyList<string> MovedIdentityIds, HeimdallProofTier ProofFrom, HeimdallProofTier? ProofTo, string? ReversesMoveId);
|
||||||
|
|
||||||
|
/// <summary>Heimdall's fixed refusal codes for a move, plus invalid_request, Heimdall's own schema 400.</summary>
|
||||||
|
public enum HeimdallMoveRefusal
|
||||||
|
{
|
||||||
|
AppAuthRequired,
|
||||||
|
NotAllowedForApp,
|
||||||
|
NotReversible,
|
||||||
|
ProofInvalid,
|
||||||
|
SameAccount,
|
||||||
|
ProofStale,
|
||||||
|
IdentityNotProved,
|
||||||
|
AlreadyMoved,
|
||||||
|
ProviderConflict,
|
||||||
|
IdentityNotFound,
|
||||||
|
RequestInvalid
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum HeimdallProofSide
|
||||||
|
{
|
||||||
|
From,
|
||||||
|
To
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="HeimdallMoveRequest.MoveId"/> is the caller's, and Heimdall answers it with the stored
|
||||||
|
/// receipt. Logs name the outcome class and refusal code only.
|
||||||
|
/// </summary>
|
||||||
|
public sealed partial class HeimdallIdentityMoveClient(
|
||||||
|
HttpClient httpClient, IOptions<HeimdallOptions> heimdallOptions, ILogger<HeimdallIdentityMoveClient> logger)
|
||||||
|
{
|
||||||
|
/// <summary>The deadline of one call, headers and body together, set on the HttpClient by <see cref="HeimdallIdentityMoveClientServices"/>.</summary>
|
||||||
|
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<HeimdallMoveOutcome> 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<HeimdallMoveOutcome> 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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<HeimdallMoveReceipt?> 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<string>();
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>The contract's closed body, or ArgumentException before any I/O when the request breaks it.</summary>
|
||||||
|
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<string, object?> { ["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
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static void AddHeimdallClients(this IServiceCollection services)
|
||||||
|
{
|
||||||
|
services.AddHttpClient<HeimdallAuthService>((serviceProvider, client) =>
|
||||||
|
HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value))
|
||||||
|
.WithoutRedirects()
|
||||||
|
.RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
|
||||||
|
services.AddHttpClient<HeimdallMemberClient>((serviceProvider, client) =>
|
||||||
|
HeimdallMemberClient.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value))
|
||||||
|
.WithoutRedirects()
|
||||||
|
.RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
|
||||||
|
services.AddHeimdallIdentityMoveClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A 3xx from Heimdall is its answer: following it would carry the app secret or a member's bearer to another origin.</summary>
|
||||||
|
public static IHttpClientBuilder WithoutRedirects(this IHttpClientBuilder builder) =>
|
||||||
|
builder.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { AllowAutoRedirect = false, PooledConnectionLifetime = TimeSpan.FromMinutes(2) });
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static IHttpClientBuilder AddHeimdallIdentityMoveClient(this IServiceCollection services) =>
|
||||||
|
services.AddHttpClient<HeimdallIdentityMoveClient>((serviceProvider, client) =>
|
||||||
|
{
|
||||||
|
HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value);
|
||||||
|
client.Timeout = HeimdallIdentityMoveClient.Timeout;
|
||||||
|
})
|
||||||
|
.WithoutRedirects()
|
||||||
|
.RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
|
||||||
|
}
|
||||||
112
src/Bifrost.Web/Features/Heimdall/HeimdallMemberClient.cs
Normal file
112
src/Bifrost.Web/Features/Heimdall/HeimdallMemberClient.cs
Normal file
|
|
@ -0,0 +1,112 @@
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Bifrost.Web.Configuration;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Heimdall;
|
||||||
|
|
||||||
|
/// <summary>One login a Heimdall account holds, as the Linked accounts page shows it. No provider user id, scope or email.</summary>
|
||||||
|
public sealed record LinkedIdentitySummary(string Id, string Provider, string? DisplayName, DateTimeOffset? LinkedAt);
|
||||||
|
|
||||||
|
public enum HeimdallMemberCall
|
||||||
|
{
|
||||||
|
Ok,
|
||||||
|
SignInRequired,
|
||||||
|
StepUpRequired,
|
||||||
|
IdentityNotFound,
|
||||||
|
LastIdentity,
|
||||||
|
Error
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record HeimdallMemberResult(HeimdallMemberCall Call, IReadOnlyList<LinkedIdentitySummary>? Identities);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Heimdall's member routes (docs/service-contract.md: GET /v1/me/identities, POST /v1/me/identities/{id}/unlink). Each
|
||||||
|
/// takes the member's bearer as an argument, uses it for that one request and keeps nothing. Its HttpClient carries no
|
||||||
|
/// app secret: these routes act only for a member who is present, so a Bifrost fault cannot reach them without one.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class HeimdallMemberClient(HttpClient httpClient)
|
||||||
|
{
|
||||||
|
private const int MaxIdentities = 32;
|
||||||
|
private const int MaxDisplayName = 80;
|
||||||
|
|
||||||
|
public static void ConfigureClient(HttpClient client, HeimdallOptions options) =>
|
||||||
|
client.BaseAddress = new Uri(options.BaseUrl.TrimEnd('/'));
|
||||||
|
|
||||||
|
public Task<HeimdallMemberResult> ListAsync(string bearer, CancellationToken cancellationToken) =>
|
||||||
|
SendAsync(HttpMethod.Get, "/v1/me/identities", bearer, cancellationToken);
|
||||||
|
|
||||||
|
public Task<HeimdallMemberResult> UnlinkAsync(string bearer, string identityId, CancellationToken cancellationToken) =>
|
||||||
|
SendAsync(HttpMethod.Post, $"/v1/me/identities/{Uri.EscapeDataString(identityId)}/unlink", bearer, cancellationToken);
|
||||||
|
|
||||||
|
private async Task<HeimdallMemberResult> SendAsync(HttpMethod method, string path, string bearer, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var message = new HttpRequestMessage(method, path);
|
||||||
|
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
|
||||||
|
using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||||
|
if (response.StatusCode == HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
return new HeimdallMemberResult(HeimdallMemberCall.Ok, await ReadIdentitiesAsync(response, cancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
var code = await HeimdallRefusal.CodeAsync(response, cancellationToken);
|
||||||
|
var call = (response.StatusCode, code) switch
|
||||||
|
{
|
||||||
|
(HttpStatusCode.Unauthorized, _) => HeimdallMemberCall.SignInRequired,
|
||||||
|
(HttpStatusCode.Forbidden, "step_up_required") => HeimdallMemberCall.StepUpRequired,
|
||||||
|
(HttpStatusCode.NotFound, "identity_not_found") => HeimdallMemberCall.IdentityNotFound,
|
||||||
|
(HttpStatusCode.Conflict, "last_identity") => HeimdallMemberCall.LastIdentity,
|
||||||
|
_ => HeimdallMemberCall.Error
|
||||||
|
};
|
||||||
|
return new HeimdallMemberResult(call, null);
|
||||||
|
}
|
||||||
|
catch (Exception error) when (error is HttpRequestException or JsonException or NotSupportedException or TaskCanceledException
|
||||||
|
&& !cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return new HeimdallMemberResult(HeimdallMemberCall.Error, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The identities array of a 200 answer, keeping only the fields the page shows; a malformed entry is dropped.</summary>
|
||||||
|
private static async Task<IReadOnlyList<LinkedIdentitySummary>> ReadIdentitiesAsync(HttpResponseMessage response, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using var body = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken);
|
||||||
|
var list = new List<LinkedIdentitySummary>();
|
||||||
|
if (body.RootElement.ValueKind != JsonValueKind.Object
|
||||||
|
|| !body.RootElement.TryGetProperty("identities", out var identities)
|
||||||
|
|| identities.ValueKind != JsonValueKind.Array)
|
||||||
|
{
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var item in identities.EnumerateArray().Take(MaxIdentities))
|
||||||
|
{
|
||||||
|
var id = Text(item, "id");
|
||||||
|
var provider = Text(item, "provider");
|
||||||
|
if (!Guid.TryParse(id, out _)
|
||||||
|
|| provider is not { Length: > 0 and <= 32 }
|
||||||
|
|| !provider.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_'))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var name = Text(item, "displayName") ?? Text(item, "username");
|
||||||
|
if (name is { Length: > MaxDisplayName })
|
||||||
|
{
|
||||||
|
name = name[..MaxDisplayName];
|
||||||
|
}
|
||||||
|
|
||||||
|
DateTimeOffset? linkedAt = DateTimeOffset.TryParse(Text(item, "linkedAt"), out var parsed) ? parsed : null;
|
||||||
|
list.Add(new LinkedIdentitySummary(id!, provider, name, linkedAt));
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Text(JsonElement item, string name) =>
|
||||||
|
item.ValueKind == JsonValueKind.Object && item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String
|
||||||
|
? value.GetString()
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
@ -64,23 +64,22 @@ public sealed class HeimdallPatronSupportIntakeService(
|
||||||
x.ProviderEventId == request.ProviderEventId.Trim(),
|
x.ProviderEventId == request.ProviderEventId.Trim(),
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
|
|
||||||
if (existingEvent is not null)
|
|
||||||
{
|
|
||||||
return HeimdallPatronSupportIntakeResult.Processed(
|
|
||||||
$"Already processed {request.Provider} patron support event {request.ProviderEventId}.",
|
|
||||||
existingEvent.Id);
|
|
||||||
}
|
|
||||||
|
|
||||||
var user = await dbContext.UserAccounts
|
var user = await dbContext.UserAccounts
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.SingleOrDefaultAsync(x => x.HeimdallAccountId == request.HeimdallAccountId.Trim(), cancellationToken);
|
.SingleOrDefaultAsync(x => x.HeimdallAccountId == request.HeimdallAccountId.Trim(), cancellationToken);
|
||||||
|
|
||||||
if (user is null)
|
if (user is null)
|
||||||
{
|
{
|
||||||
return HeimdallPatronSupportIntakeResult.BadRequest(
|
return existingEvent is not null
|
||||||
$"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}.");
|
? HeimdallPatronSupportIntakeResult.Processed(
|
||||||
|
$"Already processed {request.Provider} patron support event {request.ProviderEventId}.",
|
||||||
|
existingEvent.Id)
|
||||||
|
: HeimdallPatronSupportIntakeResult.BadRequest(
|
||||||
|
$"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The write gate behind RecordSupportEventAsync routes a folded account's event to its survivor and journals it, and on a
|
||||||
|
// provider retry returns the stored event, journalling it if it sits on the survivor and was left unjournalled.
|
||||||
var supportEvent = await patronageService.RecordSupportEventAsync(
|
var supportEvent = await patronageService.RecordSupportEventAsync(
|
||||||
actorUserAccountId: null,
|
actorUserAccountId: null,
|
||||||
userAccountId: user.Id,
|
userAccountId: user.Id,
|
||||||
|
|
@ -98,7 +97,9 @@ public sealed class HeimdallPatronSupportIntakeService(
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
|
|
||||||
return HeimdallPatronSupportIntakeResult.Processed(
|
return HeimdallPatronSupportIntakeResult.Processed(
|
||||||
$"Processed {request.Provider} patron support event {request.ProviderEventId}.",
|
existingEvent is not null
|
||||||
|
? $"Already processed {request.Provider} patron support event {request.ProviderEventId}."
|
||||||
|
: $"Processed {request.Provider} patron support event {request.ProviderEventId}.",
|
||||||
supportEvent.Id);
|
supportEvent.Id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
58
src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs
Normal file
58
src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Heimdall;
|
||||||
|
|
||||||
|
/// <summary>Reads the one thing Bifrost takes from a Heimdall refusal body: its error code, and only if it is a safe token.</summary>
|
||||||
|
public static class HeimdallRefusal
|
||||||
|
{
|
||||||
|
private const int BodyLimit = 4096;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The error code in the first 4 KiB of a body when it is a short snake_case token, else null. A body that cannot be
|
||||||
|
/// read or parsed yields null: a refusal never becomes a 500, and free text or tokens never reach a log or a page.
|
||||||
|
/// </summary>
|
||||||
|
public static async Task<string?> CodeAsync(HttpResponseMessage response, CancellationToken cancellationToken) =>
|
||||||
|
(await ReadAsync(response, cancellationToken))?.Code;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The error code plus the two qualifiers a move refusal carries (the contract's `proof`, only "from" or "to", and `provider`, a
|
||||||
|
/// short snake_case token), each kept only when it is that safe shape. Nothing else of the body is read. Null when no code reads.
|
||||||
|
/// </summary>
|
||||||
|
public static async Task<HeimdallRefusalBody?> ReadAsync(HttpResponseMessage response, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
|
||||||
|
var head = new byte[BodyLimit];
|
||||||
|
var length = 0;
|
||||||
|
while (length < head.Length && await stream.ReadAsync(head.AsMemory(length), cancellationToken) is > 0 and var read)
|
||||||
|
{
|
||||||
|
length += read;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var body = JsonDocument.Parse(head.AsMemory(0, length));
|
||||||
|
if (body.RootElement.ValueKind == JsonValueKind.Object && Token(body.RootElement, "error", 64) is { } code)
|
||||||
|
{
|
||||||
|
var proof = body.RootElement.TryGetProperty("proof", out var side) && side.ValueKind == JsonValueKind.String ? side.GetString() : null;
|
||||||
|
return new HeimdallRefusalBody(code, proof is "from" or "to" ? proof : null, Token(body.RootElement, "provider", 32));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception) when (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Token(JsonElement root, string name, int maxLength) =>
|
||||||
|
root.TryGetProperty(name, out var value)
|
||||||
|
&& value.ValueKind == JsonValueKind.String
|
||||||
|
&& value.GetString() is { Length: > 0 } text
|
||||||
|
&& text.Length <= maxLength
|
||||||
|
&& text.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_')
|
||||||
|
? text
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A Heimdall refusal's safe fields: the code, the proof side ("from"/"to") and the provider, when present and well formed.</summary>
|
||||||
|
public sealed record HeimdallRefusalBody(string Code, string? Proof, string? Provider);
|
||||||
35
src/Bifrost.Web/Features/Heimdall/LinkedAccountsSnapshots.cs
Normal file
35
src/Bifrost.Web/Features/Heimdall/LinkedAccountsSnapshots.cs
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Heimdall;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What the Linked accounts page last read from Heimdall for an account: id, provider, display name and link date of
|
||||||
|
/// each login, nothing else, for <see cref="Lifetime"/>. It lives in this process only, keyed by the Heimdall account id,
|
||||||
|
/// and is never given to the browser; it holds no bearer. The page renders from it because the list is fetched inside a
|
||||||
|
/// completion request, which redirects. After a restart it is empty and the page offers to read the list again.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class LinkedAccountsSnapshots(TimeProvider timeProvider)
|
||||||
|
{
|
||||||
|
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
|
||||||
|
|
||||||
|
private readonly ConcurrentDictionary<string, (IReadOnlyList<LinkedIdentitySummary> Identities, DateTimeOffset ExpiresAt)> _held = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
public void Put(string accountId, IReadOnlyList<LinkedIdentitySummary> identities)
|
||||||
|
{
|
||||||
|
var now = timeProvider.GetUtcNow();
|
||||||
|
foreach (var (key, value) in _held)
|
||||||
|
{
|
||||||
|
if (value.ExpiresAt <= now)
|
||||||
|
{
|
||||||
|
_held.TryRemove(key, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_held[accountId] = (identities, now + Lifetime);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<LinkedIdentitySummary>? Get(string accountId) =>
|
||||||
|
_held.TryGetValue(accountId, out var value) && value.ExpiresAt > timeProvider.GetUtcNow() ? value.Identities : null;
|
||||||
|
|
||||||
|
public void Remove(string accountId) => _held.TryRemove(accountId, out _);
|
||||||
|
}
|
||||||
768
src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs
Normal file
768
src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs
Normal file
|
|
@ -0,0 +1,768 @@
|
||||||
|
using System.Globalization;
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Patronage;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Membership;
|
||||||
|
|
||||||
|
/// <summary>How an account stands under a merge: the folded account of an unfinished merge is Frozen, of a landed one Folded.</summary>
|
||||||
|
public abstract record MergeStanding(Guid MergeId)
|
||||||
|
{
|
||||||
|
public sealed record Frozen(Guid MergeId) : MergeStanding(MergeId);
|
||||||
|
|
||||||
|
public sealed record Folded(Guid MergeId, Guid SurvivorId) : MergeStanding(MergeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record MergePlanEntry(
|
||||||
|
AccountMergeEntryKind Kind,
|
||||||
|
AccountMergeEntryAction Action,
|
||||||
|
Guid RecordId,
|
||||||
|
Guid? PriorUserAccountId = null,
|
||||||
|
string? PriorText = null,
|
||||||
|
DateTimeOffset? PriorAtUtc = null);
|
||||||
|
|
||||||
|
/// <summary>A dry run: the block codes (never account names), the journal entries a commit would write, and the record counts left untouched.</summary>
|
||||||
|
public sealed record MergePlan(
|
||||||
|
IReadOnlyList<string> Blocks,
|
||||||
|
IReadOnlyList<MergePlanEntry> Entries,
|
||||||
|
IReadOnlyDictionary<string, int> Left)
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The one owner of what an account merge does to Bifrost records and of how an account stands under one: the plan, the Committed
|
||||||
|
/// save, the undo save, the Final transition and StandingAsync. A merge only reduces: nothing is deleted, votes and
|
||||||
|
/// appraisals are stamped void (the model's query filter then removes them from every tally) or re-pointed, and every change is
|
||||||
|
/// journalled in AccountMergeEntry. Design: /opt/commons/handoff/heimdall-account-merge-design-20261113.md sections 3, 5, 7.
|
||||||
|
/// </summary>
|
||||||
|
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<MergeStanding?> StandingAsync(Guid userAccountId, CancellationToken cancellationToken) =>
|
||||||
|
StandingAsync(dbContext, userAccountId, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>The single reading of standing, shared by the actor accessor and the OIDC refusal, which holds only a context. Derived from the merge state on every call.</summary>
|
||||||
|
public static async Task<MergeStanding?> StandingAsync(BifrostDbContext db, Guid userAccountId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var merge = await db.AccountMerges.AsNoTracking()
|
||||||
|
.Where(x => x.FoldedUserAccountId == userAccountId &&
|
||||||
|
(FrozenStates.Contains(x.State) || FoldedStates.Contains(x.State)))
|
||||||
|
.OrderByDescending(x => x.CreatedUtc)
|
||||||
|
.FirstOrDefaultAsync(cancellationToken);
|
||||||
|
|
||||||
|
return merge is null
|
||||||
|
? null
|
||||||
|
: FrozenStates.Contains(merge.State)
|
||||||
|
? new MergeStanding.Frozen(merge.Id)
|
||||||
|
: new MergeStanding.Folded(merge.Id, merge.SurvivorUserAccountId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="CommitAsync"/> takes exclusively before it reduces, across the
|
||||||
|
/// standing read and everything <paramref name="write"/> 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 <paramref name="write"/> 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.
|
||||||
|
/// </summary>
|
||||||
|
public static async Task<T> WriteAsAsync<T>(BifrostDbContext db, Guid userAccountId, Func<MergeStanding?, Task<T>> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A transaction for the caller to commit, or null where there is none to open: not Postgres, or one already open (its owner commits).</summary>
|
||||||
|
private static async Task<Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction?> BeginAsync(BifrostDbContext db, CancellationToken cancellationToken) =>
|
||||||
|
db.Database.IsNpgsql() && db.Database.CurrentTransaction is null ? await db.Database.BeginTransactionAsync(cancellationToken) : null;
|
||||||
|
|
||||||
|
/// <summary>The account's lock, on the key the chain trigger uses (hashtextextended of the id's text). A no-op off Postgres.</summary>
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes nothing. <paramref name="exceptMergeId"/> lets the saga re-plan a merge it already holds without it blocking itself.</summary>
|
||||||
|
public async Task<MergePlan> PlanAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? exceptMergeId = null)
|
||||||
|
{
|
||||||
|
var blocks = await BlocksAsync(survivorId, foldedId, exceptMergeId, cancellationToken);
|
||||||
|
var entries = new List<MergePlanEntry>();
|
||||||
|
var left = new Dictionary<string, int>();
|
||||||
|
|
||||||
|
if (!blocks.Contains("account_missing"))
|
||||||
|
{
|
||||||
|
var reduction = await ReduceAsync(survivorId, foldedId, cancellationToken);
|
||||||
|
entries.AddRange(reduction.Entries);
|
||||||
|
left["ConsentReceipts"] = await dbContext.ConsentReceipts.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
|
||||||
|
left["PasskeyCredentials"] = await dbContext.PasskeyCredentials.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
|
||||||
|
left["LedgerEntries"] = await dbContext.LedgerEntries.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new MergePlan(blocks, entries, left);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IReadOnlyList<string>> BlocksAsync(Guid survivorId, Guid foldedId, Guid? exceptMergeId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var blocks = new List<string>();
|
||||||
|
if (survivorId == foldedId)
|
||||||
|
{
|
||||||
|
blocks.Add("same_account");
|
||||||
|
}
|
||||||
|
|
||||||
|
var accounts = await dbContext.UserAccounts.AsNoTracking()
|
||||||
|
.Where(x => x.Id == survivorId || x.Id == foldedId)
|
||||||
|
.Select(x => new { x.Id, x.HeimdallAccountId })
|
||||||
|
.ToListAsync(cancellationToken);
|
||||||
|
if (accounts.Count < (survivorId == foldedId ? 1 : 2))
|
||||||
|
{
|
||||||
|
blocks.Add("account_missing");
|
||||||
|
return blocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await dbContext.MindPersonas.AnyAsync(x => x.UserAccountId == survivorId || x.UserAccountId == foldedId, cancellationToken))
|
||||||
|
{
|
||||||
|
blocks.Add("mind_account");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (accounts.Any(x => string.IsNullOrWhiteSpace(x.HeimdallAccountId)))
|
||||||
|
{
|
||||||
|
blocks.Add("native_account");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await dbContext.AccountMerges.AnyAsync(
|
||||||
|
x => x.Id != exceptMergeId &&
|
||||||
|
InFlightStates.Contains(x.State) &&
|
||||||
|
(x.SurvivorUserAccountId == survivorId || x.FoldedUserAccountId == survivorId ||
|
||||||
|
x.SurvivorUserAccountId == foldedId || x.FoldedUserAccountId == foldedId),
|
||||||
|
cancellationToken))
|
||||||
|
{
|
||||||
|
blocks.Add("merge_in_flight");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await FoldedLinkAsync(survivorId, exceptMergeId, cancellationToken))
|
||||||
|
{
|
||||||
|
blocks.Add("survivor_is_folded");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await FoldedLinkAsync(foldedId, exceptMergeId, cancellationToken))
|
||||||
|
{
|
||||||
|
blocks.Add("already_folded");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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<bool> FoldedLinkAsync(Guid accountId, Guid? exceptMergeId, CancellationToken cancellationToken) =>
|
||||||
|
dbContext.AccountMerges.AnyAsync(
|
||||||
|
x => x.Id != exceptMergeId && x.FoldedUserAccountId == accountId && FoldedStates.Contains(x.State),
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Applies the merge to Bifrost records in one save, together with State=Committed. Total: blocks were checked before the move
|
||||||
|
/// and a refusal now would strand moved logins, so it recomputes the reductions from current rows and applies them. Committed
|
||||||
|
/// and Final are no-ops returning the receipt; any other state but HeimdallMoved is an error.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<AccountMerge> CommitAsync(Guid mergeId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, cancellationToken);
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Replays the journal backward in one save with State=Undone. Total, like commit. Undone is a no-op; any other state but HeimdallReversed is an error.</summary>
|
||||||
|
public async Task<AccountMerge> UndoLocalAsync(Guid mergeId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, cancellationToken);
|
||||||
|
if (merge.State == AccountMergeState.Undone)
|
||||||
|
{
|
||||||
|
return merge;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (merge.State != AccountMergeState.HeimdallReversed)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"Merge {mergeId} is {merge.State}; only a HeimdallReversed merge can be undone locally.");
|
||||||
|
}
|
||||||
|
|
||||||
|
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<MembershipStatus>(entry.PriorText, out _);
|
||||||
|
if (restore)
|
||||||
|
{
|
||||||
|
folded.Membership!.Status = Enum.Parse<MembershipStatus>(entry.PriorText!);
|
||||||
|
}
|
||||||
|
|
||||||
|
Record(entry, restore);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case (AccountMergeEntryKind.Standing, AccountMergeEntryAction.Suspended):
|
||||||
|
{
|
||||||
|
// Only while the survivor still carries exactly this merge's suspension; an admin who changed it since owns the standing now.
|
||||||
|
var restore = survivor.Membership is { Status: MembershipStatus.Suspended } member &&
|
||||||
|
member.SuspensionReason == SuspensionReason(mergeId) &&
|
||||||
|
Enum.TryParse<MembershipStatus>(entry.PriorText, out _);
|
||||||
|
if (restore)
|
||||||
|
{
|
||||||
|
survivor.Membership!.Status = Enum.Parse<MembershipStatus>(entry.PriorText!);
|
||||||
|
survivor.Membership.SuspensionReason = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Record(entry, restore);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case (AccountMergeEntryKind.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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Committed merges whose grace has ended become Final; returns how many this call finalized. Undo is never allowed past Final.
|
||||||
|
/// State is the merge's concurrency token, so a merge another writer moved first (UndoRequested) fails its save and is left to that
|
||||||
|
/// transition: a stale Committed read can never overwrite it.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<int> FinalizeDueAsync(DateTimeOffset now, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="PatronageService.RecordSupportEventAsync"/>, the only caller. Idempotent: a provider retry stages nothing.
|
||||||
|
/// </summary>
|
||||||
|
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<MergePlanEntry> entries,
|
||||||
|
List<Action<Guid, DateTimeOffset>> effects,
|
||||||
|
List<Vote> movedVotes,
|
||||||
|
bool movedPatronEvents)
|
||||||
|
{
|
||||||
|
public UserAccount Survivor { get; } = survivor;
|
||||||
|
|
||||||
|
public UserAccount Folded { get; } = folded;
|
||||||
|
|
||||||
|
public IReadOnlyList<MergePlanEntry> Entries => entries;
|
||||||
|
|
||||||
|
public bool MovedPatronEvents { get; } = movedPatronEvents;
|
||||||
|
|
||||||
|
public Guid MergeId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>A moved vote carries the survivor's weight, derived once from the survivor's tiers as they stand after the restage, never the folded account's.</summary>
|
||||||
|
public void ReweighMovedVotes()
|
||||||
|
{
|
||||||
|
foreach (var vote in movedVotes)
|
||||||
|
{
|
||||||
|
vote.Weight = Survivor.Membership!.EffectiveVotingWeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Apply(DateTimeOffset now)
|
||||||
|
{
|
||||||
|
foreach (var effect in effects)
|
||||||
|
{
|
||||||
|
effect(MergeId, now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What a merge does to records, computed from current rows without writing: the journal entries and the effects that apply them.
|
||||||
|
/// Rules (design 5): suspension wins; the folded membership is closed and its roles never copied; open standard motions and
|
||||||
|
/// concept appraisals keep one voice per person (the survivor's), a lone folded one moving only to an Active survivor; patron
|
||||||
|
/// events follow the person.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<Reduction> ReduceAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? mergeId = null)
|
||||||
|
{
|
||||||
|
var survivor = await dbContext.UserAccounts.Include(x => x.Membership!).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<MergePlanEntry>();
|
||||||
|
var effects = new List<Action<Guid, DateTimeOffset>>();
|
||||||
|
var movedVotes = new List<Vote>();
|
||||||
|
|
||||||
|
var foldedSuspended = folded.Membership?.Status == MembershipStatus.Suspended;
|
||||||
|
var survivorSuspendedNow = survivor.Membership?.Status == MembershipStatus.Suspended;
|
||||||
|
var survivorStanding = survivor.Membership?.Status;
|
||||||
|
if (foldedSuspended && !survivorSuspendedNow)
|
||||||
|
{
|
||||||
|
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<PatronSupportEvent> 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<VoterClass>(prior![..split], out var voterClass) ? (voterClass, prior[(split + 1)..]) : (null, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AccountMergeSweeper(IServiceScopeFactory scopes, TimeProvider clock, ILogger<AccountMergeSweeper> 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<MergeProofs>().PruneExpired();
|
||||||
|
await scope.ServiceProvider.GetRequiredService<AccountMergeSaga>().AdvanceDueAsync(now, stoppingToken);
|
||||||
|
await scope.ServiceProvider.GetRequiredService<AccountMergeLedger>().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));
|
||||||
|
}
|
||||||
|
}
|
||||||
576
src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs
Normal file
576
src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs
Normal file
|
|
@ -0,0 +1,576 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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: <see cref="PrintMembers"/> never prints it (nor the account id), so no log or exception that holds a proof can leak it.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record MergeProof(string AccessToken, string HeimdallAccountId, string Provider)
|
||||||
|
{
|
||||||
|
private bool PrintMembers(StringBuilder builder)
|
||||||
|
{
|
||||||
|
builder.Append($"Provider = {Provider}");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What the member confirmed: the pair, the plan digest they saw, and a proof for every login of each side that must speak.</summary>
|
||||||
|
public sealed record ConfirmMergeRequest(
|
||||||
|
Guid ActorUserAccountId,
|
||||||
|
Guid SurvivorUserAccountId,
|
||||||
|
Guid FoldedUserAccountId,
|
||||||
|
string PreviewDigest,
|
||||||
|
MergeProof SurvivorProof,
|
||||||
|
IReadOnlyList<MergeProof> FoldedProofs);
|
||||||
|
|
||||||
|
/// <summary>The closed answer to a confirm. Only Confirmed wrote a row.</summary>
|
||||||
|
public abstract record ConfirmOutcome
|
||||||
|
{
|
||||||
|
private ConfirmOutcome()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record Confirmed(Guid MergeId) : ConfirmOutcome;
|
||||||
|
|
||||||
|
/// <summary>The plan's block codes (never account names), or merge_in_flight when the database refused an overlapping merge.</summary>
|
||||||
|
public sealed record Blocked(IReadOnlyList<string> Codes) : ConfirmOutcome;
|
||||||
|
|
||||||
|
public sealed record PreviewStale : ConfirmOutcome;
|
||||||
|
|
||||||
|
public sealed record NotParty : ConfirmOutcome;
|
||||||
|
|
||||||
|
public sealed record ProofAccountMismatch : ConfirmOutcome;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The closed answer to an undo request. Only Requested wrote.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
public enum SettleChoice
|
||||||
|
{
|
||||||
|
FailForward,
|
||||||
|
AbandonUndo
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The closed answer to an operator's settle. Only Settled wrote.</summary>
|
||||||
|
public abstract record SettleOutcome
|
||||||
|
{
|
||||||
|
private SettleOutcome()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record Settled : SettleOutcome;
|
||||||
|
|
||||||
|
/// <summary>The merge is missing, in another state than the choice ends, or not stuck on one of the settleable outcomes.</summary>
|
||||||
|
public sealed record NotStuck : SettleOutcome;
|
||||||
|
|
||||||
|
public sealed record WrongMoveId : SettleOutcome;
|
||||||
|
|
||||||
|
/// <summary>The State token went to another writer first; the other transition stands and nothing was changed.</summary>
|
||||||
|
public sealed record Lost : SettleOutcome;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The one owner of an account merge's lifecycle outside the ledger's Committed, Final and Undone, and the only caller of
|
||||||
|
/// <see cref="HeimdallIdentityMoveClient"/>. It inserts Confirmed (the consent record, with the Heimdall bearers sealed and the move
|
||||||
|
/// id minted), runs the one idempotent step function <see cref="AdvanceAsync"/> (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 <see cref="AccountMergeLedger.WriteAsAsync{T}"/>.
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed partial class AccountMergeSaga(
|
||||||
|
BifrostDbContext dbContext,
|
||||||
|
AccountMergeLedger ledger,
|
||||||
|
HeimdallIdentityMoveClient mover,
|
||||||
|
IDataProtectionProvider dataProtection,
|
||||||
|
AuditTrailService audit,
|
||||||
|
TimeProvider timeProvider,
|
||||||
|
ILogger<AccountMergeSaga> 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<string> 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 ----
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="AdvanceAsync"/>.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<ConfirmOutcome> 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<ConfirmOutcome> 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 ----
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<UndoOutcome> RequestUndoAsync(
|
||||||
|
Guid mergeId, Guid actorUserAccountId, IReadOnlyList<MergeProof> 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<UndoOutcome> WriteUndoRequestedAsync(
|
||||||
|
Guid mergeId, Guid actorUserAccountId, IReadOnlyList<MergeProof> 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 ----
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<AccountMerge> 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<AccountMerge> 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<AccountMerge> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Advances every in-flight merge that is due, oldest first. One that throws is logged and skipped; returns how many were advanced.</summary>
|
||||||
|
public async Task<int> 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 ----
|
||||||
|
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
public static readonly IReadOnlyList<string> SettleableOutcomes = [ReceiptMismatch, ProofsUnreadable, MoveIdConflict];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsSettleable(AccountMerge merge) =>
|
||||||
|
merge.State is AccountMergeState.Confirmed or AccountMergeState.UndoRequested && SettleableOutcomes.Contains(merge.LastOutcome);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="AdvanceAsync"/>
|
||||||
|
/// answers Lost and changes nothing. The caller has checked the operator's authority.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<SettleOutcome> 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 ----
|
||||||
|
|
||||||
|
/// <summary>The merge as stored now: a row this context already tracks is reloaded, never trusted.</summary>
|
||||||
|
private async Task<AccountMerge?> 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<string> HeimdallAccountAsync(Guid userAccountId, CancellationToken cancellationToken) =>
|
||||||
|
dbContext.UserAccounts.AsNoTracking().Where(x => x.Id == userAccountId).Select(x => x.HeimdallAccountId).SingleAsync(cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
private static void RequireProofs(MergeProof? one, IReadOnlyList<MergeProof> 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<string> 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<ProofSeal>(_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("(?<!^)([A-Z])")]
|
||||||
|
private static partial Regex WordBoundary();
|
||||||
|
|
||||||
|
/// <summary>The database's refusal of an overlapping merge: the live-merge unique index or the chain trigger's exclusion violation.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -49,6 +49,12 @@ public sealed class MembershipSuspensionService(BifrostDbContext dbContext, Audi
|
||||||
return SuspensionOutcome.NoSuchAccount;
|
return SuspensionOutcome.NoSuchAccount;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A merged account is terminal: only the merge ledger leaves that status, so neither suspending nor lifting applies.
|
||||||
|
if (membership.IsMerged)
|
||||||
|
{
|
||||||
|
return SuspensionOutcome.NotApplicable;
|
||||||
|
}
|
||||||
|
|
||||||
// An admin cannot suspend themselves or another platform admin here (the same derivation that makes an actor an admin):
|
// An admin cannot suspend themselves or another platform admin here (the same derivation that makes an actor an admin):
|
||||||
// bootstrap admins are re-promoted to Active at sign-in by configuration, so the suspension would be undone without a receipt.
|
// bootstrap admins are re-promoted to Active at sign-in by configuration, so the suspension would be undone without a receipt.
|
||||||
if (suspend && (user.Id == actor.UserAccount.Id || new CurrentBifrostActor(true, user).IsPlatformAdmin))
|
if (suspend && (user.Id == actor.UserAccount.Id || new CurrentBifrostActor(true, user).IsPlatformAdmin))
|
||||||
|
|
|
||||||
131
src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs
Normal file
131
src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs
Normal file
|
|
@ -0,0 +1,131 @@
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Bifrost.Web.Configuration;
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Membership;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The chat host's pull of merge notices: GET the unacked feed, POST an ack. JSON only because the reader is the chat host's script (a xenos
|
||||||
|
/// boundary). The bearer is the chat host's own secret (ChatNotices:Token); an empty token turns both routes off. No cookie, no CORS, never stored.
|
||||||
|
/// </summary>
|
||||||
|
public static class MergeNoticeEndpoints
|
||||||
|
{
|
||||||
|
private const int MaxAckBodyBytes = 1024;
|
||||||
|
|
||||||
|
public static void Map(WebApplication app)
|
||||||
|
{
|
||||||
|
app.MapGet("/api/merge-notices/chat", async (HttpContext http, IOptions<ChatNoticesOptions> options, MergeNoticeFeed feed, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
if (Gate(http, options.Value) is { } refused)
|
||||||
|
{
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
|
||||||
|
DateTimeOffset? after = null;
|
||||||
|
if (http.Request.Query.TryGetValue("after", out var raw) && raw.Count > 0)
|
||||||
|
{
|
||||||
|
if (!DateTimeOffset.TryParse(raw[0], CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var parsed))
|
||||||
|
{
|
||||||
|
return Results.StatusCode(StatusCodes.Status400BadRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
after = parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
int? limit = http.Request.Query.TryGetValue("limit", out var rawLimit) && int.TryParse(rawLimit[0], CultureInfo.InvariantCulture, out var n) ? n : null;
|
||||||
|
var notices = await feed.ReadAsync(AccountMergeNoticeTarget.Chat, after, limit, ct);
|
||||||
|
return Results.Text(JsonSerializer.Serialize(notices.Select(Wire)), "application/json");
|
||||||
|
}).AllowAnonymous();
|
||||||
|
|
||||||
|
app.MapPost("/api/merge-notices/chat/ack", async (HttpContext http, IOptions<ChatNoticesOptions> options, MergeNoticeFeed feed, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
if (Gate(http, options.Value) is { } refused)
|
||||||
|
{
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await ReadAckAsync(http.Request, ct) is not var (mergeId, kind))
|
||||||
|
{
|
||||||
|
return Results.StatusCode(StatusCodes.Status400BadRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await feed.AckAsync(AccountMergeNoticeTarget.Chat, mergeId, kind, ct)
|
||||||
|
? Results.StatusCode(StatusCodes.Status204NoContent)
|
||||||
|
: Results.StatusCode(StatusCodes.Status404NotFound);
|
||||||
|
}).AllowAnonymous();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IResult? Gate(HttpContext http, ChatNoticesOptions options)
|
||||||
|
{
|
||||||
|
http.Response.Headers.CacheControl = "no-store";
|
||||||
|
if (string.IsNullOrEmpty(options.Token))
|
||||||
|
{
|
||||||
|
return Results.StatusCode(StatusCodes.Status404NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
var header = http.Request.Headers.Authorization.ToString();
|
||||||
|
const string scheme = "Bearer ";
|
||||||
|
var presented = header.StartsWith(scheme, StringComparison.Ordinal) ? header[scheme.Length..] : string.Empty;
|
||||||
|
// Both sides are hashed first, so the comparison is over equal-length digests and says nothing about the token's length.
|
||||||
|
var matches = CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(presented)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Token)));
|
||||||
|
return matches && presented.Length > 0 ? null : Results.StatusCode(StatusCodes.Status401Unauthorized);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<(Guid MergeId, AccountMergeNoticeKind Kind)?> ReadAckAsync(HttpRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var buffer = new byte[MaxAckBodyBytes + 1];
|
||||||
|
var read = 0;
|
||||||
|
int n;
|
||||||
|
while (read < buffer.Length && (n = await request.Body.ReadAsync(buffer.AsMemory(read), ct)) > 0)
|
||||||
|
{
|
||||||
|
read += n;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (read == 0 || read > MaxAckBodyBytes)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var document = JsonDocument.Parse(buffer.AsMemory(0, read));
|
||||||
|
var root = document.RootElement;
|
||||||
|
if (root.ValueKind != JsonValueKind.Object ||
|
||||||
|
!root.TryGetProperty("merge_id", out var id) || id.ValueKind != JsonValueKind.String || !Guid.TryParse(id.GetString(), out var mergeId) ||
|
||||||
|
!root.TryGetProperty("type", out var type) || type.ValueKind != JsonValueKind.String)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
AccountMergeNoticeKind? kind = type.GetString() switch
|
||||||
|
{
|
||||||
|
"merged" => AccountMergeNoticeKind.Merged,
|
||||||
|
"undone" => AccountMergeNoticeKind.Undone,
|
||||||
|
"final" => AccountMergeNoticeKind.Final,
|
||||||
|
_ => null
|
||||||
|
};
|
||||||
|
return kind is { } k ? (mergeId, k) : null;
|
||||||
|
}
|
||||||
|
catch (JsonException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The wire shape, exactly these keys: ids in format D, times ISO 8601 UTC, no email, display name, Heimdall id or Matrix id.</summary>
|
||||||
|
private static Dictionary<string, object?> Wire(MergeNotice notice) => new()
|
||||||
|
{
|
||||||
|
["type"] = notice.Kind.ToString().ToLowerInvariant(),
|
||||||
|
["merge_id"] = notice.MergeId.ToString("D"),
|
||||||
|
["occurred_at"] = notice.OccurredAt.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture),
|
||||||
|
["grace_ends_at"] = notice.GraceEndsAt?.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture),
|
||||||
|
["old_subject"] = notice.OldSubject.ToString("D"),
|
||||||
|
["new_subject"] = notice.NewSubject.ToString("D"),
|
||||||
|
["old_preferred_username"] = notice.OldPreferredUsername,
|
||||||
|
["new_preferred_username"] = notice.NewPreferredUsername
|
||||||
|
};
|
||||||
|
}
|
||||||
96
src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs
Normal file
96
src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs
Normal file
|
|
@ -0,0 +1,96 @@
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Membership;
|
||||||
|
|
||||||
|
/// <summary>What the chat host is told about one merge. Derived from the merge row on every read; never stored.</summary>
|
||||||
|
public sealed record MergeNotice(
|
||||||
|
AccountMergeNoticeKind Kind,
|
||||||
|
Guid MergeId,
|
||||||
|
DateTimeOffset OccurredAt,
|
||||||
|
DateTimeOffset? GraceEndsAt,
|
||||||
|
Guid OldSubject,
|
||||||
|
Guid NewSubject,
|
||||||
|
string OldPreferredUsername,
|
||||||
|
string NewPreferredUsername);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The one owner of what a notice reader is told about merges: merged (CommittedUtc), undone (UndoneUtc) and final (FinalizedUtc) are read off
|
||||||
|
/// the AccountMerges row on every call, so a notice cannot disagree with the merge, and the reader's ack row is the only thing stored.
|
||||||
|
/// Reads only AccountMerges and UserAccounts; writes only AccountMergeNoticeAck.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class MergeNoticeFeed(BifrostDbContext dbContext, TimeProvider timeProvider)
|
||||||
|
{
|
||||||
|
public const int DefaultLimit = 50;
|
||||||
|
public const int MaxLimit = 200;
|
||||||
|
|
||||||
|
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
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Unacked notices for <paramref name="target"/>, oldest first by (occurred_at, merge_id, kind), strictly later than <paramref name="after"/> when given. Acks are the cursor; <c>after</c> only narrows the scan.</summary>
|
||||||
|
public async Task<IReadOnlyList<MergeNotice>> ReadAsync(AccountMergeNoticeTarget target, DateTimeOffset? after, int? limit, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var take = limit is > 0 ? Math.Min(limit.Value, MaxLimit) : DefaultLimit;
|
||||||
|
var picked = new List<(AccountMerge Merge, AccountMergeNoticeKind Kind, DateTimeOffset At)>();
|
||||||
|
// Each kind's own oldest `take` rows contain every row of the overall oldest `take`, so merging three bounded lists is exact.
|
||||||
|
foreach (var kind in Kinds)
|
||||||
|
{
|
||||||
|
var rows = await dbContext.AccountMerges.AsNoTracking()
|
||||||
|
.Where(x => (kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) != null)
|
||||||
|
.Where(x => after == null || (kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) > after)
|
||||||
|
.Where(x => !dbContext.AccountMergeNoticeAcks.Any(a => a.MergeId == x.Id && a.Kind == kind && a.Target == target))
|
||||||
|
.OrderBy(x => kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc)
|
||||||
|
.ThenBy(x => x.Id)
|
||||||
|
.Take(take)
|
||||||
|
.ToListAsync(cancellationToken);
|
||||||
|
picked.AddRange(rows.Select(x => (x, kind, OccurredAt(x, kind)!.Value)));
|
||||||
|
}
|
||||||
|
|
||||||
|
var page = picked.OrderBy(x => x.At).ThenBy(x => x.Merge.Id).ThenBy(x => x.Kind).Take(take).ToList();
|
||||||
|
var ids = page.SelectMany(x => new[] { x.Merge.FoldedUserAccountId, x.Merge.SurvivorUserAccountId }).Distinct().ToList();
|
||||||
|
var names = await dbContext.UserAccounts.AsNoTracking().Where(x => ids.Contains(x.Id))
|
||||||
|
.Select(x => new { x.Id, x.NormalizedBifrostIdentity }).ToDictionaryAsync(x => x.Id, x => x.NormalizedBifrostIdentity, cancellationToken);
|
||||||
|
return [.. page.Select(x => new MergeNotice(
|
||||||
|
x.Kind, x.Merge.Id, x.At, x.Merge.GraceEndsUtc, x.Merge.FoldedUserAccountId, x.Merge.SurvivorUserAccountId,
|
||||||
|
names.GetValueOrDefault(x.Merge.FoldedUserAccountId, string.Empty), names.GetValueOrDefault(x.Merge.SurvivorUserAccountId, string.Empty)))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Records that the reader has seen (merge, kind). False when the feed would not emit that notice now (no such merge, or its timestamp unset); true otherwise, a repeat included.</summary>
|
||||||
|
public async Task<bool> AckAsync(AccountMergeNoticeTarget target, Guid mergeId, AccountMergeNoticeKind kind, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var merge = await dbContext.AccountMerges.AsNoTracking().SingleOrDefaultAsync(x => x.Id == mergeId, cancellationToken);
|
||||||
|
if (merge is null || OccurredAt(merge, kind) is null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await dbContext.AccountMergeNoticeAcks.AnyAsync(x => x.MergeId == mergeId && x.Kind == kind && x.Target == target, cancellationToken))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
dbContext.AccountMergeNoticeAcks.Add(new AccountMergeNoticeAck { MergeId = mergeId, Kind = kind, Target = target, AckedUtc = timeProvider.GetUtcNow() });
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
catch (DbUpdateException)
|
||||||
|
{
|
||||||
|
// A concurrent ack of the same key won the unique index; the notice is acked, which is what the caller asked for.
|
||||||
|
dbContext.ChangeTracker.Clear();
|
||||||
|
if (!await dbContext.AccountMergeNoticeAcks.AnyAsync(x => x.MergeId == mergeId && x.Kind == kind && x.Target == target, cancellationToken))
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
93
src/Bifrost.Web/Features/Membership/MergePreview.cs
Normal file
93
src/Bifrost.Web/Features/Membership/MergePreview.cs
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Membership;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The only wording of what a merge would do, in closed vocabulary: counts by entry kind and action from <see cref="MergePlan"/>, the
|
||||||
|
/// sentence for each block code, and the statements every merge carries. It decides nothing, and names no account: the plan holds none.
|
||||||
|
/// </summary>
|
||||||
|
public static class MergePreview
|
||||||
|
{
|
||||||
|
public static IReadOnlyList<string> Lines(MergePlan plan)
|
||||||
|
{
|
||||||
|
var lines = new List<string>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
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."
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The block for two accounts that both hold a login of one provider, which Heimdall will not combine. Providers only: no account is named.</summary>
|
||||||
|
public static string ProviderConflict(IEnumerable<string> 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.";
|
||||||
|
|
||||||
|
/// <summary>What every merge says, whatever the plan: what it cannot carry over, what it asks again, and how long it can be undone.</summary>
|
||||||
|
public static IReadOnlyList<string> 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
|
||||||
|
};
|
||||||
|
}
|
||||||
238
src/Bifrost.Web/Features/Membership/MergeProofs.cs
Normal file
238
src/Bifrost.Web/Features/Membership/MergeProofs.cs
Normal file
|
|
@ -0,0 +1,238 @@
|
||||||
|
using Bifrost.Web.Features.Heimdall;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Membership;
|
||||||
|
|
||||||
|
public enum MergeSide
|
||||||
|
{
|
||||||
|
/// <summary>The account signed in here.</summary>
|
||||||
|
Self,
|
||||||
|
|
||||||
|
/// <summary>The second account, proved by its own fresh sign-in.</summary>
|
||||||
|
Other
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum PutOutcome
|
||||||
|
{
|
||||||
|
Stored,
|
||||||
|
AmbiguousLogins,
|
||||||
|
TooManyProofs
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What a page may know of one side: no bearer, no Heimdall account id, no login names.</summary>
|
||||||
|
public sealed record MergeSideView(
|
||||||
|
Guid UserAccountId, IReadOnlyList<string> ProvedProviders, IReadOnlyList<string> 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<MergeProof> Folded) : PeekResult;
|
||||||
|
|
||||||
|
/// <summary>A side holds no live proof.</summary>
|
||||||
|
public sealed record Expired : PeekResult;
|
||||||
|
|
||||||
|
/// <summary>Logins whose provider has no live proof, by provider name only.</summary>
|
||||||
|
public sealed record LoginsUnproved(IReadOnlyList<string> Providers) : PeekResult;
|
||||||
|
|
||||||
|
/// <summary>Both accounts hold a login of these providers, a pair Heimdall always refuses; by provider name only.</summary>
|
||||||
|
public sealed record ProviderConflict(IReadOnlyList<string> Providers) : PeekResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
public abstract record UndoPeekResult
|
||||||
|
{
|
||||||
|
private UndoPeekResult()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record Ready(IReadOnlyList<MergeProof> Proofs) : UndoPeekResult;
|
||||||
|
|
||||||
|
public sealed record Expired : UndoPeekResult;
|
||||||
|
|
||||||
|
public sealed record LoginsUnproved(IReadOnlyList<string> Providers) : UndoPeekResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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. <see cref="ProofLifetime"/> 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 <see cref="Clear"/>s once the saga
|
||||||
|
/// has taken the proofs, so a refusal that wrote nothing does not cost a re-proof.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class MergeProofs(TimeProvider timeProvider)
|
||||||
|
{
|
||||||
|
public static readonly TimeSpan ProofLifetime = TimeSpan.FromSeconds(270);
|
||||||
|
|
||||||
|
/// <summary>The saga's own bound on the proofs of one move.</summary>
|
||||||
|
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<LinkedIdentitySummary> Logins { get; set; } = [];
|
||||||
|
|
||||||
|
public Dictionary<string, Held> Proofs { get; } = new(StringComparer.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly Dictionary<Guid, Dictionary<MergeSide, Side>> _held = [];
|
||||||
|
private readonly object _gate = new();
|
||||||
|
|
||||||
|
public PutOutcome Put(Guid actorId, MergeSide side, MergeProof proof, Guid userAccountId, IReadOnlyList<LinkedIdentitySummary> 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)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The Self side's proofs for an undo, once every login whose id is in <paramref name="movedIdentityIds"/> is proved.</summary>
|
||||||
|
public UndoPeekResult PeekUndo(Guid actorId, IReadOnlyCollection<string> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Drops every expired bearer without any member touching the page; the merge sweeper's tick calls it, so none outlives <see cref="ProofLifetime"/> plus one tick.</summary>
|
||||||
|
public void PruneExpired()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
Prune(timeProvider.GetUtcNow());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<string> UnprovedProviders(Side side, IEnumerable<string> providers) =>
|
||||||
|
[.. providers.Distinct(StringComparer.Ordinal).Where(x => !side.Proofs.ContainsKey(x))];
|
||||||
|
|
||||||
|
private MergeSideView? View(Dictionary<MergeSide, Side>? 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;
|
||||||
|
|
||||||
|
/// <summary>Drops every proof at or past its lifetime, then every side without one, then every actor without a side.</summary>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
114
src/Bifrost.Web/Features/Membership/MergeWording.cs
Normal file
114
src/Bifrost.Web/Features/Membership/MergeWording.cs
Normal file
|
|
@ -0,0 +1,114 @@
|
||||||
|
using System.Globalization;
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Membership;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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."
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Why Heimdall refused a merge, by its refusal code; null for a code this class does not know.</summary>
|
||||||
|
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
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
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."
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The words for a closed undo code (<see cref="UndoCode"/> or <c>logins_unproved</c>); empty for anything else.</summary>
|
||||||
|
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
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The words for a closed code the merge page answers a confirm or a start with; empty for anything else.</summary>
|
||||||
|
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.";
|
||||||
|
|
||||||
|
/// <summary>Whole days from <paramref name="now"/> to <paramref name="end"/>, rounded up, at least one while the window is open.</summary>
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
using Bifrost.Web.Data;
|
using Bifrost.Web.Data;
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
using Bifrost.Web.Features.Shared;
|
using Bifrost.Web.Features.Shared;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
|
@ -52,6 +53,7 @@ public sealed class MotionGovernanceService(
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var actorUser = actor.UserAccount ?? throw new UnauthorizedAccessException("A linked Bifrost actor is required.");
|
var actorUser = actor.UserAccount ?? throw new UnauthorizedAccessException("A linked Bifrost actor is required.");
|
||||||
|
|
||||||
var motion = await dbContext.Motions
|
var motion = await dbContext.Motions
|
||||||
.Include(x => x.Votes)
|
.Include(x => x.Votes)
|
||||||
.SingleAsync(x => x.Id == motionId, cancellationToken);
|
.SingleAsync(x => x.Id == motionId, cancellationToken);
|
||||||
|
|
@ -61,28 +63,44 @@ public sealed class MotionGovernanceService(
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var vote = motion.Votes.SingleOrDefault(x => x.UserAccountId == actorUser.Id);
|
// An actor resolved before a merge froze this account must not write a vote after it: the write gate reads standing at the write.
|
||||||
if (vote is null)
|
var wrote = await AccountMergeLedger.WriteAsAsync(dbContext, actorUser.Id, async standing =>
|
||||||
{
|
{
|
||||||
dbContext.Votes.Add(new Vote
|
if (standing is not null)
|
||||||
{
|
{
|
||||||
MotionId = motionId,
|
return false;
|
||||||
UserAccountId = actorUser.Id,
|
}
|
||||||
Choice = choice,
|
|
||||||
Weight = actor.EffectiveVotingWeight,
|
var vote = motion.Votes.SingleOrDefault(x => x.UserAccountId == actorUser.Id);
|
||||||
Comment = comment?.Trim() ?? string.Empty,
|
if (vote is null)
|
||||||
CastAtUtc = timeProvider.GetUtcNow()
|
{
|
||||||
});
|
dbContext.Votes.Add(new Vote
|
||||||
}
|
{
|
||||||
else
|
MotionId = motionId,
|
||||||
|
UserAccountId = actorUser.Id,
|
||||||
|
Choice = choice,
|
||||||
|
Weight = actor.EffectiveVotingWeight,
|
||||||
|
Comment = comment?.Trim() ?? string.Empty,
|
||||||
|
CastAtUtc = timeProvider.GetUtcNow()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
vote.Choice = choice;
|
||||||
|
vote.Weight = actor.EffectiveVotingWeight;
|
||||||
|
vote.Comment = comment?.Trim() ?? string.Empty;
|
||||||
|
vote.CastAtUtc = timeProvider.GetUtcNow();
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
return true;
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
|
if (!wrote)
|
||||||
{
|
{
|
||||||
vote.Choice = choice;
|
return;
|
||||||
vote.Weight = actor.EffectiveVotingWeight;
|
|
||||||
vote.Comment = comment?.Trim() ?? string.Empty;
|
|
||||||
vote.CastAtUtc = timeProvider.GetUtcNow();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
|
||||||
await auditTrailService.RecordAsync(
|
await auditTrailService.RecordAsync(
|
||||||
actorUser.Id,
|
actorUser.Id,
|
||||||
nameof(Motion),
|
nameof(Motion),
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ using System.Text;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using Bifrost.Web.Data;
|
using Bifrost.Web.Data;
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
using Bifrost.Web.Features.Shared;
|
using Bifrost.Web.Features.Shared;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
@ -99,21 +100,27 @@ public sealed class SealedBallotService(
|
||||||
throw new SealedBallotException(SealedBallotFailure.Invalid, "A commitment is 64 lowercase hex characters (SHA-256).");
|
throw new SealedBallotException(SealedBallotFailure.Invalid, "A commitment is 64 lowercase hex characters (SHA-256).");
|
||||||
}
|
}
|
||||||
|
|
||||||
var ballot = await dbContext.SealedBallots
|
var ballot = await AccountMergeLedger.WriteAsAsync(dbContext, user.Id, async standing =>
|
||||||
.SingleOrDefaultAsync(x => x.MotionId == motionId && x.UserAccountId == user.Id, cancellationToken);
|
|
||||||
if (ballot is null)
|
|
||||||
{
|
{
|
||||||
ballot = new SealedBallot { MotionId = motionId, UserAccountId = user.Id };
|
RequireStanding(standing);
|
||||||
dbContext.SealedBallots.Add(ballot);
|
var written = await dbContext.SealedBallots
|
||||||
}
|
.SingleOrDefaultAsync(x => x.MotionId == motionId && x.UserAccountId == user.Id, cancellationToken);
|
||||||
else
|
if (written is null)
|
||||||
{
|
{
|
||||||
ballot.Revision++;
|
written = new SealedBallot { MotionId = motionId, UserAccountId = user.Id };
|
||||||
}
|
dbContext.SealedBallots.Add(written);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
written.Revision++;
|
||||||
|
}
|
||||||
|
|
||||||
|
written.Commitment = commitment;
|
||||||
|
written.CommittedAtUtc = now;
|
||||||
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
return written;
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
ballot.Commitment = commitment;
|
|
||||||
ballot.CommittedAtUtc = now;
|
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
|
||||||
await auditTrailService.RecordAsync(
|
await auditTrailService.RecordAsync(
|
||||||
user.Id, nameof(Motion), motionId, "sealed.committed",
|
user.Id, nameof(Motion), motionId, "sealed.committed",
|
||||||
$"{actor.DisplayName} committed a sealed ballot (revision {ballot.Revision}), commitment {commitment}.",
|
$"{actor.DisplayName} committed a sealed ballot (revision {ballot.Revision}), commitment {commitment}.",
|
||||||
|
|
@ -159,36 +166,43 @@ public sealed class SealedBallotService(
|
||||||
|
|
||||||
// RevealSeq and Status are concurrency tokens. A conflict means either the close froze the set (refuse, truthfully) or
|
// RevealSeq and Status are concurrency tokens. A conflict means either the close froze the set (refuse, truthfully) or
|
||||||
// another voter's reveal landed first while the window is still open (re-read the row and write again).
|
// another voter's reveal landed first while the window is still open (re-read the row and write again).
|
||||||
for (var attempt = 0; ; attempt++)
|
// Standing is read once, under the gate's lock, which holds across every attempt: a merge cannot freeze the account between them.
|
||||||
|
await AccountMergeLedger.WriteAsAsync(dbContext, user.Id, async standing =>
|
||||||
{
|
{
|
||||||
ballot.RevealedCandidate = candidate;
|
RequireStanding(standing);
|
||||||
ballot.RevealedReason = reason;
|
for (var attempt = 0; ; attempt++)
|
||||||
ballot.Salt = document.Salt;
|
|
||||||
ballot.RevealedAtUtc = now;
|
|
||||||
motion.RevealSeq++;
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
ballot.RevealedCandidate = candidate;
|
||||||
break;
|
ballot.RevealedReason = reason;
|
||||||
}
|
ballot.Salt = document.Salt;
|
||||||
catch (DbUpdateConcurrencyException error)
|
ballot.RevealedAtUtc = now;
|
||||||
{
|
motion.RevealSeq++;
|
||||||
foreach (var entry in error.Entries)
|
try
|
||||||
{
|
{
|
||||||
await entry.ReloadAsync(cancellationToken);
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
catch (DbUpdateConcurrencyException error)
|
||||||
if (PhaseOf(motion, now) != SealedPhase.Reveal)
|
|
||||||
{
|
{
|
||||||
throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The motion closed; the reveal window is over.");
|
foreach (var entry in error.Entries)
|
||||||
}
|
{
|
||||||
|
await entry.ReloadAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
if (attempt >= 4)
|
if (PhaseOf(motion, now) != SealedPhase.Reveal)
|
||||||
{
|
{
|
||||||
throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The reveal is contended; send it again.");
|
throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The motion closed; the reveal window is over.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attempt >= 4)
|
||||||
|
{
|
||||||
|
throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The reveal is contended; send it again.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
return true;
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
await auditTrailService.RecordAsync(
|
await auditTrailService.RecordAsync(
|
||||||
user.Id, nameof(Motion), motionId, "sealed.revealed",
|
user.Id, nameof(Motion), motionId, "sealed.revealed",
|
||||||
|
|
@ -359,6 +373,15 @@ public sealed class SealedBallotService(
|
||||||
|
|
||||||
private static string NameOf(UserAccount user) => user.MemberProfile?.Nickname ?? user.DisplayName;
|
private static string NameOf(UserAccount user) => user.MemberProfile?.Nickname ?? user.DisplayName;
|
||||||
|
|
||||||
|
// A member resolved before a merge froze the account must not write a ballot after it: the write gate reads standing at the write.
|
||||||
|
private static void RequireStanding(MergeStanding? standing)
|
||||||
|
{
|
||||||
|
if (standing is not null)
|
||||||
|
{
|
||||||
|
throw new SealedBallotException(SealedBallotFailure.Forbidden, "An active member is required.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static UserAccount RequireMember(CurrentBifrostActor actor) =>
|
private static UserAccount RequireMember(CurrentBifrostActor actor) =>
|
||||||
actor is { IsActiveMember: true, UserAccount: { } user }
|
actor is { IsActiveMember: true, UserAccount: { } user }
|
||||||
? user
|
? user
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ namespace Bifrost.Web.Features.Oidc;
|
||||||
public static class OidcEndpoints
|
public static class OidcEndpoints
|
||||||
{
|
{
|
||||||
public const string SuspendedDescription = "The account is suspended.";
|
public const string SuspendedDescription = "The account is suspended.";
|
||||||
|
public const string MergedDescription = "The account is part of an account merge and can no longer sign in.";
|
||||||
public const string NoIdentityDescription = "The account has no Bifrost identity.";
|
public const string NoIdentityDescription = "The account has no Bifrost identity.";
|
||||||
public const string ReservedIdentityDescription = "The account's Bifrost identity is reserved.";
|
public const string ReservedIdentityDescription = "The account's Bifrost identity is reserved.";
|
||||||
public const string ConsentRequiredDescription = "Agreement to the training notice in force is needed to speak in a recorded room.";
|
public const string ConsentRequiredDescription = "Agreement to the training notice in force is needed to speak in a recorded room.";
|
||||||
|
|
@ -56,7 +57,7 @@ public static class OidcEndpoints
|
||||||
// every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync).
|
// every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync).
|
||||||
if (actor.UserAccount is null)
|
if (actor.UserAccount is null)
|
||||||
{
|
{
|
||||||
return Deny(Errors.AccessDenied, NoIdentityDescription);
|
return Deny(Errors.AccessDenied, actor.Merge is not null ? MergedDescription : NoIdentityDescription);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (actor.Membership?.Status == MembershipStatus.Suspended)
|
if (actor.Membership?.Status == MembershipStatus.Suspended)
|
||||||
|
|
@ -176,6 +177,12 @@ public static class OidcEndpoints
|
||||||
return SuspendedDescription;
|
return SuspendedDescription;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A folded or frozen subject's chat sessions end: token, userinfo and the logout reconciler all read this one refusal.
|
||||||
|
if (await AccountMergeLedger.StandingAsync(db, accountId, cancellationToken) is not null)
|
||||||
|
{
|
||||||
|
return MergedDescription;
|
||||||
|
}
|
||||||
|
|
||||||
return deskToken || await ConsentEndpoints.HasLiveReceiptAsync(db, accountId, cancellationToken) ? null : ConsentRequiredDescription;
|
return deskToken || await ConsentEndpoints.HasLiveReceiptAsync(db, accountId, cancellationToken) ? null : ConsentRequiredDescription;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -187,6 +194,12 @@ public static class OidcEndpoints
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A folded or frozen subject's live token acts as nobody on the desk too: the same standing the cookie gate and ChatRefusalAsync read.
|
||||||
|
if (await AccountMergeLedger.StandingAsync(db, accountId, cancellationToken) is not null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
var account = await db.UserAccounts.AsNoTracking()
|
var account = await db.UserAccounts.AsNoTracking()
|
||||||
.Include(x => x.Membership)
|
.Include(x => x.Membership)
|
||||||
.SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken);
|
.SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken);
|
||||||
|
|
|
||||||
139
src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs
Normal file
139
src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs
Normal file
|
|
@ -0,0 +1,139 @@
|
||||||
|
using Bifrost.Web.Features.Shared;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Passkeys;
|
||||||
|
|
||||||
|
public enum CeremonyKind
|
||||||
|
{
|
||||||
|
/// <summary>Permission to enrol one passkey, earned by a fresh Heimdall sign-in. Held by id in a cookie of the browser that signed in.</summary>
|
||||||
|
EnrolTicket,
|
||||||
|
/// <summary>The WebAuthn creation options in flight for an account.</summary>
|
||||||
|
EnrolChallenge,
|
||||||
|
/// <summary>The WebAuthn request options in flight for an account's unlink of one identity.</summary>
|
||||||
|
UnlinkChallenge,
|
||||||
|
/// <summary>The fact "this account's passkey assertion was verified for unlinking this identity". Carries no bearer and no credential.</summary>
|
||||||
|
UnlinkProof
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The short-lived single-use server-side state of the passkey flows, in this process only (like the Linked accounts list):
|
||||||
|
/// a restart empties it and every flow is simply begun again. Every entry is bound to an account and a kind, and the unlink
|
||||||
|
/// kinds to the identity they are for; <c>Take</c> removes the entry whether or not the caller then succeeds, so a
|
||||||
|
/// challenge, a ticket or an assertion fact can be spent once. A challenge kind has one live entry per account: a newer one
|
||||||
|
/// replaces the older. A full table refuses new entries rather than grow.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PasskeyCeremonies(TimeProvider clock)
|
||||||
|
{
|
||||||
|
public static readonly TimeSpan TicketLifetime = TimeSpan.FromMinutes(5);
|
||||||
|
public static readonly TimeSpan ChallengeLifetime = TimeSpan.FromMinutes(2);
|
||||||
|
public static readonly TimeSpan ProofLifetime = TimeSpan.FromMinutes(5);
|
||||||
|
public const int MaxLive = 2048;
|
||||||
|
|
||||||
|
public sealed record Entry(string Id, CeremonyKind Kind, string Account, string? Subject, string? Data, DateTimeOffset ExpiresAt);
|
||||||
|
|
||||||
|
private readonly Dictionary<string, Entry> _held = new(StringComparer.Ordinal);
|
||||||
|
private readonly object _gate = new();
|
||||||
|
|
||||||
|
/// <summary>Adds an entry and returns its id, or null when the table is full.</summary>
|
||||||
|
public string? Issue(CeremonyKind kind, string account, string? subject, string? data, TimeSpan lifetime)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
Purge();
|
||||||
|
if (kind != CeremonyKind.UnlinkProof)
|
||||||
|
{
|
||||||
|
foreach (var old in _held.Values.Where(x => x.Kind == kind && x.Account == account).ToList())
|
||||||
|
{
|
||||||
|
_held.Remove(old.Id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_held.Count >= MaxLive)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var id = Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32))
|
||||||
|
.Replace('+', '-').Replace('/', '_').TrimEnd('=');
|
||||||
|
_held[id] = new Entry(id, kind, account, subject, data, clock.GetUtcNow() + lifetime);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The live entry, without spending it. <paramref name="id"/> null finds the account's one current entry of that kind.</summary>
|
||||||
|
public Entry? Peek(CeremonyKind kind, string account, string? subject, string? id)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
Purge();
|
||||||
|
return Find(kind, account, subject, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The live entry, removed: it can be taken once.</summary>
|
||||||
|
public Entry? Take(CeremonyKind kind, string account, string? subject, string? id)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
Purge();
|
||||||
|
var entry = Find(kind, account, subject, id);
|
||||||
|
if (entry is not null)
|
||||||
|
{
|
||||||
|
_held.Remove(entry.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Discard(string? id)
|
||||||
|
{
|
||||||
|
if (id is not null)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_held.Remove(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Entry? Find(CeremonyKind kind, string account, string? subject, string? id)
|
||||||
|
{
|
||||||
|
var entry = id is null
|
||||||
|
? _held.Values.FirstOrDefault(x => x.Kind == kind && x.Account == account)
|
||||||
|
: _held.GetValueOrDefault(id);
|
||||||
|
return entry is not null && entry.Kind == kind
|
||||||
|
&& string.Equals(entry.Account, account, StringComparison.Ordinal)
|
||||||
|
&& string.Equals(entry.Subject, subject, StringComparison.Ordinal)
|
||||||
|
? entry
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Purge()
|
||||||
|
{
|
||||||
|
var now = clock.GetUtcNow();
|
||||||
|
foreach (var dead in _held.Values.Where(x => x.ExpiresAt <= now).ToList())
|
||||||
|
{
|
||||||
|
_held.Remove(dead.Id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The budgets on the passkey ceremonies, per Heimdall account, on the shared <see cref="FixedWindowBudget"/>. Two separate
|
||||||
|
/// ones: asking for options or starting an enrolment sign-in (anyone holding the session can do that), and verifying a
|
||||||
|
/// registration or an assertion, which is spent only after the caller holds what the verification needs (a live ticket, or one of
|
||||||
|
/// the account's own strong credentials and a live challenge). Junk from a session thief that names no credential of the account, or
|
||||||
|
/// arrives with no live challenge, spends nothing; junk naming one of the account's credentials spends one permit per challenge that
|
||||||
|
/// was asked for, because the first such post takes the challenge. A session holder can still exhaust both budgets by asking for
|
||||||
|
/// challenges over and over: a lockout the same session already has through revoking passkeys, not a bypass. Budgets are per process.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PasskeyRateLimit(TimeProvider clock)
|
||||||
|
{
|
||||||
|
public const int Permits = 20;
|
||||||
|
public static readonly TimeSpan Window = TimeSpan.FromMinutes(10);
|
||||||
|
|
||||||
|
private readonly FixedWindowBudget _options = new(Permits, Window, 10_000, clock);
|
||||||
|
private readonly FixedWindowBudget _verifications = new(Permits, Window, 10_000, clock);
|
||||||
|
|
||||||
|
public bool TryAcquire(string account, bool verification = false) => (verification ? _verifications : _options).Spend(account) is null;
|
||||||
|
}
|
||||||
54
src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs
Normal file
54
src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
using Bifrost.Web.Configuration;
|
||||||
|
using Fido2NetLib;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Passkeys;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The relying party every passkey ceremony runs as. RP ID and origin come from <see cref="BifrostHostOptions"/> and from
|
||||||
|
/// nothing the browser sends: the public base URL must be https and its host must be the expected host, otherwise passkeys
|
||||||
|
/// are unavailable (the page offers none and every ceremony endpoint refuses). A passkey is bound to the RP ID by the
|
||||||
|
/// authenticator, so a wrong or http origin would enrol keys that cannot be used or can be phished.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PasskeyRelyingParty
|
||||||
|
{
|
||||||
|
public const string Name = "Bifrost";
|
||||||
|
|
||||||
|
public PasskeyRelyingParty(IOptions<BifrostHostOptions> hostOptions, ILogger<PasskeyRelyingParty> logger)
|
||||||
|
{
|
||||||
|
var host = hostOptions.Value;
|
||||||
|
if (host.ExpectedHost.Contains(':') || System.Net.IPAddress.TryParse(host.ExpectedHost.Trim('[', ']'), out _))
|
||||||
|
{
|
||||||
|
logger.LogWarning("Passkeys are unavailable: Host:ExpectedHost must be a bare DNS host name, with no port and not an IP address (an IP address is not a valid RP ID).");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Uri.TryCreate(host.PublicBaseUrl, UriKind.Absolute, out var url)
|
||||||
|
|| url.Scheme != Uri.UriSchemeHttps
|
||||||
|
|| string.IsNullOrWhiteSpace(host.ExpectedHost)
|
||||||
|
|| !string.Equals(url.Host, host.ExpectedHost, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
logger.LogWarning("Passkeys are unavailable: Host:PublicBaseUrl must be https and its host must equal Host:ExpectedHost.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Origin = url.GetLeftPart(UriPartial.Authority);
|
||||||
|
RpId = url.Host.ToLowerInvariant();
|
||||||
|
Fido2 = new Fido2(new Fido2Configuration
|
||||||
|
{
|
||||||
|
RPID = RpId,
|
||||||
|
RPName = Name,
|
||||||
|
Origins = new HashSet<string>([Origin], StringComparer.Ordinal),
|
||||||
|
ChallengeSize = 32,
|
||||||
|
Timeout = 120_000
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsAvailable => Fido2 is not null;
|
||||||
|
|
||||||
|
public string? Origin { get; }
|
||||||
|
|
||||||
|
public string? RpId { get; }
|
||||||
|
|
||||||
|
public IFido2? Fido2 { get; }
|
||||||
|
}
|
||||||
470
src/Bifrost.Web/Features/Passkeys/PasskeyService.cs
Normal file
470
src/Bifrost.Web/Features/Passkeys/PasskeyService.cs
Normal file
|
|
@ -0,0 +1,470 @@
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Heimdall;
|
||||||
|
using Fido2NetLib;
|
||||||
|
using Fido2NetLib.Objects;
|
||||||
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Passkeys;
|
||||||
|
|
||||||
|
/// <summary>One passkey as the Linked accounts page shows it: a label, its cooling-off state, never a key.</summary>
|
||||||
|
public sealed record PasskeyView(Guid Id, string Label, DateTimeOffset CreatedUtc, DateTimeOffset StrongFromUtc, DateTimeOffset? LastUsedUtc, bool IsStrong);
|
||||||
|
|
||||||
|
/// <summary>The base64url fields a browser posts after navigator.credentials.get (an assertion) or .create (an enrolment).</summary>
|
||||||
|
public sealed record PasskeyFields(
|
||||||
|
string? Id, string? RawId, string? AuthenticatorData, string? ClientDataJson, string? Signature, string? UserHandle,
|
||||||
|
string? AttestationObject, string? Transports);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Passkeys for accounts that have a Heimdall account id (docs/passkeys.md). Enrolment needs a ticket earned by a fresh
|
||||||
|
/// Heimdall sign-in and starts a credential in a 48 hour cooling-off; an assertion for an unlink needs a credential that is
|
||||||
|
/// the session's own, not revoked and past its cooling-off, and records a single-use fact for that account and identity.
|
||||||
|
/// The WebAuthn parsing and verification (CBOR, COSE, signatures, origin, RP ID, challenge, user verification, sign count)
|
||||||
|
/// is Fido2NetLib's; this class decides who may begin, what is bound to what, and what is kept. Outcomes are the closed set
|
||||||
|
/// of <see cref="HeimdallLinkOutcome"/> the page words itself.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PasskeyService(
|
||||||
|
BifrostDbContext db,
|
||||||
|
PasskeyRelyingParty relyingParty,
|
||||||
|
PasskeyCeremonies ceremonies,
|
||||||
|
PasskeyRateLimit rateLimit,
|
||||||
|
TimeProvider clock,
|
||||||
|
ILogger<PasskeyService> logger)
|
||||||
|
{
|
||||||
|
public const int MaxActive = 5;
|
||||||
|
public const int MaxLabel = 40;
|
||||||
|
public static readonly TimeSpan CoolingOff = TimeSpan.FromHours(48);
|
||||||
|
|
||||||
|
private static readonly HashSet<string> TransportNames = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
"usb", "nfc", "ble", "internal", "hybrid", "smart-card"
|
||||||
|
};
|
||||||
|
|
||||||
|
public bool IsAvailable => relyingParty.IsAvailable;
|
||||||
|
|
||||||
|
private Task<UserAccount?> AccountAsync(string heimdallAccountId, CancellationToken ct) =>
|
||||||
|
string.IsNullOrEmpty(heimdallAccountId)
|
||||||
|
? Task.FromResult<UserAccount?>(null)
|
||||||
|
: db.UserAccounts.SingleOrDefaultAsync(x => x.HeimdallAccountId == heimdallAccountId, ct);
|
||||||
|
|
||||||
|
private IQueryable<PasskeyCredential> Active(Guid userId) =>
|
||||||
|
db.PasskeyCredentials.Where(x => x.UserAccountId == userId && x.RevokedUtc == null);
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<PasskeyView>> ListAsync(string heimdallAccountId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = clock.GetUtcNow();
|
||||||
|
var rows = await Active(user.Id).ToListAsync(ct);
|
||||||
|
return rows.OrderBy(x => x.CreatedUtc)
|
||||||
|
.Select(x => new PasskeyView(x.Id, x.Label, x.CreatedUtc, x.StrongFromUtc, x.LastUsedUtc, x.StrongFromUtc <= now))
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether a fresh enrolment ticket is held by this browser for this account.</summary>
|
||||||
|
public bool HasTicket(string heimdallAccountId, string? ticketId) =>
|
||||||
|
ticketId is not null && ceremonies.Peek(CeremonyKind.EnrolTicket, heimdallAccountId, null, ticketId) is not null;
|
||||||
|
|
||||||
|
/// <summary>Why a fresh sign-in for enrolment may not even start, or null when it may. Spends a ceremony permit.</summary>
|
||||||
|
public async Task<HeimdallLinkOutcome?> PreflightEnrolStartAsync(string heimdallAccountId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!relyingParty.IsAvailable)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.PasskeysUnavailable;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.Error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await Active(user.Id).CountAsync(ct) >= MaxActive)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.PasskeyLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
return rateLimit.TryAcquire(heimdallAccountId) ? null : HeimdallLinkOutcome.RateLimited;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The creation options for one enrolment, bound to the account; needs the ticket the fresh sign-in earned.</summary>
|
||||||
|
public async Task<(HeimdallLinkOutcome? Refusal, string? OptionsJson)> BeginEnrolAsync(string heimdallAccountId, string? ticketId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!relyingParty.IsAvailable)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.PasskeysUnavailable, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!HasTicket(heimdallAccountId, ticketId) || await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.EnrolNeedsSignIn, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!rateLimit.TryAcquire(heimdallAccountId))
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.RateLimited, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var existing = await Active(user.Id).Select(x => x.CredentialId).ToListAsync(ct);
|
||||||
|
if (existing.Count >= MaxActive)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.PasskeyLimit, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var options = relyingParty.Fido2!.RequestNewCredential(new RequestNewCredentialParams
|
||||||
|
{
|
||||||
|
User = new Fido2User { Id = user.Id.ToByteArray(), Name = Label(user.DisplayName, "Bifrost member"), DisplayName = Label(user.DisplayName, "Bifrost member") },
|
||||||
|
ExcludeCredentials = existing.Select(x => new PublicKeyCredentialDescriptor(x)).ToList(),
|
||||||
|
AuthenticatorSelection = new AuthenticatorSelection
|
||||||
|
{
|
||||||
|
ResidentKey = ResidentKeyRequirement.Preferred,
|
||||||
|
UserVerification = UserVerificationRequirement.Required
|
||||||
|
},
|
||||||
|
AttestationPreference = AttestationConveyancePreference.None
|
||||||
|
});
|
||||||
|
var json = options.ToJson();
|
||||||
|
return ceremonies.Issue(CeremonyKind.EnrolChallenge, heimdallAccountId, null, json, PasskeyCeremonies.ChallengeLifetime) is null
|
||||||
|
? (HeimdallLinkOutcome.Error, null)
|
||||||
|
: (null, json);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies a registration and stores the credential, cooling off for <see cref="CoolingOff"/>. The ticket and the
|
||||||
|
/// challenge are both spent here, whatever the outcome: a failed attempt needs a fresh sign-in and a new challenge.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<HeimdallLinkOutcome> EnrolAsync(
|
||||||
|
string heimdallAccountId, string? ticketId, PasskeyFields fields, string? label, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!relyingParty.IsAvailable)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.PasskeysUnavailable;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The caller's own preconditions first, spending nothing: someone with only the session has no ticket, so junk from them
|
||||||
|
// can neither burn the member's ticket and challenge nor spend the verification permits.
|
||||||
|
if (!HasTicket(heimdallAccountId, ticketId) || await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.EnrolNeedsSignIn;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await Active(user.Id).CountAsync(ct) >= MaxActive)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.PasskeyLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!TryDecode(fields.RawId, out var rawId) || !TryDecode(fields.AttestationObject, out var attestation)
|
||||||
|
|| !TryDecode(fields.ClientDataJson, out var clientData) || fields.Id is null)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.PasskeyFailed;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!rateLimit.TryAcquire(heimdallAccountId, verification: true))
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.RateLimited;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now both are spent, whatever the outcome.
|
||||||
|
var ticket = ceremonies.Take(CeremonyKind.EnrolTicket, heimdallAccountId, null, ticketId);
|
||||||
|
var challenge = ceremonies.Take(CeremonyKind.EnrolChallenge, heimdallAccountId, null, null);
|
||||||
|
if (ticket is null)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.EnrolNeedsSignIn;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (challenge?.Data is null)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.PasskeyExpired;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var registered = await relyingParty.Fido2!.MakeNewCredentialAsync(new MakeNewCredentialParams
|
||||||
|
{
|
||||||
|
AttestationResponse = new AuthenticatorAttestationRawResponse
|
||||||
|
{
|
||||||
|
Id = fields.Id,
|
||||||
|
RawId = rawId,
|
||||||
|
Type = PublicKeyCredentialType.PublicKey,
|
||||||
|
ClientExtensionResults = new AuthenticationExtensionsClientOutputs(),
|
||||||
|
Response = new AuthenticatorAttestationRawResponse.AttestationResponse
|
||||||
|
{
|
||||||
|
AttestationObject = attestation,
|
||||||
|
ClientDataJson = clientData,
|
||||||
|
Transports = Transports(fields.Transports)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
OriginalOptions = CredentialCreateOptions.FromJson(challenge.Data),
|
||||||
|
IsCredentialIdUniqueToUserCallback = async (parameters, token) =>
|
||||||
|
!await db.PasskeyCredentials.AnyAsync(x => x.CredentialId == parameters.CredentialId, token)
|
||||||
|
}, ct);
|
||||||
|
|
||||||
|
var now = clock.GetUtcNow();
|
||||||
|
db.PasskeyCredentials.Add(new PasskeyCredential
|
||||||
|
{
|
||||||
|
UserAccountId = user.Id,
|
||||||
|
CredentialId = registered.Id,
|
||||||
|
PublicKey = registered.PublicKey,
|
||||||
|
SignCount = registered.SignCount,
|
||||||
|
Transports = string.Join(',', Transports(fields.Transports).Select(x => TransportName(x))),
|
||||||
|
AaGuid = registered.AaGuid == Guid.Empty ? null : registered.AaGuid,
|
||||||
|
Label = Label(label, "Passkey"),
|
||||||
|
CreatedUtc = now,
|
||||||
|
StrongFromUtc = now + CoolingOff
|
||||||
|
});
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
return HeimdallLinkOutcome.PasskeyAdded;
|
||||||
|
}
|
||||||
|
catch (Exception error) when (error is Fido2VerificationException or DbUpdateException or FormatException or System.Text.Json.JsonException)
|
||||||
|
{
|
||||||
|
logger.LogWarning("Passkey enrolment refused: {Reason}", error is Fido2VerificationException f ? f.Code.ToString() : error.GetType().Name);
|
||||||
|
return HeimdallLinkOutcome.PasskeyFailed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Revokes one of the session's own passkeys. Needs no strong proof; the page shows the revocation.</summary>
|
||||||
|
public async Task<HeimdallLinkOutcome> RevokeAsync(string heimdallAccountId, Guid credentialId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.Error;
|
||||||
|
}
|
||||||
|
|
||||||
|
var credential = await Active(user.Id).SingleOrDefaultAsync(x => x.Id == credentialId, ct);
|
||||||
|
if (credential is null)
|
||||||
|
{
|
||||||
|
return HeimdallLinkOutcome.PasskeyFailed;
|
||||||
|
}
|
||||||
|
|
||||||
|
credential.RevokedUtc = clock.GetUtcNow();
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
return HeimdallLinkOutcome.PasskeyRevoked;
|
||||||
|
}
|
||||||
|
|
||||||
|
private IQueryable<PasskeyCredential> Strong(Guid userId)
|
||||||
|
{
|
||||||
|
var now = clock.GetUtcNow();
|
||||||
|
return Active(userId).Where(x => x.StrongFromUtc <= now);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> HasStrongAsync(string heimdallAccountId, CancellationToken ct) =>
|
||||||
|
await AccountAsync(heimdallAccountId, ct) is { } user && await Strong(user.Id).AnyAsync(ct);
|
||||||
|
|
||||||
|
/// <summary>When the first cooling-off credential becomes strong, or null when none is cooling.</summary>
|
||||||
|
public async Task<DateTimeOffset?> NextStrongAtAsync(string heimdallAccountId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = clock.GetUtcNow();
|
||||||
|
var cooling = await Active(user.Id).Where(x => x.StrongFromUtc > now).Select(x => x.StrongFromUtc).ToListAsync(ct);
|
||||||
|
return cooling.Count == 0 ? null : cooling.Min();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The request options for unlinking one identity: only the account's strong passkeys may answer, with user verification.</summary>
|
||||||
|
public async Task<(HeimdallLinkOutcome? Refusal, string? OptionsJson)> BeginAssertionAsync(string heimdallAccountId, string identityId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!relyingParty.IsAvailable)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.PasskeysUnavailable, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!rateLimit.TryAcquire(heimdallAccountId))
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.RateLimited, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.Error, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var strong = await Strong(user.Id).ToListAsync(ct);
|
||||||
|
if (strong.Count == 0)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.PasskeyRequired, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var options = relyingParty.Fido2!.GetAssertionOptions(new GetAssertionOptionsParams
|
||||||
|
{
|
||||||
|
AllowedCredentials = strong.Select(x => new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PublicKey, x.CredentialId, Transports(x.Transports))).ToList(),
|
||||||
|
UserVerification = UserVerificationRequirement.Required
|
||||||
|
});
|
||||||
|
var json = options.ToJson();
|
||||||
|
return ceremonies.Issue(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, json, PasskeyCeremonies.ChallengeLifetime) is null
|
||||||
|
? (HeimdallLinkOutcome.Error, null)
|
||||||
|
: (null, json);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies an assertion made for unlinking <paramref name="identityId"/>. The challenge is spent first. On success the
|
||||||
|
/// credential's sign count and last use are recorded and a single-use fact for this account and identity is issued; its id
|
||||||
|
/// (not a credential, not a bearer) is what the fresh Heimdall sign-in's attempt carries.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<(HeimdallLinkOutcome? Refusal, string? FactId)> VerifyAssertionAsync(
|
||||||
|
string heimdallAccountId, string identityId, PasskeyFields fields, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!relyingParty.IsAvailable)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.PasskeysUnavailable, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The caller's own preconditions first, spending nothing: a decodable assertion naming one of this account's strong,
|
||||||
|
// un-revoked credentials. Junk from someone holding only the session fails here and burns neither the member's challenge
|
||||||
|
// nor the verification permits.
|
||||||
|
if (await AccountAsync(heimdallAccountId, ct) is not { } user
|
||||||
|
|| !TryDecode(fields.RawId, out var rawId) || !TryDecode(fields.AuthenticatorData, out var authenticatorData)
|
||||||
|
|| !TryDecode(fields.ClientDataJson, out var clientData) || !TryDecode(fields.Signature, out var signature)
|
||||||
|
|| fields.Id is null)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.PasskeyFailed, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[]? userHandle = null;
|
||||||
|
if (!string.IsNullOrEmpty(fields.UserHandle) && !TryDecode(fields.UserHandle, out userHandle))
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.PasskeyFailed, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The credential must be this session's own, not revoked and past its cooling-off. Anything else is not a strong proof.
|
||||||
|
var credential = await Strong(user.Id).SingleOrDefaultAsync(x => x.CredentialId == rawId, ct);
|
||||||
|
if (credential is null)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.PasskeyFailed, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without a live challenge for this account and identity nothing can verify, so no permit is spent either: junk naming the
|
||||||
|
// account's own credential spends at most one permit per challenge that was asked for (the first junk then takes it).
|
||||||
|
if (ceremonies.Peek(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, null) is null)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.PasskeyExpired, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!rateLimit.TryAcquire(heimdallAccountId, verification: true))
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.RateLimited, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Spent from here on, whatever the outcome.
|
||||||
|
var challenge = ceremonies.Take(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, null);
|
||||||
|
if (challenge?.Data is null)
|
||||||
|
{
|
||||||
|
return (HeimdallLinkOutcome.PasskeyExpired, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await relyingParty.Fido2!.MakeAssertionAsync(new MakeAssertionParams
|
||||||
|
{
|
||||||
|
AssertionResponse = new AuthenticatorAssertionRawResponse
|
||||||
|
{
|
||||||
|
Id = fields.Id,
|
||||||
|
RawId = rawId,
|
||||||
|
Type = PublicKeyCredentialType.PublicKey,
|
||||||
|
ClientExtensionResults = new AuthenticationExtensionsClientOutputs(),
|
||||||
|
Response = new AuthenticatorAssertionRawResponse.AssertionResponse
|
||||||
|
{
|
||||||
|
AuthenticatorData = authenticatorData,
|
||||||
|
ClientDataJson = clientData,
|
||||||
|
Signature = signature,
|
||||||
|
UserHandle = userHandle
|
||||||
|
}
|
||||||
|
},
|
||||||
|
OriginalOptions = AssertionOptions.FromJson(challenge.Data),
|
||||||
|
StoredPublicKey = credential.PublicKey,
|
||||||
|
StoredSignatureCounter = (uint)credential.SignCount,
|
||||||
|
IsUserHandleOwnerOfCredentialIdCallback = (parameters, _) =>
|
||||||
|
Task.FromResult(parameters.UserHandle.AsSpan().SequenceEqual(user.Id.ToByteArray()) && parameters.CredentialId.AsSpan().SequenceEqual(credential.CredentialId))
|
||||||
|
}, ct);
|
||||||
|
|
||||||
|
credential.SignCount = result.SignCount;
|
||||||
|
credential.LastUsedUtc = clock.GetUtcNow();
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
}
|
||||||
|
catch (Exception error) when (error is Fido2VerificationException or FormatException or System.Text.Json.JsonException)
|
||||||
|
{
|
||||||
|
logger.LogWarning("Passkey assertion refused: {Reason}", error is Fido2VerificationException f ? f.Code.ToString() : error.GetType().Name);
|
||||||
|
return (HeimdallLinkOutcome.PasskeyFailed, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var fact = ceremonies.Issue(CeremonyKind.UnlinkProof, heimdallAccountId, identityId, credential.Id.ToString(), PasskeyCeremonies.ProofLifetime);
|
||||||
|
return fact is null ? (HeimdallLinkOutcome.Error, null) : (null, fact);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void DiscardFact(string? factId) => ceremonies.Discard(factId);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the credential an assertion fact was made with is still this account's own, un-revoked and strong. Asked in the
|
||||||
|
/// completion, before Heimdall is: a passkey revoked between the assertion and the completion no longer proves anything.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> StillStrongAsync(string heimdallAccountId, string? credentialId, CancellationToken ct) =>
|
||||||
|
Guid.TryParse(credentialId, out var id) && await AccountAsync(heimdallAccountId, ct) is { } user
|
||||||
|
&& await Strong(user.Id).AnyAsync(x => x.Id == id, ct);
|
||||||
|
|
||||||
|
/// <summary>A label from a form field: trimmed, control characters dropped, bounded; the fallback when nothing is left.</summary>
|
||||||
|
private static string Label(string? value, string fallback)
|
||||||
|
{
|
||||||
|
// By rune and by text element, never by UTF-16 unit: a cut inside a surrogate pair is not valid text and Postgres refuses it.
|
||||||
|
// Control and format characters (bidi overrides, joiners, zero-width marks) are dropped; a lone surrogate becomes U+FFFD.
|
||||||
|
var runes = (value ?? string.Empty).EnumerateRunes()
|
||||||
|
.Where(r => Rune.GetUnicodeCategory(r) is not (UnicodeCategory.Control or UnicodeCategory.Format))
|
||||||
|
.Take(MaxLabel * 4);
|
||||||
|
var cleaned = string.Concat(runes.Select(r => r.ToString())).Trim();
|
||||||
|
var elements = new StringInfo(cleaned);
|
||||||
|
if (elements.LengthInTextElements > MaxLabel)
|
||||||
|
{
|
||||||
|
cleaned = elements.SubstringByTextElements(0, MaxLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
return cleaned.Length == 0 ? fallback : cleaned;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryDecode(string? value, out byte[] bytes)
|
||||||
|
{
|
||||||
|
bytes = [];
|
||||||
|
if (string.IsNullOrEmpty(value) || value.Length > 16_384)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
bytes = WebEncoders.Base64UrlDecode(value);
|
||||||
|
return bytes.Length > 0;
|
||||||
|
}
|
||||||
|
catch (FormatException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AuthenticatorTransport[] Transports(string? csv)
|
||||||
|
{
|
||||||
|
var parsed = new List<AuthenticatorTransport>();
|
||||||
|
foreach (var name in (csv ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Distinct())
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Only names of the closed set reach the converter; one it does not know is dropped.
|
||||||
|
if (TransportNames.Contains(name))
|
||||||
|
{
|
||||||
|
parsed.Add(System.Text.Json.JsonSerializer.Deserialize<AuthenticatorTransport>($"\"{name}\""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (System.Text.Json.JsonException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsed.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string TransportName(AuthenticatorTransport transport) =>
|
||||||
|
System.Text.Json.JsonSerializer.Serialize(transport).Trim('"');
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
using Bifrost.Web.Data;
|
using Bifrost.Web.Data;
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
using Bifrost.Web.Features.Shared;
|
using Bifrost.Web.Features.Shared;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
|
@ -10,6 +11,13 @@ public sealed class PatronageService(
|
||||||
AuditTrailService auditTrailService,
|
AuditTrailService auditTrailService,
|
||||||
TimeProvider timeProvider)
|
TimeProvider timeProvider)
|
||||||
{
|
{
|
||||||
|
private const string CurrentPatronIndex = "UX_TierSnapshots_MembershipId_CurrentPatron";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records a patron event for an account, through the merge ledger's write gate: an event for a folded account lands on its survivor
|
||||||
|
/// and is journalled in the same save (an undo moves it back); an event for a frozen account lands on it, where the commit's
|
||||||
|
/// reduction finds it. A provider retry returns the stored event and, if it sits on a folded account's survivor, journals it once.
|
||||||
|
/// </summary>
|
||||||
public async Task<PatronSupportEvent> RecordSupportEventAsync(
|
public async Task<PatronSupportEvent> RecordSupportEventAsync(
|
||||||
Guid? actorUserAccountId,
|
Guid? actorUserAccountId,
|
||||||
Guid userAccountId,
|
Guid userAccountId,
|
||||||
|
|
@ -27,105 +35,128 @@ public sealed class PatronageService(
|
||||||
CancellationToken cancellationToken,
|
CancellationToken cancellationToken,
|
||||||
Guid? projectId = null)
|
Guid? projectId = null)
|
||||||
{
|
{
|
||||||
var user = await dbContext.UserAccounts
|
|
||||||
.Include(x => x.Membership)
|
|
||||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
|
||||||
|
|
||||||
if (user.Membership is null || user.Membership.Status == MembershipStatus.Suspended)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("Patron support can only be recorded for an unsuspended Bifrost account.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (amount <= 0 && kind != PatronSupportEventKind.SupportAdjustment)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("Patron support amount must be greater than zero.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (amount == 0)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("Patron support amount must not be zero.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (kind == PatronSupportEventKind.SupportAdjustment && amount > 0)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("Patron support adjustments must reduce support.");
|
|
||||||
}
|
|
||||||
|
|
||||||
var normalizedProviderEventId = providerEventId.Trim();
|
var normalizedProviderEventId = providerEventId.Trim();
|
||||||
if (provider != ExternalPatronProvider.Manual && string.IsNullOrWhiteSpace(normalizedProviderEventId))
|
var (supportEvent, recordedOn, isNew, recordedFor) = await AccountMergeLedger.WriteAsAsync(dbContext, userAccountId, async standing =>
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("External patron provider events require a provider event id.");
|
var folded = standing as MergeStanding.Folded;
|
||||||
}
|
var recordOnId = folded?.SurvivorId ?? userAccountId;
|
||||||
|
var now = timeProvider.GetUtcNow();
|
||||||
|
|
||||||
var existingProviderEvent = string.IsNullOrWhiteSpace(normalizedProviderEventId)
|
var existingProviderEvent = string.IsNullOrWhiteSpace(normalizedProviderEventId)
|
||||||
? null
|
? null
|
||||||
: await dbContext.PatronSupportEvents
|
: await dbContext.PatronSupportEvents
|
||||||
.SingleOrDefaultAsync(x => x.Provider == provider && x.ProviderEventId == normalizedProviderEventId, cancellationToken);
|
.SingleOrDefaultAsync(x => x.Provider == provider && x.ProviderEventId == normalizedProviderEventId, cancellationToken);
|
||||||
|
|
||||||
if (existingProviderEvent is not null)
|
if (existingProviderEvent is not null)
|
||||||
{
|
|
||||||
return existingProviderEvent;
|
|
||||||
}
|
|
||||||
|
|
||||||
var now = timeProvider.GetUtcNow();
|
|
||||||
var normalizedCurrency = string.IsNullOrWhiteSpace(currencyCode)
|
|
||||||
? "USD"
|
|
||||||
: currencyCode.Trim().ToUpperInvariant();
|
|
||||||
|
|
||||||
if (kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport)
|
|
||||||
{
|
|
||||||
var existingCurrentEvents = await dbContext.PatronSupportEvents
|
|
||||||
.Where(x => x.UserAccountId == userAccountId &&
|
|
||||||
x.Kind == PatronSupportEventKind.RecurringSupportSnapshot &&
|
|
||||||
x.IsCurrentRecurringSupport)
|
|
||||||
.ToListAsync(cancellationToken);
|
|
||||||
|
|
||||||
foreach (var existing in existingCurrentEvents)
|
|
||||||
{
|
{
|
||||||
existing.IsCurrentRecurringSupport = false;
|
if (folded is not null && existingProviderEvent.UserAccountId == folded.SurvivorId)
|
||||||
|
{
|
||||||
|
await AccountMergeLedger.StageIntakeJournalAsync(dbContext, folded.MergeId, userAccountId, existingProviderEvent.Id, now, cancellationToken);
|
||||||
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (existingProviderEvent, recordOnId, false, string.Empty);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.UserAccounts
|
||||||
|
.Include(x => x.Membership)
|
||||||
|
.SingleAsync(x => x.Id == recordOnId, cancellationToken);
|
||||||
|
|
||||||
|
if (user.Membership is null || user.Membership.Status == MembershipStatus.Suspended)
|
||||||
|
{
|
||||||
|
throw new PatronSupportRefusedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (amount <= 0 && kind != PatronSupportEventKind.SupportAdjustment)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Patron support amount must be greater than zero.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (amount == 0)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Patron support amount must not be zero.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kind == PatronSupportEventKind.SupportAdjustment && amount > 0)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Patron support adjustments must reduce support.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (provider != ExternalPatronProvider.Manual && string.IsNullOrWhiteSpace(normalizedProviderEventId))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("External patron provider events require a provider event id.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var normalizedCurrency = string.IsNullOrWhiteSpace(currencyCode)
|
||||||
|
? "USD"
|
||||||
|
: currencyCode.Trim().ToUpperInvariant();
|
||||||
|
|
||||||
|
if (kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport)
|
||||||
|
{
|
||||||
|
var existingCurrentEvents = await dbContext.PatronSupportEvents
|
||||||
|
.Where(x => x.UserAccountId == recordOnId &&
|
||||||
|
x.Kind == PatronSupportEventKind.RecurringSupportSnapshot &&
|
||||||
|
x.IsCurrentRecurringSupport)
|
||||||
|
.ToListAsync(cancellationToken);
|
||||||
|
|
||||||
|
foreach (var existing in existingCurrentEvents)
|
||||||
|
{
|
||||||
|
existing.IsCurrentRecurringSupport = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var created = new PatronSupportEvent
|
||||||
|
{
|
||||||
|
UserAccountId = recordOnId,
|
||||||
|
ProjectId = projectId,
|
||||||
|
Kind = kind,
|
||||||
|
ExternalSupportId = externalSupportId.Trim(),
|
||||||
|
Provider = provider,
|
||||||
|
ProviderEventId = normalizedProviderEventId,
|
||||||
|
ProviderPayerId = providerPayerId.Trim(),
|
||||||
|
ProviderSubscriptionId = providerSubscriptionId.Trim(),
|
||||||
|
Amount = amount,
|
||||||
|
CurrencyCode = normalizedCurrency,
|
||||||
|
IsCurrentRecurringSupport = kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport,
|
||||||
|
SupportedAtUtc = supportedAtUtc.ToUniversalTime(),
|
||||||
|
RecordedAtUtc = now,
|
||||||
|
Notes = notes.Trim()
|
||||||
|
};
|
||||||
|
|
||||||
|
dbContext.PatronSupportEvents.Add(created);
|
||||||
|
dbContext.PointTransactions.Add(new PointTransaction
|
||||||
|
{
|
||||||
|
UserAccountId = recordOnId,
|
||||||
|
ProjectId = projectId,
|
||||||
|
Type = PointTransactionType.PatronSupport,
|
||||||
|
Amount = amount,
|
||||||
|
IsDecaying = kind == PatronSupportEventKind.OneTimeDonation,
|
||||||
|
CreatedAtUtc = now,
|
||||||
|
Note = $"Recorded {provider} {kind} patron support event {created.ExternalSupportId}."
|
||||||
|
});
|
||||||
|
|
||||||
|
if (folded is not null)
|
||||||
|
{
|
||||||
|
await AccountMergeLedger.StageIntakeJournalAsync(dbContext, folded.MergeId, userAccountId, created.Id, now, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
return (created, recordOnId, true, user.DisplayName);
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
|
if (isNew)
|
||||||
|
{
|
||||||
|
await auditTrailService.RecordAsync(
|
||||||
|
actorUserAccountId,
|
||||||
|
nameof(PatronSupportEvent),
|
||||||
|
supportEvent.Id,
|
||||||
|
"patron-support.recorded",
|
||||||
|
$"Recorded {amount:0.##} {supportEvent.CurrencyCode} {provider} {kind} patron support for {recordedFor}.",
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
await RefreshPatronTierSnapshotAsync(actorUserAccountId, recordedOn, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
var supportEvent = new PatronSupportEvent
|
|
||||||
{
|
|
||||||
UserAccountId = userAccountId,
|
|
||||||
ProjectId = projectId,
|
|
||||||
Kind = kind,
|
|
||||||
ExternalSupportId = externalSupportId.Trim(),
|
|
||||||
Provider = provider,
|
|
||||||
ProviderEventId = normalizedProviderEventId,
|
|
||||||
ProviderPayerId = providerPayerId.Trim(),
|
|
||||||
ProviderSubscriptionId = providerSubscriptionId.Trim(),
|
|
||||||
Amount = amount,
|
|
||||||
CurrencyCode = normalizedCurrency,
|
|
||||||
IsCurrentRecurringSupport = kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport,
|
|
||||||
SupportedAtUtc = supportedAtUtc.ToUniversalTime(),
|
|
||||||
RecordedAtUtc = now,
|
|
||||||
Notes = notes.Trim()
|
|
||||||
};
|
|
||||||
|
|
||||||
dbContext.PatronSupportEvents.Add(supportEvent);
|
|
||||||
dbContext.PointTransactions.Add(new PointTransaction
|
|
||||||
{
|
|
||||||
UserAccountId = userAccountId,
|
|
||||||
ProjectId = projectId,
|
|
||||||
Type = PointTransactionType.PatronSupport,
|
|
||||||
Amount = amount,
|
|
||||||
IsDecaying = kind == PatronSupportEventKind.OneTimeDonation,
|
|
||||||
CreatedAtUtc = now,
|
|
||||||
Note = $"Recorded {provider} {kind} patron support event {supportEvent.ExternalSupportId}."
|
|
||||||
});
|
|
||||||
|
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
|
||||||
await auditTrailService.RecordAsync(
|
|
||||||
actorUserAccountId,
|
|
||||||
nameof(PatronSupportEvent),
|
|
||||||
supportEvent.Id,
|
|
||||||
"patron-support.recorded",
|
|
||||||
$"Recorded {amount:0.##} {normalizedCurrency} {provider} {kind} patron support for {user.DisplayName}.",
|
|
||||||
cancellationToken);
|
|
||||||
|
|
||||||
await RefreshPatronTierSnapshotAsync(actorUserAccountId, userAccountId, cancellationToken);
|
|
||||||
return supportEvent;
|
return supportEvent;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -134,24 +165,67 @@ public sealed class PatronageService(
|
||||||
Guid userAccountId,
|
Guid userAccountId,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
dbContext.ChangeTracker.Clear();
|
// One current Patron snapshot per membership is a database invariant (UX_TierSnapshots_MembershipId_CurrentPatron). A restage that
|
||||||
|
// lost a race to another restage of the same membership reads the winner's snapshot and derives again from the events it now sees.
|
||||||
var user = await dbContext.UserAccounts
|
UserAccount user;
|
||||||
.Include(x => x.Membership)
|
PatronPointSummary summary;
|
||||||
.Include(x => x.PatronSupportEvents)
|
PatronTierDefinition? tier;
|
||||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
for (var attempt = 0; ; attempt++)
|
||||||
|
|
||||||
if (user.Membership is null)
|
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
|
dbContext.ChangeTracker.Clear();
|
||||||
|
|
||||||
|
user = await dbContext.UserAccounts
|
||||||
|
.Include(x => x.Membership)
|
||||||
|
.Include(x => x.PatronSupportEvents)
|
||||||
|
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
||||||
|
|
||||||
|
if (user.Membership is null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
|
||||||
|
}
|
||||||
|
|
||||||
|
(summary, tier) = await StageTierSnapshotAsync(user.Membership, user.PatronSupportEvents, timeProvider.GetUtcNow(), cancellationToken);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (DbUpdateException error) when (attempt < 3 &&
|
||||||
|
error.InnerException is Npgsql.PostgresException { SqlState: Npgsql.PostgresErrorCodes.UniqueViolation, ConstraintName: CurrentPatronIndex })
|
||||||
|
{
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var summary = CalculatePatronPoints(user.PatronSupportEvents, timeProvider.GetUtcNow());
|
await auditTrailService.RecordAsync(
|
||||||
|
actorUserAccountId,
|
||||||
|
nameof(TierSnapshot),
|
||||||
|
user.Membership.Id,
|
||||||
|
"patron-tier.derived",
|
||||||
|
tier is null
|
||||||
|
? $"Cleared patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points."
|
||||||
|
: $"Derived {tier.Label} patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points.",
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
return summary with { TierLabel = tier?.Label ?? string.Empty, VotingWeight = tier?.VotingWeight ?? 0m };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Derives the membership's patron tier from the events once and stages it on the tracker: demotes the current Patron snapshots
|
||||||
|
/// and adds the new one. It never saves and never clears the tracker, so a caller can stage it inside a larger single save
|
||||||
|
/// (the account merge ledger does).
|
||||||
|
/// </summary>
|
||||||
|
public async Task<(PatronPointSummary Summary, PatronTierDefinition? Tier)> StageTierSnapshotAsync(
|
||||||
|
Bifrost.Web.Domain.Membership membership,
|
||||||
|
IEnumerable<PatronSupportEvent> events,
|
||||||
|
DateTimeOffset now,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var summary = CalculatePatronPoints(events, now);
|
||||||
var tier = PatronTierPolicy.ResolveTier(summary.EffectivePoints);
|
var tier = PatronTierPolicy.ResolveTier(summary.EffectivePoints);
|
||||||
var now = timeProvider.GetUtcNow();
|
|
||||||
|
|
||||||
var currentPatronSnapshots = await dbContext.TierSnapshots
|
var currentPatronSnapshots = await dbContext.TierSnapshots
|
||||||
.Where(x => x.MembershipId == user.Membership.Id &&
|
.Where(x => x.MembershipId == membership.Id &&
|
||||||
x.Kind == TierSnapshotKind.Patron &&
|
x.Kind == TierSnapshotKind.Patron &&
|
||||||
x.IsCurrent)
|
x.IsCurrent)
|
||||||
.ToListAsync(cancellationToken);
|
.ToListAsync(cancellationToken);
|
||||||
|
|
@ -165,7 +239,7 @@ public sealed class PatronageService(
|
||||||
{
|
{
|
||||||
dbContext.TierSnapshots.Add(new TierSnapshot
|
dbContext.TierSnapshots.Add(new TierSnapshot
|
||||||
{
|
{
|
||||||
MembershipId = user.Membership.Id,
|
MembershipId = membership.Id,
|
||||||
Kind = TierSnapshotKind.Patron,
|
Kind = TierSnapshotKind.Patron,
|
||||||
Label = PatronTierPolicy.SnapshotLabel(tier),
|
Label = PatronTierPolicy.SnapshotLabel(tier),
|
||||||
Weight = tier.VotingWeight,
|
Weight = tier.VotingWeight,
|
||||||
|
|
@ -176,18 +250,7 @@ public sealed class PatronageService(
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
return (summary, tier);
|
||||||
await auditTrailService.RecordAsync(
|
|
||||||
actorUserAccountId,
|
|
||||||
nameof(TierSnapshot),
|
|
||||||
user.Membership.Id,
|
|
||||||
"patron-tier.derived",
|
|
||||||
tier is null
|
|
||||||
? $"Cleared patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points."
|
|
||||||
: $"Derived {tier.Label} patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points.",
|
|
||||||
cancellationToken);
|
|
||||||
|
|
||||||
return summary with { TierLabel = tier?.Label ?? string.Empty, VotingWeight = tier?.VotingWeight ?? 0m };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static PatronPointSummary CalculatePatronPoints(
|
public static PatronPointSummary CalculatePatronPoints(
|
||||||
|
|
@ -215,6 +278,9 @@ public sealed class PatronageService(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The account patron support would record on has no membership or is suspended.</summary>
|
||||||
|
public sealed class PatronSupportRefusedException() : InvalidOperationException("Patron support can only be recorded for an unsuspended Bifrost account.");
|
||||||
|
|
||||||
public sealed record PatronPointSummary(
|
public sealed record PatronPointSummary(
|
||||||
decimal RecurringPoints,
|
decimal RecurringPoints,
|
||||||
decimal HistoricalPoints,
|
decimal HistoricalPoints,
|
||||||
|
|
|
||||||
|
|
@ -66,7 +66,7 @@ public sealed class StripeWebhookService(
|
||||||
|
|
||||||
var patronageAccount = await ResolvePatronageAccountAsync(session, stripeOptions, cancellationToken);
|
var patronageAccount = await ResolvePatronageAccountAsync(session, stripeOptions, cancellationToken);
|
||||||
|
|
||||||
if (patronageAccount?.Membership is null || patronageAccount.Membership.Status == MembershipStatus.Suspended)
|
if (patronageAccount is null)
|
||||||
{
|
{
|
||||||
return StripeWebhookResult.NotConfigured(
|
return StripeWebhookResult.NotConfigured(
|
||||||
"Stripe checkout session is not linked to an unsuspended Bifrost patron account.");
|
"Stripe checkout session is not linked to an unsuspended Bifrost patron account.");
|
||||||
|
|
@ -83,22 +83,32 @@ public sealed class StripeWebhookService(
|
||||||
? "USD"
|
? "USD"
|
||||||
: session.Currency.ToUpperInvariant();
|
: session.Currency.ToUpperInvariant();
|
||||||
|
|
||||||
await patronageService.RecordSupportEventAsync(
|
// A checkout opened by an account that has since folded pays the survivor: the write gate behind RecordSupportEventAsync routes it.
|
||||||
actorUserAccountId: null,
|
PatronSupportEvent supportEvent;
|
||||||
patronageAccount.Id,
|
try
|
||||||
PatronSupportEventKind.OneTimeDonation,
|
{
|
||||||
amount,
|
supportEvent = await patronageService.RecordSupportEventAsync(
|
||||||
currencyCode,
|
actorUserAccountId: null,
|
||||||
session.Id,
|
patronageAccount.Id,
|
||||||
ExternalPatronProvider.Stripe,
|
PatronSupportEventKind.OneTimeDonation,
|
||||||
stripeEvent.Id,
|
amount,
|
||||||
session.Customer,
|
currencyCode,
|
||||||
string.Empty,
|
session.Id,
|
||||||
DateTimeOffset.FromUnixTimeSeconds(stripeEvent.Created),
|
ExternalPatronProvider.Stripe,
|
||||||
isCurrentRecurringSupport: false,
|
stripeEvent.Id,
|
||||||
BuildNotes(session),
|
session.Customer,
|
||||||
cancellationToken,
|
string.Empty,
|
||||||
projectId.ProjectId);
|
DateTimeOffset.FromUnixTimeSeconds(stripeEvent.Created),
|
||||||
|
isCurrentRecurringSupport: false,
|
||||||
|
BuildNotes(session),
|
||||||
|
cancellationToken,
|
||||||
|
projectId.ProjectId);
|
||||||
|
}
|
||||||
|
catch (PatronSupportRefusedException)
|
||||||
|
{
|
||||||
|
return StripeWebhookResult.NotConfigured(
|
||||||
|
"Stripe checkout session is not linked to an unsuspended Bifrost patron account.");
|
||||||
|
}
|
||||||
|
|
||||||
return StripeWebhookResult.Processed("Stripe patronage support event recorded.");
|
return StripeWebhookResult.Processed("Stripe patronage support event recorded.");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -55,12 +55,18 @@ public sealed class ApplicationBootstrapper(
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The one bootstrap-admin promotion, used at startup and at sign-in. A Suspended account is left exactly as it is (an admin's
|
/// The one bootstrap-admin promotion, used at startup and at sign-in. A Merged or Suspended account is left exactly as it is (an admin's
|
||||||
/// decision; only the suspension service lifts it) and the refusal is logged by account id. Returns whether it promoted.
|
/// decision; only the suspension service lifts it) and the refusal is logged by account id. Returns whether it promoted.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static bool TryPromoteBootstrapAdmin(UserAccount account, DateTimeOffset now, ILogger logger)
|
public static bool TryPromoteBootstrapAdmin(UserAccount account, DateTimeOffset now, ILogger logger)
|
||||||
{
|
{
|
||||||
var membership = account.Membership!;
|
var membership = account.Membership!;
|
||||||
|
if (membership.IsMerged)
|
||||||
|
{
|
||||||
|
logger.LogWarning("Bootstrap admin promotion skipped for merged account {UserAccountId}.", account.Id);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (membership.Status == MembershipStatus.Suspended)
|
if (membership.Status == MembershipStatus.Suspended)
|
||||||
{
|
{
|
||||||
logger.LogWarning("Bootstrap admin promotion skipped for suspended account {UserAccountId}.", account.Id);
|
logger.LogWarning("Bootstrap admin promotion skipped for suspended account {UserAccountId}.", account.Id);
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ public static class BifrostCookies
|
||||||
public const string Antiforgery = HostPrefix + "bifrost_antiforgery";
|
public const string Antiforgery = HostPrefix + "bifrost_antiforgery";
|
||||||
public const string Voter = HostPrefix + "bifrost_voter";
|
public const string Voter = HostPrefix + "bifrost_voter";
|
||||||
public const string HeimdallAttemptPrefix = HostPrefix + "bifrost_heimdall_";
|
public const string HeimdallAttemptPrefix = HostPrefix + "bifrost_heimdall_";
|
||||||
|
public const string PasskeyTicket = HostPrefix + "bifrost_passkey_ticket";
|
||||||
|
|
||||||
public const string Path = "/";
|
public const string Path = "/";
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,13 @@
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
|
|
||||||
namespace Bifrost.Web.Features.Shared;
|
namespace Bifrost.Web.Features.Shared;
|
||||||
|
|
||||||
public sealed record CurrentBifrostActor(bool IsAuthenticated, UserAccount? UserAccount)
|
public sealed record CurrentBifrostActor(bool IsAuthenticated, UserAccount? UserAccount)
|
||||||
{
|
{
|
||||||
|
/// <summary>Set when the account behind this sign-in is frozen or folded by an account merge; the actor then has no account.</summary>
|
||||||
|
public MergeStanding? Merge { get; init; }
|
||||||
|
|
||||||
public static readonly CurrentBifrostActor Anonymous = new(false, null);
|
public static readonly CurrentBifrostActor Anonymous = new(false, null);
|
||||||
|
|
||||||
public Bifrost.Web.Domain.Membership? Membership => UserAccount?.Membership;
|
public Bifrost.Web.Domain.Membership? Membership => UserAccount?.Membership;
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,8 @@ public interface ICurrentBifrostActorAccessor
|
||||||
|
|
||||||
public sealed class CurrentBifrostActorAccessor(
|
public sealed class CurrentBifrostActorAccessor(
|
||||||
IHttpContextAccessor httpContextAccessor,
|
IHttpContextAccessor httpContextAccessor,
|
||||||
BifrostDbContext dbContext) : ICurrentBifrostActorAccessor
|
BifrostDbContext dbContext,
|
||||||
|
AccountMergeLedger ledger) : ICurrentBifrostActorAccessor
|
||||||
{
|
{
|
||||||
private const string CacheKey = "Bifrost.CurrentActor";
|
private const string CacheKey = "Bifrost.CurrentActor";
|
||||||
|
|
||||||
|
|
@ -45,18 +46,41 @@ public sealed class CurrentBifrostActorAccessor(
|
||||||
return Cache(httpContext, CurrentBifrostActor.Anonymous);
|
return Cache(httpContext, CurrentBifrostActor.Anonymous);
|
||||||
}
|
}
|
||||||
|
|
||||||
var userAccount = await dbContext.UserAccounts
|
// One credential names one row: identity first, then Heimdall id, then GitHub id; the first hit wins. Two rows matching
|
||||||
|
// one principal (a merge can leave a login on either side) must never throw or pick by luck.
|
||||||
|
var accounts = dbContext.UserAccounts
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.Include(x => x.MemberProfile)
|
.Include(x => x.MemberProfile)
|
||||||
.Include(x => x.Membership!)
|
.Include(x => x.Membership!)
|
||||||
.ThenInclude(x => x.RoleAssignments)
|
.ThenInclude(x => x.RoleAssignments)
|
||||||
.Include(x => x.Membership!)
|
.Include(x => x.Membership!)
|
||||||
.ThenInclude(x => x.TierSnapshots)
|
.ThenInclude(x => x.TierSnapshots);
|
||||||
.SingleOrDefaultAsync(
|
|
||||||
x => (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity) && x.NormalizedBifrostIdentity == normalizedBifrostIdentity) ||
|
Bifrost.Web.Domain.UserAccount? userAccount = null;
|
||||||
(!string.IsNullOrWhiteSpace(heimdallAccountId) && x.HeimdallAccountId == heimdallAccountId) ||
|
if (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity))
|
||||||
(hasGitHubUserId && x.GitHubUserId == gitHubUserId),
|
{
|
||||||
cancellationToken);
|
userAccount = await accounts.SingleOrDefaultAsync(x => x.NormalizedBifrostIdentity == normalizedBifrostIdentity, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (userAccount is null && !string.IsNullOrWhiteSpace(heimdallAccountId))
|
||||||
|
{
|
||||||
|
userAccount = await accounts.SingleOrDefaultAsync(x => x.HeimdallAccountId == heimdallAccountId, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (userAccount is null && hasGitHubUserId)
|
||||||
|
{
|
||||||
|
userAccount = await accounts.SingleOrDefaultAsync(x => x.GitHubUserId == gitHubUserId, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A folded or frozen account acts as nobody on every route: this is the one gate (merge ledger standing, derived per request).
|
||||||
|
if (userAccount is not null)
|
||||||
|
{
|
||||||
|
var standing = await ledger.StandingAsync(userAccount.Id, cancellationToken);
|
||||||
|
if (standing is not null)
|
||||||
|
{
|
||||||
|
return Cache(httpContext, new CurrentBifrostActor(true, null) { Merge = standing });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return Cache(httpContext, new CurrentBifrostActor(true, userAccount));
|
return Cache(httpContext, new CurrentBifrostActor(true, userAccount));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,9 @@ public sealed class StartupConfigurationValidator(
|
||||||
{
|
{
|
||||||
var failures = new List<string>();
|
var failures = new List<string>();
|
||||||
|
|
||||||
|
// Building the options resolves Heimdall:AppSecretFile, and a bad file stops startup in every environment.
|
||||||
|
_ = heimdallOptions.Value;
|
||||||
|
|
||||||
// Checked in every environment: a bad value here would otherwise pass startup and throw on every cast.
|
// Checked in every environment: a bad value here would otherwise pass startup and throw on every cast.
|
||||||
var conceptVotes = conceptVoteOptions.Value;
|
var conceptVotes = conceptVoteOptions.Value;
|
||||||
if (!NetworkPrefix.IsValidLength(conceptVotes.IPv4PrefixLength, NetworkPrefix.IPv4Bits))
|
if (!NetworkPrefix.IsValidLength(conceptVotes.IPv4PrefixLength, NetworkPrefix.IPv4Bits))
|
||||||
|
|
@ -102,6 +105,13 @@ public sealed class StartupConfigurationValidator(
|
||||||
failures.Add("Heimdall:PatronSupportIntakeSecret is required when patron support intake is enabled.");
|
failures.Add("Heimdall:PatronSupportIntakeSecret is required when patron support intake is enabled.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The options are already resolved, so a secret from Heimdall:AppSecretFile or Heimdall:AppSecret lands in AppSecret.
|
||||||
|
// Blank would silently switch Discord and Patreon member sign-in off.
|
||||||
|
if (string.IsNullOrWhiteSpace(heimdallOptions.Value.AppSecret))
|
||||||
|
{
|
||||||
|
failures.Add("Heimdall:AppSecretFile (or Heimdall:AppSecret) must supply the Heimdall app secret outside development.");
|
||||||
|
}
|
||||||
|
|
||||||
if (stripeOptions.Value.EnableCheckout)
|
if (stripeOptions.Value.EnableCheckout)
|
||||||
{
|
{
|
||||||
if (!stripeOptions.Value.IsCheckoutConfigured)
|
if (!stripeOptions.Value.IsCheckoutConfigured)
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,8 @@ public sealed class IndexModel(
|
||||||
internal const string ApproveSuspendedNotice = "Nothing changed: a suspended account can only be lifted with Unsuspend.";
|
internal const string ApproveSuspendedNotice = "Nothing changed: a suspended account can only be lifted with Unsuspend.";
|
||||||
/// <summary>Admin-only text for a Suspended row whose reason predates the SuspensionReason column; the old text is never read back from the audit trail.</summary>
|
/// <summary>Admin-only text for a Suspended row whose reason predates the SuspensionReason column; the old text is never read back from the audit trail.</summary>
|
||||||
internal const string LegacySuspensionText = "Suspended before reasons were recorded";
|
internal const string LegacySuspensionText = "Suspended before reasons were recorded";
|
||||||
|
internal const string ApproveMergedNotice = "Nothing changed: that account was merged into another and cannot be approved.";
|
||||||
|
|
||||||
internal const string NoMembershipNotice = "Nothing changed: that account has no membership yet.";
|
internal const string NoMembershipNotice = "Nothing changed: that account has no membership yet.";
|
||||||
internal const string OwnAdminRoleNotice = "Nothing changed: you cannot remove or change your own platform admin role.";
|
internal const string OwnAdminRoleNotice = "Nothing changed: you cannot remove or change your own platform admin role.";
|
||||||
internal const string RoleOnSuspendedNotice = "Nothing changed: a suspended account's roles cannot be changed until it is unsuspended.";
|
internal const string RoleOnSuspendedNotice = "Nothing changed: a suspended account's roles cannot be changed until it is unsuspended.";
|
||||||
|
|
@ -136,6 +138,12 @@ public sealed class IndexModel(
|
||||||
return RedirectToPage();
|
return RedirectToPage();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (user.Membership.IsMerged)
|
||||||
|
{
|
||||||
|
Notice = ApproveMergedNotice; // only the merge ledger leaves Merged
|
||||||
|
return RedirectToPage();
|
||||||
|
}
|
||||||
|
|
||||||
user.Membership.Status = MembershipStatus.Active;
|
user.Membership.Status = MembershipStatus.Active;
|
||||||
user.Membership.ApprovedAtUtc = timeProvider.GetUtcNow();
|
user.Membership.ApprovedAtUtc = timeProvider.GetUtcNow();
|
||||||
ApplicationBootstrapper.EnsureRole(
|
ApplicationBootstrapper.EnsureRole(
|
||||||
|
|
|
||||||
72
src/Bifrost.Web/Pages/App/Merges/Index.cshtml
Normal file
72
src/Bifrost.Web/Pages/App/Merges/Index.cshtml
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
@page
|
||||||
|
@using Bifrost.Web.Domain
|
||||||
|
@model Bifrost.Web.Pages.App.Merges.IndexModel
|
||||||
|
@{
|
||||||
|
ViewData["Title"] = "Stuck merges";
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="panel-grid">
|
||||||
|
<article class="panel">
|
||||||
|
<span class="eyebrow">Merges</span>
|
||||||
|
<h1>Stuck account merges</h1>
|
||||||
|
<p class="panel-intro">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
@if (!string.IsNullOrEmpty(Model.Notice))
|
||||||
|
{
|
||||||
|
<p class="validation-summary-errors" role="alert">@Model.Notice</p>
|
||||||
|
}
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="table-panel" style="margin-top: 1.5rem;">
|
||||||
|
@if (Model.Merges.Count == 0)
|
||||||
|
{
|
||||||
|
<div class="empty-state" style="margin: 1.25rem;">No merge is stuck.</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="table-shell">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Merge</th>
|
||||||
|
<th>State</th>
|
||||||
|
<th>Last outcome</th>
|
||||||
|
<th>Attempts</th>
|
||||||
|
<th>Move id of this leg</th>
|
||||||
|
<th>End it</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var merge in Model.Merges)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<td>@merge.Id</td>
|
||||||
|
<td>@merge.State</td>
|
||||||
|
<td>@merge.LastOutcome</td>
|
||||||
|
<td>@merge.Attempts</td>
|
||||||
|
<td><code>@merge.MoveId</code></td>
|
||||||
|
<td>
|
||||||
|
@if (!merge.CanSettle)
|
||||||
|
{
|
||||||
|
<span>Still being retried; nothing to end.</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="@(merge.State == AccountMergeState.UndoRequested ? "AbandonUndo" : "FailForward")">
|
||||||
|
<input type="hidden" name="mergeId" value="@merge.Id" />
|
||||||
|
<input type="text" name="moveId" autocomplete="off" spellcheck="false" aria-label="Type the move id to confirm" />
|
||||||
|
<button class="button" type="submit">@(merge.State == AccountMergeState.UndoRequested ? "Give up the undo" : "Fail the merge")</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
82
src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs
Normal file
82
src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>One in-flight merge the sweeper has stopped advancing, as an operator may see it: no account, Heimdall id or login of either side.</summary>
|
||||||
|
public sealed record StuckMerge(Guid Id, AccountMergeState State, string LastOutcome, int Attempts, string MoveId, bool CanSettle);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="AccountMergeSaga.SettleStuckAsync"/>, the one writer. It calls no Heimdall.
|
||||||
|
/// </summary>
|
||||||
|
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<string, string> ResultWords = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["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<StuckMerge> Merges { get; private set; } = [];
|
||||||
|
|
||||||
|
/// <summary>The words for the closed <c>?result=</c> code of the last settle; null for no code or one this page does not know.</summary>
|
||||||
|
public string? Notice { get; private set; }
|
||||||
|
|
||||||
|
public async Task<IActionResult> 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<IActionResult> OnPostFailForwardAsync(Guid mergeId, string? moveId, CancellationToken cancellationToken) =>
|
||||||
|
SettleAsync(mergeId, SettleChoice.FailForward, moveId, cancellationToken);
|
||||||
|
|
||||||
|
public Task<IActionResult> OnPostAbandonUndoAsync(Guid mergeId, string? moveId, CancellationToken cancellationToken) =>
|
||||||
|
SettleAsync(mergeId, SettleChoice.AbandonUndo, moveId, cancellationToken);
|
||||||
|
|
||||||
|
private async Task<IActionResult> 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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
237
src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml
Normal file
237
src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml
Normal file
|
|
@ -0,0 +1,237 @@
|
||||||
|
@page
|
||||||
|
@model Bifrost.Web.Pages.Membership.LinkedAccountsModel
|
||||||
|
@{
|
||||||
|
ViewData["Title"] = "Linked accounts";
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<span class="eyebrow">Heimdall</span>
|
||||||
|
<h1>Linked accounts</h1>
|
||||||
|
<p class="panel-intro">
|
||||||
|
The provider logins that sign in to this account. Heimdall holds them and decides what may change; Bifrost keeps none of
|
||||||
|
your Heimdall sign-in, so each action sends you through Heimdall once more.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
@if (Model.ResultMessage is not null)
|
||||||
|
{
|
||||||
|
<div class="callout" role="status">@Model.ResultMessage</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (!Model.HasHeimdallAccount)
|
||||||
|
{
|
||||||
|
<div class="callout warning">
|
||||||
|
This session is not a Heimdall account, so there are no provider logins to manage here. Sign in with Discord or Patreon
|
||||||
|
through Heimdall to see them.
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<h2>Your logins</h2>
|
||||||
|
@if (Model.Identities is null)
|
||||||
|
{
|
||||||
|
<p class="muted">
|
||||||
|
Bifrost does not hold the list: it asks Heimdall, which means signing in to Heimdall again, and keeps the answer for
|
||||||
|
five minutes. It also cannot tell which logins this account holds right now, so it will not choose one for you.
|
||||||
|
Pick a login you know it holds. Signing in through Discord or Patreon when the account no longer holds that login
|
||||||
|
would create a separate Heimdall account holding it. Google cannot do that: Heimdall refuses a Google sign-in for a
|
||||||
|
login no account holds.
|
||||||
|
</p>
|
||||||
|
<div class="panel-actions">
|
||||||
|
@foreach (var provider in Model.LinkableProviders.OrderBy(x => x == "google" ? 0 : 1))
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="Refresh" class="inline-actions">
|
||||||
|
<input type="hidden" name="via" value="@provider" />
|
||||||
|
<button class="button secondary" type="submit">Show my logins through @LinkedAccountsModel.ProviderName(provider)@(provider == "google" ? " (cannot create an account)" : "")</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul>
|
||||||
|
@foreach (var identity in Model.Identities)
|
||||||
|
{
|
||||||
|
<li>
|
||||||
|
<strong>@LinkedAccountsModel.ProviderName(identity.Provider)</strong>
|
||||||
|
@if (identity.DisplayName is not null)
|
||||||
|
{
|
||||||
|
<span>@identity.DisplayName</span>
|
||||||
|
}
|
||||||
|
@if (identity.LinkedAt is { } linkedAt)
|
||||||
|
{
|
||||||
|
<span class="muted">linked @linkedAt.UtcDateTime.ToString("dd MMM yyyy") UTC</span>
|
||||||
|
}
|
||||||
|
@if (Model.HasStrongPasskey)
|
||||||
|
{
|
||||||
|
@if (Model.PasskeysAvailable)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="UnlinkPasskey" class="inline-actions" data-passkey-unlink>
|
||||||
|
<input type="hidden" name="identityId" value="@identity.Id" />
|
||||||
|
<input type="hidden" name="id" />
|
||||||
|
<input type="hidden" name="rawId" />
|
||||||
|
<input type="hidden" name="authenticatorData" />
|
||||||
|
<input type="hidden" name="clientDataJson" />
|
||||||
|
<input type="hidden" name="signature" />
|
||||||
|
<input type="hidden" name="userHandle" />
|
||||||
|
<button class="button secondary" type="submit">Unlink with passkey</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (Model.HasGoogle)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="Unlink" class="inline-actions">
|
||||||
|
<input type="hidden" name="identityId" value="@identity.Id" />
|
||||||
|
<button class="button secondary" type="submit">Unlink</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
@if (Model.Identities.Count == 1)
|
||||||
|
{
|
||||||
|
<p class="muted">This is your only login. Heimdall will not remove the last one.</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Model.HasStrongPasskey && !Model.PasskeysAvailable)
|
||||||
|
{
|
||||||
|
<p class="callout warning">
|
||||||
|
This account has a passkey, so unlinking needs it, but passkeys are not available on this server right now (a
|
||||||
|
configuration fault the operator must fix), so nothing can be unlinked from here at the moment. Nothing is lost:
|
||||||
|
try again later. If you cannot wait, revoke your passkeys below; unlinking then falls back to a fresh Google sign-in,
|
||||||
|
if a Google login is linked to this account.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
else if (Model.HasStrongPasskey)
|
||||||
|
{
|
||||||
|
<p class="muted">Unlinking asks for one of your passkeys, then signs you in to Heimdall once more and removes only the login you picked.</p>
|
||||||
|
}
|
||||||
|
else if (Model.HasGoogle)
|
||||||
|
{
|
||||||
|
<p class="muted">Unlinking asks you to sign in with Google again as proof, then removes only the login you picked. A passkey, once it has cooled off, is stronger proof and takes over from Google.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="muted">
|
||||||
|
Unlinking needs strong proof, and none is available. Add a passkey below@(Model.NextStrongAt is { } waiting
|
||||||
|
? $" (your newest one counts from {waiting.UtcDateTime:dd MMM yyyy HH:mm} UTC)"
|
||||||
|
: " (it counts after a 48 hour cooling-off)"),
|
||||||
|
or link a Google login once Heimdall has Google set up. Discord and Patreon cannot give that proof.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<form method="post" asp-page-handler="Refresh" class="panel-actions">
|
||||||
|
<button class="button secondary" type="submit">Read the list again</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
|
||||||
|
<h2>Passkeys</h2>
|
||||||
|
@if (!Model.PasskeysAvailable)
|
||||||
|
{
|
||||||
|
<p class="muted">Passkeys are not available on this server right now, so none can be added or used. You can still revoke the ones listed.</p>
|
||||||
|
}
|
||||||
|
@if (Model.PasskeysAvailable)
|
||||||
|
{
|
||||||
|
<p class="muted">
|
||||||
|
A passkey is the strong proof for unlinking a login: it stays on your device, and a site that is not Bifrost cannot use it.
|
||||||
|
A new passkey is added only right after you sign in to Heimdall again, and it counts as strong proof 48 hours later, so
|
||||||
|
someone who borrows your open browser cannot add one and use it at once. You can revoke a passkey here at any time.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
@if (Model.Passkeys.Count > 0)
|
||||||
|
{
|
||||||
|
<ul>
|
||||||
|
@foreach (var key in Model.Passkeys)
|
||||||
|
{
|
||||||
|
<li>
|
||||||
|
<strong>@key.Label</strong>
|
||||||
|
@if (key.IsStrong)
|
||||||
|
{
|
||||||
|
<span class="muted">active</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="muted">cooling off until @key.StrongFromUtc.UtcDateTime.ToString("dd MMM yyyy HH:mm") UTC; cannot unlink yet</span>
|
||||||
|
}
|
||||||
|
<span class="muted">added @key.CreatedUtc.UtcDateTime.ToString("dd MMM yyyy") UTC</span>
|
||||||
|
@if (key.LastUsedUtc is { } used)
|
||||||
|
{
|
||||||
|
<span class="muted">last used @used.UtcDateTime.ToString("dd MMM yyyy") UTC</span>
|
||||||
|
}
|
||||||
|
<form method="post" asp-page-handler="PasskeyRevoke" class="inline-actions">
|
||||||
|
<input type="hidden" name="credentialId" value="@key.Id" />
|
||||||
|
<button class="button secondary" type="submit">Revoke</button>
|
||||||
|
</form>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Model.PasskeysAvailable)
|
||||||
|
{
|
||||||
|
if (Model.PasskeyLimitReached)
|
||||||
|
{
|
||||||
|
<p class="muted">This is the most passkeys an account can hold. Revoke one to add another.</p>
|
||||||
|
}
|
||||||
|
else if (Model.CanEnrol)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="PasskeyEnrol" id="passkey-enrol" data-passkey-enrol>
|
||||||
|
<input type="hidden" name="id" />
|
||||||
|
<input type="hidden" name="rawId" />
|
||||||
|
<input type="hidden" name="attestationObject" />
|
||||||
|
<input type="hidden" name="clientDataJson" />
|
||||||
|
<input type="hidden" name="transports" />
|
||||||
|
<label>Name for this passkey <input type="text" name="label" maxlength="40" value="Passkey" /></label>
|
||||||
|
<button class="button" type="submit">Add a passkey</button>
|
||||||
|
</form>
|
||||||
|
<noscript><p class="muted">Adding a passkey needs JavaScript.</p></noscript>
|
||||||
|
}
|
||||||
|
else if (Model.Identities is not null)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="PasskeyEnrolStart" class="panel-actions">
|
||||||
|
<button class="button secondary" type="submit">Sign in again to add a passkey</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="muted">Read your linked logins first; adding a passkey then asks you to sign in to Heimdall once more.</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<p id="passkey-status" class="muted" role="status"></p>
|
||||||
|
|
||||||
|
@if (Model.Identities is not null)
|
||||||
|
{
|
||||||
|
<h2>Link another login</h2>
|
||||||
|
<p class="muted">
|
||||||
|
You will sign in to Heimdall again, then to the provider you pick. If that login already belongs to another account,
|
||||||
|
nothing is linked and nothing is merged.
|
||||||
|
</p>
|
||||||
|
<div class="panel-actions">
|
||||||
|
@foreach (var provider in Model.LinkableProviders)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="Link" class="inline-actions">
|
||||||
|
<input type="hidden" name="provider" value="@provider" />
|
||||||
|
<button class="button secondary" type="submit">Link @LinkedAccountsModel.ProviderName(provider)</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Model.MergeEnabled)
|
||||||
|
{
|
||||||
|
<p class="muted">
|
||||||
|
Hold two accounts? <a asp-page="/Membership/MergeAccounts">Merge two accounts</a>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="panel-actions">
|
||||||
|
<a class="button secondary" asp-page="/Membership/Status">Back to membership status</a>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@section Scripts {
|
||||||
|
@if (Model.HasHeimdallAccount && Model.PasskeysAvailable)
|
||||||
|
{
|
||||||
|
<script src="~/js/passkeys.js" asp-append-version="true"></script>
|
||||||
|
}
|
||||||
|
}
|
||||||
316
src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml.cs
Normal file
316
src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml.cs
Normal file
|
|
@ -0,0 +1,316 @@
|
||||||
|
using System.Security.Claims;
|
||||||
|
using Bifrost.Web.Configuration;
|
||||||
|
using Bifrost.Web.Features.Heimdall;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
|
using Bifrost.Web.Features.Passkeys;
|
||||||
|
using Bifrost.Web.Features.Shared;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
|
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Pages.Membership;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The member's provider logins (docs/linked-accounts.md). Bifrost keeps no Heimdall token, so every action here begins a
|
||||||
|
/// fresh Heimdall sign-in for the account already signed in and finishes inside that sign-in's completion
|
||||||
|
/// (<c>POST /auth/heimdall/complete</c>); this page only starts them and shows what the last read found. Every handler is a
|
||||||
|
/// POST with antiforgery. Nothing from the query or the form is ever shown: the outcome is a code from a closed set.
|
||||||
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
|
public sealed class LinkedAccountsModel(
|
||||||
|
HeimdallAuthService heimdallAuthService,
|
||||||
|
LinkedAccountsSnapshots snapshots,
|
||||||
|
PasskeyService passkeys,
|
||||||
|
ICurrentBifrostActorAccessor actors,
|
||||||
|
IOptions<BifrostHostOptions> hostOptions,
|
||||||
|
IOptions<AccountMergeOptions> mergeOptions,
|
||||||
|
ILogger<LinkedAccountsModel> logger) : PageModel
|
||||||
|
{
|
||||||
|
private static readonly Dictionary<string, string> ProviderNames = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["discord"] = "Discord",
|
||||||
|
["patreon"] = "Patreon",
|
||||||
|
["google"] = "Google"
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A folded or frozen account manages no logins and enrols no passkey: the page's handlers all begin a Heimdall flow on the
|
||||||
|
/// account's raw claim, so the one gate is here, on the actor accessor's standing, before any handler runs.
|
||||||
|
/// </summary>
|
||||||
|
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
|
||||||
|
{
|
||||||
|
if ((await actors.GetAsync(context.HttpContext.RequestAborted)).Merge is not null)
|
||||||
|
{
|
||||||
|
context.Result = Forbid();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await base.OnPageHandlerExecutionAsync(context, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
private string? AccountId => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 } id ? id : null;
|
||||||
|
|
||||||
|
/// <summary>Whether the merge page exists on this server (a flag, dark until Heimdall can move logins).</summary>
|
||||||
|
public bool MergeEnabled => mergeOptions.Value.Enabled;
|
||||||
|
|
||||||
|
/// <summary>The wording of the outcome the page was sent back with: a closed set, null for anything else.</summary>
|
||||||
|
public string? ResultMessage { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Whether this session is a Heimdall account. A Bifrost-native GitHub session has none, so there is nothing to list.</summary>
|
||||||
|
public bool HasHeimdallAccount => AccountId is not null;
|
||||||
|
|
||||||
|
/// <summary>The logins the last read found, or null when there is none or it has expired.</summary>
|
||||||
|
public IReadOnlyList<LinkedIdentitySummary>? Identities { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Whether a fresh Google sign-in can be had for this account: without a strong passkey, unlinking needs one, and only Google can give it.</summary>
|
||||||
|
public bool HasGoogle => Identities?.Any(x => x.Provider == HeimdallAuthService.StepUpProvider) == true;
|
||||||
|
|
||||||
|
/// <summary>The account's passkeys that are not revoked, with their cooling-off state.</summary>
|
||||||
|
public IReadOnlyList<PasskeyView> Passkeys { get; private set; } = [];
|
||||||
|
|
||||||
|
/// <summary>Whether a passkey past its cooling-off exists: unlinking then needs it and no longer accepts Google as the proof.</summary>
|
||||||
|
public bool HasStrongPasskey => Passkeys.Any(x => x.IsStrong);
|
||||||
|
|
||||||
|
/// <summary>When the first passkey still cooling off becomes strong.</summary>
|
||||||
|
public DateTimeOffset? NextStrongAt => Passkeys.Where(x => !x.IsStrong).Select(x => (DateTimeOffset?)x.StrongFromUtc).Min();
|
||||||
|
|
||||||
|
/// <summary>Whether this browser holds a live ticket from a fresh sign-in, so a passkey can be added now.</summary>
|
||||||
|
public bool CanEnrol { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Whether this server can run passkey ceremonies at all (https and the host it expects).</summary>
|
||||||
|
public bool PasskeysAvailable => passkeys.IsAvailable;
|
||||||
|
|
||||||
|
public bool PasskeyLimitReached => Passkeys.Count >= PasskeyService.MaxActive;
|
||||||
|
|
||||||
|
public bool CanUnlink => HasStrongPasskey || HasGoogle;
|
||||||
|
|
||||||
|
public IReadOnlyList<string> LinkableProviders => HeimdallAuthService.LinkableProviders;
|
||||||
|
|
||||||
|
public static string ProviderName(string provider) => ProviderNames.GetValueOrDefault(provider, provider);
|
||||||
|
|
||||||
|
public async Task OnGetAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ResultMessage = HeimdallLinkOutcomes.Wording(Request.Query[HeimdallLinkOutcomes.ResultParameter].ToString());
|
||||||
|
Identities = AccountId is { } id ? snapshots.Get(id) : null;
|
||||||
|
if (AccountId is { } account)
|
||||||
|
{
|
||||||
|
Passkeys = await passkeys.ListAsync(account, cancellationToken);
|
||||||
|
CanEnrol = passkeys.HasTicket(account, Request.Cookies[BifrostCookies.PasskeyTicket]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads the account's logins: an ordinary Heimdall sign-in, then the list inside its completion.</summary>
|
||||||
|
public Task<IActionResult> OnPostRefreshAsync(string? via, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
// With no current list Bifrost cannot tell which provider the account still holds, so the member names one.
|
||||||
|
if (AccountId is not { } id || (snapshots.Get(id) is null && (via is null || !HeimdallAuthService.LinkableProviders.Contains(via))))
|
||||||
|
{
|
||||||
|
return Task.FromResult(Done(HeimdallLinkOutcome.ProviderNeeded));
|
||||||
|
}
|
||||||
|
|
||||||
|
return BeginAsync(
|
||||||
|
(account, ct) => heimdallAuthService.StartListAsync(account, via, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
|
||||||
|
HeimdallLinkOutcome.Error,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Links another provider. The provider is one Heimdall's bifrost profile admits; anything else starts nothing, and so does a missing list.</summary>
|
||||||
|
public Task<IActionResult> OnPostLinkAsync(string? provider, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (provider is null || !HeimdallAuthService.LinkableProviders.Contains(provider))
|
||||||
|
{
|
||||||
|
return Task.FromResult(Done(HeimdallLinkOutcome.Error));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (AccountId is not { } id || snapshots.Get(id) is null)
|
||||||
|
{
|
||||||
|
return Task.FromResult(Done(HeimdallLinkOutcome.ListExpired));
|
||||||
|
}
|
||||||
|
|
||||||
|
return BeginAsync(
|
||||||
|
(account, ct) => heimdallAuthService.StartLinkAsync(account, provider, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
|
||||||
|
HeimdallLinkOutcome.Error,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Unlinks one login with fresh proof. The identity must be on the list this account was last shown and the account must
|
||||||
|
/// hold a Google login to prove with; otherwise Heimdall is not asked, and the page says so.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<IActionResult> OnPostUnlinkAsync(string? identityId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var shown = AccountId is { } id ? snapshots.Get(id) : null;
|
||||||
|
if (shown is null || identityId is null || !shown.Any(x => x.Id == identityId))
|
||||||
|
{
|
||||||
|
return Done(HeimdallLinkOutcome.ListExpired);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A strong passkey replaces Google as the proof: a member who has one is never asked for the weaker one.
|
||||||
|
if (await passkeys.HasStrongAsync(AccountId!, cancellationToken))
|
||||||
|
{
|
||||||
|
return Done(HeimdallLinkOutcome.PasskeyRequired);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!shown.Any(x => x.Provider == HeimdallAuthService.StepUpProvider))
|
||||||
|
{
|
||||||
|
return Done(HeimdallLinkOutcome.ProofUnavailable);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await BeginAsync(
|
||||||
|
(account, ct) => heimdallAuthService.StartUnlinkAsync(account, identityId, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
|
||||||
|
HeimdallLinkOutcome.ProofUnavailable,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Begins the fresh sign-in whose completion issues the enrolment ticket. Needs a current list: the proof provider is never guessed.</summary>
|
||||||
|
public async Task<IActionResult> OnPostPasskeyEnrolStartAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (AccountId is not { } id)
|
||||||
|
{
|
||||||
|
return Done(HeimdallLinkOutcome.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (snapshots.Get(id) is null)
|
||||||
|
{
|
||||||
|
return Done(HeimdallLinkOutcome.ListExpired);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await passkeys.PreflightEnrolStartAsync(id, cancellationToken) is { } refused)
|
||||||
|
{
|
||||||
|
return Done(refused);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await BeginAsync(
|
||||||
|
(account, ct) => heimdallAuthService.StartEnrolProofAsync(account, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
|
||||||
|
HeimdallLinkOutcome.Error,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The WebAuthn creation options for the ticket this browser holds, as JSON for the page's script.</summary>
|
||||||
|
public async Task<IActionResult> OnPostPasskeyEnrolOptionsAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (AccountId is not { } id)
|
||||||
|
{
|
||||||
|
return Options(HeimdallLinkOutcome.Error, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var (refusal, json) = await passkeys.BeginEnrolAsync(id, Request.Cookies[BifrostCookies.PasskeyTicket], cancellationToken);
|
||||||
|
return Options(refusal, json);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies the registration the script posted. The ticket cookie is spent whatever the outcome.</summary>
|
||||||
|
public async Task<IActionResult> OnPostPasskeyEnrolAsync(
|
||||||
|
string? id, string? rawId, string? attestationObject, string? clientDataJson, string? transports, string? label, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (AccountId is not { } account)
|
||||||
|
{
|
||||||
|
return Done(HeimdallLinkOutcome.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
var outcome = await passkeys.EnrolAsync(
|
||||||
|
account, Request.Cookies[BifrostCookies.PasskeyTicket],
|
||||||
|
new PasskeyFields(id, rawId, null, clientDataJson, null, null, attestationObject, transports), label, cancellationToken);
|
||||||
|
Response.Cookies.Delete(BifrostCookies.PasskeyTicket, HeimdallAttemptCookie.DeleteOptions());
|
||||||
|
return Done(outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IActionResult> OnPostPasskeyRevokeAsync(Guid credentialId, CancellationToken cancellationToken) =>
|
||||||
|
AccountId is { } id ? Done(await passkeys.RevokeAsync(id, credentialId, cancellationToken)) : Done(HeimdallLinkOutcome.Error);
|
||||||
|
|
||||||
|
/// <summary>The WebAuthn request options for unlinking one identity, as JSON for the page's script.</summary>
|
||||||
|
public async Task<IActionResult> OnPostPasskeyChallengeAsync(string? identityId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (AccountId is not { } id)
|
||||||
|
{
|
||||||
|
return Options(HeimdallLinkOutcome.Error, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (snapshots.Get(id) is not { } shown || identityId is null || !shown.Any(x => x.Id == identityId))
|
||||||
|
{
|
||||||
|
return Options(HeimdallLinkOutcome.ListExpired, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var (refusal, json) = await passkeys.BeginAssertionAsync(id, identityId, cancellationToken);
|
||||||
|
return Options(refusal, json);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Unlinks one login on a passkey assertion. The assertion is verified here; only then does Bifrost start the fresh Heimdall sign-in
|
||||||
|
/// whose completion asks Heimdall for the step-up and unlinks. A refused or unverifiable assertion starts no sign-in.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<IActionResult> OnPostUnlinkPasskeyAsync(
|
||||||
|
string? identityId, string? id, string? rawId, string? authenticatorData, string? clientDataJson, string? signature, string? userHandle,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var shown = AccountId is { } account ? snapshots.Get(account) : null;
|
||||||
|
if (shown is null || identityId is null || !shown.Any(x => x.Id == identityId))
|
||||||
|
{
|
||||||
|
return Done(HeimdallLinkOutcome.ListExpired);
|
||||||
|
}
|
||||||
|
|
||||||
|
var (refusal, factId) = await passkeys.VerifyAssertionAsync(
|
||||||
|
AccountId!, identityId, new PasskeyFields(id, rawId, authenticatorData, clientDataJson, signature, userHandle, null, null), cancellationToken);
|
||||||
|
if (refusal is { } failed)
|
||||||
|
{
|
||||||
|
return Done(failed);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var started = await heimdallAuthService.StartUnlinkPasskeyAsync(
|
||||||
|
AccountId!, identityId, factId!, 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("Linked accounts start refused: {Reason}", error.Message);
|
||||||
|
passkeys.DiscardFact(factId);
|
||||||
|
return Done(HeimdallLinkOutcome.ProofUnavailable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>JSON for the page's script: the options, or only a closed outcome code with the status that fits.</summary>
|
||||||
|
private IActionResult Options(HeimdallLinkOutcome? refusal, string? json)
|
||||||
|
{
|
||||||
|
if (refusal is null && json is not null)
|
||||||
|
{
|
||||||
|
return Content(json, "application/json");
|
||||||
|
}
|
||||||
|
|
||||||
|
var status = refusal == HeimdallLinkOutcome.RateLimited ? StatusCodes.Status429TooManyRequests : StatusCodes.Status400BadRequest;
|
||||||
|
return new ContentResult
|
||||||
|
{
|
||||||
|
StatusCode = status,
|
||||||
|
ContentType = "application/json",
|
||||||
|
Content = "{\"error\":\"" + HeimdallLinkOutcomes.Code(refusal ?? HeimdallLinkOutcome.Error) + "\"}"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private IActionResult Done(HeimdallLinkOutcome outcome) =>
|
||||||
|
RedirectToPage(null, new Dictionary<string, string?> { [HeimdallLinkOutcomes.ResultParameter] = HeimdallLinkOutcomes.Code(outcome) });
|
||||||
|
|
||||||
|
private async Task<IActionResult> BeginAsync(
|
||||||
|
Func<string, CancellationToken, Task<HeimdallAuthStartResult>> start, HeimdallLinkOutcome onRefusal, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (AccountId is not { } accountId)
|
||||||
|
{
|
||||||
|
return Done(HeimdallLinkOutcome.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var started = await start(accountId, cancellationToken);
|
||||||
|
Response.Cookies.Append(started.CookieName, started.CookieValue, HeimdallAttemptCookie.Options());
|
||||||
|
return Redirect(started.AuthorizationUrl.ToString());
|
||||||
|
}
|
||||||
|
catch (HeimdallAuthException error)
|
||||||
|
{
|
||||||
|
logger.LogWarning("Linked accounts start refused: {Reason}", error.Message);
|
||||||
|
return Done(onRefusal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
148
src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml
Normal file
148
src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml
Normal file
|
|
@ -0,0 +1,148 @@
|
||||||
|
@page
|
||||||
|
@model Bifrost.Web.Pages.Membership.MergeAccountsModel
|
||||||
|
@{
|
||||||
|
ViewData["Title"] = "Merge two accounts";
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<span class="eyebrow">Account merge</span>
|
||||||
|
<h1>Merge two accounts</h1>
|
||||||
|
<p class="panel-intro">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
@if (Model.ResultMessage is not null)
|
||||||
|
{
|
||||||
|
<div class="callout" role="status">@Model.ResultMessage</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Model.ConfirmMessage is not null)
|
||||||
|
{
|
||||||
|
<div class="callout warning" role="status">@Model.ConfirmMessage</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Model.Stage == Bifrost.Web.Pages.Membership.MergeAccountsModel.MergeStage.Prove)
|
||||||
|
{
|
||||||
|
<h2>Prove both accounts</h2>
|
||||||
|
<p class="muted">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h3>This account</h3>
|
||||||
|
@if (Model.SelfProved)
|
||||||
|
{
|
||||||
|
<p>This account is proved.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="panel-actions">
|
||||||
|
@foreach (var provider in Model.LinkableProviders)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="ProveSelf" class="inline-actions">
|
||||||
|
<input type="hidden" name="via" value="@provider" />
|
||||||
|
<button class="button secondary" type="submit">Prove this account with @Bifrost.Web.Pages.Membership.MergeAccountsModel.ProviderName(provider)</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
<h3>The other account</h3>
|
||||||
|
@if (Model.OtherProved)
|
||||||
|
{
|
||||||
|
<p>The other account is proved.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="panel-actions">
|
||||||
|
@foreach (var provider in Model.LinkableProviders)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="ProveOther" class="inline-actions">
|
||||||
|
<input type="hidden" name="via" value="@provider" />
|
||||||
|
<button class="button secondary" type="submit">Prove the other account with @Bifrost.Web.Pages.Membership.MergeAccountsModel.ProviderName(provider)</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<h2>The two accounts</h2>
|
||||||
|
<ul>
|
||||||
|
<li>This account: <strong>@Model.SelfName</strong></li>
|
||||||
|
<li>The other account: <strong>@Model.OtherName</strong></li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
@if (Model.Keep is null)
|
||||||
|
{
|
||||||
|
<p>Choose the account that stays. The other one is folded into it.</p>
|
||||||
|
<div class="panel-actions">
|
||||||
|
<a class="button" asp-page="/Membership/MergeAccounts" asp-route-keep="self">Keep this account</a>
|
||||||
|
<a class="button" asp-page="/Membership/MergeAccounts" asp-route-keep="other">Keep the other account</a>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<h2>Keep @Model.KeptName</h2>
|
||||||
|
<p>@Model.FoldedName is folded into it.</p>
|
||||||
|
<ul>
|
||||||
|
@foreach (var line in Model.PreviewLines)
|
||||||
|
{
|
||||||
|
<li>@line</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
@foreach (var statement in Model.Statements)
|
||||||
|
{
|
||||||
|
<p class="muted">@statement</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<a asp-page="/Membership/MergeAccounts" asp-route-keep="@(Model.Keep == "self" ? "other" : "self")">Keep @Model.FoldedName instead</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
@if (Model.BlockWords.Count > 0)
|
||||||
|
{
|
||||||
|
<div class="callout warning">
|
||||||
|
<ul>
|
||||||
|
@foreach (var words in Model.BlockWords)
|
||||||
|
{
|
||||||
|
<li>@words</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else if (Model.Stage == Bifrost.Web.Pages.Membership.MergeAccountsModel.MergeStage.ProveRemaining)
|
||||||
|
{
|
||||||
|
<p>
|
||||||
|
@Model.FoldedName holds more logins. Sign in once more through each one, so Heimdall knows the whole account agrees.
|
||||||
|
</p>
|
||||||
|
<div class="panel-actions">
|
||||||
|
@foreach (var provider in Model.ProvidersToProve)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="ProveRemaining" class="inline-actions">
|
||||||
|
<input type="hidden" name="via" value="@provider" />
|
||||||
|
<input type="hidden" name="keep" value="@Model.Keep" />
|
||||||
|
<button class="button secondary" type="submit">Sign in with @Bifrost.Web.Pages.Membership.MergeAccountsModel.ProviderName(provider)</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else if (Model.Stage == Bifrost.Web.Pages.Membership.MergeAccountsModel.MergeStage.Confirm)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="Confirm">
|
||||||
|
<input type="hidden" name="keep" value="@Model.Keep" />
|
||||||
|
<input type="hidden" name="digest" value="@Model.Digest" />
|
||||||
|
<p>
|
||||||
|
<label><input type="checkbox" name="consentSelf" value="true" /> I agree, for the account @Model.SelfName.</label>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<label><input type="checkbox" name="consentOther" value="true" /> I agree, for the account @Model.OtherName.</label>
|
||||||
|
</p>
|
||||||
|
<button class="button" type="submit">Merge into @Model.KeptName</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</section>
|
||||||
270
src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml.cs
Normal file
270
src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml.cs
Normal file
|
|
@ -0,0 +1,270 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="MergeProofs"/> 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: <see cref="AccountMergeSaga.ConfirmAsync"/> inserts the one Confirmed row that is the consent.
|
||||||
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
|
public sealed class MergeAccountsModel(
|
||||||
|
ICurrentBifrostActorAccessor actors,
|
||||||
|
BifrostDbContext dbContext,
|
||||||
|
AccountMergeLedger ledger,
|
||||||
|
AccountMergeSaga saga,
|
||||||
|
MergeProofs proofs,
|
||||||
|
HeimdallAuthService heimdallAuthService,
|
||||||
|
IOptions<BifrostHostOptions> hostOptions,
|
||||||
|
IOptions<AccountMergeOptions> mergeOptions,
|
||||||
|
ILogger<MergeAccountsModel> 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
|
||||||
|
{
|
||||||
|
/// <summary>One side or both lack a proof: nothing is named.</summary>
|
||||||
|
Prove,
|
||||||
|
|
||||||
|
/// <summary>Both sides are proved: the member chooses which stays.</summary>
|
||||||
|
Choose,
|
||||||
|
|
||||||
|
/// <summary>A direction is chosen and the folded account's remaining logins are asked one sign-in each.</summary>
|
||||||
|
ProveRemaining,
|
||||||
|
|
||||||
|
/// <summary>Everything the saga needs is held: the confirm form.</summary>
|
||||||
|
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; }
|
||||||
|
|
||||||
|
/// <summary>Display names, set only once both sides are proved.</summary>
|
||||||
|
public string? SelfName { get; private set; }
|
||||||
|
|
||||||
|
public string? OtherName { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>The chosen direction, "self" or "other", or null.</summary>
|
||||||
|
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<string> PreviewLines { get; private set; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<string> BlockWords { get; private set; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<string> Statements => MergePreview.Statements;
|
||||||
|
|
||||||
|
public IReadOnlyList<string> ProvidersToProve { get; private set; } = [];
|
||||||
|
|
||||||
|
public string Digest { get; private set; } = string.Empty;
|
||||||
|
|
||||||
|
public IReadOnlyList<string> 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;
|
||||||
|
|
||||||
|
/// <summary>Off, the page does not exist; a folded or frozen account is forbidden it, as it is Linked accounts.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Starts a fresh sign-in of the account signed in here.</summary>
|
||||||
|
public Task<IActionResult> OnPostProveSelfAsync(string? via, CancellationToken cancellationToken) => BeginAsync(MergeSide.Self, via, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Starts a fresh sign-in of the other account. The member names the provider: Bifrost never guesses one.</summary>
|
||||||
|
public Task<IActionResult> OnPostProveOtherAsync(string? via, CancellationToken cancellationToken) => BeginAsync(MergeSide.Other, via, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Starts the next sign-in the chosen folded account still owes; its side follows from the chosen direction.</summary>
|
||||||
|
public Task<IActionResult> 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"));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<IActionResult> 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<IActionResult> BeginAsync(MergeSide side, string? via, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var start = side == MergeSide.Self
|
||||||
|
? (Func<string, Task<HeimdallAuthStartResult>>)(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<string, string?> { [HeimdallLinkOutcomes.ResultParameter] = HeimdallLinkOutcomes.Code(HeimdallLinkOutcome.Error) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const string ReturnPath = "/Membership/MergeAccounts";
|
||||||
|
|
||||||
|
private IActionResult Refused(string? keep, string code)
|
||||||
|
{
|
||||||
|
var query = new Dictionary<string, string?>();
|
||||||
|
if (keep is Self or Other)
|
||||||
|
{
|
||||||
|
query[KeepParameter] = keep;
|
||||||
|
}
|
||||||
|
|
||||||
|
query[MergeParameter] = code;
|
||||||
|
return RedirectToPage(null, query);
|
||||||
|
}
|
||||||
|
}
|
||||||
100
src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml
Normal file
100
src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
@page
|
||||||
|
@model Bifrost.Web.Pages.Membership.MergeStatusModel
|
||||||
|
@{
|
||||||
|
ViewData["Title"] = "Merge status";
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<span class="eyebrow">Account merge</span>
|
||||||
|
<h1>Merge status</h1>
|
||||||
|
<p class="panel-intro">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
@if (Model.ResultMessage is not null)
|
||||||
|
{
|
||||||
|
<div class="callout">@Model.ResultMessage</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Model.UndoMessage is not null)
|
||||||
|
{
|
||||||
|
<div class="callout">@Model.UndoMessage</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Model.Merges.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="muted">There is no merge to show for this account.</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
@foreach (var merge in Model.Merges)
|
||||||
|
{
|
||||||
|
<article class="status-banner">
|
||||||
|
<strong>@merge.State</strong>
|
||||||
|
@if (merge.Why is not null)
|
||||||
|
{
|
||||||
|
<p class="muted">@merge.Why</p>
|
||||||
|
}
|
||||||
|
@if (merge.Outcome is not null)
|
||||||
|
{
|
||||||
|
<p class="muted">@merge.Outcome</p>
|
||||||
|
}
|
||||||
|
<ul>
|
||||||
|
@if (merge.Confirmed is not null)
|
||||||
|
{
|
||||||
|
<li>Confirmed @merge.Confirmed</li>
|
||||||
|
}
|
||||||
|
@if (merge.Committed is not null)
|
||||||
|
{
|
||||||
|
<li>Merged @merge.Committed</li>
|
||||||
|
}
|
||||||
|
@if (merge.GraceEnds is not null)
|
||||||
|
{
|
||||||
|
<li>Undo window ends @merge.GraceEnds</li>
|
||||||
|
}
|
||||||
|
@if (merge.Final is not null)
|
||||||
|
{
|
||||||
|
<li>Final @merge.Final</li>
|
||||||
|
}
|
||||||
|
@if (merge.SurvivorProofs.Count > 0)
|
||||||
|
{
|
||||||
|
<li>Kept account proved with: @string.Join(", ", merge.SurvivorProofs)</li>
|
||||||
|
}
|
||||||
|
@if (merge.FoldedProofs.Count > 0)
|
||||||
|
{
|
||||||
|
<li>Folded account proved with: @string.Join(", ", merge.FoldedProofs)</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
@if (merge.DaysLeft is not null)
|
||||||
|
{
|
||||||
|
<p><span class="pill warning">@merge.DaysLeft</span></p>
|
||||||
|
}
|
||||||
|
@if (merge.TierNote is not null)
|
||||||
|
{
|
||||||
|
<p class="muted">@merge.TierNote</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (merge.CanUndo)
|
||||||
|
{
|
||||||
|
@if (merge.Ready)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="Undo">
|
||||||
|
<input type="hidden" name="mergeId" value="@merge.Id" />
|
||||||
|
<button class="button" type="submit">Undo this merge</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="muted">To undo, sign in again through each login that moved. The sign-ins are held in memory for a few minutes.</p>
|
||||||
|
@foreach (var provider in merge.NeedProof)
|
||||||
|
{
|
||||||
|
<form method="post" asp-page-handler="ProveForUndo">
|
||||||
|
<input type="hidden" name="via" value="@provider" />
|
||||||
|
<button class="button secondary" type="submit">Sign in with @Bifrost.Web.Pages.Membership.LinkedAccountsModel.ProviderName(provider)</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</article>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
206
src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml.cs
Normal file
206
src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml.cs
Normal file
|
|
@ -0,0 +1,206 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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
|
||||||
|
/// <see cref="MergeWording"/>'s closed words, and the undo. It reads merge rows and writes none: undo is the saga's
|
||||||
|
/// <see cref="AccountMergeSaga.RequestUndoAsync"/> followed by its own <see cref="AccountMergeSaga.AdvanceAsync"/>, with fresh proofs
|
||||||
|
/// of every moved login held by <see cref="MergeProofs"/>. 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.
|
||||||
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
|
public sealed class MergeStatusModel(
|
||||||
|
ICurrentBifrostActorAccessor actors,
|
||||||
|
BifrostDbContext dbContext,
|
||||||
|
AccountMergeSaga saga,
|
||||||
|
MergeProofs proofs,
|
||||||
|
HeimdallAuthService heimdallAuthService,
|
||||||
|
IOptions<BifrostHostOptions> hostOptions,
|
||||||
|
TimeProvider timeProvider,
|
||||||
|
ILogger<MergeStatusModel> 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<string> SurvivorProofs,
|
||||||
|
IReadOnlyList<string> FoldedProofs,
|
||||||
|
bool CanUndo,
|
||||||
|
bool Ready,
|
||||||
|
IReadOnlyList<string> NeedProof);
|
||||||
|
|
||||||
|
public IReadOnlyList<MergeRow> 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))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Starts a fresh sign-in of this account through <paramref name="via"/>, held in memory until the undo takes it.</summary>
|
||||||
|
public async Task<IActionResult> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Asks the saga to undo one merge with the proofs this member holds, then runs its step function once, as the sweeper would.</summary>
|
||||||
|
public async Task<IActionResult> 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<string> 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<string> MovedIds(AccountMerge merge)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return merge.MovedIdentityIds is { } json ? JsonSerializer.Deserialize<string[]>(json) ?? [] : [];
|
||||||
|
}
|
||||||
|
catch (JsonException)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private IActionResult Undone(string code) =>
|
||||||
|
RedirectToPage(null, new Dictionary<string, string?> { [UndoParameter] = code });
|
||||||
|
|
||||||
|
private IActionResult Result(HeimdallLinkOutcome outcome) =>
|
||||||
|
RedirectToPage(null, new Dictionary<string, string?> { [HeimdallLinkOutcomes.ResultParameter] = HeimdallLinkOutcomes.Code(outcome) });
|
||||||
|
}
|
||||||
|
|
@ -24,6 +24,22 @@
|
||||||
<p class="muted">@Model.StatusMessage</p>
|
<p class="muted">@Model.StatusMessage</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@if (Model.CanManageLogins)
|
||||||
|
{
|
||||||
|
<div class="panel-actions">
|
||||||
|
<a class="button secondary" asp-page="/Membership/LinkedAccounts">Linked accounts</a>
|
||||||
|
<span class="muted">See, add and remove the provider logins that sign in to this account.</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Model.HasMerges)
|
||||||
|
{
|
||||||
|
<div class="panel-actions">
|
||||||
|
<a class="button secondary" asp-page="/Membership/MergeStatus">Merge status</a>
|
||||||
|
<span class="muted">See an account merge and, for seven days, undo it.</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
@if (Model.Invitation is not null)
|
@if (Model.Invitation is not null)
|
||||||
{
|
{
|
||||||
<div class="callout success">
|
<div class="callout success">
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
using Bifrost.Web.Data;
|
using Bifrost.Web.Data;
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
using Bifrost.Web.Features.Shared;
|
using Bifrost.Web.Features.Shared;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||||
|
|
@ -12,6 +14,12 @@ public sealed class StatusModel(
|
||||||
ICurrentBifrostActorAccessor actorAccessor,
|
ICurrentBifrostActorAccessor actorAccessor,
|
||||||
BifrostDbContext dbContext) : PageModel
|
BifrostDbContext dbContext) : PageModel
|
||||||
{
|
{
|
||||||
|
/// <summary>Whether this session belongs to a Heimdall account whose logins the Linked accounts page can manage.</summary>
|
||||||
|
public bool CanManageLogins => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 };
|
||||||
|
|
||||||
|
/// <summary>Whether this account is in, or was in, a merge: the link to Merge status is shown only then.</summary>
|
||||||
|
public bool HasMerges { get; private set; }
|
||||||
|
|
||||||
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
|
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
|
||||||
|
|
||||||
public MembershipInvitation? Invitation { get; private set; }
|
public MembershipInvitation? Invitation { get; private set; }
|
||||||
|
|
@ -45,6 +53,9 @@ public sealed class StatusModel(
|
||||||
public async Task OnGetAsync(CancellationToken cancellationToken)
|
public async Task OnGetAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
Actor = await actorAccessor.GetAsync(cancellationToken);
|
Actor = await actorAccessor.GetAsync(cancellationToken);
|
||||||
|
HasMerges = Actor.Merge is not null
|
||||||
|
|| (Actor.UserAccount is { } account
|
||||||
|
&& await dbContext.AccountMerges.AnyAsync(x => x.SurvivorUserAccountId == account.Id || x.FoldedUserAccountId == account.Id, cancellationToken));
|
||||||
|
|
||||||
if (Actor.UserAccount is null)
|
if (Actor.UserAccount is null)
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
@model string
|
||||||
|
<aside class="merge-notice" role="status">
|
||||||
|
<span>@Model</span>
|
||||||
|
<a asp-page="/Membership/MergeStatus">Merge status</a>
|
||||||
|
</aside>
|
||||||
|
|
@ -57,6 +57,11 @@
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
@if (User.Identity?.IsAuthenticated == true)
|
||||||
|
{
|
||||||
|
@await Component.InvokeAsync("MergeNotice")
|
||||||
|
}
|
||||||
|
|
||||||
<main class="page-frame">
|
<main class="page-frame">
|
||||||
@RenderBody()
|
@RenderBody()
|
||||||
</main>
|
</main>
|
||||||
|
|
|
||||||
|
|
@ -64,7 +64,8 @@ builder.Services
|
||||||
|
|
||||||
builder.Services
|
builder.Services
|
||||||
.AddOptions<HeimdallOptions>()
|
.AddOptions<HeimdallOptions>()
|
||||||
.BindConfiguration(HeimdallOptions.SectionName);
|
.BindConfiguration(HeimdallOptions.SectionName)
|
||||||
|
.PostConfigure<ILogger<HeimdallOptions>>(HeimdallOptions.ResolveAppSecret);
|
||||||
|
|
||||||
builder.Services
|
builder.Services
|
||||||
.AddOptions<StripeOptions>()
|
.AddOptions<StripeOptions>()
|
||||||
|
|
@ -92,6 +93,7 @@ builder.Services.AddAntiforgery(options =>
|
||||||
builder.Services.AddRazorPages(options =>
|
builder.Services.AddRazorPages(options =>
|
||||||
{
|
{
|
||||||
options.Conventions.AuthorizePage("/Membership/Status");
|
options.Conventions.AuthorizePage("/Membership/Status");
|
||||||
|
options.Conventions.AuthorizePage("/Membership/LinkedAccounts");
|
||||||
options.Conventions.AuthorizeFolder("/App", ActiveMemberRequirement.PolicyName);
|
options.Conventions.AuthorizeFolder("/App", ActiveMemberRequirement.PolicyName);
|
||||||
options.Conventions.AllowAnonymousToFolder("/Mill");
|
options.Conventions.AllowAnonymousToFolder("/Mill");
|
||||||
});
|
});
|
||||||
|
|
@ -137,6 +139,13 @@ builder.Services.AddSingleton<RegistrationChallengeService>();
|
||||||
builder.Services.AddSingleton<RegistrationRateLimit>();
|
builder.Services.AddSingleton<RegistrationRateLimit>();
|
||||||
builder.Services.AddScoped<NativeRegistration>();
|
builder.Services.AddScoped<NativeRegistration>();
|
||||||
builder.Services.AddHostedService<SealedBallotCloser>();
|
builder.Services.AddHostedService<SealedBallotCloser>();
|
||||||
|
builder.Services.AddOptions<AccountMergeOptions>().BindConfiguration(AccountMergeOptions.SectionName);
|
||||||
|
builder.Services.AddScoped<Bifrost.Web.Features.Membership.AccountMergeLedger>();
|
||||||
|
builder.Services.AddScoped<Bifrost.Web.Features.Membership.AccountMergeSaga>();
|
||||||
|
builder.Services.AddScoped<Bifrost.Web.Features.Membership.MergeNoticeFeed>();
|
||||||
|
builder.Services.AddOptions<ChatNoticesOptions>().BindConfiguration(ChatNoticesOptions.SectionName);
|
||||||
|
builder.Services.AddSingleton<Bifrost.Web.Features.Membership.MergeProofs>();
|
||||||
|
builder.Services.AddHostedService<Bifrost.Web.Features.Membership.AccountMergeSweeper>();
|
||||||
builder.Services.AddScoped<MotionEveSurfaceService>();
|
builder.Services.AddScoped<MotionEveSurfaceService>();
|
||||||
builder.Services.AddScoped<PatronageService>();
|
builder.Services.AddScoped<PatronageService>();
|
||||||
builder.Services.AddScoped<StripeWebhookService>();
|
builder.Services.AddScoped<StripeWebhookService>();
|
||||||
|
|
@ -149,9 +158,13 @@ builder.Services.AddScoped<ReadinessService>();
|
||||||
builder.Services.AddScoped<ApplicationBootstrapper>();
|
builder.Services.AddScoped<ApplicationBootstrapper>();
|
||||||
builder.Services.AddSingleton<StartupConfigurationValidator>();
|
builder.Services.AddSingleton<StartupConfigurationValidator>();
|
||||||
builder.Services.AddScoped<IAuthorizationHandler, ActiveMemberAuthorizationHandler>();
|
builder.Services.AddScoped<IAuthorizationHandler, ActiveMemberAuthorizationHandler>();
|
||||||
builder.Services.AddHttpClient<HeimdallAuthService>((serviceProvider, client) =>
|
// The app-secret and member-bearer clients and the mover: no redirects (see HeimdallClientServices).
|
||||||
HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value))
|
builder.Services.AddHeimdallClients();
|
||||||
.RedactLoggedHeaders(header => string.Equals(header, HeimdallAuthService.AppSecretHeader, StringComparison.OrdinalIgnoreCase));
|
builder.Services.AddSingleton<LinkedAccountsSnapshots>();
|
||||||
|
builder.Services.AddSingleton<Bifrost.Web.Features.Passkeys.PasskeyRelyingParty>();
|
||||||
|
builder.Services.AddSingleton<Bifrost.Web.Features.Passkeys.PasskeyCeremonies>();
|
||||||
|
builder.Services.AddSingleton<Bifrost.Web.Features.Passkeys.PasskeyRateLimit>();
|
||||||
|
builder.Services.AddScoped<Bifrost.Web.Features.Passkeys.PasskeyService>();
|
||||||
builder.Services.AddSingleton<HeimdallTokenVerifier>();
|
builder.Services.AddSingleton<HeimdallTokenVerifier>();
|
||||||
builder.Services.AddHttpClient(HeimdallTokenVerifier.ClientName, (serviceProvider, client) =>
|
builder.Services.AddHttpClient(HeimdallTokenVerifier.ClientName, (serviceProvider, client) =>
|
||||||
HeimdallTokenVerifier.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value));
|
HeimdallTokenVerifier.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value));
|
||||||
|
|
@ -274,6 +287,8 @@ var app = builder.Build();
|
||||||
var appJsonSerializerOptions = CreateAppJsonSerializerOptions();
|
var appJsonSerializerOptions = CreateAppJsonSerializerOptions();
|
||||||
|
|
||||||
app.Services.GetRequiredService<StartupConfigurationValidator>().Validate();
|
app.Services.GetRequiredService<StartupConfigurationValidator>().Validate();
|
||||||
|
// Resolved now so a misconfigured RP (not https, host differs, a port in ExpectedHost) is logged once at boot, not on the first ceremony.
|
||||||
|
_ = app.Services.GetRequiredService<Bifrost.Web.Features.Passkeys.PasskeyRelyingParty>();
|
||||||
await using (var scope = app.Services.CreateAsyncScope())
|
await using (var scope = app.Services.CreateAsyncScope())
|
||||||
{
|
{
|
||||||
await scope.ServiceProvider
|
await scope.ServiceProvider
|
||||||
|
|
@ -808,6 +823,8 @@ app.MapPost("/api/sealed-motions/{id:guid}/mind", async (
|
||||||
: await SealedCall(async () => await service.HandleAsync(id, envelope, ct));
|
: await SealedCall(async () => await service.HandleAsync(id, envelope, ct));
|
||||||
}).AllowAnonymous();
|
}).AllowAnonymous();
|
||||||
|
|
||||||
|
MergeNoticeEndpoints.Map(app);
|
||||||
|
|
||||||
app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
|
app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
|
||||||
{
|
{
|
||||||
httpContext.Response.Headers.CacheControl = "no-store";
|
httpContext.Response.Headers.CacheControl = "no-store";
|
||||||
|
|
@ -822,11 +839,53 @@ app.MapPost("/auth/heimdall/complete", async (
|
||||||
ILogger<HeimdallAuthService> logger,
|
ILogger<HeimdallAuthService> logger,
|
||||||
CancellationToken cancellationToken) =>
|
CancellationToken cancellationToken) =>
|
||||||
{
|
{
|
||||||
|
// Every answer here sets or clears an attempt cookie or signs someone in: none may be stored.
|
||||||
|
httpContext.Response.Headers.CacheControl = "no-store";
|
||||||
var form = await ReadFormOrNullAsync(httpContext.Request, cancellationToken);
|
var form = await ReadFormOrNullAsync(httpContext.Request, cancellationToken);
|
||||||
var attempt = form?["attempt"].ToString();
|
var attempt = form?["attempt"].ToString();
|
||||||
var held = heimdallAuthService.FindAttemptCookie(httpContext.Request.Cookies, attempt);
|
var held = heimdallAuthService.FindAttemptCookie(httpContext.Request.Cookies, attempt);
|
||||||
|
var linking = held is not null
|
||||||
|
&& heimdallAuthService.PurposeOf(held.Value.Value, attempt) is not (null or HeimdallAttemptPurpose.SignIn);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
if (linking)
|
||||||
|
{
|
||||||
|
// A link step never signs anyone in: the session in this browser is the one being linked.
|
||||||
|
var step = await heimdallAuthService.ContinueLinkAsync(
|
||||||
|
hostOptions.Value.PublicBaseUrl,
|
||||||
|
attempt,
|
||||||
|
held!.Value.Name,
|
||||||
|
held.Value.Value,
|
||||||
|
form?["code"].ToString(),
|
||||||
|
form?["pendingLinkId"].ToString(),
|
||||||
|
// A folded or frozen account links nothing: the actor accessor's standing decides, not the raw claim.
|
||||||
|
(await httpContext.RequestServices.GetRequiredService<ICurrentBifrostActorAccessor>().GetAsync(cancellationToken)).Merge is null
|
||||||
|
? httpContext.User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId)
|
||||||
|
: null,
|
||||||
|
cancellationToken);
|
||||||
|
if (step.Next is not null)
|
||||||
|
{
|
||||||
|
httpContext.Response.Cookies.Append(step.CookieName, step.CookieValue!, HeimdallAttemptCookie.Options());
|
||||||
|
return Results.Redirect(step.Next.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (step.EnrolTicket is not null)
|
||||||
|
{
|
||||||
|
// The ticket id goes only to the browser that completed the fresh sign-in; the server holds what it is bound to.
|
||||||
|
httpContext.Response.Cookies.Append(BifrostCookies.PasskeyTicket, step.EnrolTicket, new CookieOptions
|
||||||
|
{
|
||||||
|
HttpOnly = true,
|
||||||
|
Secure = true,
|
||||||
|
SameSite = SameSiteMode.Lax,
|
||||||
|
Path = BifrostCookies.Path,
|
||||||
|
MaxAge = Bifrost.Web.Features.Passkeys.PasskeyCeremonies.TicketLifetime
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
httpContext.Response.Cookies.Delete(step.CookieName, HeimdallAttemptCookie.DeleteOptions());
|
||||||
|
return Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(step.Outcome!.Value, step.ReturnPath));
|
||||||
|
}
|
||||||
|
|
||||||
var signIn = await heimdallAuthService.CompleteAsync(
|
var signIn = await heimdallAuthService.CompleteAsync(
|
||||||
hostOptions.Value.PublicBaseUrl,
|
hostOptions.Value.PublicBaseUrl,
|
||||||
attempt,
|
attempt,
|
||||||
|
|
@ -845,7 +904,9 @@ app.MapPost("/auth/heimdall/complete", async (
|
||||||
httpContext.Response.Cookies.Delete(held.Value.Name, HeimdallAttemptCookie.DeleteOptions());
|
httpContext.Response.Cookies.Delete(held.Value.Name, HeimdallAttemptCookie.DeleteOptions());
|
||||||
}
|
}
|
||||||
|
|
||||||
return Results.Redirect(HeimdallAuthService.ErrorRedirect);
|
return linking
|
||||||
|
? Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(HeimdallLinkOutcome.Error, heimdallAuthService.MergeReturnPathOf(held?.Value, attempt)))
|
||||||
|
: Results.Redirect(HeimdallAuthService.ErrorRedirect);
|
||||||
}
|
}
|
||||||
}).AllowAnonymous();
|
}).AllowAnonymous();
|
||||||
|
|
||||||
|
|
|
||||||
57
src/Bifrost.Web/ViewComponents/MergeNotice.cs
Normal file
57
src/Bifrost.Web/ViewComponents/MergeNotice.cs
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="MergeWording"/>'s, and no account name or id is ever in them.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class MergeNotice(ICurrentBifrostActorAccessor actors, BifrostDbContext dbContext, TimeProvider timeProvider) : ViewComponent
|
||||||
|
{
|
||||||
|
public async Task<IViewComponentResult> 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<string?> 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -28,6 +28,7 @@
|
||||||
"BaseUrl": "https://heimdall.gamecult.org",
|
"BaseUrl": "https://heimdall.gamecult.org",
|
||||||
"AppSlug": "bifrost",
|
"AppSlug": "bifrost",
|
||||||
"AppSecret": "",
|
"AppSecret": "",
|
||||||
|
"AppSecretFile": "",
|
||||||
"DiscordGuildId": "",
|
"DiscordGuildId": "",
|
||||||
"DiscordAllowedRoleIds": [],
|
"DiscordAllowedRoleIds": [],
|
||||||
"PatreonTierTitle": "Inner Sanctum",
|
"PatreonTierTitle": "Inner Sanctum",
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,19 @@
|
||||||
"resolved": "2.4.0",
|
"resolved": "2.4.0",
|
||||||
"contentHash": "SwXsAV3sMvAU/Nn31pbjhWurYSjJ+/giI/0n6tCrYoupEK34iIHCuk3STAd9fx8yudM85KkLSVdn951vTng/vQ=="
|
"contentHash": "SwXsAV3sMvAU/Nn31pbjhWurYSjJ+/giI/0n6tCrYoupEK34iIHCuk3STAd9fx8yudM85KkLSVdn951vTng/vQ=="
|
||||||
},
|
},
|
||||||
|
"Fido2": {
|
||||||
|
"type": "Direct",
|
||||||
|
"requested": "[4.3.3, )",
|
||||||
|
"resolved": "4.3.3",
|
||||||
|
"contentHash": "++G8ohXlhp9AH49FXIvYqziXUAEpuCtT+z5HBevX6+Pl6sYz9zfDHGTgvne6t3UEhM0hudesgMudyNG7RlpaEA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Fido2.Models": "4.3.3",
|
||||||
|
"Microsoft.Extensions.Http": "9.0.0",
|
||||||
|
"Microsoft.IdentityModel.JsonWebTokens": "8.2.0",
|
||||||
|
"NSec.Cryptography": "25.4.0",
|
||||||
|
"System.Formats.Cbor": "9.0.24"
|
||||||
|
}
|
||||||
|
},
|
||||||
"MessagePack": {
|
"MessagePack": {
|
||||||
"type": "Direct",
|
"type": "Direct",
|
||||||
"requested": "[3.1.12, )",
|
"requested": "[3.1.12, )",
|
||||||
|
|
@ -111,11 +124,24 @@
|
||||||
"resolved": "8.0.5",
|
"resolved": "8.0.5",
|
||||||
"contentHash": "0f1B50Ss7rqxXiaBJyzUu9bWFOO2/zSlifZ/UNMdiIpDYe4cY4LQQicP4nirK1OS31I43rn062UIJ1Q9bpmHpg=="
|
"contentHash": "0f1B50Ss7rqxXiaBJyzUu9bWFOO2/zSlifZ/UNMdiIpDYe4cY4LQQicP4nirK1OS31I43rn062UIJ1Q9bpmHpg=="
|
||||||
},
|
},
|
||||||
|
"Fido2.Models": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "4.3.3",
|
||||||
|
"contentHash": "G/Q8MYgptOwMrbWgDoGsy90u3J5GTdNAHub8aZRg/mQrUETzB5CqFzstGdTXE9UhL0qD6sRynOoPUnqCwKRnMw==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Bcl.Memory": "9.0.14"
|
||||||
|
}
|
||||||
|
},
|
||||||
"Humanizer.Core": {
|
"Humanizer.Core": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "2.14.1",
|
"resolved": "2.14.1",
|
||||||
"contentHash": "lQKvtaTDOXnoVJ20ibTuSIOf2i0uO0MPbDhd1jm238I+U/2ZnRENj0cktKZhtchBMtCUSRQ5v4xBCUbKNmyVMw=="
|
"contentHash": "lQKvtaTDOXnoVJ20ibTuSIOf2i0uO0MPbDhd1jm238I+U/2ZnRENj0cktKZhtchBMtCUSRQ5v4xBCUbKNmyVMw=="
|
||||||
},
|
},
|
||||||
|
"libsodium": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "1.0.20.1",
|
||||||
|
"contentHash": "pkiceEqJDQFHjbga3k/oPfTVX9g+GKJZ1VrkuiLhaymt9YNw1Dr7cX9hNuZuNaWcr9WD0moW55k4pMwzQ7JaZQ=="
|
||||||
|
},
|
||||||
"MessagePack.Annotations": {
|
"MessagePack.Annotations": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "3.1.12",
|
"resolved": "3.1.12",
|
||||||
|
|
@ -139,6 +165,11 @@
|
||||||
"System.Formats.Asn1": "10.0.2"
|
"System.Formats.Asn1": "10.0.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"Microsoft.Bcl.Memory": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.14",
|
||||||
|
"contentHash": "laQCcjTM2FnbyznkAu9hwBuQh3z2/OtJKwjGkJOUevylFpFXZIUVq/+MU2jM0HQm1n5wsjjwtLIDOiWJ6Nai3A=="
|
||||||
|
},
|
||||||
"Microsoft.CodeAnalysis.Analyzers": {
|
"Microsoft.CodeAnalysis.Analyzers": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "3.3.3",
|
"resolved": "3.3.3",
|
||||||
|
|
@ -226,26 +257,43 @@
|
||||||
"Microsoft.Extensions.Primitives": "8.0.0"
|
"Microsoft.Extensions.Primitives": "8.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"Microsoft.Extensions.Configuration": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "YIMO9T3JL8MeEXgVozKt2v79hquo/EFtnY0vgxmLnUvk1Rei/halI7kOWZL2RBeV9FMGzgM9LZA8CVaNwFMaNA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"Microsoft.Extensions.Configuration.Abstractions": {
|
"Microsoft.Extensions.Configuration.Abstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.0",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "3lE/iLSutpgX1CC0NOW70FJoGARRHbyKmG7dc0klnUZ9Dd9hS6N/POPWhKhMLCEuNN5nXEY5agmlFtH562vqhQ==",
|
"contentHash": "lqvd7W3FGKUO1+ZoUEMaZ5XDJeWvjpy2/M/ptCGz3tXLD4HWVaSzjufsAsjemasBEg+2SxXVtYVvGt5r2nKDlg==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"Microsoft.Extensions.Primitives": "8.0.0"
|
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Microsoft.Extensions.Configuration.Binder": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "RiScL99DcyngY9zJA2ROrri7Br8tn5N4hP4YNvGdTN/bvg1A3dwvDOxHnNZ3Im7x2SJ5i4LkX1uPiR/MfSFBLQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Extensions.Configuration.Abstractions": "9.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.DependencyInjection": {
|
"Microsoft.Extensions.DependencyInjection": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.1",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "BmANAnR5Xd4Oqw7yQ75xOAYODybZQRzdeNucg7kS5wWKd2PNnMdYtJ2Vciy0QLylRmv42DGl5+AFL9izA6F1Rw==",
|
"contentHash": "MCPrg7v3QgNMr0vX4vzRXvkNGgLg8vKWX0nKCWUxu2uPyMsaRgiRc1tHBnbTcfJMhMKj2slE/j2M9oGkd25DNw==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
|
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.2",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "3iE7UF7MQkCv1cxzCahz+Y/guQbTqieyxyaWKhrRO91itI9cOKO76OHeQDahqG4MmW5umr3CcCvGmK92lWNlbg=="
|
"contentHash": "+6f2qv2a3dLwd5w6JanPIPs47CxRbnk+ZocMJUhv9NxP88VlOcJYZs9jY+MYSjxvady08bUZn6qgiNh7DadGgg=="
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.DependencyModel": {
|
"Microsoft.Extensions.DependencyModel": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
|
|
@ -256,37 +304,83 @@
|
||||||
"System.Text.Json": "8.0.0"
|
"System.Text.Json": "8.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"Microsoft.Extensions.Diagnostics": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "0CF9ZrNw5RAlRfbZuVIvzzhP8QeWqHiUmMBU/2H7Nmit8/vwP3/SbHeEctth7D4Gz2fBnEbokPc1NU8/j/1ZLw==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Extensions.Configuration": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Diagnostics.Abstractions": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Options.ConfigurationExtensions": "9.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Microsoft.Extensions.Diagnostics.Abstractions": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "1K8P7XzuzX8W8pmXcZjcrqS6x5eSSdvhQohmcpgiQNY/HlDAlnrhR9dvlURfFz428A+RTCJpUyB+aKTA6AgVcQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Options": "9.0.0",
|
||||||
|
"System.Diagnostics.DiagnosticSource": "9.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Microsoft.Extensions.Http": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "DqI4q54U4hH7bIAq9M5a/hl5Odr/KBAoaZ0dcT4OgutD8dook34CbkvAfAIzkMVjYXiL+E5ul9etwwqiX4PHGw==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
|
||||||
|
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Diagnostics": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Logging": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Logging.Abstractions": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Options": "9.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"Microsoft.Extensions.Logging": {
|
"Microsoft.Extensions.Logging": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.1",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "4x+pzsQEbqxhNf1QYRr5TDkLP9UsLT3A6MdRKDDEgrW7h1ljiEPgTNhKYUhNCCAaVpQECVQ+onA91PTPnIp6Lw==",
|
"contentHash": "crjWyORoug0kK7RSNJBTeSE6VX8IQgLf3nUpTB9m62bPXp/tzbnOsnbe8TXEG0AASNaKZddnpHKw7fET8E++Pg==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"Microsoft.Extensions.DependencyInjection": "8.0.1",
|
"Microsoft.Extensions.DependencyInjection": "9.0.0",
|
||||||
"Microsoft.Extensions.Logging.Abstractions": "8.0.2",
|
"Microsoft.Extensions.Logging.Abstractions": "9.0.0",
|
||||||
"Microsoft.Extensions.Options": "8.0.2"
|
"Microsoft.Extensions.Options": "9.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.Logging.Abstractions": {
|
"Microsoft.Extensions.Logging.Abstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.2",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "nroMDjS7hNBPtkZqVBbSiQaQjWRDxITI8Y7XnDs97rqG3EbzVTNLZQf7bIeUJcaHOV8bca47s1Uxq94+2oGdxA==",
|
"contentHash": "g0UfujELzlLbHoVG8kPKVBaW470Ewi+jnptGS9KUi6jcb+k2StujtK3m26DFSGGwQ/+bVgZfsWqNzlP6YOejvw==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
|
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||||
|
"System.Diagnostics.DiagnosticSource": "9.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.Options": {
|
"Microsoft.Extensions.Options": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.2",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "dWGKvhFybsaZpGmzkGCbNNwBD1rVlWzrZKANLW/CcbFJpCEceMCGzT7zZwHOGBCbwM0SzBuceMj5HN1LKV1QqA==",
|
"contentHash": "y2146b3jrPI3Q0lokKXdKLpmXqakYbDIPDV6r3M8SqvSf45WwOTzkyfDpxnZXJsJQEpAsAqjUq5Pu8RCJMjubg==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0",
|
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||||
"Microsoft.Extensions.Primitives": "8.0.0"
|
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Microsoft.Extensions.Options.ConfigurationExtensions": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "Ob3FXsXkcSMQmGZi7qP07EQ39kZpSBlTcAZLbJLdI4FIf0Jug8biv2HTavWmnTirchctPlq9bl/26CXtQRguzA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Configuration.Binder": "9.0.0",
|
||||||
|
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Options": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.Primitives": {
|
"Microsoft.Extensions.Primitives": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.0",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "bXJEZrW9ny8vjMF1JV253WeLhpEVzFo1lyaZu1vQ4ZxWUlVvknZ/+ftFgVheLubb4eZPSwwxBeqS1JkCOjxd8g=="
|
"contentHash": "N3qEBzmLMYiASUlKxxFIISP4AiwuPTHF5uCh+2CWSwwzAJiIYx0kBJsS30cp1nvhSySFAVi30jecD307jV+8Kg=="
|
||||||
},
|
},
|
||||||
"Microsoft.IdentityModel.Abstractions": {
|
"Microsoft.IdentityModel.Abstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
|
|
@ -340,6 +434,14 @@
|
||||||
"System.CodeDom": "4.4.0"
|
"System.CodeDom": "4.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"NSec.Cryptography": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "25.4.0",
|
||||||
|
"contentHash": "Z3wPpG0xefMLmhn9T+Ka/EzAmMQPT0THL/5E4lf9cXI/N9rbGH0G23ZFpRcPnD0ast2k7ieG6QSVNIjmfPCXBQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"libsodium": "[1.0.20.1, 1.0.21)"
|
||||||
|
}
|
||||||
|
},
|
||||||
"OpenIddict.Abstractions": {
|
"OpenIddict.Abstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "7.7.1",
|
"resolved": "7.7.1",
|
||||||
|
|
@ -448,11 +550,21 @@
|
||||||
"System.Composition.Runtime": "6.0.0"
|
"System.Composition.Runtime": "6.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"System.Diagnostics.DiagnosticSource": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "ddppcFpnbohLWdYKr/ZeLZHmmI+DXFgZ3Snq+/E7SwcdW4UnvxmaugkwGywvGVWkHPGCSZjCP+MLzu23AL5SDw=="
|
||||||
|
},
|
||||||
"System.Formats.Asn1": {
|
"System.Formats.Asn1": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "10.0.2",
|
"resolved": "10.0.2",
|
||||||
"contentHash": "9Hee6iQ74pDgdRNIL6lO8Vlx2onVWd5aDnqwk4Pvo0h5FklBd7QwcQDKgxeLuhiy0o3ibzUVO0KFQe0/hPXU+Q=="
|
"contentHash": "9Hee6iQ74pDgdRNIL6lO8Vlx2onVWd5aDnqwk4Pvo0h5FklBd7QwcQDKgxeLuhiy0o3ibzUVO0KFQe0/hPXU+Q=="
|
||||||
},
|
},
|
||||||
|
"System.Formats.Cbor": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.24",
|
||||||
|
"contentHash": "SEfEvHu6qXcXoDsDKagddLDf8A9iHIhHUD0hGemdmwlP206KLLCI5ksskOpeXMgNpQCs2diB0fOBKcnjySHFUQ=="
|
||||||
|
},
|
||||||
"System.IO.Pipelines": {
|
"System.IO.Pipelines": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "6.0.3",
|
"resolved": "6.0.3",
|
||||||
|
|
|
||||||
125
src/Bifrost.Web/wwwroot/js/passkeys.js
Normal file
125
src/Bifrost.Web/wwwroot/js/passkeys.js
Normal file
|
|
@ -0,0 +1,125 @@
|
||||||
|
// The Linked accounts page's passkey ceremonies (docs/passkeys.md). First-party, no dependency. It asks the server for
|
||||||
|
// WebAuthn options, calls navigator.credentials, and posts back only base64url strings in a same-origin form. Nothing it
|
||||||
|
// reads from the options is shown or evaluated; the server checks the origin, the challenge and the signature.
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
var status = document.getElementById("passkey-status");
|
||||||
|
|
||||||
|
function say(text) {
|
||||||
|
if (status) {
|
||||||
|
status.textContent = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBytes(value) {
|
||||||
|
var padded = value.replace(/-/g, "+").replace(/_/g, "/");
|
||||||
|
while (padded.length % 4) {
|
||||||
|
padded += "=";
|
||||||
|
}
|
||||||
|
var raw = atob(padded);
|
||||||
|
var bytes = new Uint8Array(raw.length);
|
||||||
|
for (var i = 0; i < raw.length; i++) {
|
||||||
|
bytes[i] = raw.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return bytes.buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toText(buffer) {
|
||||||
|
var bytes = new Uint8Array(buffer);
|
||||||
|
var raw = "";
|
||||||
|
for (var i = 0; i < bytes.length; i++) {
|
||||||
|
raw += String.fromCharCode(bytes[i]);
|
||||||
|
}
|
||||||
|
return btoa(raw).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function token(form) {
|
||||||
|
var field = form.querySelector("input[name=__RequestVerificationToken]");
|
||||||
|
return field ? field.value : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Posts to a handler of this page with the form's antiforgery token and returns the parsed JSON, or throws.
|
||||||
|
function options(handler, form, fields) {
|
||||||
|
return fetch(location.pathname + "?handler=" + handler, {
|
||||||
|
method: "POST",
|
||||||
|
credentials: "same-origin",
|
||||||
|
headers: { "RequestVerificationToken": token(form), "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams(fields)
|
||||||
|
}).then(function (response) {
|
||||||
|
return response.json().then(function (body) {
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body && body.error ? body.error : "error");
|
||||||
|
}
|
||||||
|
return body;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function descriptors(list) {
|
||||||
|
return (list || []).map(function (item) {
|
||||||
|
var copy = { type: item.type, id: toBytes(item.id) };
|
||||||
|
if (item.transports) {
|
||||||
|
copy.transports = item.transports;
|
||||||
|
}
|
||||||
|
return copy;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function set(form, name, value) {
|
||||||
|
form.elements[name].value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function failed(error) {
|
||||||
|
var code = error && error.message ? error.message : "error";
|
||||||
|
location.assign(location.pathname + "?result=" + (/^[a-z_]+$/.test(code) && code !== "error" ? encodeURIComponent(code) : "passkey_failed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll("form[data-passkey-enrol]").forEach(function (form) {
|
||||||
|
form.addEventListener("submit", function (event) {
|
||||||
|
if (form.dataset.ready === "1") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
say("Waiting for your device...");
|
||||||
|
options("PasskeyEnrolOptions", form, {}).then(function (created) {
|
||||||
|
created.challenge = toBytes(created.challenge);
|
||||||
|
created.user.id = toBytes(created.user.id);
|
||||||
|
created.excludeCredentials = descriptors(created.excludeCredentials);
|
||||||
|
return navigator.credentials.create({ publicKey: created });
|
||||||
|
}).then(function (credential) {
|
||||||
|
set(form, "id", credential.id);
|
||||||
|
set(form, "rawId", toText(credential.rawId));
|
||||||
|
set(form, "attestationObject", toText(credential.response.attestationObject));
|
||||||
|
set(form, "clientDataJson", toText(credential.response.clientDataJSON));
|
||||||
|
set(form, "transports", credential.response.getTransports ? credential.response.getTransports().join(",") : "");
|
||||||
|
form.dataset.ready = "1";
|
||||||
|
form.submit();
|
||||||
|
}).catch(failed);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll("form[data-passkey-unlink]").forEach(function (form) {
|
||||||
|
form.addEventListener("submit", function (event) {
|
||||||
|
if (form.dataset.ready === "1") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
say("Waiting for your device...");
|
||||||
|
options("PasskeyChallenge", form, { identityId: form.elements.identityId.value }).then(function (requested) {
|
||||||
|
requested.challenge = toBytes(requested.challenge);
|
||||||
|
requested.allowCredentials = descriptors(requested.allowCredentials);
|
||||||
|
return navigator.credentials.get({ publicKey: requested });
|
||||||
|
}).then(function (credential) {
|
||||||
|
set(form, "id", credential.id);
|
||||||
|
set(form, "rawId", toText(credential.rawId));
|
||||||
|
set(form, "authenticatorData", toText(credential.response.authenticatorData));
|
||||||
|
set(form, "clientDataJson", toText(credential.response.clientDataJSON));
|
||||||
|
set(form, "signature", toText(credential.response.signature));
|
||||||
|
set(form, "userHandle", credential.response.userHandle ? toText(credential.response.userHandle) : "");
|
||||||
|
form.dataset.ready = "1";
|
||||||
|
form.submit();
|
||||||
|
}).catch(failed);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
439
tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs
Normal file
439
tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs
Normal file
|
|
@ -0,0 +1,439 @@
|
||||||
|
using System.Net;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Tests.Support;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Tests;
|
||||||
|
|
||||||
|
/// <summary>A folded member's browser and Heimdall's patron intake, over HTTP: the merge ledger is the single gate behind both.</summary>
|
||||||
|
public sealed class AccountMergeHttpTests(TestWebApplicationFactory factory) : IClassFixture<TestWebApplicationFactory>
|
||||||
|
{
|
||||||
|
private sealed record Seeded(Guid Survivor, Guid Folded, Guid Motion, string FoldedHeimdallId, long SurvivorGitHubId, long FoldedGitHubId);
|
||||||
|
|
||||||
|
private async Task<Seeded> SeedAsync()
|
||||||
|
{
|
||||||
|
using var scope = factory.Services.CreateScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||||
|
var seed = Random.Shared.NextInt64(1_000_000, 900_000_000);
|
||||||
|
UserAccount Make(string name, long gitHubId) => new()
|
||||||
|
{
|
||||||
|
DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = name, GitHubUserId = gitHubId, GitHubLogin = name, NormalizedGitHubLogin = name,
|
||||||
|
HeimdallAccountId = "hd-" + name,
|
||||||
|
MemberProfile = new MemberProfile { Nickname = name, Headline = "seed", UpdatedAtUtc = DateTimeOffset.UtcNow },
|
||||||
|
Membership = new Bifrost.Web.Domain.Membership { Status = MembershipStatus.Active, ApprovedAtUtc = DateTimeOffset.UtcNow }
|
||||||
|
};
|
||||||
|
var survivor = Make($"surv-{seed}", seed);
|
||||||
|
var folded = Make($"fold-{seed}", seed + 1);
|
||||||
|
db.UserAccounts.AddRange(survivor, folded);
|
||||||
|
var motion = new Motion
|
||||||
|
{
|
||||||
|
CreatedByUserAccountId = survivor.Id, Title = "Open motion", Status = MotionStatus.Open, OpensAtUtc = DateTimeOffset.UtcNow.AddHours(-1),
|
||||||
|
ClosesAtUtc = DateTimeOffset.UtcNow.AddDays(2), CreatedAtUtc = DateTimeOffset.UtcNow
|
||||||
|
};
|
||||||
|
db.Motions.Add(motion);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
return new Seeded(survivor.Id, folded.Id, motion.Id, folded.HeimdallAccountId, seed, seed + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpClient ClientFor(long gitHubId, string login)
|
||||||
|
{
|
||||||
|
var client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, BaseAddress = new Uri("https://localhost"), HandleCookies = true });
|
||||||
|
client.DefaultRequestHeaders.Add("X-Test-GitHub-Id", gitHubId.ToString());
|
||||||
|
client.DefaultRequestHeaders.Add("X-Test-GitHub-Login", login);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<string> TokenAsync(HttpClient client)
|
||||||
|
{
|
||||||
|
using var page = await client.GetAsync("/App/Motions");
|
||||||
|
var html = await page.Content.ReadAsStringAsync();
|
||||||
|
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
|
||||||
|
Assert.NotEmpty(token);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task<HttpResponseMessage> VoteAsync(HttpClient client, Guid motion, string token) =>
|
||||||
|
client.PostAsync("/App/Motions?handler=Vote", new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["motionId"] = motion.ToString(), ["choice"] = "For", ["comment"] = "yes", ["__RequestVerificationToken"] = token
|
||||||
|
}));
|
||||||
|
|
||||||
|
private async Task<T> WithDb<T>(Func<BifrostDbContext, Task<T>> read)
|
||||||
|
{
|
||||||
|
using var scope = factory.Services.CreateScope();
|
||||||
|
return await read(scope.ServiceProvider.GetRequiredService<BifrostDbContext>());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<int> VoteRowsAsync(Guid motion) => WithDb(db => db.Votes.IgnoreQueryFilters().CountAsync(x => x.MotionId == motion));
|
||||||
|
|
||||||
|
private async Task<Guid> MergeAsync(Seeded s, AccountMergeState state)
|
||||||
|
{
|
||||||
|
using var scope = factory.Services.CreateScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||||
|
var merge = new AccountMerge { SurvivorUserAccountId = s.Survivor, FoldedUserAccountId = s.Folded, State = state, CreatedUtc = DateTimeOffset.UtcNow };
|
||||||
|
db.AccountMerges.Add(merge);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
return merge.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SetStateAsync(Guid mergeId, AccountMergeState state) =>
|
||||||
|
await WithDb(async db =>
|
||||||
|
{
|
||||||
|
(await db.AccountMerges.SingleAsync(x => x.Id == mergeId)).State = state;
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_folded_session_cookie_acts_as_nobody_while_Frozen_and_after_Committed_and_the_survivor_still_votes()
|
||||||
|
{
|
||||||
|
var s = await SeedAsync();
|
||||||
|
using var folded = ClientFor(s.FoldedGitHubId, $"fold-{s.SurvivorGitHubId}");
|
||||||
|
var token = await TokenAsync(folded); // a live, valid form from before the merge: the cookie outlives the merge
|
||||||
|
var merge = await MergeAsync(s, AccountMergeState.Confirmed);
|
||||||
|
|
||||||
|
using (var whileFrozen = await VoteAsync(folded, s.Motion, token))
|
||||||
|
{
|
||||||
|
Assert.NotEqual(HttpStatusCode.OK, whileFrozen.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(0, await VoteRowsAsync(s.Motion));
|
||||||
|
using (var page = await folded.GetAsync("/App/Motions"))
|
||||||
|
{
|
||||||
|
Assert.NotEqual(HttpStatusCode.OK, page.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
await SetStateAsync(merge, AccountMergeState.HeimdallMoved);
|
||||||
|
await SetStateAsync(merge, AccountMergeState.Committed);
|
||||||
|
using (var afterCommit = await VoteAsync(folded, s.Motion, token))
|
||||||
|
{
|
||||||
|
Assert.NotEqual(HttpStatusCode.OK, afterCommit.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(0, await VoteRowsAsync(s.Motion));
|
||||||
|
|
||||||
|
using var survivor = ClientFor(s.SurvivorGitHubId, $"surv-{s.SurvivorGitHubId}");
|
||||||
|
using var control = await VoteAsync(survivor, s.Motion, await TokenAsync(survivor));
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, control.StatusCode);
|
||||||
|
Assert.Equal(1, await VoteRowsAsync(s.Motion));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<HttpStatusCode> 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<List<Guid>> EventOwnersAsync(Seeded s) =>
|
||||||
|
WithDb(db => db.PatronSupportEvents.Where(x => x.UserAccountId == s.Survivor || x.UserAccountId == s.Folded).Select(x => x.UserAccountId).ToListAsync());
|
||||||
|
|
||||||
|
/// <summary>Lands the merge through the ledger's own commit, as the saga will: the move done, then the Bifrost records reduced.</summary>
|
||||||
|
private async Task<Guid> CommitMergeAsync(Seeded s)
|
||||||
|
{
|
||||||
|
var merge = await MergeAsync(s, AccountMergeState.HeimdallMoved);
|
||||||
|
await WithDb(async db =>
|
||||||
|
{
|
||||||
|
using var scope = factory.Services.CreateScope();
|
||||||
|
await scope.ServiceProvider.GetRequiredService<Bifrost.Web.Features.Membership.AccountMergeLedger>().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<Bifrost.Web.Features.Membership.AccountMergeLedger>().UndoLocalAsync(merge, default);
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.Equal([s.Folded], await EventOwnersAsync(s));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<List<AccountMergeEntry>> 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<Bifrost.Web.Features.Membership.AccountMergeLedger>().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<HttpResponseMessage> 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<string, string> { ["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<Bifrost.Web.Features.Membership.AccountMergeLedger>().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<Bifrost.Web.Features.Patronage.PatronageService>().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<string, string>
|
||||||
|
{
|
||||||
|
["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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Forbid answers 403 or sends the browser to the access-denied page; either way the page and its Heimdall flows are not served.</summary>
|
||||||
|
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<string, string>
|
||||||
|
{
|
||||||
|
["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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The desk's bearer door judges standing the way the cookie gate and the chat refusal do.</summary>
|
||||||
|
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<DeskReply> 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<BifrostDbContext>();
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
1121
tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs
Normal file
1121
tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs
Normal file
File diff suppressed because it is too large
Load diff
981
tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs
Normal file
981
tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs
Normal file
|
|
@ -0,0 +1,981 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
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<string> _databases = [];
|
||||||
|
|
||||||
|
private static string? Admin => Environment.GetEnvironmentVariable(PostgresGate.Variable);
|
||||||
|
|
||||||
|
public Task InitializeAsync() => Task.CompletedTask;
|
||||||
|
|
||||||
|
/// <summary>A fresh database, built by the real migrations, and a world over it.</summary>
|
||||||
|
public async Task<AccountMergeLedgerTests.World> NewWorldAsync()
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
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<MergePostgres>
|
||||||
|
{
|
||||||
|
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}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Runs an action once, just before the first save of a context: the rival writer that lands inside a read-then-save window.</summary>
|
||||||
|
private sealed class BeforeFirstSave(Func<Task> rival) : SaveChangesInterceptor
|
||||||
|
{
|
||||||
|
private int _fired;
|
||||||
|
|
||||||
|
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (Interlocked.Exchange(ref _fired, 1) == 0)
|
||||||
|
{
|
||||||
|
await rival();
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Holds each of two contexts at its save until both have arrived, so both have read before either writes.</summary>
|
||||||
|
private sealed class Rendezvous : SaveChangesInterceptor
|
||||||
|
{
|
||||||
|
private readonly Barrier _barrier = new(2);
|
||||||
|
|
||||||
|
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
await Task.Run(() => _barrier.SignalAndWait(TimeSpan.FromSeconds(30)), cancellationToken);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<Exception> 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<DbUpdateException>(() => 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<DbUpdateException>(() => 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<Exception?> 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<DbUpdateConcurrencyException>(() => 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<DbUpdateException>(() => world.SetStateAsync(second, AccountMergeState.Confirmed));
|
||||||
|
Assert.Equal(("23505", "UX_AccountMerges_FoldedUserAccountId_Live"), (Pg(refused).SqlState, Pg(refused).ConstraintName));
|
||||||
|
var inserted = await Assert.ThrowsAsync<DbUpdateException>(() => 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<DbUpdateException>(() => 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<DbUpdateException>(() => 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<Exception>(() => db.GetService<IMigrator>().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<IMigrator>().MigrateAsync("20261113120000_AddPasskeyCredentials");
|
||||||
|
Assert.Equal("20261113120000_AddPasskeyCredentials", (await down.Database.GetAppliedMigrationsAsync()).Last());
|
||||||
|
await down.GetService<IMigrator>().MigrateAsync(); // and up again, trigger and index and all
|
||||||
|
Assert.Equal("20261114140000_AddAccountMergeNoticeAcks", (await down.Database.GetAppliedMigrationsAsync()).Last());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 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<Exception?> 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<Exception>(), 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<IMigrator>().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<IMigrator>().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<Exception>(() => db.GetService<IMigrator>().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<AccountMerge>? 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<AccountMerge>? 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<AccountMerge>? 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 ----
|
||||||
|
|
||||||
|
/// <summary>Holds the first save of each of two contexts until both have arrived: both have read, neither has written.</summary>
|
||||||
|
private sealed class FirstSaveRendezvous : SaveChangesInterceptor
|
||||||
|
{
|
||||||
|
private readonly Barrier _barrier = new(2);
|
||||||
|
private readonly HashSet<Guid> _seen = [];
|
||||||
|
|
||||||
|
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The fake Heimdall's account model behind the real move client, one key ring for every saga built over it.</summary>
|
||||||
|
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<HeimdallIdentityMoveClient>.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<AccountMergeSaga>.Instance);
|
||||||
|
|
||||||
|
/// <summary>A world account with one login at the fake Heimdall and a weak proof through it.</summary>
|
||||||
|
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<ConfirmOutcome.Confirmed>(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<AccountMerge> 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<Guid, (MergeProof Survivor, string Digest)>();
|
||||||
|
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<ConfirmOutcome> 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<ConfirmOutcome.Confirmed>());
|
||||||
|
var blocked = Assert.Single(results.OfType<ConfirmOutcome.Blocked>());
|
||||||
|
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<Exception>(() =>
|
||||||
|
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<ConfirmOutcome.Confirmed>(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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A Confirmed merge with sealed proofs, stopped on the given outcome, and the operator who will settle it.</summary>
|
||||||
|
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<ConfirmOutcome.Confirmed>(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<SettleOutcome.Lost>(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<DbUpdateException>(() => 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<SettleOutcome> 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<SettleOutcome.Settled>());
|
||||||
|
Assert.Single(both.OfType<SettleOutcome.Lost>());
|
||||||
|
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<Exception>(() => db.GetService<IMigrator>().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<IMigrator>().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<IMigrator>().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<long> 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())!;
|
||||||
|
}
|
||||||
|
}
|
||||||
732
tests/Bifrost.Web.Tests/AccountMergeSagaTests.cs
Normal file
732
tests/Bifrost.Web.Tests/AccountMergeSagaTests.cs
Normal file
|
|
@ -0,0 +1,732 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AccountMergeSagaTests
|
||||||
|
{
|
||||||
|
private const string Passkey = "bifrost-passkey";
|
||||||
|
|
||||||
|
internal sealed record Party(Guid Id, string HeimdallId, IReadOnlyDictionary<string, string> Logins);
|
||||||
|
|
||||||
|
/// <summary>A host plus the helpers every test needs: accounts with logins at the fake Heimdall, proofs, a scope per operation.</summary>
|
||||||
|
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<Party> 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<BifrostDbContext>();
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A fresh sign-in through the login of <paramref name="provider"/>: a weak proof of that login only.</summary>
|
||||||
|
public MergeProof Weak(Party who, string provider) => new(Moves.Issue(who.HeimdallId, who.Logins[provider]), who.HeimdallId, provider);
|
||||||
|
|
||||||
|
/// <summary>A fresh sign-in of <paramref name="holder"/> through a login that came from <paramref name="origin"/> (a login the merge moved to it).</summary>
|
||||||
|
public MergeProof Moved(Party holder, Party origin, string provider) => new(Moves.Issue(holder.HeimdallId, origin.Logins[provider]), holder.HeimdallId, provider);
|
||||||
|
|
||||||
|
/// <summary>A passkey assertion: a strong proof that speaks for the whole account.</summary>
|
||||||
|
public MergeProof Strong(Party who) => new(Moves.Issue(who.HeimdallId, stepUpMethod: Passkey), who.HeimdallId, "passkey");
|
||||||
|
|
||||||
|
public async Task<T> InScopeAsync<T>(Func<IServiceProvider, Task<T>> work)
|
||||||
|
{
|
||||||
|
using var scope = Host.Services.CreateScope();
|
||||||
|
return await work(scope.ServiceProvider);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string> DigestAsync(Party survivor, Party folded) =>
|
||||||
|
await InScopeAsync(async sp => (await sp.GetRequiredService<AccountMergeLedger>().PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id));
|
||||||
|
|
||||||
|
public async Task<ConfirmOutcome> ConfirmAsync(Party survivor, Party folded, MergeProof survivorProof, params MergeProof[] foldedProofs)
|
||||||
|
{
|
||||||
|
var digest = await DigestAsync(survivor, folded);
|
||||||
|
return await InScopeAsync(sp => sp.GetRequiredService<AccountMergeSaga>().ConfirmAsync(
|
||||||
|
new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, digest, survivorProof, foldedProofs), default));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Guid> ConfirmedAsync(Party survivor, Party folded, MergeProof survivorProof, params MergeProof[] foldedProofs) =>
|
||||||
|
Assert.IsType<ConfirmOutcome.Confirmed>(await ConfirmAsync(survivor, folded, survivorProof, foldedProofs)).MergeId;
|
||||||
|
|
||||||
|
public Task<AccountMerge> AdvanceAsync(Guid id) => InScopeAsync(sp => sp.GetRequiredService<AccountMergeSaga>().AdvanceAsync(id, default));
|
||||||
|
|
||||||
|
public Task<int> AdvanceDueAsync() => InScopeAsync(sp => sp.GetRequiredService<AccountMergeSaga>().AdvanceDueAsync(Clock.Now, default));
|
||||||
|
|
||||||
|
public Task<AccountMerge> MergeAsync(Guid id) =>
|
||||||
|
InScopeAsync(sp => sp.GetRequiredService<BifrostDbContext>().AccountMerges.AsNoTracking().SingleAsync(x => x.Id == id));
|
||||||
|
|
||||||
|
public Task<List<AccountMergeEntry>> JournalAsync(Guid id) =>
|
||||||
|
InScopeAsync(sp => sp.GetRequiredService<BifrostDbContext>().AccountMergeEntries.Where(x => x.MergeId == id).ToListAsync());
|
||||||
|
|
||||||
|
public Task<MergeStanding?> StandingAsync(Party who) =>
|
||||||
|
InScopeAsync(sp => sp.GetRequiredService<AccountMergeLedger>().StandingAsync(who.Id, default));
|
||||||
|
|
||||||
|
public Task<int> MergeCountAsync() => InScopeAsync(sp => sp.GetRequiredService<BifrostDbContext>().AccountMerges.CountAsync());
|
||||||
|
|
||||||
|
public async Task<Motion> MotionAsync(Party author)
|
||||||
|
{
|
||||||
|
using var scope = Host.Services.CreateScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||||
|
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<BifrostDbContext>();
|
||||||
|
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<string[]> 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<MergeStanding.Frozen>(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<string[]>(final.MovedIdentityIds!)!.Order());
|
||||||
|
Assert.IsType<MergeStanding.Folded>(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<BifrostDbContext>();
|
||||||
|
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<BifrostDbContext>();
|
||||||
|
(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<AccountMerge>().Any(x => x.Entity.State == AccountMergeState.HeimdallMoved);
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<InvalidOperationException>(() => 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<AccountMerge>().Any(x => x.Entity.State == AccountMergeState.Committed);
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<InvalidOperationException>(() => 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Starts the production sweeper (its first pass runs at once, before its 30 s timer) and stops it once the pass is over.</summary>
|
||||||
|
private static async Task RunOneSweepAsync(Rig rig)
|
||||||
|
{
|
||||||
|
var sweeper = new AccountMergeSweeper(rig.Host.Services.GetRequiredService<IServiceScopeFactory>(), rig.Clock, NullLogger<AccountMergeSweeper>.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<BifrostDbContext>().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<HeimdallMoveOutcome.Moved>(await rig.InScopeAsync(sp => sp.GetRequiredService<HeimdallIdentityMoveClient>().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<BifrostDbContext>().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<ConfirmOutcome> Confirm(Guid actor, string digestSeen, MergeProof survivorProof, params MergeProof[] proofs) =>
|
||||||
|
rig.InScopeAsync(sp => sp.GetRequiredService<AccountMergeSaga>().ConfirmAsync(
|
||||||
|
new ConfirmMergeRequest(actor, survivor.Id, folded.Id, digestSeen, survivorProof, proofs), default));
|
||||||
|
|
||||||
|
Assert.IsType<ConfirmOutcome.NotParty>(await Confirm(stranger.Id, digest, good, foldedProof));
|
||||||
|
Assert.IsType<ConfirmOutcome.ProofAccountMismatch>(await Confirm(survivor.Id, digest, rig.Weak(stranger, "github"), foldedProof));
|
||||||
|
Assert.IsType<ConfirmOutcome.ProofAccountMismatch>(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<ConfirmOutcome.PreviewStale>(await Confirm(survivor.Id, digest, good, foldedProof));
|
||||||
|
Assert.Equal(0, await rig.MergeCountAsync());
|
||||||
|
|
||||||
|
var blocked = Assert.IsType<ConfirmOutcome.Blocked>(await rig.InScopeAsync(sp => sp.GetRequiredService<AccountMergeSaga>().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<ConfirmOutcome.Confirmed>(await Confirm(survivor.Id, fresh, good, foldedProof));
|
||||||
|
var second = Assert.IsType<ConfirmOutcome.Blocked>(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<ArgumentException>(() =>
|
||||||
|
rig.InScopeAsync(sp => sp.GetRequiredService<AccountMergeSaga>().ConfirmAsync(request with { FoldedProofs = nine }, default)));
|
||||||
|
var tooLong = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||||
|
rig.InScopeAsync(sp => sp.GetRequiredService<AccountMergeSaga>().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<UndoOutcome.Requested>(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<UndoOutcome> RequestUndoAsync(Rig rig, Guid id, Party actor, params MergeProof[] proofs) =>
|
||||||
|
rig.InScopeAsync(sp => sp.GetRequiredService<AccountMergeSaga>().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<BifrostDbContext>();
|
||||||
|
(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<BifrostDbContext>();
|
||||||
|
(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<MergeStanding.Frozen>(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<MergeStanding.Frozen>(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<UndoOutcome.Requested>(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<MergeStanding.Folded>(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<UndoOutcome.Requested>(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<MergeStanding.Folded>(await rig.StandingAsync(folded));
|
||||||
|
|
||||||
|
rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromMinutes(1));
|
||||||
|
await rig.InScopeAsync(async sp =>
|
||||||
|
{
|
||||||
|
await sp.GetRequiredService<AccountMergeSaga>().AdvanceDueAsync(rig.Clock.Now, default);
|
||||||
|
return await sp.GetRequiredService<AccountMergeLedger>().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<UndoOutcome.NotCommitted>(await RequestUndoAsync(rig, id, survivor, rig.Weak(survivor, "twitch")));
|
||||||
|
Assert.IsType<UndoOutcome.NotCommitted>(await RequestUndoAsync(rig, Guid.NewGuid(), survivor, rig.Weak(survivor, "twitch")));
|
||||||
|
await rig.AdvanceAsync(id);
|
||||||
|
|
||||||
|
Assert.IsType<UndoOutcome.NotSurvivor>(await RequestUndoAsync(rig, id, folded, rig.Weak(folded, "discord")));
|
||||||
|
Assert.IsType<UndoOutcome.ProofAccountMismatch>(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<UndoOutcome.GraceOver>(await RequestUndoAsync(rig, id, survivor, proof)); // Committed, but the grace ended
|
||||||
|
await rig.InScopeAsync(sp => sp.GetRequiredService<AccountMergeLedger>().FinalizeDueAsync(rig.Clock.Now, default));
|
||||||
|
Assert.IsType<UndoOutcome.GraceOver>(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<BifrostDbContext>();
|
||||||
|
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<BifrostDbContext>().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<UndoOutcome.GraceOver>(await RequestUndoAsync(rig, id, survivor, rig.Weak(survivor, "twitch")));
|
||||||
|
rig.Clock.Advance(TimeSpan.FromSeconds(-1));
|
||||||
|
Assert.IsType<UndoOutcome.Requested>(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<string> { "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<UndoOutcome.Requested>(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<Bifrost.Web.Features.Membership.AccountMergeSaga>", 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");
|
||||||
|
}
|
||||||
|
}
|
||||||
160
tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs
Normal file
160
tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs
Normal file
|
|
@ -0,0 +1,160 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
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<World> 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<BifrostDbContext>();
|
||||||
|
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<HttpResponseMessage> 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<string, string> { ["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<BifrostDbContext>().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);
|
||||||
|
}
|
||||||
|
}
|
||||||
292
tests/Bifrost.Web.Tests/AccountMergeSettleTests.cs
Normal file
292
tests/Bifrost.Web.Tests/AccountMergeSettleTests.cs
Normal file
|
|
@ -0,0 +1,292 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AccountMergeSettleTests
|
||||||
|
{
|
||||||
|
private static readonly Guid Operator = Guid.NewGuid();
|
||||||
|
|
||||||
|
internal sealed record Stuck(Guid Id, Party Survivor, Party Folded);
|
||||||
|
|
||||||
|
/// <summary>A Confirmed merge that is stuck on <paramref name="outcome"/>: the two the saga records itself are reached through the real step, the third is the stored Unknown reason.</summary>
|
||||||
|
internal static async Task<Stuck> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A merge in UndoRequested whose reversal got a receipt for another account.</summary>
|
||||||
|
internal static async Task<Stuck> 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<AccountMergeSaga>().RequestUndoAsync(id, survivor.Id, [rig.Moved(survivor, folded, "discord")], default));
|
||||||
|
Assert.IsType<UndoOutcome.Requested>(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<BifrostDbContext> change) => rig.InScopeAsync(async sp =>
|
||||||
|
{
|
||||||
|
var db = sp.GetRequiredService<BifrostDbContext>();
|
||||||
|
change(db);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
internal static Task EditMerge(Rig rig, Guid id, Action<AccountMerge> change) => Edit(rig, db => change(db.AccountMerges.Single(x => x.Id == id)));
|
||||||
|
|
||||||
|
private static Task<SettleOutcome> SettleAsync(Rig rig, Guid id, SettleChoice choice, string? typed) =>
|
||||||
|
rig.InScopeAsync(sp => sp.GetRequiredService<AccountMergeSaga>().SettleStuckAsync(id, choice, typed!, Operator, default));
|
||||||
|
|
||||||
|
private static Task<List<AuditEvent>> AuditAsync(Rig rig, Guid id) =>
|
||||||
|
rig.InScopeAsync(sp => sp.GetRequiredService<BifrostDbContext>().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<MergeStanding.Frozen>(await rig.StandingAsync(stuck.Folded));
|
||||||
|
var moveId = (await rig.MergeAsync(stuck.Id)).HeimdallMoveId!;
|
||||||
|
|
||||||
|
Assert.IsType<SettleOutcome.Settled>(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<SettleOutcome.Settled>(await SettleAsync(rig, stuck.Id, SettleChoice.FailForward, (await rig.MergeAsync(stuck.Id)).HeimdallMoveId));
|
||||||
|
|
||||||
|
Assert.IsType<ConfirmOutcome.Confirmed>(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<SettleOutcome.Settled>(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<MergeStanding.Folded>(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<AccountMergeLedger>().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<SettleOutcome.NotStuck>(await SettleAsync(rig, id, SettleChoice.FailForward, moveId));
|
||||||
|
await EditMerge(rig, id, x => { x.LastOutcome = "transport"; x.Attempts = 9; });
|
||||||
|
Assert.IsType<SettleOutcome.NotStuck>(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<SettleOutcome.NotStuck>(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<SettleOutcome.NotStuck>(await SettleAsync(rig, id, SettleChoice.FailForward, moveId));
|
||||||
|
Assert.IsType<SettleOutcome.NotStuck>(await SettleAsync(rig, id, SettleChoice.AbandonUndo, moveId));
|
||||||
|
Assert.Equal(state, (await rig.MergeAsync(id)).State);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsType<SettleOutcome.NotStuck>(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<SettleOutcome.WrongMoveId>(await SettleAsync(rig, stuck.Id, SettleChoice.FailForward, typed));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsType<SettleOutcome.WrongMoveId>(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<SettleOutcome.WrongMoveId>(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<AccountMerge>().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<SettleOutcome.Lost>(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<MergeStanding.Folded>(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<MergeProofs>();
|
||||||
|
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<IServiceScopeFactory>(), rig.Clock, NullLogger<AccountMergeSweeper>.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;
|
||||||
|
}
|
||||||
|
|
@ -36,6 +36,7 @@ public sealed class CookieHardeningTests(CookieHardeningTests.OAuthConfiguredFac
|
||||||
Assert.Equal("__Host-bifrost_antiforgery", BifrostCookies.Antiforgery);
|
Assert.Equal("__Host-bifrost_antiforgery", BifrostCookies.Antiforgery);
|
||||||
Assert.Equal("__Host-bifrost_voter", VoterKeyResolver.CookieName);
|
Assert.Equal("__Host-bifrost_voter", VoterKeyResolver.CookieName);
|
||||||
Assert.Equal("__Host-bifrost_heimdall_", HeimdallAttemptCookie.Prefix);
|
Assert.Equal("__Host-bifrost_heimdall_", HeimdallAttemptCookie.Prefix);
|
||||||
|
Assert.Equal("__Host-bifrost_passkey_ticket", BifrostCookies.PasskeyTicket);
|
||||||
Assert.All(HeimdallAttemptCookie.SlotNames, x => Assert.StartsWith("__Host-", x, StringComparison.Ordinal));
|
Assert.All(HeimdallAttemptCookie.SlotNames, x => Assert.StartsWith("__Host-", x, StringComparison.Ordinal));
|
||||||
Assert.Equal("/", BifrostCookies.Path);
|
Assert.Equal("/", BifrostCookies.Path);
|
||||||
Assert.Equal("/", VoterKeyResolver.CookiePath);
|
Assert.Equal("/", VoterKeyResolver.CookiePath);
|
||||||
|
|
|
||||||
168
tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs
Normal file
168
tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs
Normal file
|
|
@ -0,0 +1,168 @@
|
||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using Bifrost.Web.Tests.Support;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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<string, object?>
|
||||||
|
{
|
||||||
|
["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)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -35,12 +35,13 @@ function run(name, search, hash) {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
const form = {
|
const form = {
|
||||||
elements: { attempt: { value: "" }, code: { value: "" } },
|
elements: { attempt: { value: "" }, code: { value: "" }, pendingLinkId: { value: "" } },
|
||||||
submit() {
|
submit() {
|
||||||
events.push("submit");
|
events.push("submit");
|
||||||
submit = {
|
submit = {
|
||||||
attempt: form.elements.attempt.value,
|
attempt: form.elements.attempt.value,
|
||||||
code: form.elements.code.value,
|
code: form.elements.code.value,
|
||||||
|
pendingLinkId: form.elements.pendingLinkId.value,
|
||||||
href: location.href,
|
href: location.href,
|
||||||
hash: location.hash,
|
hash: location.hash,
|
||||||
};
|
};
|
||||||
|
|
@ -59,6 +60,14 @@ console.log(
|
||||||
run("error-status-with-code", "?attempt=NONCE", "#heimdall_status=error&heimdall_error=denied" + complete),
|
run("error-status-with-code", "?attempt=NONCE", "#heimdall_status=error&heimdall_error=denied" + complete),
|
||||||
run("no-code", "?attempt=NONCE", "#heimdall_status=success"),
|
run("no-code", "?attempt=NONCE", "#heimdall_status=success"),
|
||||||
run("no-attempt", "", "#heimdall_status=success" + complete),
|
run("no-attempt", "", "#heimdall_status=success" + complete),
|
||||||
|
run("link-return", "?attempt=NONCE", "#heimdall_status=success&heimdall_pending_link_id=PEND1"),
|
||||||
|
run("link-return-with-decoy-query-id", "?attempt=NONCE&heimdall_pending_link_id=QPEND", "#heimdall_status=success&heimdall_pending_link_id=PEND1"),
|
||||||
|
run("link-error-with-pending-id", "?attempt=NONCE", "#heimdall_status=error&heimdall_error=denied&heimdall_pending_link_id=PEND1"),
|
||||||
|
run("link-pending-id-in-query-only", "?attempt=NONCE&heimdall_pending_link_id=QPEND", ""),
|
||||||
|
run("link-refused-elsewhere", "?attempt=NONCE", "#heimdall_status=error&heimdall_error=link_initiator_mismatch"),
|
||||||
|
run("link-refused-elsewhere-no-attempt", "", "#heimdall_status=error&heimdall_error=link_initiator_mismatch"),
|
||||||
|
run("other-refusal-text", "?attempt=NONCE", "#heimdall_status=error&heimdall_error=%3Cb%3Ex&heimdall_error_description=EVIL"),
|
||||||
|
run("refusal-in-query-only", "?attempt=NONCE&heimdall_error=link_initiator_mismatch", ""),
|
||||||
run("code-in-query-only", "?attempt=NONCE&heimdall_completion_code=QCODE", ""),
|
run("code-in-query-only", "?attempt=NONCE&heimdall_completion_code=QCODE", ""),
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
|
|
|
||||||
96
tests/Bifrost.Web.Tests/Fixtures/passkey-script-harness.cjs
Normal file
96
tests/Bifrost.Web.Tests/Fixtures/passkey-script-harness.cjs
Normal file
|
|
@ -0,0 +1,96 @@
|
||||||
|
// Runs wwwroot/js/passkeys.js against a simulated browser, once per scenario, and prints what it did as JSON:
|
||||||
|
// every fetch (URL, headers, body), the arguments to navigator.credentials, the form values at the submit, and any navigation.
|
||||||
|
// Usage: node passkey-script-harness.cjs <passkeys.js>
|
||||||
|
const fs = require("fs");
|
||||||
|
const vm = require("vm");
|
||||||
|
|
||||||
|
const source = fs.readFileSync(process.argv[2], "utf8");
|
||||||
|
const buf = (...bytes) => Uint8Array.from(bytes).buffer;
|
||||||
|
|
||||||
|
function form(names, extra = {}) {
|
||||||
|
const elements = {};
|
||||||
|
for (const name of names) {
|
||||||
|
elements[name] = { value: "" };
|
||||||
|
}
|
||||||
|
Object.assign(elements, extra);
|
||||||
|
return {
|
||||||
|
elements,
|
||||||
|
dataset: {},
|
||||||
|
handler: null,
|
||||||
|
addEventListener(type, fn) {
|
||||||
|
if (type === "submit") this.handler = fn;
|
||||||
|
},
|
||||||
|
querySelector() {
|
||||||
|
return { value: "TOKEN" };
|
||||||
|
},
|
||||||
|
submit() {
|
||||||
|
this.submitted = Object.fromEntries(Object.entries(this.elements).map(([k, v]) => [k, v.value]));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function run(name, { kind, fetchReply, credentialsReply }) {
|
||||||
|
const enrol = kind === "enrol";
|
||||||
|
const theForm = enrol
|
||||||
|
? form(["id", "rawId", "attestationObject", "clientDataJson", "transports", "label"])
|
||||||
|
: form(["id", "rawId", "authenticatorData", "clientDataJson", "signature", "userHandle"], { identityId: { value: "IDENTITY" } });
|
||||||
|
const log = { name, fetches: [], credentialCall: null, navigations: [], status: "" };
|
||||||
|
const statusEl = { textContent: "" };
|
||||||
|
const document = {
|
||||||
|
getElementById: (id) => (id === "passkey-status" ? statusEl : null),
|
||||||
|
querySelectorAll: (selector) => (selector === (enrol ? "form[data-passkey-enrol]" : "form[data-passkey-unlink]") ? [theForm] : []),
|
||||||
|
};
|
||||||
|
const location = { pathname: "/Membership/LinkedAccounts", assign: (url) => log.navigations.push(url) };
|
||||||
|
const fetch = async (url, init) => {
|
||||||
|
log.fetches.push({ url, method: init.method, headers: init.headers, body: String(init.body), credentials: init.credentials });
|
||||||
|
return { ok: fetchReply.ok, json: async () => fetchReply.body };
|
||||||
|
};
|
||||||
|
const call = async (publicKey) => {
|
||||||
|
log.credentialCall = {
|
||||||
|
challengeIsBuffer: publicKey.challenge instanceof ArrayBuffer,
|
||||||
|
challengeBytes: Array.from(new Uint8Array(publicKey.challenge)),
|
||||||
|
userIdBytes: publicKey.user ? Array.from(new Uint8Array(publicKey.user.id)) : null,
|
||||||
|
listIdsAreBuffers: (publicKey.excludeCredentials || publicKey.allowCredentials).every((x) => x.id instanceof ArrayBuffer),
|
||||||
|
};
|
||||||
|
if (credentialsReply === "reject") throw new Error("NotAllowedError");
|
||||||
|
return credentialsReply;
|
||||||
|
};
|
||||||
|
const navigator = {
|
||||||
|
credentials: enrol ? { create: ({ publicKey }) => call(publicKey) } : { get: ({ publicKey }) => call(publicKey) },
|
||||||
|
};
|
||||||
|
vm.runInNewContext(source, { document, location, fetch, navigator, URLSearchParams, Uint8Array, ArrayBuffer, atob, btoa, Promise, Error });
|
||||||
|
await theForm.handler({ preventDefault() {} });
|
||||||
|
await new Promise((r) => setTimeout(r, 20));
|
||||||
|
log.submitted = theForm.submitted || null;
|
||||||
|
log.status = statusEl.textContent;
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const creationOptions = {
|
||||||
|
ok: true,
|
||||||
|
body: { challenge: "AQID", user: { id: "BAUG" }, excludeCredentials: [{ type: "public-key", id: "BwgJ" }] },
|
||||||
|
};
|
||||||
|
const requestOptions = {
|
||||||
|
ok: true,
|
||||||
|
body: { challenge: "AQID", allowCredentials: [{ type: "public-key", id: "BwgJ", transports: ["internal"] }] },
|
||||||
|
};
|
||||||
|
const created = {
|
||||||
|
id: "CRED-ID",
|
||||||
|
rawId: buf(251, 255, 254),
|
||||||
|
response: { attestationObject: buf(1, 2, 3), clientDataJSON: buf(4, 5), getTransports: () => ["internal", "hybrid"] },
|
||||||
|
};
|
||||||
|
const asserted = {
|
||||||
|
id: "CRED-ID",
|
||||||
|
rawId: buf(251, 255, 254),
|
||||||
|
response: { authenticatorData: buf(9, 9), clientDataJSON: buf(4, 5), signature: buf(7, 7, 7), userHandle: buf(1, 1) },
|
||||||
|
};
|
||||||
|
const out = [
|
||||||
|
await run("enrol", { kind: "enrol", fetchReply: creationOptions, credentialsReply: created }),
|
||||||
|
await run("unlink", { kind: "unlink", fetchReply: requestOptions, credentialsReply: asserted }),
|
||||||
|
await run("refused", { kind: "enrol", fetchReply: { ok: false, body: { error: "enrol_needs_sign_in" } }, credentialsReply: created }),
|
||||||
|
await run("hostile-error", { kind: "unlink", fetchReply: { ok: false, body: { error: "<script>alert(1)</script>" } }, credentialsReply: asserted }),
|
||||||
|
await run("cancelled", { kind: "unlink", fetchReply: requestOptions, credentialsReply: "reject" }),
|
||||||
|
];
|
||||||
|
console.log(JSON.stringify(out));
|
||||||
|
})();
|
||||||
157
tests/Bifrost.Web.Tests/HeimdallAppSecretFileTests.cs
Normal file
157
tests/Bifrost.Web.Tests/HeimdallAppSecretFileTests.cs
Normal file
|
|
@ -0,0 +1,157 @@
|
||||||
|
using Bifrost.Web.Configuration;
|
||||||
|
using Bifrost.Web.Tests.Support;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Tests;
|
||||||
|
|
||||||
|
public sealed class HeimdallAppSecretFileTests : IDisposable
|
||||||
|
{
|
||||||
|
private const string FileSecret = "file-secret-7f3a91c2";
|
||||||
|
private const string EnvSecret = "env-secret-0b5d44e8";
|
||||||
|
|
||||||
|
private readonly string _directory = Directory.CreateTempSubdirectory("bifrost-appsecret-").FullName;
|
||||||
|
private readonly CapturingLoggerProvider _logs = new();
|
||||||
|
|
||||||
|
public void Dispose() => Directory.Delete(_directory, recursive: true);
|
||||||
|
|
||||||
|
private string Write(string content)
|
||||||
|
{
|
||||||
|
var path = Path.Combine(_directory, Guid.NewGuid().ToString("N"));
|
||||||
|
File.WriteAllText(path, content);
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HeimdallOptions Resolve(string appSecret = "", string appSecretFile = "")
|
||||||
|
{
|
||||||
|
var options = new HeimdallOptions { AppSecret = appSecret, AppSecretFile = appSecretFile };
|
||||||
|
HeimdallOptions.ResolveAppSecret(options, _logs.CreateLogger("test"));
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void AssertNoSecretLogged()
|
||||||
|
{
|
||||||
|
foreach (var line in _logs.Lines)
|
||||||
|
{
|
||||||
|
Assert.DoesNotContain(FileSecret, line);
|
||||||
|
Assert.DoesNotContain(EnvSecret, line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData("\n")]
|
||||||
|
[InlineData("\r\n")]
|
||||||
|
public void The_file_is_the_secret_with_only_trailing_newlines_trimmed(string ending)
|
||||||
|
{
|
||||||
|
var options = Resolve(appSecretFile: Write(FileSecret + ending));
|
||||||
|
|
||||||
|
Assert.Equal(FileSecret, options.AppSecret);
|
||||||
|
Assert.False(options.IsDiscordConfigured); // no guild configured
|
||||||
|
Assert.True(options.IsPatreonConfigured);
|
||||||
|
Assert.Empty(_logs.Lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Inner_whitespace_survives_the_trim()
|
||||||
|
{
|
||||||
|
Assert.Equal(" a b ", Resolve(appSecretFile: Write(" a b \n")).AppSecret);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_file_wins_over_the_environment_value_and_the_deprecation_is_logged()
|
||||||
|
{
|
||||||
|
var options = Resolve(EnvSecret, Write(FileSecret + "\n"));
|
||||||
|
|
||||||
|
Assert.Equal(FileSecret, options.AppSecret);
|
||||||
|
Assert.Contains(_logs.WarningLines, line => line.Contains("deprecated"));
|
||||||
|
AssertNoSecretLogged();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_missing_file_fails_closed_naming_option_and_path_but_no_secret()
|
||||||
|
{
|
||||||
|
var path = Path.Combine(_directory, "absent");
|
||||||
|
|
||||||
|
var failure = Assert.Throws<InvalidOperationException>(() => Resolve(EnvSecret, path));
|
||||||
|
|
||||||
|
Assert.Contains("Heimdall:AppSecretFile", failure.Message);
|
||||||
|
Assert.Contains(path, failure.Message);
|
||||||
|
Assert.DoesNotContain(EnvSecret, failure.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_directory_in_place_of_the_file_fails_closed()
|
||||||
|
{
|
||||||
|
Assert.Throws<InvalidOperationException>(() => Resolve(appSecretFile: _directory));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData("\n")]
|
||||||
|
[InlineData(" \r\n")]
|
||||||
|
public void An_empty_file_fails_closed_even_when_the_environment_value_is_set(string content)
|
||||||
|
{
|
||||||
|
var path = Write(content);
|
||||||
|
|
||||||
|
var failure = Assert.Throws<InvalidOperationException>(() => Resolve(EnvSecret, path));
|
||||||
|
|
||||||
|
Assert.Contains("Heimdall:AppSecretFile", failure.Message);
|
||||||
|
Assert.Contains(path, failure.Message);
|
||||||
|
Assert.DoesNotContain(EnvSecret, failure.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_environment_value_alone_still_works_and_warns_without_logging_it()
|
||||||
|
{
|
||||||
|
var options = Resolve(EnvSecret);
|
||||||
|
|
||||||
|
Assert.Equal(EnvSecret, options.AppSecret);
|
||||||
|
Assert.Single(_logs.WarningLines, line => line.Contains("deprecated") && line.Contains("Heimdall:AppSecretFile"));
|
||||||
|
AssertNoSecretLogged();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Neither_set_is_unconfigured_as_before_and_silent()
|
||||||
|
{
|
||||||
|
var options = Resolve();
|
||||||
|
|
||||||
|
Assert.Equal(string.Empty, options.AppSecret);
|
||||||
|
Assert.False(options.IsPatreonConfigured);
|
||||||
|
Assert.Empty(_logs.Lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
private TestWebApplicationFactory Host(string file) => new TestHost(file, _logs);
|
||||||
|
|
||||||
|
private sealed class TestHost(string file, CapturingLoggerProvider logs) : TestWebApplicationFactory
|
||||||
|
{
|
||||||
|
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||||
|
{
|
||||||
|
base.ConfigureWebHost(builder);
|
||||||
|
builder.ConfigureAppConfiguration((_, configuration) =>
|
||||||
|
configuration.AddInMemoryCollection(new Dictionary<string, string?> { ["Heimdall:AppSecretFile"] = file }));
|
||||||
|
builder.ConfigureLogging(logging => logging.AddProvider(logs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_running_host_resolves_the_file_into_its_options()
|
||||||
|
{
|
||||||
|
using var host = Host(Write(FileSecret + "\n"));
|
||||||
|
|
||||||
|
Assert.Equal(FileSecret, host.Services.GetRequiredService<IOptions<HeimdallOptions>>().Value.AppSecret);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_running_host_refuses_to_start_on_a_missing_file_in_every_environment()
|
||||||
|
{
|
||||||
|
using var host = Host(Path.Combine(_directory, "absent"));
|
||||||
|
|
||||||
|
var failure = Assert.ThrowsAny<Exception>(() => host.CreateClient());
|
||||||
|
|
||||||
|
Assert.Contains("Heimdall:AppSecretFile", failure.ToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -15,7 +15,7 @@ public sealed class HeimdallCompletePageScriptTests
|
||||||
|
|
||||||
private sealed record Run(string Name, string[] Events, Submit? Submit);
|
private sealed record Run(string Name, string[] Events, Submit? Submit);
|
||||||
|
|
||||||
private sealed record Submit(string Attempt, string Code, string Href, string Hash);
|
private sealed record Submit(string Attempt, string Code, string Href, string Hash, string PendingLinkId);
|
||||||
|
|
||||||
private static async Task<Dictionary<string, Run>> RunScenariosAsync()
|
private static async Task<Dictionary<string, Run>> RunScenariosAsync()
|
||||||
{
|
{
|
||||||
|
|
@ -81,7 +81,7 @@ public sealed class HeimdallCompletePageScriptTests
|
||||||
{
|
{
|
||||||
var runs = await RunScenariosAsync();
|
var runs = await RunScenariosAsync();
|
||||||
|
|
||||||
Assert.Equal(new Submit("NONCE", "CODE123", "/auth/heimdall/complete?attempt=NONCE", ""), runs["success"].Submit);
|
Assert.Equal(new Submit("NONCE", "CODE123", "/auth/heimdall/complete?attempt=NONCE", "", ""), runs["success"].Submit);
|
||||||
Assert.Equal("CODE123", runs["success-with-decoy-query-code"].Submit!.Code);
|
Assert.Equal("CODE123", runs["success-with-decoy-query-code"].Submit!.Code);
|
||||||
|
|
||||||
var queryOnly = runs["code-in-query-only"];
|
var queryOnly = runs["code-in-query-only"];
|
||||||
|
|
@ -90,6 +90,50 @@ public sealed class HeimdallCompletePageScriptTests
|
||||||
Assert.Equal(ErrorTarget, queryOnly.Events[^1]);
|
Assert.Equal(ErrorTarget, queryOnly.Events[^1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_pending_link_id_is_read_only_from_the_fragment_and_posted_without_a_code()
|
||||||
|
{
|
||||||
|
var runs = await RunScenariosAsync();
|
||||||
|
|
||||||
|
foreach (var name in new[] { "link-return", "link-return-with-decoy-query-id" })
|
||||||
|
{
|
||||||
|
var run = runs[name];
|
||||||
|
Assert.Equal(new Submit("NONCE", "", run.Submit!.Href, "", "PEND1"), run.Submit);
|
||||||
|
Assert.DoesNotContain("PEND1", run.Submit.Href);
|
||||||
|
Assert.StartsWith("replaceState:", run.Events[0]);
|
||||||
|
Assert.DoesNotContain("PEND1", run.Events[0]);
|
||||||
|
Assert.DoesNotContain("#", run.Events[0]);
|
||||||
|
Assert.Equal("submit", run.Events[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Null(runs["link-pending-id-in-query-only"].Submit);
|
||||||
|
Assert.Equal(ErrorTarget, runs["link-pending-id-in-query-only"].Events[^1]);
|
||||||
|
Assert.Null(runs["link-error-with-pending-id"].Submit);
|
||||||
|
Assert.Equal(ErrorTarget, runs["link-error-with-pending-id"].Events[^1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_link_refused_because_the_login_belongs_to_another_account_goes_to_the_page_with_a_fixed_result_and_submits_nothing()
|
||||||
|
{
|
||||||
|
var runs = await RunScenariosAsync();
|
||||||
|
const string Target = "replace:/Membership/LinkedAccounts?result=identity_linked_elsewhere";
|
||||||
|
|
||||||
|
var run = runs["link-refused-elsewhere"];
|
||||||
|
Assert.Null(run.Submit);
|
||||||
|
Assert.Equal(Target, run.Events[^1]);
|
||||||
|
Assert.DoesNotContain("submit", run.Events);
|
||||||
|
Assert.Contains(run.Events, x => x.StartsWith("replaceState:", StringComparison.Ordinal) && !x.Contains('#'));
|
||||||
|
|
||||||
|
// Without an attempt, from the query only, or for any other refusal text, it is the ordinary error exit.
|
||||||
|
foreach (var name in new[] { "link-refused-elsewhere-no-attempt", "other-refusal-text", "refusal-in-query-only" })
|
||||||
|
{
|
||||||
|
Assert.Null(runs[name].Submit);
|
||||||
|
Assert.Equal(ErrorTarget, runs[name].Events[^1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.DoesNotContain("EVIL", string.Join("\n", runs["other-refusal-text"].Events));
|
||||||
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("error-status-with-code")]
|
[InlineData("error-status-with-code")]
|
||||||
[InlineData("no-code")]
|
[InlineData("no-code")]
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ using System.Text.Json;
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
using Bifrost.Web.Features.Heimdall;
|
using Bifrost.Web.Features.Heimdall;
|
||||||
using Bifrost.Web.Features.Membership;
|
using Bifrost.Web.Features.Membership;
|
||||||
|
using Bifrost.Web.Features.Patronage;
|
||||||
using Bifrost.Web.Features.Shared;
|
using Bifrost.Web.Features.Shared;
|
||||||
using Bifrost.Web.Tests.Support;
|
using Bifrost.Web.Tests.Support;
|
||||||
using Microsoft.AspNetCore.Authentication.OAuth;
|
using Microsoft.AspNetCore.Authentication.OAuth;
|
||||||
|
|
@ -888,6 +889,101 @@ public sealed class HeimdallCompletionTests
|
||||||
Assert.Equal(rolesBefore, after.RoleAssignments.Count);
|
Assert.Equal(rolesBefore, after.RoleAssignments.Count);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_merged_account_stays_merged_through_a_sign_in_with_the_member_claim()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost();
|
||||||
|
var foldedId = HeimdallShapes.NewAccountId();
|
||||||
|
var survivorId = HeimdallShapes.NewAccountId();
|
||||||
|
Assert.True((await Genuine(host, await host.StartAsync(member: true), foldedId, ["member_access"])).SignedIn);
|
||||||
|
Assert.True((await Genuine(host, await host.StartAsync(member: true), survivorId, ["member_access"])).SignedIn);
|
||||||
|
await host.Db(async db =>
|
||||||
|
{
|
||||||
|
var folded = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == foldedId);
|
||||||
|
var survivor = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == survivorId);
|
||||||
|
var merge = new AccountMerge { SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = folded.Id, State = AccountMergeState.HeimdallMoved, CreatedUtc = DateTimeOffset.UtcNow };
|
||||||
|
db.AccountMerges.Add(merge);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
var clock = TimeProvider.System;
|
||||||
|
await new AccountMergeLedger(db, new PatronageService(db, new AuditTrailService(db, clock), clock), clock).CommitAsync(merge.Id, default);
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
Assert.Equal(MembershipStatus.Merged, (await host.Account(foldedId))!.Membership!.Status);
|
||||||
|
|
||||||
|
var again = await Genuine(host, await host.StartAsync(member: true), foldedId, ["member_access"]);
|
||||||
|
|
||||||
|
Assert.True(again.SignedIn); // the login still completes; it is the actor gate that makes it act as nobody
|
||||||
|
Assert.Equal(MembershipStatus.Merged, (await host.Account(foldedId))!.Membership!.Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_legacy_account_without_a_membership_row_signs_in_and_gets_one()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost();
|
||||||
|
var accountId = HeimdallShapes.NewAccountId();
|
||||||
|
Assert.True((await Genuine(host, await host.StartAsync(member: false), accountId)).SignedIn);
|
||||||
|
await host.Db(async db =>
|
||||||
|
{
|
||||||
|
db.Memberships.RemoveRange(db.Memberships.Where(x => x.UserAccount.HeimdallAccountId == accountId));
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
Assert.Null((await host.Account(accountId))!.Membership);
|
||||||
|
|
||||||
|
var again = await Genuine(host, await host.StartAsync(member: true), accountId, ["member_access"]);
|
||||||
|
|
||||||
|
Assert.True(again.SignedIn);
|
||||||
|
Assert.Equal(MembershipStatus.Active, (await host.Account(accountId))!.Membership!.Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(AccountMergeState.Confirmed)]
|
||||||
|
[InlineData(AccountMergeState.Committed)]
|
||||||
|
public async Task A_chat_tier_account_without_a_membership_that_a_merge_froze_or_folded_signs_in_without_getting_one(AccountMergeState state)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost();
|
||||||
|
var foldedId = HeimdallShapes.NewAccountId();
|
||||||
|
var survivorId = HeimdallShapes.NewAccountId();
|
||||||
|
Assert.True((await Genuine(host, await host.StartAsync(member: false), foldedId)).SignedIn);
|
||||||
|
Assert.True((await Genuine(host, await host.StartAsync(member: false), survivorId)).SignedIn);
|
||||||
|
await MergeAsync(host, survivorId, foldedId, state, dropFoldedMembership: true); // a chat-tier account holds none
|
||||||
|
|
||||||
|
await Genuine(host, await host.StartAsync(member: true), foldedId, ["member_access"]);
|
||||||
|
|
||||||
|
Assert.Null((await host.Account(foldedId))!.Membership);
|
||||||
|
Assert.Equal(0, await host.Db(db => db.Memberships.CountAsync(x => x.UserAccount.HeimdallAccountId == foldedId)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_frozen_accounts_sign_in_with_member_access_does_not_activate_its_membership()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost();
|
||||||
|
var foldedId = HeimdallShapes.NewAccountId();
|
||||||
|
var survivorId = HeimdallShapes.NewAccountId();
|
||||||
|
Assert.True((await Genuine(host, await host.StartAsync(member: false), foldedId)).SignedIn);
|
||||||
|
Assert.True((await Genuine(host, await host.StartAsync(member: false), survivorId)).SignedIn);
|
||||||
|
await MergeAsync(host, survivorId, foldedId, AccountMergeState.HeimdallMoved, dropFoldedMembership: false);
|
||||||
|
|
||||||
|
await Genuine(host, await host.StartAsync(member: true), foldedId, ["member_access"]);
|
||||||
|
|
||||||
|
Assert.Equal(MembershipStatus.Authenticated, (await host.Account(foldedId))!.Membership!.Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task MergeAsync(HeimdallHost host, string survivorId, string foldedId, AccountMergeState state, bool dropFoldedMembership) =>
|
||||||
|
host.Db(async db =>
|
||||||
|
{
|
||||||
|
if (dropFoldedMembership)
|
||||||
|
{
|
||||||
|
db.Memberships.RemoveRange(db.Memberships.Where(x => x.UserAccount.HeimdallAccountId == foldedId));
|
||||||
|
}
|
||||||
|
|
||||||
|
var folded = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == foldedId);
|
||||||
|
var survivor = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == survivorId);
|
||||||
|
db.AccountMerges.Add(new AccountMerge { SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = folded.Id, State = state, CreatedUtc = DateTimeOffset.UtcNow });
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task A_chat_only_account_that_later_signs_in_with_member_access_becomes_a_member()
|
public async Task A_chat_only_account_that_later_signs_in_with_member_access_becomes_a_member()
|
||||||
{
|
{
|
||||||
|
|
@ -1115,7 +1211,7 @@ public sealed class HeimdallCompletionTests
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(HttpStatusCode.InternalServerError, "{}", "Heimdall rejected the auth start.")]
|
[InlineData(HttpStatusCode.InternalServerError, "{}", "Heimdall rejected the auth start (HTTP 500).")]
|
||||||
[InlineData(HttpStatusCode.OK, "{}", "Heimdall auth start returned no authorization URL.")]
|
[InlineData(HttpStatusCode.OK, "{}", "Heimdall auth start returned no authorization URL.")]
|
||||||
[InlineData(HttpStatusCode.OK, "{\"authorizationUrl\":\" \"}", "Heimdall auth start returned no authorization URL.")]
|
[InlineData(HttpStatusCode.OK, "{\"authorizationUrl\":\" \"}", "Heimdall auth start returned no authorization URL.")]
|
||||||
public async Task A_start_Heimdall_cannot_serve_issues_no_cookie_and_a_fixed_refusal(HttpStatusCode status, string body, string reason)
|
public async Task A_start_Heimdall_cannot_serve_issues_no_cookie_and_a_fixed_refusal(HttpStatusCode status, string body, string reason)
|
||||||
|
|
@ -1132,6 +1228,71 @@ public sealed class HeimdallCompletionTests
|
||||||
Assert.Contains("Heimdall start refused: " + reason, string.Join("\n", host.Logs.Lines));
|
Assert.Contains("Heimdall start refused: " + reason, string.Join("\n", host.Logs.Lines));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(HttpStatusCode.Unauthorized, """{"error":"app_auth_required"}""", "Heimdall rejected the auth start (HTTP 401, app_auth_required).")]
|
||||||
|
[InlineData(HttpStatusCode.BadRequest, """{"error":"provider_not_supported_for_app","detail":"free text"}""", "Heimdall rejected the auth start (HTTP 400, provider_not_supported_for_app).")]
|
||||||
|
[InlineData(HttpStatusCode.Unauthorized, """{"error":"<b>Not a code</b> CANARY secret=abc"}""", "Heimdall rejected the auth start (HTTP 401).")]
|
||||||
|
[InlineData(HttpStatusCode.Unauthorized, """{"error":{"nested":"app_auth_required"}}""", "Heimdall rejected the auth start (HTTP 401).")]
|
||||||
|
[InlineData(HttpStatusCode.Unauthorized, "not json at all", "Heimdall rejected the auth start (HTTP 401).")]
|
||||||
|
public async Task A_refused_start_logs_the_status_and_a_well_formed_error_code_and_nothing_else_from_the_body(
|
||||||
|
HttpStatusCode status, string body, string reason)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost();
|
||||||
|
host.Heimdall.StartStatus = status;
|
||||||
|
host.Heimdall.StartBody = body;
|
||||||
|
|
||||||
|
var attempt = await host.StartAsync(member: true);
|
||||||
|
|
||||||
|
Assert.Equal(ErrorRedirect, attempt.Response.Headers.Location!.OriginalString);
|
||||||
|
var logs = string.Join("\n", host.Logs.Lines);
|
||||||
|
Assert.Contains("Heimdall start refused: " + reason, logs);
|
||||||
|
Assert.DoesNotContain("CANARY", logs);
|
||||||
|
Assert.DoesNotContain("free text", logs);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_code_longer_than_sixty_four_characters_is_not_logged()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost();
|
||||||
|
host.Heimdall.StartStatus = HttpStatusCode.Unauthorized;
|
||||||
|
host.Heimdall.StartBody = "{\"error\":\"" + new string('a', 65) + "\"}";
|
||||||
|
|
||||||
|
await host.StartAsync(member: true);
|
||||||
|
|
||||||
|
var logs = string.Join("\n", host.Logs.Lines);
|
||||||
|
Assert.Contains("Heimdall start refused: Heimdall rejected the auth start (HTTP 401).", logs);
|
||||||
|
Assert.DoesNotContain(new string('a', 65), logs);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("text/html; charset=windows-1252")]
|
||||||
|
[InlineData("text/html; charset=bogus")]
|
||||||
|
[InlineData("text/html; charset=utf-7")]
|
||||||
|
public async Task A_refusal_with_an_unusual_charset_still_redirects_with_the_status(string contentType)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost();
|
||||||
|
host.Heimdall.StartStatus = HttpStatusCode.BadGateway;
|
||||||
|
host.Heimdall.StartContentType = contentType;
|
||||||
|
host.Heimdall.StartBody = "<html>bad gateway</html>";
|
||||||
|
|
||||||
|
var attempt = await host.StartAsync();
|
||||||
|
|
||||||
|
Assert.Equal(ErrorRedirect, attempt.Response.Headers.Location!.OriginalString);
|
||||||
|
Assert.Contains("Heimdall start refused: Heimdall rejected the auth start (HTTP 502).", string.Join("\n", host.Logs.Lines));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Only_the_head_of_a_refusal_body_is_read()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost();
|
||||||
|
host.Heimdall.StartStatus = HttpStatusCode.Unauthorized;
|
||||||
|
host.Heimdall.StartBody = "{\"pad\":\"" + new string('x', 200_000) + "\",\"error\":\"app_auth_required\"}";
|
||||||
|
|
||||||
|
await host.StartAsync(member: true);
|
||||||
|
|
||||||
|
Assert.Contains("Heimdall start refused: Heimdall rejected the auth start (HTTP 401).", string.Join("\n", host.Logs.Lines));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Refusals_echo_no_input_in_responses_or_logs()
|
public async Task Refusals_echo_no_input_in_responses_or_logs()
|
||||||
{
|
{
|
||||||
|
|
@ -1445,7 +1606,7 @@ public sealed class HeimdallCompletionTests
|
||||||
var inputs = Regex.Matches(form.Groups[2].Value, @"<input\b([^>]*)>");
|
var inputs = Regex.Matches(form.Groups[2].Value, @"<input\b([^>]*)>");
|
||||||
Assert.All(inputs, x => Assert.Contains("type=\"hidden\"", x.Groups[1].Value));
|
Assert.All(inputs, x => Assert.Contains("type=\"hidden\"", x.Groups[1].Value));
|
||||||
var names = inputs.Select(x => Regex.Match(x.Groups[1].Value, @"\bname=""([^""]*)""").Groups[1].Value).ToArray();
|
var names = inputs.Select(x => Regex.Match(x.Groups[1].Value, @"\bname=""([^""]*)""").Groups[1].Value).ToArray();
|
||||||
Assert.Equal(new[] { "attempt", "code" }, names);
|
Assert.Equal(new[] { "attempt", "code", "pendingLinkId" }, names);
|
||||||
|
|
||||||
// The page's own field names and action, filled as its script fills them, complete a sign-in.
|
// The page's own field names and action, filled as its script fills them, complete a sign-in.
|
||||||
var attempt = await host.StartAsync();
|
var attempt = await host.StartAsync();
|
||||||
|
|
|
||||||
630
tests/Bifrost.Web.Tests/HeimdallGoogleLinkTests.cs
Normal file
630
tests/Bifrost.Web.Tests/HeimdallGoogleLinkTests.cs
Normal file
|
|
@ -0,0 +1,630 @@
|
||||||
|
using System.Net;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Heimdall;
|
||||||
|
using Bifrost.Web.Features.Shared;
|
||||||
|
using Bifrost.Web.Tests.Support;
|
||||||
|
using Microsoft.AspNetCore.DataProtection;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attaching a Google login to a signed-in Heimdall account by explicit link. Bifrost keeps no Heimdall token: each
|
||||||
|
/// Heimdall call that needs a bearer follows a fresh Heimdall sign-in, and the bearer lives inside that one request.
|
||||||
|
/// The attempt cookie carries only a purpose, the expected account and a pending link id.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class HeimdallGoogleLinkTests
|
||||||
|
{
|
||||||
|
private const string LinkedPage = "/Membership/LinkedAccounts";
|
||||||
|
private const string ErrorRedirect = "/?auth=heimdall-error";
|
||||||
|
|
||||||
|
private sealed record Step(HttpResponseMessage Response, StartedAttempt Next, string Token);
|
||||||
|
|
||||||
|
private static string Jar(string session, StartedAttempt attempt) =>
|
||||||
|
$"{BifrostCookies.Session}={session}; {attempt.CookieName}={attempt.Cookie}";
|
||||||
|
|
||||||
|
private static string? Location(HttpResponseMessage response) => response.Headers.Location?.OriginalString;
|
||||||
|
|
||||||
|
/// <summary>B: the fresh sign-in of a LinkStart attempt completes; Bifrost asks Heimdall for the Google link.</summary>
|
||||||
|
private static async Task<Step> StepB(HeimdallHost host, string session, StartedAttempt start, string account, string? token = null)
|
||||||
|
{
|
||||||
|
token ??= host.Token(account);
|
||||||
|
var code = host.CodeFor(start, account, token);
|
||||||
|
var before = host.Heimdall.StartBodies.Count;
|
||||||
|
var response = await host.PostCompleteAsync(
|
||||||
|
new Dictionary<string, string> { ["attempt"] = start.Nonce, ["code"] = code }, Jar(session, start));
|
||||||
|
return new Step(response, host.AttemptFrom(response, before), token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>C: the browser is back from Google with a pending link id; Bifrost starts a fresh sign-in.</summary>
|
||||||
|
private static async Task<Step> StepC(HeimdallHost host, string session, StartedAttempt awaiting, string pendingLinkId)
|
||||||
|
{
|
||||||
|
var before = host.Heimdall.StartBodies.Count;
|
||||||
|
var response = await host.PostCompleteAsync(
|
||||||
|
new Dictionary<string, string> { ["attempt"] = awaiting.Nonce, ["pendingLinkId"] = pendingLinkId }, Jar(session, awaiting));
|
||||||
|
return new Step(response, host.AttemptFrom(response, before), string.Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>D: the fresh sign-in of a LinkConfirm attempt completes; Bifrost confirms the link.</summary>
|
||||||
|
private static async Task<Step> StepD(HeimdallHost host, string session, StartedAttempt confirming, string account, string? token = null)
|
||||||
|
{
|
||||||
|
token ??= host.Token(account);
|
||||||
|
var code = host.CodeFor(confirming, account, token);
|
||||||
|
var response = await host.PostCompleteAsync(
|
||||||
|
new Dictionary<string, string> { ["attempt"] = confirming.Nonce, ["code"] = code }, Jar(session, confirming));
|
||||||
|
return new Step(response, confirming, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record Journey(string Account, string Session, StartedAttempt Start, Step B, string PendingLinkId, Step C);
|
||||||
|
|
||||||
|
/// <summary>Everything up to the LinkConfirm attempt, waiting for the fresh sign-in's code.</summary>
|
||||||
|
private static async Task<Journey> ThroughC(HeimdallHost host, string? pendingLinkId = null)
|
||||||
|
{
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session);
|
||||||
|
var b = await StepB(host, session, start, account);
|
||||||
|
var pending = host.Heimdall.RegisterPendingLink(pendingLinkId);
|
||||||
|
var c = await StepC(host, session, b.Next, pending);
|
||||||
|
return new Journey(account, session, start, b, pending, c);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Unprotect(HeimdallHost host, string cookie) =>
|
||||||
|
host.Services.GetRequiredService<IDataProtectionProvider>().CreateProtector("Bifrost.Heimdall.Attempt.v1").Unprotect(cookie);
|
||||||
|
|
||||||
|
// ---- 1. the link start carries a fresh bearer ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task The_account_page_starts_an_ordinary_sign_in_and_the_link_start_follows_with_the_fresh_bearer()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var signInStarts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var start = await host.StartLinkAsync(session);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, start.Response.StatusCode);
|
||||||
|
Assert.Equal(signInStarts + 1, host.Heimdall.StartBodies.Count);
|
||||||
|
using (var body = JsonDocument.Parse(host.Heimdall.StartBodies[^1]))
|
||||||
|
{
|
||||||
|
Assert.Equal("sign_in", body.RootElement.GetProperty("mode").GetString());
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal("/v1/oauth/discord/start", host.Heimdall.StartPaths[^1]);
|
||||||
|
Assert.Null(host.Heimdall.StartAuthorizations[^1]);
|
||||||
|
Assert.NotNull(start.Cookie);
|
||||||
|
|
||||||
|
var b = await StepB(host, session, start, account);
|
||||||
|
|
||||||
|
Assert.Equal(signInStarts + 2, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal("/v1/oauth/google/start", host.Heimdall.StartPaths[^1]);
|
||||||
|
Assert.Equal("Bearer " + b.Token, host.Heimdall.StartAuthorizations[^1]);
|
||||||
|
using var link = JsonDocument.Parse(host.Heimdall.StartBodies[^1]);
|
||||||
|
Assert.Equal("link", link.RootElement.GetProperty("mode").GetString());
|
||||||
|
Assert.Equal("bifrost", link.RootElement.GetProperty("appSlug").GetString());
|
||||||
|
Assert.Equal("browser_completion", link.RootElement.GetProperty("handoff").GetProperty("kind").GetString());
|
||||||
|
Assert.StartsWith("https://localhost/auth/heimdall/complete?attempt=", link.RootElement.GetProperty("returnTo").GetString());
|
||||||
|
Assert.NotEqual(start.Nonce, b.Next.Nonce);
|
||||||
|
Assert.Equal("https://heimdall.test/oauth/google/authorize?state=link-fixture", Location(b.Response));
|
||||||
|
// The sign-in session is untouched: the link flow never replaces who is signed in.
|
||||||
|
Assert.Null(HeimdallHost.CookieValue(b.Response, BifrostCookies.Session));
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, b.Response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_link_start_attempt_without_a_code_asks_Heimdall_for_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session);
|
||||||
|
var before = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var response = await host.PostCompleteAsync(
|
||||||
|
new Dictionary<string, string> { ["attempt"] = start.Nonce }, Jar(session, start));
|
||||||
|
|
||||||
|
Assert.Equal(before, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(LinkedPage + "?result=error", Location(response));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_link_start_attempt_cannot_sign_in_a_session()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session);
|
||||||
|
var other = HeimdallShapes.NewAccountId();
|
||||||
|
|
||||||
|
var done = await host.CompleteAsync(start, host.CodeFor(start, other));
|
||||||
|
|
||||||
|
Assert.False(done.SignedIn);
|
||||||
|
Assert.Null(await host.Account(other));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 2. only a signed-in user, only by POST with antiforgery ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Without_a_session_a_link_post_starts_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var before = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var start = await host.StartLinkAsync(session: null);
|
||||||
|
|
||||||
|
Assert.Equal(before, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Null(start.Cookie);
|
||||||
|
Assert.NotEqual(HttpStatusCode.OK, start.Response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_get_never_starts_a_link()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
var before = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var start = await host.StartLinkAsync(session, method: HttpMethod.Get);
|
||||||
|
|
||||||
|
Assert.Equal(before, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Null(start.Cookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_link_post_without_the_antiforgery_token_starts_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
var before = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var start = await host.StartLinkAsync(session, antiforgery: false);
|
||||||
|
|
||||||
|
Assert.Equal(before, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Null(start.Cookie);
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, start.Response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 3. a browser that is not the one that began the link ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_foreign_browser_holding_a_pending_link_id_confirms_nothing_and_calls_Heimdall_zero_times()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var journey = await ThroughC(host);
|
||||||
|
var redeems = host.Heimdall.RedeemCalls;
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
// No cookie at all, and a session of its own; then an unrelated sign-in attempt's cookie.
|
||||||
|
var strangerAccount = HeimdallShapes.NewAccountId();
|
||||||
|
var stranger = await host.SignInSessionAsync(strangerAccount);
|
||||||
|
redeems = host.Heimdall.RedeemCalls;
|
||||||
|
starts = host.Heimdall.StartBodies.Count;
|
||||||
|
var noCookie = await host.PostCompleteAsync(
|
||||||
|
new Dictionary<string, string> { ["attempt"] = journey.B.Next.Nonce, ["pendingLinkId"] = journey.PendingLinkId },
|
||||||
|
$"{BifrostCookies.Session}={stranger}");
|
||||||
|
var unrelated = await host.StartAsync();
|
||||||
|
starts = host.Heimdall.StartBodies.Count;
|
||||||
|
var wrongCookie = await host.PostCompleteAsync(
|
||||||
|
new Dictionary<string, string> { ["attempt"] = journey.B.Next.Nonce, ["pendingLinkId"] = journey.PendingLinkId },
|
||||||
|
$"{BifrostCookies.Session}={stranger}; {unrelated.CookieName}={unrelated.Cookie}");
|
||||||
|
var forgedCode = host.CodeFor(journey.C.Next, strangerAccount);
|
||||||
|
var confirmWithoutCookie = await host.PostCompleteAsync(
|
||||||
|
new Dictionary<string, string> { ["attempt"] = journey.C.Next.Nonce, ["code"] = forgedCode },
|
||||||
|
$"{BifrostCookies.Session}={stranger}");
|
||||||
|
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(redeems, host.Heimdall.RedeemCalls);
|
||||||
|
Assert.Empty(host.Heimdall.ConfirmBodies);
|
||||||
|
foreach (var response in new[] { noCookie, wrongCookie, confirmWithoutCookie })
|
||||||
|
{
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.DoesNotContain("Bearer", Location(response));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 4. a different Heimdall account ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Completion_for_a_different_account_than_the_session_is_refused_with_no_link_call()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session);
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var b = await StepB(host, session, start, HeimdallShapes.NewAccountId());
|
||||||
|
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(LinkedPage + "?result=error", Location(b.Response));
|
||||||
|
AssertAttemptCleared(b.Response, start);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_link_begun_before_a_merge_froze_the_account_does_not_continue_after_it()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var survivorAccount = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
await host.SignInSessionAsync(survivorAccount);
|
||||||
|
var start = await host.StartLinkAsync(session);
|
||||||
|
await host.Db(async db =>
|
||||||
|
{
|
||||||
|
var folded = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == account);
|
||||||
|
var survivor = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == survivorAccount);
|
||||||
|
db.AccountMerges.Add(new AccountMerge { SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = folded.Id, State = AccountMergeState.Confirmed, CreatedUtc = DateTimeOffset.UtcNow });
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var b = await StepB(host, session, start, account);
|
||||||
|
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count); // no Google link was asked for on the frozen account
|
||||||
|
Assert.Equal(LinkedPage + "?result=error", Location(b.Response));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_session_of_another_account_cannot_continue_the_link()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session);
|
||||||
|
var intruder = HeimdallShapes.NewAccountId();
|
||||||
|
var intruderSession = await host.SignInSessionAsync(intruder);
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
var redeems = host.Heimdall.RedeemCalls;
|
||||||
|
|
||||||
|
var b = await StepB(host, intruderSession, start, intruder);
|
||||||
|
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(redeems, host.Heimdall.RedeemCalls);
|
||||||
|
Assert.Equal(LinkedPage + "?result=error", Location(b.Response));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_confirming_sign_in_for_another_account_confirms_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var journey = await ThroughC(host);
|
||||||
|
var other = HeimdallShapes.NewAccountId();
|
||||||
|
|
||||||
|
var d = await StepD(host, journey.Session, journey.C.Next, other);
|
||||||
|
|
||||||
|
Assert.Empty(host.Heimdall.ConfirmBodies);
|
||||||
|
Assert.Equal(LinkedPage + "?result=error", Location(d.Response));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertAttemptCleared(HttpResponseMessage response, StartedAttempt attempt)
|
||||||
|
{
|
||||||
|
var header = HeimdallHost.SetCookieHeader(response, attempt.CookieName!);
|
||||||
|
Assert.NotNull(header);
|
||||||
|
Assert.Contains("1970", header);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 5. outcomes ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Success_confirms_once_with_the_pending_link_id_and_a_fresh_bearer_and_shows_linked()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var journey = await ThroughC(host);
|
||||||
|
Assert.Empty(host.Heimdall.ConfirmBodies);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, journey.C.Response.StatusCode);
|
||||||
|
Assert.Equal("/v1/oauth/discord/start", host.Heimdall.StartPaths[^1]);
|
||||||
|
Assert.Null(host.Heimdall.StartAuthorizations[^1]);
|
||||||
|
|
||||||
|
var d = await StepD(host, journey.Session, journey.C.Next, journey.Account);
|
||||||
|
|
||||||
|
Assert.Equal(LinkedPage + "?result=linked", Location(d.Response));
|
||||||
|
Assert.Single(host.Heimdall.ConfirmBodies);
|
||||||
|
using var body = JsonDocument.Parse(host.Heimdall.ConfirmBodies[0]);
|
||||||
|
Assert.Equal(journey.PendingLinkId, body.RootElement.GetProperty("pendingLinkId").GetString());
|
||||||
|
Assert.Equal("Bearer " + d.Token, host.Heimdall.ConfirmAuthorizations[0]);
|
||||||
|
Assert.NotEqual("Bearer " + journey.B.Token, host.Heimdall.ConfirmAuthorizations[0]);
|
||||||
|
AssertAttemptCleared(d.Response, journey.C.Next);
|
||||||
|
Assert.Null(HeimdallHost.CookieValue(d.Response, BifrostCookies.Session));
|
||||||
|
var account = await host.Account(journey.Account);
|
||||||
|
Assert.Equal(MembershipStatus.Authenticated, account!.Membership!.Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(HttpStatusCode.Conflict, "identity_linked_elsewhere")]
|
||||||
|
[InlineData(HttpStatusCode.Gone, "expired")]
|
||||||
|
[InlineData(HttpStatusCode.Unauthorized, "error")]
|
||||||
|
[InlineData(HttpStatusCode.InternalServerError, "error")]
|
||||||
|
public async Task A_refused_confirm_redirects_with_its_own_fixed_outcome(HttpStatusCode status, string outcome)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var journey = await ThroughC(host);
|
||||||
|
host.Heimdall.ConfirmStatus = status;
|
||||||
|
|
||||||
|
var d = await StepD(host, journey.Session, journey.C.Next, journey.Account);
|
||||||
|
|
||||||
|
Assert.Equal($"{LinkedPage}?result={outcome}", Location(d.Response));
|
||||||
|
Assert.DoesNotContain("HEIMDALL FREE TEXT", string.Join("\n", host.Logs.Lines));
|
||||||
|
AssertAttemptCleared(d.Response, journey.C.Next);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task The_account_page_words_each_outcome_from_a_closed_set_and_ignores_anything_else()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
using var client = host.NewClient();
|
||||||
|
|
||||||
|
async Task<string> Page(string link)
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, LinkedPage + "?result=" + Uri.EscapeDataString(link));
|
||||||
|
request.Headers.Add("Cookie", $"{BifrostCookies.Session}={session}");
|
||||||
|
return await (await client.SendAsync(request)).Content.ReadAsStringAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Contains("now linked to your Heimdall account", await Page("linked"));
|
||||||
|
Assert.Contains("belongs to another account", await Page("identity_linked_elsewhere"));
|
||||||
|
Assert.Contains("expired before it was confirmed", await Page("expired"));
|
||||||
|
Assert.Contains("could not be completed", await Page("error"));
|
||||||
|
var hostile = await Page("<script>alert(1)</script>");
|
||||||
|
Assert.DoesNotContain("alert(1)", hostile);
|
||||||
|
Assert.DoesNotContain("now linked to your", hostile);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 6. google stays out of sign-in and member access ----
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("/auth/heimdall/google")]
|
||||||
|
[InlineData("/auth/heimdall/google?access=member")]
|
||||||
|
[InlineData("/auth/heimdall/Google")]
|
||||||
|
public async Task Google_is_refused_as_a_sign_in_provider_and_asks_Heimdall_for_nothing(string url)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
|
||||||
|
var start = await host.StartAtAsync(url);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, start.Response.StatusCode);
|
||||||
|
Assert.Equal(ErrorRedirect, Location(start.Response));
|
||||||
|
Assert.Empty(host.Heimdall.StartBodies);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 7. nothing secret leaves the request ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task No_heimdall_token_or_pending_link_id_reaches_a_log_a_cookie_or_a_location()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(traceHttp: true, realSessions: true);
|
||||||
|
const string pendingCanary = "PENDING-CANARY-7f3a";
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session);
|
||||||
|
var b = await StepB(host, session, start, account);
|
||||||
|
var pending = host.Heimdall.RegisterPendingLink(pendingCanary);
|
||||||
|
var c = await StepC(host, session, b.Next, pending);
|
||||||
|
var d = await StepD(host, session, c.Next, account);
|
||||||
|
Assert.Equal(LinkedPage + "?result=linked", Location(d.Response));
|
||||||
|
|
||||||
|
var tokens = new[] { b.Token, d.Token }
|
||||||
|
.SelectMany(token => new[] { token, token.Split('.')[2], token.Split('.')[1] })
|
||||||
|
.ToArray();
|
||||||
|
var logs = string.Join("\n", host.Logs.Lines);
|
||||||
|
Assert.Contains("Bearer", string.Join("\n", host.Heimdall.StartAuthorizations.Where(x => x is not null)));
|
||||||
|
foreach (var secret in tokens.Append(pendingCanary))
|
||||||
|
{
|
||||||
|
Assert.DoesNotContain(secret, logs);
|
||||||
|
foreach (var step in new[] { start.Response, b.Response, c.Response, d.Response })
|
||||||
|
{
|
||||||
|
Assert.DoesNotContain(secret, Location(step) ?? string.Empty);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every attempt cookie Bifrost set along the way, unprotected: purpose, account and pending id only.
|
||||||
|
foreach (var cookie in new[] { start.Cookie, b.Next.Cookie, c.Next.Cookie })
|
||||||
|
{
|
||||||
|
var payload = Unprotect(host, cookie!);
|
||||||
|
foreach (var token in tokens)
|
||||||
|
{
|
||||||
|
Assert.DoesNotContain(token, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.DoesNotContain("eyJ", payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.DoesNotContain(pendingCanary, Unprotect(host, start.Cookie!));
|
||||||
|
Assert.DoesNotContain(pendingCanary, Unprotect(host, b.Next.Cookie!));
|
||||||
|
Assert.Contains(account, Unprotect(host, b.Next.Cookie!));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 8. old attempt cookies keep signing in ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task An_attempt_cookie_written_before_purposes_existed_still_completes_a_normal_sign_in()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var nonce = "legacy-nonce-" + Guid.NewGuid().ToString("N");
|
||||||
|
var protector = host.Services.GetRequiredService<IDataProtectionProvider>().CreateProtector("Bifrost.Heimdall.Attempt.v1");
|
||||||
|
var legacy = protector.Protect(JsonSerializer.Serialize(new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["Nonce"] = nonce,
|
||||||
|
["Provider"] = "discord",
|
||||||
|
["RequiresMemberAccess"] = false,
|
||||||
|
["ReturnPath"] = "/App/Mill",
|
||||||
|
["ExpiresAt"] = host.Clock.Now.AddMinutes(5)
|
||||||
|
}));
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var attempt = new StartedAttempt(
|
||||||
|
nonce, HeimdallAttemptCookie.SlotNames[0], legacy, $"https://localhost/auth/heimdall/complete?attempt={nonce}", null!);
|
||||||
|
|
||||||
|
var done = await host.CompleteAsync(attempt, host.CodeFor(attempt, account));
|
||||||
|
|
||||||
|
Assert.True(done.SignedIn);
|
||||||
|
Assert.Equal("/App/Mill", Location(done.Response));
|
||||||
|
Assert.NotNull(await host.Account(account));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 9. attempts are single use ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Replaying_a_consumed_link_start_attempt_does_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session);
|
||||||
|
var code = host.CodeFor(start, account);
|
||||||
|
var fields = new Dictionary<string, string> { ["attempt"] = start.Nonce, ["code"] = code };
|
||||||
|
var first = await host.PostCompleteAsync(fields, Jar(session, start));
|
||||||
|
Assert.Contains("google", Location(first));
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var replay = await host.PostCompleteAsync(fields, Jar(session, start));
|
||||||
|
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(LinkedPage + "?result=error", Location(replay));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Replaying_a_consumed_confirm_attempt_confirms_nothing_twice()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var journey = await ThroughC(host);
|
||||||
|
var code = host.CodeFor(journey.C.Next, journey.Account);
|
||||||
|
var fields = new Dictionary<string, string> { ["attempt"] = journey.C.Next.Nonce, ["code"] = code };
|
||||||
|
var first = await host.PostCompleteAsync(fields, Jar(journey.Session, journey.C.Next));
|
||||||
|
Assert.Equal(LinkedPage + "?result=linked", Location(first));
|
||||||
|
|
||||||
|
var replay = await host.PostCompleteAsync(fields, Jar(journey.Session, journey.C.Next));
|
||||||
|
|
||||||
|
Assert.Single(host.Heimdall.ConfirmBodies);
|
||||||
|
Assert.Equal(LinkedPage + "?result=error", Location(replay));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Replaying_a_consumed_await_attempt_links_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var journey = await ThroughC(host);
|
||||||
|
var again = await StepC(host, journey.Session, journey.B.Next, journey.PendingLinkId);
|
||||||
|
|
||||||
|
// The replay can only begin another fresh sign-in; the pending id is spent at Heimdall by the first confirm.
|
||||||
|
var d = await StepD(host, journey.Session, again.Next, journey.Account);
|
||||||
|
var replayed = await StepD(host, journey.Session, journey.C.Next, journey.Account);
|
||||||
|
|
||||||
|
Assert.Equal(LinkedPage + "?result=linked", Location(d.Response));
|
||||||
|
Assert.Equal(LinkedPage + "?result=expired", Location(replayed.Response));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 10. pins for guards the first pass left unproven ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_link_continues_in_its_own_slot_and_leaves_a_parallel_sign_in_attempt_alive()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var parallel = await host.StartAsync();
|
||||||
|
var parallelCookie = $"{parallel.CookieName}={parallel.Cookie}";
|
||||||
|
var start = await host.StartLinkAsync(session, extraCookies: parallelCookie);
|
||||||
|
// The parallel attempt holds slot 0, so the link lives in the other slot.
|
||||||
|
Assert.Equal(HeimdallAttemptCookie.SlotNames[0], parallel.CookieName);
|
||||||
|
Assert.Equal(HeimdallAttemptCookie.SlotNames[1], start.CookieName);
|
||||||
|
|
||||||
|
var b = await StepB(host, session, start, account);
|
||||||
|
var awaiting = new Step(b.Response, b.Next, b.Token);
|
||||||
|
var pending = host.Heimdall.RegisterPendingLink();
|
||||||
|
var c = await StepC(host, session, awaiting.Next, pending);
|
||||||
|
var d = await StepD(host, session, c.Next, account);
|
||||||
|
|
||||||
|
// Every continuation wrote the link's own slot and none touched the parallel attempt's slot.
|
||||||
|
foreach (var response in new[] { b.Response, c.Response })
|
||||||
|
{
|
||||||
|
Assert.NotNull(HeimdallHost.SetCookieHeader(response, start.CookieName!));
|
||||||
|
Assert.Null(HeimdallHost.SetCookieHeader(response, parallel.CookieName!));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(start.CookieName, b.Next.CookieName);
|
||||||
|
Assert.Equal(start.CookieName, c.Next.CookieName);
|
||||||
|
Assert.Equal(LinkedPage + "?result=linked", Location(d.Response));
|
||||||
|
Assert.Null(HeimdallHost.SetCookieHeader(d.Response, parallel.CookieName!));
|
||||||
|
|
||||||
|
var signIn = await host.CompleteWithHeaderAsync(
|
||||||
|
parallel.Nonce, host.CodeFor(parallel, HeimdallShapes.NewAccountId()), parallelCookie);
|
||||||
|
Assert.True(signIn.SignedIn);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("11")]
|
||||||
|
[InlineData("-1")]
|
||||||
|
[InlineData("99")]
|
||||||
|
public async Task An_attempt_cookie_with_an_undefined_purpose_is_no_attempt_and_asks_Heimdall_for_nothing(string purpose)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var nonce = "crafted-" + Guid.NewGuid().ToString("N");
|
||||||
|
var protector = host.Services.GetRequiredService<IDataProtectionProvider>().CreateProtector("Bifrost.Heimdall.Attempt.v1");
|
||||||
|
var crafted = protector.Protect(
|
||||||
|
$$"""{"Nonce":"{{nonce}}","Provider":"discord","RequiresMemberAccess":false,"ReturnPath":"/App/Mill","ExpiresAt":"{{host.Clock.Now.AddMinutes(5):O}}","Purpose":{{purpose}},"ExpectedAccountId":"{{account}}","PendingLinkId":"p"}""");
|
||||||
|
var attempt = new StartedAttempt(
|
||||||
|
nonce, HeimdallAttemptCookie.SlotNames[0], crafted, $"https://localhost/auth/heimdall/complete?attempt={nonce}", null!);
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
var redeems = host.Heimdall.RedeemCalls;
|
||||||
|
|
||||||
|
var response = await host.PostCompleteAsync(
|
||||||
|
new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["attempt"] = nonce, ["code"] = host.CodeFor(attempt, account), ["pendingLinkId"] = "p"
|
||||||
|
},
|
||||||
|
Jar(session, attempt));
|
||||||
|
|
||||||
|
Assert.Equal(ErrorRedirect, Location(response));
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(redeems, host.Heimdall.RedeemCalls);
|
||||||
|
Assert.Empty(host.Heimdall.ConfirmBodies);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
public async Task An_await_step_without_a_pending_link_id_is_refused_before_Heimdall_hears_of_it(string pendingLinkId)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session);
|
||||||
|
var b = await StepB(host, session, start, account);
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
var redeems = host.Heimdall.RedeemCalls;
|
||||||
|
|
||||||
|
var c = await StepC(host, session, b.Next, pendingLinkId);
|
||||||
|
|
||||||
|
Assert.Equal(LinkedPage + "?result=error", Location(c.Response));
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(redeems, host.Heimdall.RedeemCalls);
|
||||||
|
Assert.Empty(host.Heimdall.ConfirmBodies);
|
||||||
|
AssertAttemptCleared(c.Response, b.Next);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData("{}")]
|
||||||
|
[InlineData("""{"status":"pending"}""")]
|
||||||
|
[InlineData("""{"status":"Linked"}""")]
|
||||||
|
[InlineData("not json")]
|
||||||
|
public async Task A_201_confirm_that_does_not_say_linked_is_not_shown_as_linked(string body)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var journey = await ThroughC(host);
|
||||||
|
host.Heimdall.ConfirmStatus = HttpStatusCode.Created;
|
||||||
|
host.Heimdall.ConfirmBody = body;
|
||||||
|
|
||||||
|
var d = await StepD(host, journey.Session, journey.C.Next, journey.Account);
|
||||||
|
|
||||||
|
Assert.Equal(LinkedPage + "?result=error", Location(d.Response));
|
||||||
|
Assert.Single(host.Heimdall.ConfirmBodies);
|
||||||
|
AssertAttemptCleared(d.Response, journey.C.Next);
|
||||||
|
}
|
||||||
|
}
|
||||||
728
tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs
Normal file
728
tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs
Normal file
|
|
@ -0,0 +1,728 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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<HeimdallIdentityMoveClient>();
|
||||||
|
|
||||||
|
private static Task<HeimdallMoveOutcome> Move(HeimdallHost host, HeimdallMoveRequest request) =>
|
||||||
|
ClientOf(host).MoveAsync(request, CancellationToken.None);
|
||||||
|
|
||||||
|
private static HeimdallMoveReceipt Receipt(HeimdallMoveOutcome outcome) => Assert.IsType<Moved>(outcome).Receipt;
|
||||||
|
|
||||||
|
/// <summary>An account holding these providers, one login each, in order.</summary>
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The usual forward move of everything: a passkey proof of the source and a weak proof of the destination.</summary>
|
||||||
|
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<Unknown>(await Move(host, request));
|
||||||
|
Assert.Single(moves.Stored);
|
||||||
|
moves.MoveApplyThenFail = HttpStatusCode.OK;
|
||||||
|
Assert.IsType<Unknown>(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, "<html><body>404 Not Found</body></html>")]
|
||||||
|
[InlineData(HttpStatusCode.NotFound, "")]
|
||||||
|
[InlineData(HttpStatusCode.BadRequest, "<html><head><title>400 Bad Request</title></head><body>nginx</body></html>")]
|
||||||
|
[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<Unknown>(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<Unknown>(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<HeimdallIdentityMoveClient>.Instance);
|
||||||
|
|
||||||
|
Assert.IsType<Unknown>(await client.MoveAsync(Plain, CancellationToken.None));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Throwing(Exception error) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
protected override Task<HttpResponseMessage> 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<Unknown>(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<Unknown>(await Move(host, request));
|
||||||
|
moves.MoveDown = new HttpRequestException("Heimdall is down");
|
||||||
|
Assert.IsType<Unknown>(await Move(host, request));
|
||||||
|
moves.MoveDown = null;
|
||||||
|
moves.MoveApplyThenFail = HttpStatusCode.OK;
|
||||||
|
Assert.IsType<Unknown>(await Move(host, request));
|
||||||
|
moves.MoveApplyThenFail = null;
|
||||||
|
|
||||||
|
using var cancelled = new CancellationTokenSource();
|
||||||
|
await cancelled.CancelAsync();
|
||||||
|
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => ClientOf(host).MoveAsync(request, cancelled.Token));
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Stub(Func<HttpContent> 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<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||||
|
Task.FromResult(new HttpResponseMessage(status) { Content = content() });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A body that serves a prefix and then stalls, resets, or streams endless filler.</summary>
|
||||||
|
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<int> ReadAsync(Memory<byte> 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<HeimdallIdentityMoveClient>.Instance);
|
||||||
|
|
||||||
|
private static Task<HeimdallMoveOutcome> 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<Moved>(await Answered(Body(), forward));
|
||||||
|
Assert.IsType<Moved>(await Answered(Body(ids: "\"not-a-guid-but-an-id\""), forward));
|
||||||
|
Assert.IsType<Moved>(await Answered(Body("move-0123456789abcdef", "move-fedcba9876543210", """{"from":"strong","to":null}"""), reversal));
|
||||||
|
|
||||||
|
Assert.IsType<Unknown>(await Answered(Body("move-someoneelse12345"), forward));
|
||||||
|
Assert.IsType<Unknown>(await Answered(Body(reverses: "move-fedcba9876543210"), forward));
|
||||||
|
Assert.IsType<Unknown>(await Answered(Body(), reversal));
|
||||||
|
Assert.IsType<Unknown>(await Answered(Body("move-0123456789abcdef", "move-other0123456789", """{"from":"strong","to":null}"""), reversal));
|
||||||
|
Assert.IsType<Unknown>(await Answered(Body("move-0123456789abcdef", "move-fedcba9876543210", """{"from":"strong","to":"weak"}"""), reversal));
|
||||||
|
Assert.IsType<Unknown>(await Answered(Body(proof: """{"from":"strong","to":null}"""), forward));
|
||||||
|
Assert.IsType<Unknown>(await Answered(Body(proof: """{"from":"maybe","to":"weak"}"""), forward));
|
||||||
|
Assert.IsType<Unknown>(await Answered(Body(ids: ""), forward));
|
||||||
|
Assert.IsType<Unknown>(await Answered(Body(ids: "123"), forward));
|
||||||
|
Assert.IsType<Unknown>(await Answered("""{"moveId":"move-0123456789abcdef"}""", forward));
|
||||||
|
Assert.IsType<Unknown>(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<ArgumentException>(() => 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<Unknown>(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<Unknown>(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<Unknown>(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<IHttpClientFactory>().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<string>();
|
||||||
|
_ = 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<HeimdallIdentityMoveClient>()
|
||||||
|
.MoveAsync(new("move-0123456789abcdef", ["FROM-BEARER"], "TO-BEARER"), CancellationToken.None);
|
||||||
|
await redirected;
|
||||||
|
await Task.Delay(300);
|
||||||
|
|
||||||
|
Assert.IsType<Unknown>(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<Refused>(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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
76
tests/Bifrost.Web.Tests/HeimdallRedirectTests.cs
Normal file
76
tests/Bifrost.Web.Tests/HeimdallRedirectTests.cs
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
using System.Net;
|
||||||
|
using Bifrost.Web.Configuration;
|
||||||
|
using Bifrost.Web.Features.Heimdall;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Every Heimdall client as Program registers it (<see cref="HeimdallClientServices.AddHeimdallClients"/>): a 3xx from Heimdall's origin
|
||||||
|
/// is the answer, never a second request. The app secret and a member's bearer reach only the origin they were configured for.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class HeimdallRedirectTests
|
||||||
|
{
|
||||||
|
private 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(typeof(HeimdallAuthService), 307)]
|
||||||
|
[InlineData(typeof(HeimdallAuthService), 302)]
|
||||||
|
[InlineData(typeof(HeimdallMemberClient), 307)]
|
||||||
|
[InlineData(typeof(HeimdallMemberClient), 302)]
|
||||||
|
[InlineData(typeof(HeimdallIdentityMoveClient), 307)]
|
||||||
|
public async Task A_redirect_from_Heimdall_is_not_followed_and_no_secret_or_bearer_reaches_the_other_host(Type client, int code)
|
||||||
|
{
|
||||||
|
int first = FreePort(), second = FreePort();
|
||||||
|
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<string>();
|
||||||
|
_ = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var context = await other.GetContextAsync();
|
||||||
|
stolen.Add(context.Request.Headers["x-heimdall-app-secret"] + context.Request.Headers["Authorization"]);
|
||||||
|
context.Response.StatusCode = 200;
|
||||||
|
context.Response.Close();
|
||||||
|
}
|
||||||
|
catch (Exception error) when (error is HttpListenerException or ObjectDisposedException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
});
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
services.AddLogging();
|
||||||
|
services.AddSingleton(Options.Create(new HeimdallOptions { BaseUrl = $"http://127.0.0.1:{first}", AppSecret = "APP-SECRET-VALUE" }));
|
||||||
|
services.AddHeimdallClients();
|
||||||
|
using var provider = services.BuildServiceProvider();
|
||||||
|
using var http = provider.GetRequiredService<IHttpClientFactory>().CreateClient(client.Name);
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/v1/me/identities");
|
||||||
|
request.Headers.Authorization = new("Bearer", "MEMBER-BEARER");
|
||||||
|
|
||||||
|
using var response = await http.SendAsync(request);
|
||||||
|
await redirected;
|
||||||
|
await Task.Delay(300);
|
||||||
|
|
||||||
|
Assert.Equal(code, (int)response.StatusCode);
|
||||||
|
Assert.Empty(stolen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -145,6 +145,36 @@ public sealed class HostTrustTests : IClassFixture<TestWebApplicationFactory>
|
||||||
Assert.DoesNotContain(canary, refusal.Message);
|
Assert.DoesNotContain(canary, refusal.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
public void Production_without_a_heimdall_app_secret_refuses_startup_naming_the_options(string blank)
|
||||||
|
{
|
||||||
|
var refusal = Assert.Throws<InvalidOperationException>(
|
||||||
|
() => Validate(keysPath: "/keys", appSecret: blank));
|
||||||
|
|
||||||
|
Assert.Contains("Heimdall:AppSecretFile", refusal.Message);
|
||||||
|
Assert.Contains("Heimdall:AppSecret", refusal.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Production_with_a_heimdall_app_secret_passes_and_other_refusals_never_echo_it()
|
||||||
|
{
|
||||||
|
Validate(keysPath: "/keys", appSecret: ValidAppSecret);
|
||||||
|
|
||||||
|
var refusal = Assert.Throws<InvalidOperationException>(
|
||||||
|
() => Validate(keysPath: null, appSecret: ValidAppSecret));
|
||||||
|
Assert.DoesNotContain(ValidAppSecret, refusal.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Development")]
|
||||||
|
[InlineData("Testing")]
|
||||||
|
public void Development_and_Testing_start_without_a_heimdall_app_secret(string environment)
|
||||||
|
{
|
||||||
|
Validate(keysPath: null, environment: environment, appSecret: "");
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Production_without_network_tag_secret_fails_and_never_echoes_values()
|
public void Production_without_network_tag_secret_fails_and_never_echoes_values()
|
||||||
{
|
{
|
||||||
|
|
@ -315,12 +345,14 @@ public sealed class HostTrustTests : IClassFixture<TestWebApplicationFactory>
|
||||||
}
|
}
|
||||||
|
|
||||||
private const string ValidTagSecret = "tag-secret-0123456789-0123456789-abcdef";
|
private const string ValidTagSecret = "tag-secret-0123456789-0123456789-abcdef";
|
||||||
|
private const string ValidAppSecret = "app-secret-5c0e91d4";
|
||||||
|
|
||||||
private static void Validate(
|
private static void Validate(
|
||||||
string? keysPath,
|
string? keysPath,
|
||||||
string environment = "Production",
|
string environment = "Production",
|
||||||
string? connectionString = "Host=db",
|
string? connectionString = "Host=db",
|
||||||
string? tagSecret = ValidTagSecret,
|
string? tagSecret = ValidTagSecret,
|
||||||
|
string appSecret = ValidAppSecret,
|
||||||
int ipv4Length = 32,
|
int ipv4Length = 32,
|
||||||
int ipv6Length = 56,
|
int ipv6Length = 56,
|
||||||
string[]? allowedOrigins = null,
|
string[]? allowedOrigins = null,
|
||||||
|
|
@ -344,7 +376,7 @@ public sealed class HostTrustTests : IClassFixture<TestWebApplicationFactory>
|
||||||
hostEnvironment,
|
hostEnvironment,
|
||||||
Options.Create(new GitHubOAuthOptions { ClientId = "id", ClientSecret = "secret" }),
|
Options.Create(new GitHubOAuthOptions { ClientId = "id", ClientSecret = "secret" }),
|
||||||
Options.Create(new GitHubAppOptions { EnableWebhookSync = false }),
|
Options.Create(new GitHubAppOptions { EnableWebhookSync = false }),
|
||||||
Options.Create(new HeimdallOptions { EnablePatronSupportIntake = false }),
|
Options.Create(new HeimdallOptions { EnablePatronSupportIntake = false, AppSecret = appSecret }),
|
||||||
Options.Create(new StripeOptions()),
|
Options.Create(new StripeOptions()),
|
||||||
Options.Create(new BifrostHostOptions
|
Options.Create(new BifrostHostOptions
|
||||||
{
|
{
|
||||||
|
|
|
||||||
912
tests/Bifrost.Web.Tests/LinkedAccountsTests.cs
Normal file
912
tests/Bifrost.Web.Tests/LinkedAccountsTests.cs
Normal file
|
|
@ -0,0 +1,912 @@
|
||||||
|
using System.Net;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Bifrost.Web.Features.Heimdall;
|
||||||
|
using Bifrost.Web.Features.Shared;
|
||||||
|
using Bifrost.Web.Tests.Support;
|
||||||
|
using Microsoft.AspNetCore.DataProtection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The Linked accounts page from the member's side, against a fake Heimdall. Bifrost keeps no Heimdall token: a list, a link
|
||||||
|
/// and an unlink each follow a fresh Heimdall sign-in begun by Bifrost, and the bearer lives inside that one completion request.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class LinkedAccountsTests
|
||||||
|
{
|
||||||
|
private const string Page = "/Membership/LinkedAccounts";
|
||||||
|
private const string ErrorRedirect = "/?auth=heimdall-error";
|
||||||
|
|
||||||
|
private static string Jar(string session, StartedAttempt attempt) =>
|
||||||
|
$"{BifrostCookies.Session}={session}; {attempt.CookieName}={attempt.Cookie}";
|
||||||
|
|
||||||
|
private static string? Location(HttpResponseMessage response) => response.Headers.Location?.OriginalString;
|
||||||
|
|
||||||
|
private static string Unprotect(HeimdallHost host, string cookie) =>
|
||||||
|
host.Services.GetRequiredService<IDataProtectionProvider>().CreateProtector("Bifrost.Heimdall.Attempt.v1").Unprotect(cookie);
|
||||||
|
|
||||||
|
/// <summary>The fresh sign-in's completion as the browser posts it: Heimdall minted a code for <paramref name="proofAccount"/>.</summary>
|
||||||
|
private static async Task<HttpResponseMessage> Finish(
|
||||||
|
HeimdallHost host, string session, StartedAttempt attempt, string proofAccount, string? token = null,
|
||||||
|
string mode = "sign_in", string provider = "discord", string? sessionOverride = null, bool? stepUpRequested = null)
|
||||||
|
{
|
||||||
|
var code = host.CodeFor(attempt, proofAccount, token, mode: mode, provider: provider, stepUpRequested: stepUpRequested);
|
||||||
|
return await host.PostCompleteAsync(
|
||||||
|
new Dictionary<string, string> { ["attempt"] = attempt.Nonce, ["code"] = code }, Jar(sessionOverride ?? session, attempt));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string StepUpToken(HeimdallHost host, string account) =>
|
||||||
|
host.Token(account, mutate: claims => claims["step_up_at"] = host.Clock.Now.ToUnixTimeSeconds());
|
||||||
|
|
||||||
|
private sealed record Member(string Account, string Session);
|
||||||
|
|
||||||
|
/// <summary>A signed-in member whose fake Heimdall account holds these providers, and whose list has been read once.</summary>
|
||||||
|
private static async Task<Member> ListedMember(HeimdallHost host, params string[] providers)
|
||||||
|
{
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
foreach (var provider in providers)
|
||||||
|
{
|
||||||
|
host.Heimdall.AddIdentity(provider, "Name of " + provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
var start = await host.StartListAsync(session, providers[0]);
|
||||||
|
var done = await Finish(host, session, start, account);
|
||||||
|
Assert.Equal(Page + "?result=listed", Location(done));
|
||||||
|
Assert.Empty(host.Heimdall.OrphanMints);
|
||||||
|
return new Member(account, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- who may use the page ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task An_anonymous_visitor_is_challenged_and_nothing_is_started()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
|
||||||
|
var (get, _) = await host.GetLinkedAccountsAsync(session: null);
|
||||||
|
var post = await host.PostLinkedAccountsAsync(session: null, "Refresh");
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, get.StatusCode);
|
||||||
|
Assert.Contains("/auth/sign-in", Location(get));
|
||||||
|
Assert.NotEqual(HttpStatusCode.OK, post.Response.StatusCode);
|
||||||
|
Assert.Empty(host.Heimdall.StartBodies);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task The_page_is_no_store_and_a_member_without_a_list_is_offered_one()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
|
||||||
|
var (response, html) = await host.GetLinkedAccountsAsync(session);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
|
||||||
|
Assert.Contains("Show my logins through", html);
|
||||||
|
Assert.Contains("Show my logins through Patreon", html);
|
||||||
|
Assert.Contains("will not choose one for you", html);
|
||||||
|
Assert.DoesNotContain("Link Discord", html);
|
||||||
|
Assert.DoesNotContain("Unlink", html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task With_a_list_the_page_offers_each_admitted_provider_to_link_and_never_twitch()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(member.Session);
|
||||||
|
|
||||||
|
Assert.Contains("Link Discord", html);
|
||||||
|
Assert.Contains("Link Patreon", html);
|
||||||
|
Assert.Contains("Link Google", html);
|
||||||
|
Assert.DoesNotContain("Link Twitch", html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task After_the_list_expired_a_proof_is_never_started_through_a_provider_the_member_unlinked()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account); // signed in through Discord
|
||||||
|
var discord = host.Heimdall.AddIdentity("discord", "D");
|
||||||
|
host.Heimdall.AddIdentity("google", "G");
|
||||||
|
var list = await host.StartListAsync(session, "discord");
|
||||||
|
await Finish(host, session, list, account);
|
||||||
|
var unlink = await host.StartUnlinkAsync(session, discord);
|
||||||
|
var done = await Finish(host, session, unlink, account, provider: "google");
|
||||||
|
Assert.Equal(Page + "?result=unlinked", Location(done));
|
||||||
|
host.Clock.Advance(LinkedAccountsSnapshots.Lifetime + TimeSpan.FromSeconds(1));
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var refresh = await host.StartListAsync(session, via: null);
|
||||||
|
var link = await host.StartLinkAsync(session, "patreon", seedList: false);
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(session);
|
||||||
|
|
||||||
|
// Signing in through Discord again would mint an unrelated account holding that login: nothing is started.
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(Page + "?result=provider_needed", Location(refresh.Response));
|
||||||
|
Assert.Equal(Page + "?result=list_expired", Location(link.Response));
|
||||||
|
Assert.Empty(host.Heimdall.OrphanMints);
|
||||||
|
Assert.Contains("will not choose one for you", html);
|
||||||
|
Assert.DoesNotContain("Link Patreon", html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(HttpStatusCode.InternalServerError)]
|
||||||
|
[InlineData(HttpStatusCode.OK)]
|
||||||
|
public async Task An_unlink_whose_answer_is_lost_drops_the_list_and_a_link_then_starts_nothing(HttpStatusCode lost)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var discord = (string)host.Heimdall.Identities[0]["id"]!;
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, discord);
|
||||||
|
host.Heimdall.UnlinkApplyThenFail = lost;
|
||||||
|
|
||||||
|
var done = await Finish(host, member.Session, start, member.Account, provider: "google");
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
var link = await host.StartLinkAsync(member.Session, "patreon", seedList: false);
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(member.Session);
|
||||||
|
|
||||||
|
// Heimdall did unlink Discord. Linking now through the stale list would sign in through Discord and mint an orphan.
|
||||||
|
Assert.Equal(Page + "?result=error", Location(done));
|
||||||
|
Assert.Single(host.Heimdall.Identities);
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(Page + "?result=list_expired", Location(link.Response));
|
||||||
|
Assert.Empty(host.Heimdall.OrphanMints);
|
||||||
|
Assert.Contains("will not choose one for you", html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Without_a_list_the_picker_names_Google_first_as_unable_to_create_an_account()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(session);
|
||||||
|
|
||||||
|
Assert.Contains("Google cannot do that", html);
|
||||||
|
Assert.Contains("through Google (cannot create an account)", html);
|
||||||
|
Assert.True(html.IndexOf("Show my logins through Google", StringComparison.Ordinal) < html.IndexOf("Show my logins through Discord", StringComparison.Ordinal));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void With_no_list_and_no_choice_there_is_no_proof_provider()
|
||||||
|
{
|
||||||
|
Assert.Null(HeimdallAuthService.ProofProvider(null, null));
|
||||||
|
Assert.Null(HeimdallAuthService.ProofProvider(null, "twitch"));
|
||||||
|
Assert.Equal("patreon", HeimdallAuthService.ProofProvider(null, "Patreon"));
|
||||||
|
Assert.Null(HeimdallAuthService.ProofProvider([], "discord"));
|
||||||
|
Assert.Null(HeimdallAuthService.ProofProvider(["twitch"], null));
|
||||||
|
Assert.Equal("patreon", HeimdallAuthService.ProofProvider(["google", "patreon"], null));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task The_service_refuses_to_start_a_proof_with_no_list_and_no_choice()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
using var scope = host.Services.CreateScope();
|
||||||
|
var service = scope.ServiceProvider.GetRequiredService<HeimdallAuthService>();
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<HeimdallAuthException>(() => service.StartListAsync(
|
||||||
|
HeimdallShapes.NewAccountId(), null, "https://localhost", [], CancellationToken.None));
|
||||||
|
await Assert.ThrowsAsync<HeimdallAuthException>(() => service.StartLinkAsync(
|
||||||
|
HeimdallShapes.NewAccountId(), "patreon", "https://localhost", [], CancellationToken.None));
|
||||||
|
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("twitch")]
|
||||||
|
[InlineData("nonsense")]
|
||||||
|
public async Task Without_a_list_the_member_must_name_an_admitted_provider_or_nothing_is_started(string? via)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var post = await host.StartListAsync(session, via);
|
||||||
|
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(Page + "?result=provider_needed", Location(post.Response));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task With_a_list_the_member_cannot_steer_the_proof_to_a_provider_the_account_does_not_hold()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "patreon", "google");
|
||||||
|
|
||||||
|
var post = await host.StartListAsync(member.Session, "discord");
|
||||||
|
|
||||||
|
Assert.Equal("/v1/oauth/patreon/start", host.Heimdall.StartPaths[^1]);
|
||||||
|
Assert.Empty(host.Heimdall.OrphanMints);
|
||||||
|
Assert.NotNull(post.Cookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_session_with_no_Heimdall_account_has_nothing_to_list_and_starts_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost();
|
||||||
|
|
||||||
|
var (response, html) = await host.GetLinkedAccountsAsync(session: null);
|
||||||
|
var start = await host.StartListAsync(session: null);
|
||||||
|
|
||||||
|
// No form, so no antiforgery token to make the response uncacheable: the page itself must say no-store.
|
||||||
|
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
|
||||||
|
Assert.Contains("not a Heimdall account", html);
|
||||||
|
Assert.DoesNotContain("Link Discord", html);
|
||||||
|
Assert.Empty(host.Heimdall.StartBodies);
|
||||||
|
Assert.Null(start.Cookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Refresh")]
|
||||||
|
[InlineData("Link")]
|
||||||
|
[InlineData("Unlink")]
|
||||||
|
public async Task Every_post_needs_the_antiforgery_token_and_a_get_starts_nothing(string handler)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
var form = new Dictionary<string, string> { ["provider"] = "discord", ["identityId"] = Guid.NewGuid().ToString() };
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var without = await host.PostLinkedAccountsAsync(session, handler, form, antiforgery: false);
|
||||||
|
var get = await host.PostLinkedAccountsAsync(session, handler, form, method: HttpMethod.Get);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, without.Response.StatusCode);
|
||||||
|
Assert.Null(without.Cookie);
|
||||||
|
Assert.Null(get.Cookie);
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the list ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task The_list_is_a_fresh_ordinary_sign_in_then_GET_identities_with_its_bearer_and_the_page_shows_it()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(traceHttp: true, realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
host.Heimdall.AddIdentity("discord", "Discord Dana");
|
||||||
|
host.Heimdall.AddIdentity("google", "Google Gale");
|
||||||
|
var signIns = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var start = await host.StartListAsync(session);
|
||||||
|
|
||||||
|
Assert.Equal(signIns + 1, host.Heimdall.StartBodies.Count);
|
||||||
|
using (var body = JsonDocument.Parse(host.Heimdall.StartBodies[^1]))
|
||||||
|
{
|
||||||
|
Assert.Equal("sign_in", body.RootElement.GetProperty("mode").GetString());
|
||||||
|
Assert.False(body.RootElement.TryGetProperty("stepUp", out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal("/v1/oauth/discord/start", host.Heimdall.StartPaths[^1]);
|
||||||
|
Assert.Empty(host.Heimdall.ListAuthorizations);
|
||||||
|
|
||||||
|
var token = host.Token(account);
|
||||||
|
var done = await Finish(host, session, start, account, token);
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=listed", Location(done));
|
||||||
|
Assert.Equal(["Bearer " + token], host.Heimdall.ListAuthorizations);
|
||||||
|
Assert.Null(HeimdallHost.CookieValue(done, BifrostCookies.Session));
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(session);
|
||||||
|
Assert.Contains("Discord Dana", html);
|
||||||
|
Assert.Contains("Google Gale", html);
|
||||||
|
Assert.Contains("13 Nov 2026", html);
|
||||||
|
// Only what the page shows was kept: nothing of the fields a login also carries.
|
||||||
|
foreach (var canary in new[] { "PUID-CANARY", "username-canary", "scope-canary" })
|
||||||
|
{
|
||||||
|
Assert.DoesNotContain(canary, html);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task No_bearer_reaches_a_cookie_a_log_a_location_or_the_page()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(traceHttp: true, realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
host.Heimdall.AddIdentity("discord");
|
||||||
|
host.Heimdall.AddIdentity("google");
|
||||||
|
var listStart = await host.StartListAsync(session);
|
||||||
|
var listToken = host.Token(account);
|
||||||
|
var listed = await Finish(host, session, listStart, account, listToken);
|
||||||
|
var unlinkStart = await host.StartUnlinkAsync(session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
var stepUpToken = StepUpToken(host, account);
|
||||||
|
var unlinked = await Finish(host, session, unlinkStart, account, stepUpToken);
|
||||||
|
Assert.Equal(Page + "?result=unlinked", Location(unlinked));
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(session);
|
||||||
|
|
||||||
|
var logs = string.Join("\n", host.Logs.Lines);
|
||||||
|
var secrets = new[] { listToken, stepUpToken }
|
||||||
|
.SelectMany(token => new[] { token, token.Split('.')[2], token.Split('.')[1] })
|
||||||
|
.ToArray();
|
||||||
|
Assert.Contains("Bearer", string.Join("\n", host.Heimdall.ListAuthorizations));
|
||||||
|
foreach (var secret in secrets)
|
||||||
|
{
|
||||||
|
Assert.DoesNotContain(secret, logs);
|
||||||
|
Assert.DoesNotContain(secret, html);
|
||||||
|
foreach (var response in new[] { listStart.Response, listed, unlinkStart.Response, unlinked })
|
||||||
|
{
|
||||||
|
Assert.DoesNotContain(secret, Location(response) ?? string.Empty);
|
||||||
|
Assert.DoesNotContain(secret, string.Join("\n", response.Headers.SelectMany(x => x.Value)));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var cookie in new[] { listStart.Cookie, unlinkStart.Cookie })
|
||||||
|
{
|
||||||
|
var payload = Unprotect(host, cookie!);
|
||||||
|
Assert.DoesNotContain(secret, payload);
|
||||||
|
Assert.DoesNotContain("eyJ", payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The completion itself sets no cookie but the attempt's deletion.
|
||||||
|
foreach (var response in new[] { listed, unlinked })
|
||||||
|
{
|
||||||
|
Assert.All(
|
||||||
|
response.Headers.TryGetValues("Set-Cookie", out var set) ? set : [],
|
||||||
|
header => Assert.StartsWith(HeimdallAttemptCookie.Prefix, header, StringComparison.Ordinal));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_list_is_per_account_and_expires_after_five_minutes()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var stranger = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
|
||||||
|
Assert.Contains("Name of discord", (await host.GetLinkedAccountsAsync(member.Session)).Html);
|
||||||
|
var (_, other) = await host.GetLinkedAccountsAsync(stranger);
|
||||||
|
Assert.DoesNotContain("Name of discord", other);
|
||||||
|
Assert.Contains("Show my logins through", other);
|
||||||
|
|
||||||
|
host.Clock.Advance(LinkedAccountsSnapshots.Lifetime + TimeSpan.FromSeconds(1));
|
||||||
|
|
||||||
|
var (_, later) = await host.GetLinkedAccountsAsync(member.Session);
|
||||||
|
Assert.DoesNotContain("Name of discord", later);
|
||||||
|
Assert.Contains("Show my logins through", later);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(HttpStatusCode.Unauthorized, "sign_in_required")]
|
||||||
|
[InlineData(HttpStatusCode.InternalServerError, "error")]
|
||||||
|
public async Task A_list_Heimdall_refuses_shows_its_fixed_outcome_and_no_list(HttpStatusCode status, string outcome)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
host.Heimdall.AddIdentity("discord");
|
||||||
|
host.Heimdall.ListStatus = status;
|
||||||
|
var start = await host.StartListAsync(session);
|
||||||
|
|
||||||
|
var done = await Finish(host, session, start, account);
|
||||||
|
|
||||||
|
Assert.Equal($"{Page}?result={outcome}", Location(done));
|
||||||
|
Assert.DoesNotContain("HEIMDALL FREE TEXT", string.Join("\n", host.Logs.Lines));
|
||||||
|
Assert.Contains("Show my logins through", (await host.GetLinkedAccountsAsync(session)).Html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_Heimdall_that_cannot_be_reached_for_the_list_changes_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
host.Heimdall.AddIdentity("discord");
|
||||||
|
var start = await host.StartListAsync(session);
|
||||||
|
host.Heimdall.MemberFailure = new HttpRequestException("connection refused");
|
||||||
|
|
||||||
|
var done = await Finish(host, session, start, account);
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=error", Location(done));
|
||||||
|
Assert.Contains("Show my logins through", (await host.GetLinkedAccountsAsync(session)).Html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_Heimdall_that_is_down_at_the_list_start_is_a_refusal_not_a_server_error()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
host.Heimdall.StartStatus = HttpStatusCode.ServiceUnavailable;
|
||||||
|
|
||||||
|
var start = await host.StartListAsync(session);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, start.Response.StatusCode);
|
||||||
|
Assert.Equal(Page + "?result=error", Location(start.Response));
|
||||||
|
Assert.Null(start.Cookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- unlink ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unlink_starts_a_step_up_sign_in_with_the_app_secret_and_the_unlink_carries_that_sign_ins_bearer()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var discord = (string)host.Heimdall.Identities[0]["id"]!;
|
||||||
|
var listToken = host.Heimdall.ListAuthorizations.Single();
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, discord);
|
||||||
|
|
||||||
|
Assert.Equal(starts + 1, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal("/v1/oauth/google/start", host.Heimdall.StartPaths[^1]);
|
||||||
|
Assert.Equal(HeimdallHost.AppSecret, host.Heimdall.StartSecrets[^1]);
|
||||||
|
Assert.Null(host.Heimdall.StartAuthorizations[^1]);
|
||||||
|
using (var body = JsonDocument.Parse(host.Heimdall.StartBodies[^1]))
|
||||||
|
{
|
||||||
|
Assert.Equal("sign_in", body.RootElement.GetProperty("mode").GetString());
|
||||||
|
Assert.True(body.RootElement.GetProperty("stepUp").GetBoolean());
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Empty(host.Heimdall.Unlinks);
|
||||||
|
var token = StepUpToken(host, member.Account);
|
||||||
|
var done = await Finish(host, member.Session, start, member.Account, token, provider: "google");
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=unlinked", Location(done));
|
||||||
|
var unlink = Assert.Single(host.Heimdall.Unlinks);
|
||||||
|
Assert.Equal(discord, unlink.Id);
|
||||||
|
Assert.Equal("Bearer " + token, unlink.Authorization);
|
||||||
|
Assert.NotEqual(listToken, unlink.Authorization);
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(member.Session);
|
||||||
|
Assert.DoesNotContain("Name of discord", html);
|
||||||
|
Assert.Contains("Name of google", html);
|
||||||
|
Assert.Contains("Heimdall will not remove the last one", html);
|
||||||
|
Assert.Contains("The login was unlinked.", (await host.GetLinkedAccountsAsync(member.Session, "?result=unlinked")).Html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task The_last_login_is_refused_by_Heimdall_and_the_page_still_shows_it()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "google");
|
||||||
|
var only = (string)host.Heimdall.Identities[0]["id"]!;
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, only);
|
||||||
|
|
||||||
|
var done = await Finish(host, member.Session, start, member.Account, StepUpToken(host, member.Account), provider: "google");
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=last_identity", Location(done));
|
||||||
|
Assert.Single(host.Heimdall.Unlinks);
|
||||||
|
Assert.Single(host.Heimdall.Identities);
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(member.Session);
|
||||||
|
Assert.Contains("Name of google", html);
|
||||||
|
Assert.Contains("will not remove it. Nothing was changed.", (await host.GetLinkedAccountsAsync(member.Session, "?result=last_identity")).Html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_sign_in_Heimdall_does_not_count_as_fresh_proof_changes_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
|
||||||
|
// An ordinary token: no step_up_at claim, so Heimdall answers 403 step_up_required.
|
||||||
|
var done = await Finish(host, member.Session, start, member.Account, host.Token(member.Account), provider: "google");
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=step_up_required", Location(done));
|
||||||
|
Assert.Equal(2, host.Heimdall.Identities.Count);
|
||||||
|
Assert.Contains("Name of discord", (await host.GetLinkedAccountsAsync(member.Session)).Html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_completion_that_does_not_say_a_step_up_was_asked_unlinks_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
|
||||||
|
// The token even carries step_up_at, but the completion is not the answer to a step-up start.
|
||||||
|
var done = await Finish(host, member.Session, start, member.Account, StepUpToken(host, member.Account), provider: "google",
|
||||||
|
stepUpRequested: false);
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=step_up_required", Location(done));
|
||||||
|
Assert.Empty(host.Heimdall.Unlinks);
|
||||||
|
Assert.Equal(2, host.Heimdall.Identities.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_proof_older_than_600_seconds_is_refused_by_Heimdall_and_changes_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
// The sign-in happened 601 seconds before the unlink reaches Heimdall (the attempt itself lives ten minutes).
|
||||||
|
var stale = host.Token(member.Account, mutate: claims => claims["step_up_at"] = host.Clock.Now.ToUnixTimeSeconds() - 601);
|
||||||
|
|
||||||
|
var done = await Finish(host, member.Session, start, member.Account, stale, provider: "google");
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=step_up_required", Location(done));
|
||||||
|
Assert.Single(host.Heimdall.Unlinks);
|
||||||
|
Assert.Equal(2, host.Heimdall.Identities.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Every_completion_answer_is_no_store()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
host.Heimdall.AddIdentity("discord");
|
||||||
|
var start = await host.StartListAsync(session);
|
||||||
|
|
||||||
|
var done = await Finish(host, session, start, account);
|
||||||
|
var refused = await host.PostCompleteAsync(new Dictionary<string, string> { ["attempt"] = "nope" }, null);
|
||||||
|
|
||||||
|
Assert.Contains("no-store", done.Headers.CacheControl?.ToString());
|
||||||
|
Assert.Contains("no-store", refused.Headers.CacheControl?.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(HttpStatusCode.NotFound, "identity_not_found")]
|
||||||
|
[InlineData(HttpStatusCode.Unauthorized, "sign_in_required")]
|
||||||
|
[InlineData(HttpStatusCode.InternalServerError, "error")]
|
||||||
|
public async Task Each_refused_unlink_has_its_own_fixed_outcome_and_leaks_no_Heimdall_text(HttpStatusCode status, string outcome)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
host.Heimdall.UnlinkStatus = status;
|
||||||
|
|
||||||
|
var done = await Finish(host, member.Session, start, member.Account, StepUpToken(host, member.Account), provider: "google");
|
||||||
|
|
||||||
|
Assert.Equal($"{Page}?result={outcome}", Location(done));
|
||||||
|
Assert.DoesNotContain("HEIMDALL FREE TEXT", string.Join("\n", host.Logs.Lines));
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(member.Session);
|
||||||
|
Assert.DoesNotContain("HEIMDALL FREE TEXT", html);
|
||||||
|
// Only a definitive refusal (401 here) leaves the list shown; not found or an unreadable end may have changed the account, so it is dropped.
|
||||||
|
Assert.Equal(status == HttpStatusCode.Unauthorized, html.Contains("Name of discord"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_Heimdall_that_cannot_be_reached_for_the_unlink_changes_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
host.Heimdall.MemberFailure = new HttpRequestException("connection refused");
|
||||||
|
|
||||||
|
var done = await Finish(host, member.Session, start, member.Account, StepUpToken(host, member.Account), provider: "google");
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=error", Location(done));
|
||||||
|
Assert.DoesNotContain("Name of discord", (await host.GetLinkedAccountsAsync(member.Session)).Html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Without_a_Google_login_no_proof_can_be_had_and_the_page_says_so_without_asking_Heimdall()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "patreon");
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(member.Session);
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var post = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
|
||||||
|
Assert.DoesNotContain(">Unlink<", html);
|
||||||
|
Assert.Contains("Unlinking needs strong proof", html);
|
||||||
|
Assert.Contains("Add a passkey below", html);
|
||||||
|
Assert.Contains("link a Google login", html);
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(Page + "?result=proof_unavailable", Location(post.Response));
|
||||||
|
Assert.Null(post.Cookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_Heimdall_with_no_Google_client_refuses_the_step_up_start_and_the_page_says_proof_is_unavailable_once()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
host.Heimdall.StartStatus = HttpStatusCode.ServiceUnavailable;
|
||||||
|
host.Heimdall.StartBody = """{"error":"provider_not_configured"}""";
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var post = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
|
||||||
|
Assert.Equal(starts + 1, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Null(post.Cookie);
|
||||||
|
Assert.Equal(Page + "?result=proof_unavailable", Location(post.Response));
|
||||||
|
Assert.Contains("Fresh proof could not be started", (await host.GetLinkedAccountsAsync(member.Session, "?result=proof_unavailable")).Html);
|
||||||
|
Assert.Equal(2, host.Heimdall.Identities.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("not-a-guid")]
|
||||||
|
[InlineData("00000000-0000-0000-0000-000000000001")]
|
||||||
|
public async Task An_identity_that_is_not_on_the_list_the_member_was_shown_starts_nothing(string? identityId)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var post = await host.PostLinkedAccountsAsync(
|
||||||
|
member.Session, "Unlink", identityId is null ? null : new Dictionary<string, string> { ["identityId"] = identityId });
|
||||||
|
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(Page + "?result=list_expired", Location(post.Response));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task An_unlink_after_the_list_expired_starts_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var id = (string)host.Heimdall.Identities[0]["id"]!;
|
||||||
|
host.Clock.Advance(LinkedAccountsSnapshots.Lifetime + TimeSpan.FromSeconds(1));
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var post = await host.StartUnlinkAsync(member.Session, id);
|
||||||
|
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(Page + "?result=list_expired", Location(post.Response));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- an attempt belongs to the account and browser that began it ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task An_unlink_attempt_held_by_another_accounts_session_does_nothing_and_asks_Heimdall_for_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
var otherAccount = HeimdallShapes.NewAccountId();
|
||||||
|
var otherSession = await host.SignInSessionAsync(otherAccount);
|
||||||
|
var redeems = host.Heimdall.RedeemCalls;
|
||||||
|
|
||||||
|
var done = await Finish(host, member.Session, start, member.Account, StepUpToken(host, member.Account), provider: "google",
|
||||||
|
sessionOverride: otherSession);
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=error", Location(done));
|
||||||
|
Assert.Equal(redeems, host.Heimdall.RedeemCalls);
|
||||||
|
Assert.Empty(host.Heimdall.Unlinks);
|
||||||
|
Assert.Equal(2, host.Heimdall.Identities.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_proof_by_another_account_unlinks_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "google");
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
var stranger = HeimdallShapes.NewAccountId();
|
||||||
|
|
||||||
|
var done = await Finish(host, member.Session, start, stranger, StepUpToken(host, stranger), provider: "google");
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=error", Location(done));
|
||||||
|
Assert.Empty(host.Heimdall.Unlinks);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_list_proof_by_another_account_lists_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
host.Heimdall.AddIdentity("discord");
|
||||||
|
var start = await host.StartListAsync(session);
|
||||||
|
|
||||||
|
var done = await Finish(host, session, start, HeimdallShapes.NewAccountId());
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=error", Location(done));
|
||||||
|
Assert.Empty(host.Heimdall.ListAuthorizations);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_consumed_unlink_attempt_cannot_be_replayed_into_a_second_unlink()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var member = await ListedMember(host, "discord", "patreon", "google");
|
||||||
|
var start = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
|
||||||
|
var fields = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["attempt"] = start.Nonce,
|
||||||
|
["code"] = host.CodeFor(start, member.Account, StepUpToken(host, member.Account), provider: "google")
|
||||||
|
};
|
||||||
|
var first = await host.PostCompleteAsync(fields, Jar(member.Session, start));
|
||||||
|
Assert.Equal(Page + "?result=unlinked", Location(first));
|
||||||
|
|
||||||
|
var replay = await host.PostCompleteAsync(fields, Jar(member.Session, start));
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=error", Location(replay));
|
||||||
|
Assert.Single(host.Heimdall.Unlinks);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- link another provider ----
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("discord")]
|
||||||
|
[InlineData("patreon")]
|
||||||
|
[InlineData("google")]
|
||||||
|
public async Task Linking_each_admitted_provider_proves_the_account_then_starts_that_providers_link_with_the_bearer(string provider)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var start = await host.StartLinkAsync(session, provider);
|
||||||
|
|
||||||
|
Assert.Equal(starts + 1, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal("/v1/oauth/discord/start", host.Heimdall.StartPaths[^1]);
|
||||||
|
Assert.Null(host.Heimdall.StartAuthorizations[^1]);
|
||||||
|
var token = host.Token(account);
|
||||||
|
var step = await Finish(host, session, start, account, token);
|
||||||
|
|
||||||
|
Assert.Equal(starts + 2, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal($"/v1/oauth/{provider}/start", host.Heimdall.StartPaths[^1]);
|
||||||
|
Assert.Equal("Bearer " + token, host.Heimdall.StartAuthorizations[^1]);
|
||||||
|
using var link = JsonDocument.Parse(host.Heimdall.StartBodies[^1]);
|
||||||
|
Assert.Equal("link", link.RootElement.GetProperty("mode").GetString());
|
||||||
|
Assert.Equal("bifrost", link.RootElement.GetProperty("appSlug").GetString());
|
||||||
|
Assert.False(link.RootElement.TryGetProperty("stepUp", out _));
|
||||||
|
Assert.Equal($"https://heimdall.test/oauth/{provider}/authorize?state=link-fixture", Location(step));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_proof_sign_in_goes_through_a_provider_the_account_still_holds()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
// Signed in through Discord, which the account has since unlinked: signing in through it again would mint another account.
|
||||||
|
var member = await ListedMember(host, "patreon", "google");
|
||||||
|
|
||||||
|
var start = await host.StartLinkAsync(member.Session, "discord");
|
||||||
|
|
||||||
|
Assert.Equal("/v1/oauth/patreon/start", host.Heimdall.StartPaths[^1]);
|
||||||
|
Assert.NotNull(start.Cookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("twitch")]
|
||||||
|
[InlineData("github")]
|
||||||
|
[InlineData("DISCORD2")]
|
||||||
|
[InlineData("")]
|
||||||
|
public async Task A_provider_Heimdalls_bifrost_profile_does_not_admit_starts_nothing(string provider)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
var starts = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
var start = await host.StartLinkAsync(session, provider);
|
||||||
|
|
||||||
|
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
|
||||||
|
Assert.Equal(Page + "?result=error", Location(start.Response));
|
||||||
|
Assert.Null(start.Cookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_provider_that_attaches_in_the_callback_comes_back_with_a_link_completion_and_is_linked_once()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session, "patreon");
|
||||||
|
var awaiting = host.AttemptFrom((await ContinueResponse(host, session, start, account)), host.Heimdall.StartBodies.Count - 1);
|
||||||
|
Assert.Contains("\"Purpose\":6", Unprotect(host, awaiting.Cookie!));
|
||||||
|
Assert.Contains("\"Target\":\"patreon\"", Unprotect(host, awaiting.Cookie!));
|
||||||
|
host.Heimdall.AddIdentity("discord");
|
||||||
|
var redeems = host.Heimdall.RedeemCalls;
|
||||||
|
|
||||||
|
var done = await Finish(host, session, awaiting, account, mode: "link", provider: "patreon");
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=linked", Location(done));
|
||||||
|
Assert.Equal(redeems + 1, host.Heimdall.RedeemCalls);
|
||||||
|
Assert.Contains("now linked to your Heimdall account", (await host.GetLinkedAccountsAsync(session, "?result=linked")).Html);
|
||||||
|
Assert.Null(HeimdallHost.CookieValue(done, BifrostCookies.Session));
|
||||||
|
var replay = await host.PostCompleteAsync(
|
||||||
|
new Dictionary<string, string> { ["attempt"] = awaiting.Nonce, ["code"] = "gone" }, Jar(session, awaiting));
|
||||||
|
Assert.Equal(Page + "?result=error", Location(replay));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<HttpResponseMessage> ContinueResponse(HeimdallHost host, string session, StartedAttempt start, string account) =>
|
||||||
|
await Finish(host, session, start, account);
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("sign_in", "patreon")]
|
||||||
|
[InlineData("link", "discord")]
|
||||||
|
public async Task A_direct_link_completion_for_another_mode_or_provider_links_nothing(string mode, string provider)
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session, "patreon");
|
||||||
|
var before = host.Heimdall.StartBodies.Count;
|
||||||
|
var awaiting = host.AttemptFrom(await ContinueResponse(host, session, start, account), before);
|
||||||
|
|
||||||
|
var done = await Finish(host, session, awaiting, account, mode: mode, provider: provider);
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=error", Location(done));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_direct_link_completion_proven_by_another_account_links_nothing()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var start = await host.StartLinkAsync(session, "discord");
|
||||||
|
var before = host.Heimdall.StartBodies.Count;
|
||||||
|
var awaiting = host.AttemptFrom(await ContinueResponse(host, session, start, account), before);
|
||||||
|
|
||||||
|
var done = await Finish(host, session, awaiting, HeimdallShapes.NewAccountId(), mode: "link", provider: "discord");
|
||||||
|
|
||||||
|
Assert.Equal(Page + "?result=error", Location(done));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_link_attempt_cookie_written_before_targets_existed_still_links_Google()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var account = HeimdallShapes.NewAccountId();
|
||||||
|
var session = await host.SignInSessionAsync(account);
|
||||||
|
var nonce = "legacy-" + Guid.NewGuid().ToString("N");
|
||||||
|
var protector = host.Services.GetRequiredService<IDataProtectionProvider>().CreateProtector("Bifrost.Heimdall.Attempt.v1");
|
||||||
|
var legacy = protector.Protect(JsonSerializer.Serialize(new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["Nonce"] = nonce, ["Provider"] = "discord", ["RequiresMemberAccess"] = false, ["ReturnPath"] = "/Membership/Status",
|
||||||
|
["ExpiresAt"] = host.Clock.Now.AddMinutes(5), ["Purpose"] = 1, ["ExpectedAccountId"] = account
|
||||||
|
}));
|
||||||
|
var attempt = new StartedAttempt(
|
||||||
|
nonce, HeimdallAttemptCookie.SlotNames[0], legacy, $"https://localhost/auth/heimdall/complete?attempt={nonce}", null!);
|
||||||
|
|
||||||
|
var step = await Finish(host, session, attempt, account);
|
||||||
|
|
||||||
|
Assert.Equal("/v1/oauth/google/start", host.Heimdall.StartPaths[^1]);
|
||||||
|
Assert.Equal("https://heimdall.test/oauth/google/authorize?state=link-fixture", Location(step));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the page and its neighbours ----
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Status_points_a_Heimdall_member_to_the_page_and_no_longer_starts_a_link_itself()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
using var client = host.NewClient();
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/Membership/Status");
|
||||||
|
request.Headers.Add("Cookie", $"{BifrostCookies.Session}={session}");
|
||||||
|
|
||||||
|
var html = await (await client.SendAsync(request)).Content.ReadAsStringAsync();
|
||||||
|
|
||||||
|
Assert.Contains(Page, html);
|
||||||
|
Assert.DoesNotContain("handler=LinkGoogle", html);
|
||||||
|
Assert.DoesNotContain("LinkGoogle", html);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("linked")]
|
||||||
|
[InlineData("identity_linked_elsewhere")]
|
||||||
|
[InlineData("expired")]
|
||||||
|
[InlineData("unlinked")]
|
||||||
|
[InlineData("last_identity")]
|
||||||
|
[InlineData("step_up_required")]
|
||||||
|
[InlineData("identity_not_found")]
|
||||||
|
[InlineData("sign_in_required")]
|
||||||
|
[InlineData("proof_unavailable")]
|
||||||
|
[InlineData("list_expired")]
|
||||||
|
[InlineData("provider_needed")]
|
||||||
|
[InlineData("error")]
|
||||||
|
public void Every_outcome_code_has_words_and_nothing_else_does(string code)
|
||||||
|
{
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(HeimdallLinkOutcomes.Wording(code)));
|
||||||
|
Assert.Null(HeimdallLinkOutcomes.Wording(code + " "));
|
||||||
|
Assert.Null(HeimdallLinkOutcomes.Wording("<b>" + code));
|
||||||
|
Assert.Contains(
|
||||||
|
Enum.GetValues<HeimdallLinkOutcome>(), outcome => HeimdallLinkOutcomes.Code(outcome) == code);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Link_refusals_say_the_login_belongs_to_another_account_without_naming_it()
|
||||||
|
{
|
||||||
|
using var host = new HeimdallHost(realSessions: true);
|
||||||
|
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
|
||||||
|
|
||||||
|
var (_, html) = await host.GetLinkedAccountsAsync(session, "?result=identity_linked_elsewhere");
|
||||||
|
|
||||||
|
Assert.Contains("That login belongs to another account. Nothing was linked.", html);
|
||||||
|
Assert.DoesNotContain("merge", html.Replace("nothing is merged", string.Empty), StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
}
|
||||||
574
tests/Bifrost.Web.Tests/MergeAccountsPageTests.cs
Normal file
574
tests/Bifrost.Web.Tests/MergeAccountsPageTests.cs
Normal file
|
|
@ -0,0 +1,574 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>The name the account carries after signing in (a sign-in refreshes it from Heimdall).</summary>
|
||||||
|
public string MyName { get; private init; } = string.Empty;
|
||||||
|
|
||||||
|
public MergePage.Antiforgery? Token { get; private set; }
|
||||||
|
|
||||||
|
public HeimdallHost Host => Rig.Host;
|
||||||
|
|
||||||
|
public List<string> Surface { get; } = [];
|
||||||
|
|
||||||
|
public List<string> Bearers { get; } = [];
|
||||||
|
|
||||||
|
public MergeProofs Proofs => Host.Services.GetRequiredService<MergeProofs>();
|
||||||
|
|
||||||
|
public static async Task<World> 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<BifrostDbContext>().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<string> Page(string query = "")
|
||||||
|
{
|
||||||
|
var (response, html) = await Get(query);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<HttpResponseMessage> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One fresh sign-in of <paramref name="proved"/> through its login of <paramref name="provider"/>, started by the page's own button and finished as Heimdall's return does.</summary>
|
||||||
|
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<string, string> { ["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);
|
||||||
|
|
||||||
|
/// <summary>Both accounts proved in full, so either can be kept.</summary>
|
||||||
|
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<HttpResponseMessage> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Forbid answers 403 or sends the browser to the access-denied page; either way the page is not served.</summary>
|
||||||
|
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<BifrostDbContext>();
|
||||||
|
(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<BifrostDbContext>().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<BifrostDbContext>().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);
|
||||||
|
}
|
||||||
|
}
|
||||||
128
tests/Bifrost.Web.Tests/MergeNoticeAuthTests.cs
Normal file
128
tests/Bifrost.Web.Tests/MergeNoticeAuthTests.cs
Normal file
|
|
@ -0,0 +1,128 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>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).</summary>
|
||||||
|
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<BifrostDbContext>().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);
|
||||||
|
}
|
||||||
|
}
|
||||||
341
tests/Bifrost.Web.Tests/MergeNoticeFeedTests.cs
Normal file
341
tests/Bifrost.Web.Tests/MergeNoticeFeedTests.cs
Normal file
|
|
@ -0,0 +1,341 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class MergeNoticeFeedTests(MergePostgres postgres) : IClassFixture<MergePostgres>
|
||||||
|
{
|
||||||
|
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<JsonElement[]> 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<HttpStatusCode> 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<AccountMergeLedger>().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<UndoOutcome.Requested>(await rig.InScopeAsync(sp =>
|
||||||
|
sp.GetRequiredService<AccountMergeSaga>().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<MergeStanding.Frozen>(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<BifrostDbContext>().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<BifrostDbContext>().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<BifrostDbContext>().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<Guid, Guid, IEnumerable<AccountMerge>> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
106
tests/Bifrost.Web.Tests/MergePreviewTests.cs
Normal file
106
tests/Bifrost.Web.Tests/MergePreviewTests.cs
Normal file
|
|
@ -0,0 +1,106 @@
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Tests;
|
||||||
|
|
||||||
|
/// <summary>The wording of a merge plan: closed vocabulary, counts from the plan's entries, the statements a member must always see.</summary>
|
||||||
|
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<MergePlanEntry> entries, IReadOnlyDictionary<string, int>? left = null) =>
|
||||||
|
new([], [.. entries], left ?? new Dictionary<string, int>());
|
||||||
|
|
||||||
|
[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<string, int> { ["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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
230
tests/Bifrost.Web.Tests/MergeProofCompletionTests.cs
Normal file
230
tests/Bifrost.Web.Tests/MergeProofCompletionTests.cs
Normal file
|
|
@ -0,0 +1,230 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="MergeProofs"/> 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.
|
||||||
|
/// </summary>
|
||||||
|
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<Member> 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<StartedAttempt> Begin(HeimdallHost host, Member session, MergeSide side, string via = "discord")
|
||||||
|
{
|
||||||
|
var auth = host.Services.GetRequiredService<HeimdallAuthService>();
|
||||||
|
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<HttpResponseMessage> 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<string, string> { ["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<MergeProofs>();
|
||||||
|
|
||||||
|
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<MergeSideView>(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<PeekResult.Ready>(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<MergeSideView>(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<HeimdallAuthService>();
|
||||||
|
var before = host.Heimdall.StartBodies.Count;
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<HeimdallAuthException>(() => auth.StartMergeProveSelfAsync(me.Account, null, Page, Callback, [], CancellationToken.None));
|
||||||
|
await Assert.ThrowsAsync<HeimdallAuthException>(() => auth.StartMergeProveOtherAsync(me.Account, "github", Page, Callback, [], CancellationToken.None));
|
||||||
|
|
||||||
|
Assert.Equal(before, host.Heimdall.StartBodies.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
243
tests/Bifrost.Web.Tests/MergeProofsTests.cs
Normal file
243
tests/Bifrost.Web.Tests/MergeProofsTests.cs
Normal file
|
|
@ -0,0 +1,243 @@
|
||||||
|
using Bifrost.Web.Features.Heimdall;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
|
using Bifrost.Web.Tests.Support;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Tests;
|
||||||
|
|
||||||
|
/// <summary>The in-memory holder of merge proofs: per actor, expiring, never consuming, bearer-free in every view.</summary>
|
||||||
|
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<PeekResult.Ready>(_proofs.Peek(_actor, MergeSide.Self));
|
||||||
|
var second = Assert.IsType<PeekResult.Ready>(_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<PeekResult.Expired>(_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<PeekResult.Ready>(_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<PeekResult.Expired>(_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<PeekResult.LoginsUnproved>(_proofs.Peek(_actor, MergeSide.Self));
|
||||||
|
|
||||||
|
Assert.Equal(PutOutcome.Stored, self);
|
||||||
|
Assert.Equal(["discord"], unproved.Providers);
|
||||||
|
|
||||||
|
PutOther("discord", discord, patreon);
|
||||||
|
var ready = Assert.IsType<PeekResult.Ready>(_proofs.Peek(_actor, MergeSide.Self));
|
||||||
|
Assert.Equal(["discord", "patreon"], ready.Folded.Select(x => x.Provider).Order().ToArray());
|
||||||
|
var replacedAt = Assert.IsType<MergeSideView>(_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<PeekResult.LoginsUnproved>(_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<MergeSideView>(_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<UndoPeekResult.LoginsUnproved>(_proofs.PeekUndo(_actor, [discord.Id, patreon.Id]));
|
||||||
|
PutSelf("patreon", discord, patreon, twitch);
|
||||||
|
var ready = Assert.IsType<UndoPeekResult.Ready>(_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<UndoPeekResult.LoginsUnproved>(_proofs.PeekUndo(_actor, [discord.Id, Guid.NewGuid().ToString()]));
|
||||||
|
Assert.IsType<UndoPeekResult.Expired>(_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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Actors with anything in memory: pruning drops a side with no proof and an actor with no side.</summary>
|
||||||
|
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<PeekResult.ProviderConflict>(_proofs.Peek(_actor, survivor));
|
||||||
|
Assert.Equal(["discord", "twitch"], conflict.Providers);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
222
tests/Bifrost.Web.Tests/MergeStatusTests.cs
Normal file
222
tests/Bifrost.Web.Tests/MergeStatusTests.cs
Normal file
|
|
@ -0,0 +1,222 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
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<World> 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<string>();
|
||||||
|
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<World> 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<string> 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<AccountMerge> change)
|
||||||
|
{
|
||||||
|
using var scope = world.Rig.Host.Services.CreateScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||||
|
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<AccountMergeLedger>().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("<form", page.Split("<main")[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
255
tests/Bifrost.Web.Tests/MergeUndoPageTests.cs
Normal file
255
tests/Bifrost.Web.Tests/MergeUndoPageTests.cs
Normal file
|
|
@ -0,0 +1,255 @@
|
||||||
|
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 static Bifrost.Web.Tests.AccountMergeSagaTests;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class MergeUndoPageTests
|
||||||
|
{
|
||||||
|
private const string Callback = "https://localhost";
|
||||||
|
|
||||||
|
/// <summary>The Heimdall account that holds a login now, by the fake's own model of where a move left it.</summary>
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>Everything a response put on the wire: bodies, Location, Set-Cookie. The privacy test reads it at the end.</summary>
|
||||||
|
public List<string> Surface { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>Every bearer the test redeemed; none may appear on the surface.</summary>
|
||||||
|
public List<string> Bearers { get; } = [];
|
||||||
|
|
||||||
|
public void Dispose() => Rig.Dispose();
|
||||||
|
|
||||||
|
public async Task<string> 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<string> 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<string> MovedIds(AccountMerge merge) => JsonSerializer.Deserialize<string[]>(merge.MovedIdentityIds!)!;
|
||||||
|
|
||||||
|
/// <summary>One fresh sign-in of the survivor's account through a moved login of <paramref name="provider"/>, as the page's button and Heimdall's return do.</summary>
|
||||||
|
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<string, string> { ["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<World> 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<MergeProofs>().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<string> { "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);
|
||||||
|
}
|
||||||
78
tests/Bifrost.Web.Tests/MergeWordingTests.cs
Normal file
78
tests/Bifrost.Web.Tests/MergeWordingTests.cs
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Heimdall;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Tests;
|
||||||
|
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
public sealed class MergeWordingTests
|
||||||
|
{
|
||||||
|
private static string Snake(HeimdallMoveRefusal code) =>
|
||||||
|
code == HeimdallMoveRefusal.RequestInvalid ? "invalid_request" : Regex.Replace(code.ToString(), "(?<!^)([A-Z])", "_$1").ToLowerInvariant();
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Every_state_has_words_and_they_differ()
|
||||||
|
{
|
||||||
|
var words = Enum.GetValues<AccountMergeState>().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<HeimdallMoveRefusal>().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")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -28,6 +28,10 @@ public sealed class MigrationDiscoveryTests
|
||||||
"20261111100000_ConsentReceiptsOneLivePerVersion",
|
"20261111100000_ConsentReceiptsOneLivePerVersion",
|
||||||
"20261111110000_AddMembershipSuspensionReason",
|
"20261111110000_AddMembershipSuspensionReason",
|
||||||
"20261111120000_ClearLegacyConsentReceipts",
|
"20261111120000_ClearLegacyConsentReceipts",
|
||||||
|
"20261113120000_AddPasskeyCredentials",
|
||||||
|
"20261114120000_AddAccountMerges",
|
||||||
|
"20261114130000_AddAccountMergeSaga",
|
||||||
|
"20261114140000_AddAccountMergeNoticeAcks",
|
||||||
];
|
];
|
||||||
|
|
||||||
// Database.GetMigrations() reads assembly metadata only; no connection is opened.
|
// Database.GetMigrations() reads assembly metadata only; no connection is opened.
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue