From 8abd9129176dda3c2dc29701a5737bf39caa6c22 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 21:26:13 +0000 Subject: [PATCH 001/113] docs: guest accounts design (role field, invite, grants, leave and erase) Co-Authored-By: Claude Sonnet 5.5 --- docs/guest-accounts.md | 255 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 docs/guest-accounts.md diff --git a/docs/guest-accounts.md b/docs/guest-accounts.md new file mode 100644 index 0000000..3044056 --- /dev/null +++ b/docs/guest-accounts.md @@ -0,0 +1,255 @@ +# 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; check it against the rulings. 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`). + +## 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` + (`Status == Active`) is the one test behind `/App`, bridge transport (`BridgeActionService` l.492), motion votes + (`EffectiveVotingWeight`, `MotionGovernanceService` l.72), concept votes (`VoterIdentity.For`, member versus + account class) and the OIDC authorize, token and userinfo endpoints (`OidcEndpoints` l.50, l.131) and the + back-channel logout reconciler. +- `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` l.37, + `Members/Index.cshtml.cs` l.34). 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 authorize, token, userinfo and the logout reconciler change their test from "Active member" to + "`Status == Active`" (any role), so a guest, user or patron can hold a chat session and a member demoted to + `Suspended` still loses it. This is the one behavioural change outside new code, and it 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. | +| `TokenHash` | SHA-256 of a 256-bit random token. The token itself is shown to the issuer once, as a link, 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 link is a bearer: whoever signs in first with it is the guest. That is the cost of not needing sletz's +provider handle in advance, and it is why the token is single-use and short-lived and why the accept is shown +to the issuer. Recommended over binding the invite to a provider handle (which needs a Discord or Google id the +issuer may not have). The issuer may still restrict `ExpectedProvider`; open fork, see Questions. + +## Sign-in via Heimdall + +1. Guest opens `/invite/guest/`. 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: Bifrost's `AllowedProviders` is `discord, patreon, twitch` +(`HeimdallAuthService.AllowedProviders`), but Heimdall's `bifrost` app profile allows `discord, patreon, google` +(`app-profiles.ts`, `bifrostProfile`). Twitch cannot start in Heimdall and Google is refused by Bifrost. 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, 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`, 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. + +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`. Rooms for guests must be +invite-only; a guest who can reach a public room needs no grant, and that is a chat configuration fact I have not +verified. + +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. The OIDC reconciler already notices a non-`Active` +subject within 30 seconds and logs MAS out, 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, so Matrix user id is `@:` (server name per MAS config, not verified here). | +| `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. | + +A Persona deciding how to treat someone looks up `identity` from the Matrix sender and reads `role`. A sender with +no document is not a Bifrost account (a bridge ghost or an unlinked user) and is `unknown`, never defaulted to +`guest` or `user`. 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. 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 (`@:`) 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): 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. 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. **Is `Role` the right name** given `MemberRole`, and is one stored role (this doc) preferred over a boolean + `IsGuest`? Recommendation: stored role. Confidence: medium; the boolean is cheaper if user and patron are not + yet needed. +2. **Bearer link or provider-bound invite?** Recommendation: bearer, single use, seven days, optional + `ExpectedProvider`. Confidence: medium; this is a trust call about how sletz will be sent the link. +3. **Which Heimdall provider will sletz sign in with?** Needed before the lists are aligned. +4. **Do guests get a `member_id` for the answer collector?** Default no. +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. From 2aabaabc53c7d9f853635f0f3470b2ce1e6be1a3 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Tue, 10 Nov 2026 06:13:02 +0000 Subject: [PATCH 002/113] docs(guest-accounts): fold in Eureka's review: matrix_id lookup, unknown/status/freshness contract, closed-room grants with steward grantor, guest DM conflict Co-Authored-By: Claude Sonnet 5.5 --- docs/guest-accounts.md | 52 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/docs/guest-accounts.md b/docs/guest-accounts.md index 3044056..5471e47 100644 --- a/docs/guest-accounts.md +++ b/docs/guest-accounts.md @@ -4,7 +4,8 @@ Status: **design, nothing implemented.** Written for `eureka-body:follow_up:bifr `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; check it against the rulings. First guest: +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`, @@ -125,6 +126,12 @@ Rooms are Matrix rooms in chat, not Bifrost objects. Bifrost owns the decision, `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. @@ -132,9 +139,19 @@ Gap (largest in this doc): something must perform "invite this Matrix user to th 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`. Rooms for guests must be -invite-only; a guest who can reach a public room needs no grant, and that is a chat configuration fact I have not -verified. +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:`, 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`, @@ -205,16 +222,31 @@ Bifrost" (`docs/oidc-issuer.md`) and chat does not need it. Publish a typed Cult | field | type | note | |---|---|---| | `account_id` | uuid | OIDC `sub`; never changes. | -| `identity` | string | `NormalizedBifrostIdentity`; the Matrix localpart, so Matrix user id is `@:` (server name per MAS config, not verified here). | +| `identity` | string | `NormalizedBifrostIdentity`; the Matrix localpart. | +| `matrix_id` | string | the full mxid `@:`, 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. | -A Persona deciding how to treat someone looks up `identity` from the Matrix sender and reads `role`. A sender with -no document is not a Bifrost account (a bridge ghost or an unlinked user) and is `unknown`, never defaulted to -`guest` or `user`. Bifrost does not decide Persona behavior; it states the role. +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. @@ -250,6 +282,8 @@ No such publisher or witness exists; Bifrost has no `.cc` export for accounts to 2. **Bearer link or provider-bound invite?** Recommendation: bearer, single use, seven days, optional `ExpectedProvider`. Confidence: medium; this is a trust call about how sletz will be sent the link. 3. **Which Heimdall provider will sletz sign in with?** Needed before the lists are aligned. -4. **Do guests get a `member_id` for the answer collector?** Default no. +4. **Do guests get a `member_id` for the answer collector?** Default no. Eureka agrees from the chat side: the + Persona turn is not the collector, and presence in a room is the room's decision (Heimdall PR #6 owns the + collector). 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. From 8e9ffb32f4b74d43727d4f2126ecde1b8fbbd7ce Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 08:04:06 +0000 Subject: [PATCH 003/113] Mouth: room tail on chat_pending.v3 (20 lines a room, 60 in all, unacked past her cursor, speakable rooms only) Co-Authored-By: Claude Sonnet 5.5 --- docs/bridge.md | 19 +++- ...mecult.persona.chat_pending.v3.tag.msgpack | Bin 197 -> 198 bytes ...ecult.persona.chat_pending.v3.tail.msgpack | Bin 0 -> 163 bytes ...na.chat_pending.v3.unproven-notice.msgpack | Bin 153 -> 154 bytes tests/persona-matrix-mouth-runtime.test.mjs | 17 ++- tests/persona-matrix-mouth.test.mjs | 100 ++++++++++++++++++ tools/persona-chat-documents.mjs | 23 +++- tools/persona-matrix-mouth.mjs | 70 ++++++++++-- 8 files changed, 212 insertions(+), 17 deletions(-) create mode 100644 tests/fixtures/persona-chat-v5/gamecult.persona.chat_pending.v3.tail.msgpack diff --git a/docs/bridge.md b/docs/bridge.md index 4468988..a6430d1 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -216,10 +216,25 @@ Proposed runtime half (follow-up `persona-wakes-on-address-only`): 1. Poll with `chat_pending_request.v2` and parse `chat_pending.v3`. 2. A delivery is *addressed* to a Persona when `form == "message"` and either `basis` is `direct`, `tag` or `reply`, or `address::addresses` matches her names or her projects' names on the text. The off-beat wake keeps the sender gate of `heartbeat.rs` `wakes` (the operator or another Mind of the roster): a stranger's tag, `@room` or DM is delivered but wakes no one off the beat. `basis == "room"` is the runtime's policy to weigh; the mouth only reports it. 3. A real-time wake, a live session's tell and the stagger apply to addressed deliveries only. A `notice` or an `edit` never wakes, whatever its basis. -4. A delivery that is not addressed is acked in sequence with the rest, so the position moves (the mouth stops reading at 500 unacked deliveries); it is not lost: Matrix is the record, and the next addressed delivery's `context` (up to 20 lines) and a beat's own room read show it. Reading the tail on a scheduled beat is a runtime read of Matrix, a follow-up of the ruling `wake-reads-room-tail`; the mouth adds no endpoint for it. +4. A delivery that is not addressed is acked in sequence with the rest, so the position moves (the mouth stops reading at 500 unacked deliveries); it is not lost: Matrix is the record, and the next addressed delivery's `context` (up to 20 lines) and a beat's own room read show it. The room tail below gives a scheduled beat those lines without a Matrix read of its own; the mouth adds no endpoint for it. 5. `basis` and `form` are evidence, not authority: a sender's claim is weighed by the runtime's own rule (`address.rs` for names, the sender gate for who may wake her); the mouth reports what the event says and what only Matrix could look up (the author of a reply target). -Golden bytes: `tests/fixtures/persona-chat-v5/`; Huginn pins the same bytes. +### Room tail (`chat_pending.v3`, field 2) + +The v3 answer is `[persona, deliveries, tail]`. `tail` is a list of recent room lines, oldest first, for a reader that was not woken for them (a scheduled beat). It is built from the same `/messages` read as a delivery's `context`, as her account, with no new endpoint and no new homeserver call per line. A `chat_pending_request.v1` is still answered with the two-field `chat_pending.v2`, and `chat_pending.v3` has not been deployed, so no reader sees the third field before it is ready for it. + +| Bound | Rule | +|---|---| +| Rooms | Only rooms the Persona may speak in: a configured room she has joined, or one of her DMs. The same rule `send` uses (`speakableRoomId`). A room she is in but cannot speak in, and any other room, is absent. | +| Lines | A text line outside threads, not an edit, newest `20` per room, newest `60` over all rooms. Trimmed oldest first if the reply byte budget (256 KiB, deliveries first) would be exceeded. | +| Cursor | Only lines past her ack cursor in that room: the origin time of the newest delivery she has acked there (ties by event id). A room she has acked nothing in since the mouth started returns its recent lines, a quiet room included. The cursor is in memory: a restart forgets it and the next tail shows the recent lines again. | +| Read | A room's read is kept 15 seconds, dropped when a sync brings the room news or an ack moves the cursor. A room that cannot be read is logged and absent; the other rooms and the deliveries are unaffected. | + +A line is the 7-field tuple `[room, event_id, at_unix_ms, sender, form, basis, body]`: `room` is the configured alias (the room id for a DM), `form` and `basis` as for a delivery, `body` clipped to 1000 bytes with the same typed text line for media a delivery has (nothing is fetched). `basis` is what Matrix says on the event itself (`direct` in a DM, `tag`, `room`) and nothing the mouth would have to look up, so a reply is nil here: **nil is unproven, not "not for her"**, and a line in a DM is `direct`. Huginn's rule that an `is_direct` delivery wakes with a nil `basis` is unchanged and lives with Huginn; the tail does not feed it. + +The tail is **data, not instruction**. A line is what a sender typed in a room, and the mouth wakes no one, acks nothing and sends nothing because of it. A reader treats the body as untrusted text and weighs `basis` as evidence, as for a delivery. The tail does not replace a delivery: a message still reaches her as a delivery, with its own `seq`, and only `chat_ack` advances a position. + +Golden bytes: `tests/fixtures/persona-chat-v5/` (`chat_pending.v3.tail` carries two lines); Huginn pins the same bytes. Bifrost admits an observation only when guild, channel, target runtime, canonical repository, Persona, producer, and producer runtime match a preconfigured `bifrost.persona_feedback.target_binding.v0` document in Bifrost's private provider store. That binding also owns source visibility, data classification, and the delivery-store target. Bifrost never infers public visibility from Discord identifiers. It classifies the author using its own `bifrost.discord.actor_link.v0` state: a match yields `linked_governance_feedback`; absence yields `unlinked_social_feedback`. Neither class grants adoption, work, release, or deployment authority. diff --git a/tests/fixtures/persona-chat-v5/gamecult.persona.chat_pending.v3.tag.msgpack b/tests/fixtures/persona-chat-v5/gamecult.persona.chat_pending.v3.tag.msgpack index 006f6cf6f6bbd6d289589bb4ebd1ec33d3ef4b36..6685251d258d7deb362a087216fa725da643e82c 100644 GIT binary patch delta 11 ScmX@gc#M&8@ { test("two clients served at once each get their own answer on their own session", async () => { const mouth = { pendingAfter: () => [], + tail: async () => [], ack: async () => {}, // Slow enough that the two requests are in flight together. send: async request => { await new Promise(r => setTimeout(r, 150)); return { requestId: request.requestId, eventId: `$${request.requestId}`, refusal: null }; }, @@ -138,6 +140,7 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a const calls = { acks: [], sends: [], reads: [] }; const mouth = { pendingAfter: after => (after < 7 ? [delivery] : []), + tail: async () => [tailLine], ack: async through => { calls.acks.push(through); }, read: async request => { calls.reads.push(request); return null; }, send: async request => { calls.sends.push(request); return request.text === "muted" ? { requestId: request.requestId, eventId: null, refusal: "Brake" } : { requestId: request.requestId, eventId: "$sent", refusal: null }; }, @@ -177,7 +180,9 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a put(docs.kinds.pendingRequestV3, "eureka", docs.pendingRequestTuple({ persona: "eureka", afterSeq: 0 })); document = await reply; assert.equal(document.schemaId, docs.kinds.pendingV3, "the kind asked by names the answer"); - assert.deepEqual(docs.parsePendingV3(msgpack.decode(document.payload)).deliveries[0], { ...delivery, basis: null, form: "message" }); + const v3 = docs.parsePendingV3(msgpack.decode(document.payload)); + assert.deepEqual(v3.deliveries[0], { ...delivery, basis: null, form: "message" }); + assert.deepEqual(v3.tail, [tailLine], "the v3 answer carries the room tail"); put(docs.kinds.ack, "eureka:7", docs.ackTuple({ persona: "eureka", throughSeq: 7 })); reply = nextReply(); @@ -322,6 +327,10 @@ const v5Dir = resolve(root, "tests", "fixtures", "persona-chat-v5"); const v5Samples = { "gamecult.persona.chat_pending_request.v2": { tuple: docs.pendingRequestTuple({ persona: "eureka", afterSeq: 3 }), parse: docs.parsePendingRequest }, "gamecult.persona.chat_pending.v3.tag": { tuple: docs.pendingV3Tuple({ persona: "eureka", deliveries: [{ ...delivery, isDirect: false, basis: "tag", form: "message" }] }), parse: docs.parsePendingV3 }, + "gamecult.persona.chat_pending.v3.tail": { tuple: docs.pendingV3Tuple({ persona: "eureka", deliveries: [], tail: [ + { roomAlias: "#operator:gamecult.org", eventId: "$e0", atUnixMs: 1_700_000_000_000, sender: "@meta:gamecult.org", form: "message", basis: null, text: "earlier" }, + { roomAlias: "#operator:gamecult.org", eventId: "$e1", atUnixMs: 1_700_000_001_000, sender: "@meta:gamecult.org", form: "notice", basis: "tag", text: "hello eureka" }, + ] }), parse: docs.parsePendingV3 }, "gamecult.persona.chat_pending.v3.unproven-notice": { tuple: docs.pendingV3Tuple({ persona: "eureka", deliveries: [{ ...delivery, isDirect: false, mentions: [], basis: null, form: "notice" }] }), parse: docs.parsePendingV3 }, }; for (const [name, { tuple, parse }] of Object.entries(v5Samples)) { @@ -331,7 +340,9 @@ for (const [name, { tuple, parse }] of Object.entries(v5Samples)) { if (process.env.UPDATE_FIXTURES === "1") { await mkdir(v5Dir, { recursive: true }); await writeFile(file, bytes); } assert.deepEqual(bytes, await readFile(file), "wire bytes changed: Huginn decodes these fixtures"); assert.deepEqual(parse(msgpack.decode(bytes)), parse(tuple)); - if (name.includes("pending.v3")) assert.equal(msgpack.decode(bytes)[1][0].length, 14); + if (name.includes("pending.v3")) assert.equal(msgpack.decode(bytes).length, 3, "persona, deliveries, tail"); + if (name.endsWith("v3.tag") || name.endsWith("unproven-notice")) assert.equal(msgpack.decode(bytes)[1][0].length, 14); + if (name.endsWith("v3.tail")) assert.equal(msgpack.decode(bytes)[2][0].length, 7); }); } @@ -370,7 +381,7 @@ test("RoomMoved is v2 only, and the v2 documents are strict about arity and newe test("the RUDP endpoint answers a v1 send with the three-field receipt and a v2 send with the four-field one", async () => { const seen = []; - const mouth = { pendingAfter: () => [], ack: async () => {}, send: async request => { + const mouth = { pendingAfter: () => [], tail: async () => [], ack: async () => {}, send: async request => { seen.push(request); return request.basis ? { requestId: request.requestId, eventId: null, refusal: "RoomMoved", newer: ["$a"] } : { requestId: request.requestId, eventId: "$sent", refusal: null, newer: [] }; } }; diff --git a/tests/persona-matrix-mouth.test.mjs b/tests/persona-matrix-mouth.test.mjs index 9458370..5558df3 100644 --- a/tests/persona-matrix-mouth.test.mjs +++ b/tests/persona-matrix-mouth.test.mjs @@ -1475,3 +1475,103 @@ test("addressing facts: a target that failed is not refetched within a minute, a assert.equal(fetched(), 2, "past the minute: read again"); } finally { await hs.close(); } }); + +// The room tail (docs/bridge.md, "Room tail"): her rooms' recent talk past her ack cursor, bounded, as data on the v3 answer. +const OPERATOR = "!operator:gamecult.test"; +const lines = (room, n, from = 0, sender = META) => Array.from({ length: n }, (_, i) => message(`$${room.slice(1, 4)}${from + i}`, sender, `line ${from + i}`, 10 + from + i)); +async function tailed({ preload, direct, member, events = [], act = async () => {} } = {}) { + const hs = await fakeHomeserver({ preload, direct, member, sync: since => since === null ? { next_batch: "b0" } : { next_batch: "b1", ...joined(events.length ? { [ROOM]: { timeline: { events } } } : {}) } }); + try { + const mouth = mouthFor(hs); + await mouth.syncOnce(); + await act(mouth); + return { tail: await mouth.tail(), mouth, hs }; + } finally { await hs.close(); } +} + +test("room tail: 600 lines in a room keep the newest 20, oldest first", async () => { + const { tail } = await tailed({ preload: { [ROOM]: lines(ROOM, 600) } }); + assert.equal(tail.length, 20); + assert.deepEqual(tail.map(l => l.text), Array.from({ length: 20 }, (_, i) => `line ${580 + i}`)); + assert.deepEqual(Object.keys(tail[0]).sort(), ["atUnixMs", "basis", "eventId", "form", "roomAlias", "sender", "text"]); + assert.equal(tail[0].roomAlias, `#swarm:${HS_NAME}`); + assert.equal(tail[0].sender, META); + assert.equal(tail[0].form, "message"); + assert.equal(tail[0].basis, null, "unproven, not 'not for her'"); +}); + +test("room tail: a quiet room, with nothing delivered, still returns its recent lines", async () => { + const { tail } = await tailed({ preload: { [OPERATOR]: lines(OPERATOR, 3) } }); + assert.deepEqual(tail.map(l => l.text), ["line 0", "line 1", "line 2"]); + assert.ok(tail.every(l => l.roomAlias === `#operator:${HS_NAME}`)); +}); + +test("room tail: a room she is not in the speaking set of is absent, and a DM she holds is present with basis direct", async () => { + const STRANGER = "!stranger:gamecult.test", DM = "!mydm:gamecult.test"; + const { tail } = await tailed({ + preload: { [STRANGER]: lines(STRANGER, 2), [DM]: lines(DM, 2), [ROOM]: lines(ROOM, 1) }, + member: [...Object.values(ROOMS), STRANGER, DM], + direct: { [META]: [DM] }, + }); + assert.deepEqual([...new Set(tail.map(l => l.roomAlias))].sort(), [DM, `#swarm:${HS_NAME}`]); + assert.ok(tail.filter(l => l.roomAlias === DM).every(l => l.basis === "direct")); + assert.ok(!tail.some(l => l.eventId.startsWith("$str"))); +}); + +test("room tail: about 60 lines over all rooms, the newest, whatever the room count", async () => { + const dms = ["!d1:gamecult.test", "!d2:gamecult.test", "!d3:gamecult.test", "!d4:gamecult.test"]; + const preload = { [ROOM]: lines(ROOM, 30, 0), [OPERATOR]: lines(OPERATOR, 30, 30) }; + dms.forEach((dm, i) => { preload[dm] = lines(dm, 30, 60 + 30 * i); }); + const { tail } = await tailed({ preload, direct: { [META]: dms }, member: [...Object.values(ROOMS), ...dms] }); + assert.equal(tail.length, 60); + assert.deepEqual(tail.map(l => l.atUnixMs), tail.map(l => l.atUnixMs).sort((a, b) => a - b), "oldest first"); + assert.equal(Math.min(...tail.map(l => l.atUnixMs)), 110, "the oldest kept is the 60th newest of the 120 offered"); +}); + +test("room tail: lines at or before her ack cursor are gone, later ones stay, and mention basis rides on the line", async () => { + const events = [ + withContent("$a", META, { body: "first" }, 3000), + withContent("$b", META, { body: "tag", "m.mentions": { user_ids: [SELF] } }, 3001), + ]; + const hs = await fakeHomeserver({ sync: since => since === null ? { next_batch: "b0" } : { next_batch: "b1", ...joined({ [ROOM]: { timeline: { events } } }) } }); + try { + const mouth = mouthFor(hs); + await mouth.syncOnce(); + const made = await mouth.syncOnce(); + assert.equal(made.length, 2); + assert.deepEqual((await mouth.tail()).map(l => [l.eventId, l.basis]), [["$a", null], ["$b", "tag"]]); + await mouth.ack(made[0].seq); + assert.deepEqual((await mouth.tail()).map(l => l.eventId), ["$b"], "unacked past the cursor only"); + await mouth.ack(made[1].seq); + assert.deepEqual(await mouth.tail(), []); + } finally { await hs.close(); } +}); + +test("room tail: a body is clipped like a context line, and an unreadable room is absent without silencing the others", async () => { + const { tail } = await tailed({ preload: { [ROOM]: [message("$big", META, "x".repeat(5000), 10)] } }); + assert.equal(Buffer.byteLength(tail[0].text), docs.limits.contextBytes); + const hs = await fakeHomeserver({ failContext: true, sync: since => ({ next_batch: since ?? "b0" }) }); + try { + const mouth = mouthFor(hs); + await mouth.syncOnce(); + assert.deepEqual(await mouth.tail(), []); + } finally { await hs.close(); } +}); + +test("room tail: only the v3 answer carries it; the v2 answer a v1 request gets is unchanged", async () => { + const { tail } = await tailed({ preload: { [ROOM]: lines(ROOM, 2) } }); + const pack = { encode: v => Buffer.from(JSON.stringify(v)) }; + assert.deepEqual(docs.parsePendingV3(pageOf("eureka", [], pack, () => {}, true, tail)).tail.map(l => l.text), ["line 0", "line 1"]); + const v2 = pageOf("eureka", [], pack, () => {}, false, tail); + assert.equal(v2.length, 2); + assert.deepEqual(docs.parsePending(v2), { persona: "eureka", deliveries: [] }); + assert.throws(() => docs.parsePendingV3(["eureka", []]), /3-field/); +}); + +test("room tail: the reply byte budget trims the oldest tail lines, never a delivery", async () => { + const pack = { encode: v => Buffer.from(JSON.stringify(v)) }; + const big = Array.from({ length: 60 }, (_, i) => ({ roomAlias: "#r:x", eventId: `$${i}`, atUnixMs: i, sender: "@a:x", form: "message", basis: null, text: "y".repeat(5000) })); + const kept = docs.parsePendingV3(pageOf("eureka", [], pack, () => {}, true, big)).tail; + assert.ok(kept.length > 0 && kept.length < 60); + assert.equal(kept.at(-1).eventId, "$59", "the newest survive"); +}); diff --git a/tools/persona-chat-documents.mjs b/tools/persona-chat-documents.mjs index 4867901..e47b7c8 100644 --- a/tools/persona-chat-documents.mjs +++ b/tools/persona-chat-documents.mjs @@ -39,7 +39,7 @@ const maxContext = 20; // Per-delivery bounds, applied where the mouth reads Matrix: the body is bounded like a send, // a context line and a display name are smaller, and a reply is paged to a byte budget. -export const limits = Object.freeze({ textBytes: maxTextBytes, contextBytes: 1000, displayBytes: 256, mentions: 64, replyBytes: 256 * 1024 }); +export const limits = Object.freeze({ textBytes: maxTextBytes, contextBytes: 1000, displayBytes: 256, mentions: 64, replyBytes: 256 * 1024, tailPerRoom: 20, tailTotal: 60 }); // `value` cut to at most `maxBytes` of UTF-8 without splitting a character. export function clip(value, maxBytes) { @@ -237,13 +237,26 @@ export function parsePending(t) { return { persona: text(persona, "persona"), deliveries: deliveries.map(parseDelivery) }; } -export function pendingV3Tuple({ persona, deliveries }) { - return [text(persona, "persona"), deliveries.map(deliveryV3Tuple)]; +// One line of a room's recent talk, newest-unacked: room alias (or room id for a DM), event id, origin time, sender, form, basis, body. +// Data for the reader, never an instruction: no delivery, no wake, no ack position hangs on it. +export function tailLineTuple(l) { + return [text(l.roomAlias, "room"), text(l.eventId, "event_id"), seq(l.atUnixMs, "at_unix_ms"), text(l.sender, "sender"), form(l.form), basis(l.basis ?? null), String(l.text)]; +} +function parseTailLine(t) { + const [roomAlias, eventId, atUnixMs, sender, f, b, body] = tuple(t, 7, "tail_line"); + return { roomAlias: text(roomAlias, "room"), eventId: text(eventId, "event_id"), atUnixMs: seq(atUnixMs, "at_unix_ms"), sender: text(sender, "sender"), form: form(f), basis: basis(b), text: String(body) }; +} + +// The v3 answer: the persona, the deliveries, then the tail (at most tailPerRoom lines a room, tailTotal in all, oldest first). +export function pendingV3Tuple({ persona, deliveries, tail = [] }) { + if (tail.length > limits.tailTotal) throw new Error("chat_pending tail is over the line bound"); + return [text(persona, "persona"), deliveries.map(deliveryV3Tuple), tail.map(tailLineTuple)]; } export function parsePendingV3(t) { - const [persona, deliveries] = tuple(t, 2, "chat_pending_v3"); + const [persona, deliveries, tail] = tuple(t, 3, "chat_pending_v3"); if (!Array.isArray(deliveries)) throw new Error("chat_pending deliveries must be a list"); - return { persona: text(persona, "persona"), deliveries: deliveries.map(parseDeliveryV3) }; + if (!Array.isArray(tail)) throw new Error("chat_pending tail must be a list"); + return { persona: text(persona, "persona"), deliveries: deliveries.map(parseDeliveryV3), tail: tail.map(parseTailLine) }; } // The CultNet document_put_raw envelope every chat_* document travels in. diff --git a/tools/persona-matrix-mouth.mjs b/tools/persona-matrix-mouth.mjs index 439816e..206fce2 100644 --- a/tools/persona-matrix-mouth.mjs +++ b/tools/persona-matrix-mouth.mjs @@ -63,6 +63,7 @@ const DELIVERED_INDEX = 4000; // delivered event ids remembered so a read report const DM_SCAN = 200; // joined rooms read when looking for an existing DM with a person const NOT_E2EE = "This room is not end-to-end encrypted: the homeserver can read what is said here."; const dayOf = ms => new Date(ms).toISOString().slice(0, 10); +const TAIL_TTL_MS = 15 * 1000; const HEAD_PAGE = 50; // the room head a gated send reads; also the most ids a RoomMoved receipt names // The kind of an event for a delivery: an edit (m.replace) and an automated notice (m.notice) are not messages anyone is addressed by. @@ -141,6 +142,8 @@ export function createMouth({ let started = false; let lastPresence = null; // 'online' | 'unavailable' | 'offline' | null: command-only, suppresses repeat presence PUTs let activeUntil = 0; // her last sign of life in a turn, plus the grace + const ackedThrough = new Map(); // room id -> { ts, ids }: the newest delivery she has acked there, ids those at exactly that time; the tail is what lies past it + const tailReads = new Map(); // room id -> { at, lines }: a room's tail read, kept TAIL_TTL_MS or until a sync brings the room news or an ack moves the cursor const delivered = new Map(); // event id -> { roomId, roomAlias, seq }: what the mouth handed her, newest last, bounded const readThrough = new Map(); // room id -> { seq, eventId } of the last receipt that landed const readTails = new Map(); // room id -> the read report in flight: reports for one room run one at a time @@ -209,6 +212,8 @@ export function createMouth({ } } const unjoined = () => joinedAliases.size < rooms.length; + // The rooms this Persona may speak in: a configured room she has joined, or one of her DMs. One rule for send and for the tail. + const speakableRoomId = alias => joinedAliases.has(alias) ? roomIdByAlias.get(alias) : directRooms.has(alias) ? alias : null; // Join the configured rooms the account is not in, only while the brake is released. // One room failing is logged and retried on the next round; it never stops the others. @@ -294,11 +299,11 @@ export function createMouth({ // thread under, an event her account wrote, so her Self run's words count as hers), "room" (an @room mention). In that order; null // when none holds. Her names, her projects' names and the sender's role are the heartbeat's to match (Huginn address.rs), never the // mouth's. A reply target that cannot be read is null and logged: unknown, not "not hers". - async function basisOf(roomId, event) { + async function basisOf(roomId, event, lookup = true) { if (directRooms.has(roomId)) return "direct"; const mentions = event.content["m.mentions"]; if (Array.isArray(mentions?.user_ids) ? mentions.user_ids.includes(selfId) : mentions === undefined && pillFor(event.content.formatted_body)) return "tag"; - if (formOf(event.content) === "message" && await repliesToMe(roomId, event.content["m.relates_to"])) return "reply"; // an edit or a notice wakes no one: no fetch for it + if (lookup && formOf(event.content) === "message" && await repliesToMe(roomId, event.content["m.relates_to"])) return "reply"; // an edit or a notice wakes no one: no fetch for it return mentions?.room === true ? "room" : null; } // A pill is an anchor whose href is exactly her matrix.to link; a longer id, an attribute that merely contains one and a quoted reply do not count. @@ -379,6 +384,7 @@ export function createMouth({ const shown = event.content?.displayname; if (event.type === "m.room.member" && typeof event.state_key === "string" && typeof shown === "string" && shown !== "") displayNames.set(event.state_key, docs.clip(shown, docs.limits.displayBytes)); } + if ((room.timeline?.events ?? []).length > 0) tailReads.delete(roomId); for (const event of room.timeline?.events ?? []) { if (event.type !== "m.room.message" || typeof event.content?.body !== "string") continue; if (typeof event.sender !== "string" || event.sender === "" || typeof event.event_id !== "string" || event.event_id === "") continue; @@ -466,12 +472,48 @@ export function createMouth({ } async function ack(throughSeq) { + for (const d of pending) if (d.seq <= throughSeq) { + const through = ackedThrough.get(d.roomId); + if (!through || d.atUnixMs > through.ts) ackedThrough.set(d.roomId, { ts: d.atUnixMs, ids: new Set([d.eventId]) }); + else if (d.atUnixMs === through.ts) through.ids.add(d.eventId); + } pending = pending.filter(d => d.seq > throughSeq); + tailReads.clear(); images?.acked(throughSeq); await commit(pending.length ? pending[0].seq - 1 : seqCounter); touch(); } + // Her rooms' recent talk, for a reader that was not woken for it: in each room she may speak in, the newest tailPerRoom lines past + // her ack cursor there (a room she has acked nothing in yields its recent lines), the newest tailTotal over all rooms, oldest + // first. From the same /messages read as a delivery's context, as her account, bodies clipped as context lines are. The basis is + // what Matrix says on the event itself (no reply lookup: nil is unproven). A room that cannot be read is logged and absent. + async function tail() { + if (!started) return []; + const targets = new Set(); + for (const alias of [...joinedAliases, ...directRooms]) { const id = speakableRoomId(alias); if (id) targets.add(id); } + const perRoom = await Promise.all([...targets].map(async roomId => { + let read = tailReads.get(roomId); + if (!read || now() - read.at >= TAIL_TTL_MS) { + read = { at: now(), lines: roomEvents(roomId).catch(error => { say(`tail for ${roomId} not fetched: ${error.message}`); return null; }) }; + tailReads.set(roomId, read); + } + const events = await read.lines; + if (events === null) { if (tailReads.get(roomId) === read) tailReads.delete(roomId); return []; } + const through = ackedThrough.get(roomId); + const alias = aliasByRoomId.get(roomId) ?? roomId; + const lines = []; + for (const e of events) { + const at = Number.isSafeInteger(e.origin_server_ts) && e.origin_server_ts >= 0 ? e.origin_server_ts : 0; + if (through && (at < through.ts || (at === through.ts && through.ids.has(e.event_id)))) continue; + if (typeof e.event_id !== "string" || e.event_id === "") continue; + lines.push({ roomAlias: alias, eventId: e.event_id, atUnixMs: at, sender: e.sender, form: formOf(e.content), basis: await basisOf(roomId, e, false), text: bodyText(e.content, docs.limits.contextBytes) }); + } + return lines.slice(-docs.limits.tailPerRoom); + })); + return perRoom.flat().sort((a, b) => a.atUnixMs - b.atUnixMs).slice(-docs.limits.tailTotal); + } + function pendingAfter(afterSeq) { return pending.filter(d => d.seq > afterSeq).map(d => ({ ...d, context: d.context.map(c => ({ ...c })), mentions: [...d.mentions], image: d.image && { ...d.image } })); } @@ -497,7 +539,7 @@ export function createMouth({ if (typeof text !== "string" || text.trim() === "") return refuse("EmptyText"); try { if (!started || unjoined()) await start(); - const roomId = joinedAliases.has(roomAlias) ? roomIdByAlias.get(roomAlias) : directRooms.has(roomAlias) ? roomAlias : null; + const roomId = speakableRoomId(roomAlias); if (!roomId) return refuse("UnknownRoom"); const result = await gate.run(roomId, async () => { if (basis) { @@ -626,7 +668,7 @@ export function createMouth({ } } - return { start, syncOnce, ack, read, pendingAfter, send, openDirect, run, get userId() { return selfId; }, get pendingCount() { return pending.length; } }; + return { start, syncOnce, ack, read, pendingAfter, tail, send, openDirect, run, get userId() { return selfId; }, get pendingCount() { return pending.length; } }; } // Replace every secret in a message. `secrets` is one string or a list. @@ -671,7 +713,8 @@ export function connectionIdFor(connectionKey) { // The reply to a chat_pending_request: deliveries oldest first, each encoded on its own so one that // will not encode is skipped and logged without silencing the rest, up to the reply byte budget. // The caller acks what it has read and asks again. -export function pageOf(persona, deliveries, msgpack, log = () => {}, v3 = false) { +// A v3 reply also carries `tail` (room lines, oldest first), trimmed oldest first to what the byte budget has left after the deliveries. +export function pageOf(persona, deliveries, msgpack, log = () => {}, v3 = false, tail = []) { const page = []; let bytes = 0; for (const delivery of deliveries) { @@ -684,7 +727,19 @@ export function pageOf(persona, deliveries, msgpack, log = () => {}, v3 = false) page.push(tuple); bytes += size; } - return [persona, page]; + if (!v3) return [persona, page]; + const lines = []; + for (const line of tail.slice().reverse()) { + let tuple, size; + try { tuple = docs.tailLineTuple(line); size = msgpack.encode(tuple).length; } catch (error) { + log(`tail line ${line?.eventId} skipped: ${error?.message ?? error}`); + continue; + } + if (bytes + size > docs.limits.replyBytes) break; + lines.unshift(tuple); + bytes += size; + } + return [persona, page, lines]; } // CultNet RUDP endpoint on loopback, one for every Persona in `mouths` (persona -> mouth). @@ -726,7 +781,8 @@ export async function startChatEndpoint({ mouths, runtime, port, connectionKey, const request = docs.parsePendingRequest(tuple); const mouth = mouths.get(request.persona); if (!mouth) return refuseUnknown(peer, request.persona); - respond(peer, request.persona, v3 ? docs.kinds.pendingV3 : docs.kinds.pending, request.persona, pageOf(request.persona, mouth.pendingAfter(request.afterSeq), msgpack, log, v3)); + const tail = v3 ? await mouth.tail().catch(error => { log(`tail not read: ${error?.message ?? error}`); return []; }) : []; + respond(peer, request.persona, v3 ? docs.kinds.pendingV3 : docs.kinds.pending, request.persona, pageOf(request.persona, mouth.pendingAfter(request.afterSeq), msgpack, log, v3, tail)); } else if (document.schemaId === docs.kinds.ack) { const request = docs.parseAck(tuple); const mouth = mouths.get(request.persona); From 5201508bdc58c262bd1a3848648fea33d7ccdc1f Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 08:12:48 +0000 Subject: [PATCH 004/113] OIDC issuer: address budget, token-row cap, scheduled prune, marker brake (#50) --- docs/oidc-issuer.md | 30 ++- docs/oidc-reserved-accounts.sql | 12 + .../Configuration/OidcIssuerOptions.cs | 28 ++ src/Bifrost.Web/Features/Oidc/OidcGuard.cs | 195 ++++++++++++++ .../Oidc/OidcServiceCollectionExtensions.cs | 3 + src/Bifrost.Web/Program.cs | 5 + tests/Bifrost.Web.Tests/OidcIssuerTests.cs | 247 +++++++++++++++++- .../Bifrost.Web.Tests/Support/OidcTestKit.cs | 68 ++++- 8 files changed, 581 insertions(+), 7 deletions(-) create mode 100644 docs/oidc-reserved-accounts.sql create mode 100644 src/Bifrost.Web/Features/Oidc/OidcGuard.cs diff --git a/docs/oidc-issuer.md b/docs/oidc-issuer.md index beaa6df..cb2ee08 100644 --- a/docs/oidc-issuer.md +++ b/docs/oidc-issuer.md @@ -44,6 +44,8 @@ echoes its value. | `Bifrost:Oidc:Clients:Mas:ClientId` | The client id MAS presents. | | `Bifrost:Oidc:Clients:Mas:ClientSecretPath` | File holding the client secret. | | `Bifrost:Oidc:Clients:Mas:RedirectUri` | MAS's callback URL, registered exactly. | +| `Bifrost:Oidc:BrakePath` | Optional. While a file exists at this path, `/connect/authorize`, `/token` and `/userinfo` answer 503 `temporarily_unavailable` and nothing is issued; delete the file to release. Checked per request, so no restart. Unset: no marker brake. | +| `Bifrost:Oidc:Limits:*` | `PerAddressPermits` (30), `Window` (1 min), `MaxTrackedKeys` (10000), `MaxTokenRows` (20000), `PruneInterval` (5 min). | | `Bifrost:Oidc:Clients:Mas:BackchannelLogoutUri` | Optional. MAS's back-channel logout URL, `https:///upstream/backchannel-logout/`; absolute http(s) or startup fails. Unset: no logout is sent and no authorization is revoked. | There are no development or ephemeral keys in the host. Key files are provisioned like the other @@ -111,17 +113,35 @@ Configure MAS's upstream provider with the issuer above, the client id and secre from `preferred_username`. MAS mints the Matrix localpart on first sign-in, so the claim must never change for an account. +## Limits, prune, brake + +`OidcGuardMiddleware` sits ahead of OpenIddict and guards the three endpoints, matched by path segment so a trailing slash +is no way around it. In order: the marker brake (503; a marker that cannot be read is treated as engaged); one per-address +budget over the three endpoints together (429 with `Retry-After`; the address is the connection's after forwarded-headers +handling that trusts only the local proxy, IPv6 keyed by /64); and a cap on token rows: a new authorize request (no +`request_uri`) is refused with 503 while the table holds `MaxTokenRows`. Any failure inside the guard is a 503, never a pass. +MAS's flow is a handful of requests per sign-in from one address, far under the defaults (30 a minute is about 15 sign-ins). + +There is no per-client budget. The one client's id is public and what a caller names is unverified, so a budget keyed on it +would let anyone spend the real client's permits and lock sign-in out. The bound on the anonymous endpoint is the address +budget plus the row cap, and the cap is itself a switch an attacker with many addresses can flip: it refuses new sign-ins +(never resumed ones) until the next prune frees rows, which is the bounded failure chosen over unbounded parked rows. +Not parking state before the user authenticates (as pushed authorization requests avoid by authenticating the client first) +would remove the switch, and OpenIddict's request caching does not offer that. + +`OidcPruner` runs every `PruneInterval` and deletes tokens past expiry (parked authorize requests, codes, access tokens) or no +longer valid, then authorizations no longer valid or ad hoc with no token left (younger than five minutes are left alone). +Live rows are untouched. Plain EF queries rather than OpenIddict's own prune, which uses ExecuteDelete and cannot run on the +in-memory provider the tests use. + +`docs/oidc-reserved-accounts.sql` is the read-only query for existing accounts that hold one of the 28 reserved names. + ## Not built Checked against the Window B list (2026-11-11). Present and tested: discovery, JWKS, authorize/token/userinfo, PKCE S256, the one client, claims to a Matrix-legal localpart (`[a-z0-9._-]`, 3-80, lower case), reserved names at creation and now at issuance, back-channel logout. Not present: -- **Rate limits and pruning.** No limiter sits on `/connect/*`, and expired OpenIddict rows (parked authorize requests, - tokens, authorizations) are never deleted. The authorize endpoint is anonymous and its client id and redirect URI are - public, so a caller can park rows without bound. Needs a budget (`FixedWindowBudget`) and a prune. -- **A brake.** The Bifrost process has none; the deploy brake belongs to Idunn. The only off switch is removing - `Bifrost:Oidc` and restarting, or membership leaving `Active` (the reconciler then logs the person out). - **Non-member sign-in.** The gate is `Active` membership, so an account with no membership gets `access_denied`. A "Users" tier for chat registration, with no vote, is a policy choice not yet made; nothing here writes membership or votes. - **MAS upstream block.** `gamecult-ops` `chat/matrix-auth/config.yaml` has no `upstream_oauth2` (provider ULID, diff --git a/docs/oidc-reserved-accounts.sql b/docs/oidc-reserved-accounts.sql new file mode 100644 index 0000000..8845053 --- /dev/null +++ b/docs/oidc-reserved-accounts.sql @@ -0,0 +1,12 @@ +-- Read-only. Which existing UserAccounts hold one of the 28 reserved localparts +-- (BifrostIdentityService.ReservedIdentities). Written for review; not run on live. +-- Run it in a read-only transaction by whoever holds the database: +-- psql -v ON_ERROR_STOP=1 -c 'BEGIN READ ONLY' -f docs/oidc-reserved-accounts.sql +-- Keep the list in step with ReservedIdentities; the issuer refuses these at authorize (#49). +SELECT a."Id", a."BifrostIdentity", a."NormalizedBifrostIdentity", a."CreatedAtUtc", a."LastSeenAtUtc" +FROM "UserAccounts" a +WHERE lower(a."NormalizedBifrostIdentity") IN ( + 'admin', 'aqua', 'deru', 'eureka', 'heimdall', 'ivixey', 'kiko', 'libby', 'meta', 'nibu', 'unnie', 'void', 'weksa', + 'root', 'system', 'matrix', 'synapse', 'support', 'bot', 'mod', 'moderator', 'postmaster', 'gamecult', + 'bifrost', 'idunn', 'odin', 'huginn', 'ratatoskr') +ORDER BY a."NormalizedBifrostIdentity"; diff --git a/src/Bifrost.Web/Configuration/OidcIssuerOptions.cs b/src/Bifrost.Web/Configuration/OidcIssuerOptions.cs index 13ba192..017648e 100644 --- a/src/Bifrost.Web/Configuration/OidcIssuerOptions.cs +++ b/src/Bifrost.Web/Configuration/OidcIssuerOptions.cs @@ -16,6 +16,15 @@ public sealed class OidcIssuerOptions public OidcClientsOptions Clients { get; init; } = new(); + public OidcLimitsOptions Limits { get; init; } = new(); + + /// + /// Optional path of the issuer's brake marker. While a file exists there, /connect/* answers 503 and nothing is issued; + /// remove it to release. Checked on every request (one stat), so engaging and releasing need no restart. + /// Unset: the issuer has no marker brake (removing this section and restarting is the other off switch). + /// + public string BrakePath { get; init; } = string.Empty; + /// Null when the section is absent. public static OidcIssuerOptions? FromConfiguration(IConfiguration configuration) { @@ -42,3 +51,22 @@ public sealed class OidcClientOptions /// MAS's back-channel logout URL for this provider. Empty: no logout is sent and no session is ended. public string BackchannelLogoutUri { get; init; } = string.Empty; } + +/// +/// One budget on /connect/authorize, /connect/token and /connect/userinfo together, per source address in one fixed window (a refused caller gets 429 with Retry-After), +/// and the bound on what the anonymous authorize endpoint can park. No per-client budget: the client id is public. The defaults suit one client (MAS) behind one proxy. +/// +public sealed class OidcLimitsOptions +{ + public int PerAddressPermits { get; init; } = 30; + + public TimeSpan Window { get; init; } = TimeSpan.FromMinutes(1); + + public int MaxTrackedKeys { get; init; } = 10_000; + + /// The most OpenIddict token rows (parked authorize requests, codes, access tokens) allowed to exist; a new authorize request beyond it is refused until the prune frees room. + public int MaxTokenRows { get; init; } = 20_000; + + /// How often expired and orphaned authorizations and tokens are deleted. + public TimeSpan PruneInterval { get; init; } = TimeSpan.FromMinutes(5); +} diff --git a/src/Bifrost.Web/Features/Oidc/OidcGuard.cs b/src/Bifrost.Web/Features/Oidc/OidcGuard.cs new file mode 100644 index 0000000..ccfd5e1 --- /dev/null +++ b/src/Bifrost.Web/Features/Oidc/OidcGuard.cs @@ -0,0 +1,195 @@ +using System.Net; +using Bifrost.Web.Configuration; +using Bifrost.Web.Data; +using Microsoft.EntityFrameworkCore; +using OpenIddict.EntityFrameworkCore.Models; +using Bifrost.Web.Features.Shared; +using Microsoft.Extensions.Options; +using OpenIddict.Abstractions; +using static OpenIddict.Abstractions.OpenIddictConstants; +using OpenIddict.Server.AspNetCore; + +namespace Bifrost.Web.Features.Oidc; + +/// +/// The issuer's front door, ahead of OpenIddict: the marker brake, the per-address budget, and the bound +/// on token rows. The address is the connection's, already corrected by the forwarded-headers handling that trusts only +/// the local proxy, so a caller cannot pick its own. It fails closed: anything this middleware cannot decide is a 503, never a pass. +/// +public sealed class OidcGuardMiddleware(RequestDelegate next, OidcIssuerOptions options, OidcRateLimit limit, ILogger logger) +{ + public async Task InvokeAsync(HttpContext http, IOpenIddictTokenManager tokens) + { + var endpoint = EndpointOf(http.Request.Path); + if (endpoint is null) + { + await next(http); + return; + } + + try + { + if (BrakeEngaged(options.BrakePath)) + { + await RefuseAsync(http, StatusCodes.Status503ServiceUnavailable, "temporarily_unavailable", TimeSpan.FromMinutes(1)); + return; + } + + if (limit.Spend(AddressKey(http.Connection.RemoteIpAddress)) is { } byAddress) + { + await RefuseAsync(http, StatusCodes.Status429TooManyRequests, "too_many_requests", byAddress.RetryAfter); + return; + } + + // A new authorize request parks a row for anyone who can name the (public) client; a resumed one carries request_uri and parks none. + if (endpoint == Authorize && !http.Request.Query.ContainsKey("request_uri") && await tokens.CountAsync(http.RequestAborted) >= options.Limits.MaxTokenRows) + { + await RefuseAsync(http, StatusCodes.Status503ServiceUnavailable, "temporarily_unavailable", options.Limits.PruneInterval); + return; + } + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError("OIDC guard could not decide ({ExceptionType}); the request is refused.", exception.GetType().Name); + await RefuseAsync(http, StatusCodes.Status503ServiceUnavailable, "temporarily_unavailable", TimeSpan.FromMinutes(1)); + return; + } + + await next(http); + } + + private const string Authorize = "authorize"; + + // OpenIddict answers these paths with or without a trailing slash, so the match is by segments, never exact equality. + private static string? EndpointOf(PathString path) => + path.StartsWithSegments(OidcServiceCollectionExtensions.AuthorizationPath, StringComparison.OrdinalIgnoreCase) ? Authorize + : path.StartsWithSegments(OidcServiceCollectionExtensions.TokenPath, StringComparison.OrdinalIgnoreCase) ? "token" + : path.StartsWithSegments(OidcServiceCollectionExtensions.UserInfoPath, StringComparison.OrdinalIgnoreCase) ? "userinfo" + : null; + + // A marker that cannot be told apart from an absent one (a permission or I/O error) throws, and the guard answers 503: the brake never releases by accident. + private static bool BrakeEngaged(string path) + { + if (string.IsNullOrWhiteSpace(path)) + { + return false; + } + + try + { + File.GetAttributes(path); + return true; + } + catch (Exception exception) when (exception is FileNotFoundException or DirectoryNotFoundException) + { + return false; + } + } + + // An IPv6 caller owns its /64, so rotating the low bits buys nothing. + private static string AddressKey(IPAddress? address) + { + if (address is null) + { + return "unknown"; + } + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6) + { + return address.ToString(); + } + + var bytes = address.GetAddressBytes(); + Array.Clear(bytes, 8, 8); + return new IPAddress(bytes).ToString() + "/64"; + } + + private static Task RefuseAsync(HttpContext http, int status, string error, TimeSpan retryAfter) + { + http.Response.StatusCode = status; + http.Response.Headers.RetryAfter = Math.Max(1, (int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture); + http.Response.ContentType = "application/json"; + return http.Response.WriteAsync($"{{\"error\":\"{error}\"}}", http.RequestAborted); + } +} + +/// +/// The issuer's per-address permits on the shared fixed-window budget. There is no per-client budget: the one client's id is +/// public and what a caller names unverified, so a budget on it would let anyone spend the real client's permits. +/// +public sealed class OidcRateLimit(OidcIssuerOptions options, TimeProvider clock) +{ + private readonly FixedWindowBudget addresses = new(options.Limits.PerAddressPermits, options.Limits.Window, options.Limits.MaxTrackedKeys, clock); + + public BudgetDenial? Spend(string address) => addresses.Spend(address); +} + +/// +/// Deletes expired and orphaned authorizations and tokens on a schedule: tokens past their expiry (parked authorize +/// requests, codes, access tokens) or no longer valid, then authorizations that are no longer valid or are ad hoc with no +/// token left. Live rows are never touched. Plain queries, not OpenIddict's ExecuteDelete prune, which the in-memory test provider +/// cannot run; an authorization takes its remaining tokens with it, because the foreign key has no cascade on Postgres. +/// +public sealed class OidcPruner(IServiceScopeFactory scopes, OidcIssuerOptions options, TimeProvider clock, ILogger logger) : BackgroundService +{ + private const int Batch = 500; + + // A fresh authorization briefly has no token yet; leave anything younger than this alone. + private static readonly TimeSpan AuthorizationGrace = TimeSpan.FromMinutes(5); + + public async Task PruneAsync(CancellationToken cancellationToken) + { + await using var scope = scopes.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var now = clock.GetUtcNow(); + var young = now - AuthorizationGrace; + + int removed; + do + { + var tokens = await db.Set() + .Where(token => token.ExpirationDate < now || (token.Status != Statuses.Valid && token.CreationDate < young)) + .Take(Batch).ToListAsync(cancellationToken); + db.RemoveRange(tokens); + await db.SaveChangesAsync(cancellationToken); + removed = tokens.Count; + } + while (removed == Batch); + + do + { + // A token row references its authorization (no cascade in the database), so the tokens go with it. + var authorizations = await db.Set() + .Include(authorization => authorization.Tokens) + .Where(authorization => authorization.CreationDate < young + && (authorization.Status != Statuses.Valid || (authorization.Type == AuthorizationTypes.AdHoc && !authorization.Tokens.Any()))) + .Take(Batch).ToListAsync(cancellationToken); + db.RemoveRange(authorizations.SelectMany(authorization => authorization.Tokens)); + db.RemoveRange(authorizations); + await db.SaveChangesAsync(cancellationToken); + removed = authorizations.Count; + } + while (removed == Batch); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(options.Limits.PruneInterval, clock); + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + try + { + await PruneAsync(stoppingToken); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError("OIDC prune failed ({ExceptionType}); the next tick tries again.", exception.GetType().Name); + } + } + } +} diff --git a/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs b/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs index 5ad30b8..78526af 100644 --- a/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs +++ b/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs @@ -67,6 +67,9 @@ public static class OidcServiceCollectionExtensions server.Issuer = issuer; }); + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(provider => provider.GetRequiredService()); services.AddHostedService(); if (!string.IsNullOrWhiteSpace(options.Clients.Mas.BackchannelLogoutUri)) { diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index 87d8088..2a5ff5f 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -285,6 +285,11 @@ if (!app.Environment.IsDevelopment()) app.UseHttpLogging(); app.UseHttpsRedirection(); +if (oidcOptions is not null) +{ + app.UseMiddleware(); // before authentication: OpenIddict answers /connect/* inside it +} + app.UseStaticFiles(); app.UseRouting(); app.UseConceptTallyCors(); diff --git a/tests/Bifrost.Web.Tests/OidcIssuerTests.cs b/tests/Bifrost.Web.Tests/OidcIssuerTests.cs index 30098f5..56f2b9a 100644 --- a/tests/Bifrost.Web.Tests/OidcIssuerTests.cs +++ b/tests/Bifrost.Web.Tests/OidcIssuerTests.cs @@ -7,6 +7,7 @@ using System.Text.Json; using Bifrost.Web.Domain; using Bifrost.Web.Features.Shared; using Bifrost.Web.Tests.Support; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; @@ -19,7 +20,7 @@ namespace Bifrost.Web.Tests; public sealed class OidcIssuerTests : IClassFixture { private static readonly Uri Origin = new("https://localhost"); - private readonly OidcWebApplicationFactory _factory; + private OidcWebApplicationFactory _factory; public OidcIssuerTests(OidcWebApplicationFactory factory) => _factory = factory; @@ -178,6 +179,250 @@ public sealed class OidcIssuerTests : IClassFixture Assert.False(redirect.ContainsKey("error")); } + private static IReadOnlyDictionary Settings(params (string Key, string Value)[] pairs) => + pairs.ToDictionary(p => $"Bifrost:Oidc:{p.Key}", p => (string?)p.Value); + + [Fact] + public async Task A_flood_from_one_address_is_refused_with_429_and_a_retry_after() + { + using var factory = new OidcSettingsFactory(Settings(("Limits:PerAddressPermits", "5"))); + using var client = factory.CreateClient(ClientOptions()); + + var statuses = new List(); + HttpResponseMessage? last = null; + for (var i = 0; i < 8; i++) + { + last?.Dispose(); + last = await client.GetAsync(NewRequest().Path); + statuses.Add(last.StatusCode); + } + + Assert.DoesNotContain(HttpStatusCode.TooManyRequests, statuses.Take(5)); + Assert.All(statuses.Skip(5), status => Assert.Equal(HttpStatusCode.TooManyRequests, status)); + Assert.True(int.Parse(last!.Headers.GetValues("Retry-After").Single()) >= 1); + using var tokenFlood = await client.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary())); + Assert.Equal(HttpStatusCode.TooManyRequests, tokenFlood.StatusCode); // one budget over all three endpoints + using var userinfoFlood = await client.GetAsync("/connect/userinfo"); + Assert.Equal(HttpStatusCode.TooManyRequests, userinfoFlood.StatusCode); + last.Dispose(); + } + + [Fact] + public async Task A_flood_naming_the_real_client_does_not_spend_anyone_elses_permits_and_a_trailing_slash_is_no_way_around() + { + using var factory = new OidcSettingsFactory(Settings(("Limits:PerAddressPermits", "4"))); + using var client = factory.CreateClient(ClientOptions()); + + var statuses = new List(); + foreach (var path in new[] { NewRequest().Path, NewRequest().Path, "/connect/authorize/?client_id=x", "/connect/token/", "/connect/userinfo/" }) + { + using var response = await client.GetAsync(path); + statuses.Add(response.StatusCode); + } + + Assert.Equal(HttpStatusCode.TooManyRequests, statuses[4]); // the slashed forms spend the same budget + Assert.DoesNotContain(HttpStatusCode.TooManyRequests, statuses.Take(4)); + } + + [Theory] + [InlineData("/connect/authorize")] + [InlineData("/connect/authorize/")] + [InlineData("/connect/token/")] + [InlineData("/connect/userinfo/")] + [InlineData("/CONNECT/Userinfo")] + public async Task The_brake_holds_for_every_spelling_of_an_endpoint(string path) + { + var marker = Path.Combine(Path.GetTempPath(), $"oidc-brake-{Guid.NewGuid():N}"); + File.WriteAllText(marker, "braked"); + try + { + using var factory = new OidcSettingsFactory(Settings(("BrakePath", marker))); + using var client = factory.CreateClient(ClientOptions()); + using var response = await client.GetAsync(path == "/connect/authorize" || path == "/connect/authorize/" ? path + "?client_id=x" : path); + Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); + } + finally + { + File.Delete(marker); + } + } + + [Fact] + public async Task A_guard_that_cannot_decide_answers_503_and_never_passes_the_request_on() + { + var reached = false; + var options = new Bifrost.Web.Configuration.OidcIssuerOptions(); + var middleware = new Bifrost.Web.Features.Oidc.OidcGuardMiddleware( + _ => { reached = true; return Task.CompletedTask; }, options, + new Bifrost.Web.Features.Oidc.OidcRateLimit(options, TimeProvider.System), + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + var http = new DefaultHttpContext(); + http.Request.Path = "/connect/authorize"; + http.Request.QueryString = new QueryString("?client_id=x"); + http.Response.Body = new MemoryStream(); + + await middleware.InvokeAsync(http, System.Reflection.DispatchProxy.Create()); + + Assert.False(reached); + Assert.Equal(StatusCodes.Status503ServiceUnavailable, http.Response.StatusCode); + } + + /// Every call fails: the row count the guard asks of the token table cannot be answered. + public class ThrowingProxy : System.Reflection.DispatchProxy + { + protected override object? Invoke(System.Reflection.MethodInfo? targetMethod, object?[]? args) => throw new InvalidOperationException("the token table is down"); + } + + [Fact] + public async Task A_resumed_authorize_request_is_not_refused_by_the_row_cap_but_a_fresh_one_is() + { + using var factory = new OidcSettingsFactory(Settings(("Limits:MaxTokenRows", "3"))); + _factory = factory; + var (client, _) = await SignedInAsync(MembershipStatus.Active, "Resumer"); + using var first = await client.GetAsync(NewRequest().Path); // parks one row, answers with a redirect carrying the request_uri + var resume = first.Headers.Location!.ToString(); + Assert.Contains("request_uri", resume); + + using var anonymous = factory.CreateClient(ClientOptions()); + for (var i = 0; i < 2; i++) + { + using var filler = await anonymous.GetAsync(NewRequest().Path); + } + + using var fresh = await anonymous.GetAsync(NewRequest().Path); + Assert.Equal(HttpStatusCode.ServiceUnavailable, fresh.StatusCode); + using var resumed = await client.GetAsync(resume); + Assert.NotEqual(HttpStatusCode.ServiceUnavailable, resumed.StatusCode); + } + + [Fact] + public async Task A_mas_flow_fits_the_default_budgets_and_the_window_reopens() + { + using var factory = new OidcSettingsFactory(Settings(("Limits:PerAddressPermits", "30"))); + _factory = factory; + var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Within Budget"); + + var verified = await ValidateIdTokenAsync((await CompleteFlowAsync(client)).IdToken, null); + Assert.Equal(identity, verified.Claim("preferred_username")); + + for (var i = 0; i < 40; i++) + { + using var burst = await client.GetAsync("/connect/userinfo"); + } + + using var refused = await client.GetAsync("/connect/userinfo"); + Assert.Equal(HttpStatusCode.TooManyRequests, refused.StatusCode); + factory.Clock.Advance(TimeSpan.FromMinutes(1)); + using var reopened = await client.GetAsync("/connect/userinfo"); + Assert.NotEqual(HttpStatusCode.TooManyRequests, reopened.StatusCode); + } + + [Fact] + public async Task The_brake_marker_stops_the_issuer_and_releasing_it_needs_no_restart() + { + var marker = Path.Combine(Path.GetTempPath(), $"bifrost-oidc-brake-{Guid.NewGuid():N}"); + using var factory = new OidcSettingsFactory(Settings(("BrakePath", marker))); + _factory = factory; + var (client, _) = await SignedInAsync(MembershipStatus.Active, "Braked"); + try + { + Assert.True((await CompleteFlowAsync(client)).IdToken.Length > 0, "released: the flow passes"); + + await File.WriteAllTextAsync(marker, "held"); + foreach (var path in new[] { NewRequest().Path, "/connect/userinfo" }) + { + using var held = await client.GetAsync(path); + Assert.Equal(HttpStatusCode.ServiceUnavailable, held.StatusCode); + Assert.True(held.Headers.Contains("Retry-After")); + } + + using var token = await client.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary())); + Assert.Equal(HttpStatusCode.ServiceUnavailable, token.StatusCode); + using var discovery = await client.GetAsync("/.well-known/openid-configuration"); + Assert.Equal(HttpStatusCode.OK, discovery.StatusCode); // the brake stops issuing, not the published keys + + File.Delete(marker); + Assert.True((await CompleteFlowAsync(client)).IdToken.Length > 0, "released again, same process"); + } + finally + { + File.Delete(marker); + } + } + + [Fact] + public async Task Anonymous_authorize_requests_cannot_park_more_than_the_row_cap_and_the_prune_gives_the_room_back() + { + using var factory = new OidcSettingsFactory(Settings(("Limits:MaxTokenRows", "3"))); + _factory = factory; + using var client = factory.CreateClient(ClientOptions()); + + var parked = new List(); + for (var i = 0; i < 5; i++) + { + using var response = await client.GetAsync(NewRequest().Path); + parked.Add(response.StatusCode); + } + + Assert.Equal(3, await factory.TokenRowsAsync()); + Assert.All(parked.Skip(3), status => Assert.Equal(HttpStatusCode.ServiceUnavailable, status)); + Assert.All(parked.Take(3), status => Assert.NotEqual(HttpStatusCode.ServiceUnavailable, status)); + + factory.Clock.Advance(TimeSpan.FromMinutes(11)); // past the ten-minute parked lifetime + await factory.PruneAsync(); + Assert.Equal(0, await factory.TokenRowsAsync()); + using var again = await client.GetAsync(NewRequest().Path); + Assert.NotEqual(HttpStatusCode.ServiceUnavailable, again.StatusCode); + } + + [Fact] + public async Task The_prune_removes_expired_rows_and_leaves_a_live_token_alone() + { + using var factory = new OidcSettingsFactory(Settings()); + _factory = factory; + var (client, _) = await SignedInAsync(MembershipStatus.Active, "Pruned"); + var tokens = await CompleteFlowAsync(client); // a parked request, a code and an access token existed along the way + using (var anonymous = factory.CreateClient(ClientOptions())) + { + using var parked = await anonymous.GetAsync(NewRequest().Path); // a parked request that will expire + } + + var before = await factory.TokenRowsAsync(); + await factory.PruneAsync(); + Assert.Equal(before, await factory.TokenRowsAsync()); // nothing has expired yet: nothing goes + + factory.Clock.Advance(TimeSpan.FromMinutes(11)); // parked requests and codes are dead, the access token (an hour) is not + await factory.PruneAsync(); + var after = await factory.TokenRowsAsync(); + Assert.True(after < before, "expired rows went"); + Assert.Contains("urn:ietf:params:oauth:token-type:access_token", await factory.TokenTypesAsync()); // the live one, not merely some row + + using var userinfo = new HttpRequestMessage(HttpMethod.Get, "/connect/userinfo"); + userinfo.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); + using var response = await factory.CreateClient(ClientOptions()).SendAsync(userinfo); + Assert.NotEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task The_prune_takes_a_revoked_authorization_with_its_tokens_and_touches_no_live_authorization() + { + using var factory = new OidcSettingsFactory(Settings()); + _factory = factory; + var (revoked, _) = await SignedInAsync(MembershipStatus.Active, "Revoked"); + await CompleteFlowAsync(revoked); + var (live, _) = await SignedInAsync(MembershipStatus.Active, "Live"); + await CompleteFlowAsync(live); + Assert.Equal(2, await factory.AuthorizationRowsAsync()); + Assert.Equal(6, await factory.TokensOfAuthorizationsAsync()); // a spent code, an access token and an id token each + await factory.RevokeFirstAuthorizationAsync(); + + factory.Clock.Advance(TimeSpan.FromMinutes(6)); // past the grace for a young row; the access tokens (an hour) are still alive + await factory.PruneAsync(); + + Assert.Equal(1, await factory.AuthorizationRowsAsync()); + Assert.Equal(2, await factory.TokenRowsAsync()); // no orphan stays either: the revoked one's tokens went with it; the live one's access and id tokens stayed, spent codes go + } + [Theory] [InlineData("unknown-client", OidcTestKit.RedirectUri, true)] [InlineData(OidcTestKit.ClientId, "https://evil.example.test/callback", true)] diff --git a/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs b/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs index 0b14d18..351ac79 100644 --- a/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs +++ b/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs @@ -5,6 +5,7 @@ using Bifrost.Web.Features.Shared; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Hosting; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; @@ -92,7 +93,9 @@ public sealed class OidcTestKit : IDisposable ["Bifrost:Oidc:EncryptionKeyPath"] = EncryptionKeyPath, ["Bifrost:Oidc:Clients:Mas:ClientId"] = ClientId, ["Bifrost:Oidc:Clients:Mas:ClientSecretPath"] = ClientSecretPath, - ["Bifrost:Oidc:Clients:Mas:RedirectUri"] = RedirectUri + ["Bifrost:Oidc:Clients:Mas:RedirectUri"] = RedirectUri, + // The shared test client has no remote address, so every request is one caller: the budgets are out of the way unless a test sets them. + ["Bifrost:Oidc:Limits:PerAddressPermits"] = "100000", }; public void Dispose() @@ -114,6 +117,11 @@ public sealed class OidcTestClock : TimeProvider public override DateTimeOffset GetUtcNow() => _now; + // The monotonic reading follows the moved time, so a budget's window can be aged the same way as a parked request. + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + + public override long GetTimestamp() => _now.UtcTicks; + public void Advance(TimeSpan by) => _now += by; } @@ -258,6 +266,64 @@ public sealed class OidcFixedIdentityFactory(string identity) : OidcWebApplicati } } +/// An OIDC host with extra settings (limits, a brake path) applied after the kit's own. +public sealed class OidcSettingsFactory(IReadOnlyDictionary settings) : OidcWebApplicationFactory +{ + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + foreach (var (key, value) in settings) + { + builder.UseSetting(key, value); + } + } + + public Task PruneAsync() => Services.GetRequiredService().PruneAsync(CancellationToken.None); + + public async Task> TokenTypesAsync() + { + using var scope = Services.CreateScope(); + var manager = scope.ServiceProvider.GetRequiredService(); + var types = new List(); + await foreach (var token in manager.ListAsync()) + { + types.Add(await manager.GetTypeAsync(token)); + } + + return types; + } + + public async Task AuthorizationRowsAsync() + { + using var scope = Services.CreateScope(); + return (int)await scope.ServiceProvider.GetRequiredService().CountAsync(); + } + + /// Tokens that belong to some authorization (the request and code rows carry none once spent). + public async Task TokensOfAuthorizationsAsync() + { + using var scope = Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Set().CountAsync(token => token.Authorization != null); + } + + public async Task RevokeFirstAuthorizationAsync() + { + using var scope = Services.CreateScope(); + var manager = scope.ServiceProvider.GetRequiredService(); + await foreach (var authorization in manager.ListAsync(count: 1, offset: 0)) + { + Assert.True(await manager.TryRevokeAsync(authorization)); + } + } + + public async Task TokenRowsAsync() + { + using var scope = Services.CreateScope(); + return (int)await scope.ServiceProvider.GetRequiredService().CountAsync(); + } +} + /// An OIDC host whose public base URL differs from the origin its requests arrive on, so the issuer cannot be request-derived. public sealed class OidcForeignIssuerFactory : OidcWebApplicationFactory { From 24f3deb88edbf3c8fc09b51bf3f0025b5e273ace Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 08:13:09 +0000 Subject: [PATCH 005/113] OIDC issuer: chat tier for accounts without Active membership (#52) --- docs/oidc-issuer.md | 28 +++---- .../Features/Oidc/OidcEndpoints.cs | 48 ++++++++---- .../Features/Oidc/OidcLogoutReconciler.cs | 6 +- tests/Bifrost.Web.Tests/OidcIssuerTests.cs | 76 +++++++++++++++---- tests/Bifrost.Web.Tests/OidcLogoutTests.cs | 21 ++++- .../Bifrost.Web.Tests/Support/OidcTestKit.cs | 26 ++++++- 6 files changed, 155 insertions(+), 50 deletions(-) diff --git a/docs/oidc-issuer.md b/docs/oidc-issuer.md index cb2ee08..06dff5f 100644 --- a/docs/oidc-issuer.md +++ b/docs/oidc-issuer.md @@ -68,25 +68,29 @@ The authorize endpoint reads the cookie session and the same actor facts the `/A - No session: challenge to `/auth/sign-in`, which resumes the original request after sign-in. OpenIddict parks the full request (its request token, in the OpenIddict token table, expiring after ten minutes, spent when used) and the return path carries only a short `request_uri`, so `LocalReturnPath.MaxLength` stays 256. -- Signed in, membership not `Active`: redirect to the client's `redirect_uri` with `error=access_denied` and - `error_description=The account is not an active GameCult member.` -- Signed in, `Active`, but `NormalizedBifrostIdentity` empty: `error=access_denied` with +- Signed in, membership `Suspended`: redirect to the client's `redirect_uri` with `error=access_denied` and + `error_description=The account is suspended.` +- Signed in with no membership, `Authenticated` or `PendingApproval` (the chat tier): treated like an active member for + sign-in to chat and nothing else. The token carries the same `openid profile` claims; the issuer writes no membership, + role or vote, and every member or governance surface (`/App`, `/eve/governance`, `/api/sealed-motions`, the fork desk) + still asks for `Active` itself, so neither the session nor the token opens them. +- Signed in, with an account that can chat, but `NormalizedBifrostIdentity` empty: `error=access_denied` with `error_description=The account has no Bifrost identity.` -- Signed in, `Active`, but the identity is a reserved localpart (`BifrostIdentityService.IsReserved`: the 13 Synapse +- Signed in, with an account that can chat, but the identity is a reserved localpart (`BifrostIdentityService.IsReserved`: the 13 Synapse accounts and the system names, the same 28 as MAS `banned_usernames`): `error=access_denied` with `error_description=The account's Bifrost identity is reserved.` Creation refuses these names, but a row minted before that refusal may hold one and there is no rename path, so the issuer never vouches for a Mind's or a system's localpart. The refusal is at authorize only: a code or access token issued for such a row before this check deployed stays redeemable until it expires (minutes), and token and userinfo re-read membership, not the name. Whether any such row exists is not known from the code; one query of `UserAccounts` against the 28 names would say. -- Signed in and `Active`: a code is issued. -- Token endpoint: membership is read again; an account no longer `Active` gets `invalid_grant` and no tokens. +- Otherwise: a code is issued. +- Token endpoint and userinfo: suspension is read again; an account suspended or deleted since gets `invalid_grant` (token) or 403 (userinfo). The logout reconciler ends the sessions of those same accounts; a chat-tier account is never logged out for lacking membership. ## Back-channel logout When `BackchannelLogoutUri` is set, a hosted reconciler (`OidcLogoutReconciler`) runs every 30 seconds. It lists the -subjects holding valid authorizations of the MAS client; for each subject whose membership is not `Active` (the same -reading the token and userinfo endpoints use; a deleted account or a subject that is not an account id counts as not -`Active`) it POSTs one OIDC back-channel logout token to MAS, and only after a 2xx revokes that subject's authorizations, -which also invalidates their tokens. Membership is never written by this path: any way of leaving `Active` (admin -action, sync, a database edit, a future suspend) is covered because the work is derived from membership state. +subjects holding valid authorizations of the MAS client; for each subject who may no longer chat (the same +reading the token and userinfo endpoints use: membership `Suspended`, a deleted account, or a subject that is not an account id; an +account with no membership or a pending one may chat and is left alone) it POSTs one OIDC back-channel logout token to MAS, and only after a 2xx revokes that subject's authorizations, +which also invalidates their tokens. Membership is never written by this path: any way of being suspended or deleted (admin +action, sync, a database edit) is covered because the work is derived from membership state. The token is an ES256 JWT signed with the issuer key, header `typ` `logout+jwt`, with `iss` as the id_token carries it, `aud` the MAS client id, `sub` the account id, `iat`, `exp` two minutes later, a fresh `jti` and the @@ -142,8 +146,6 @@ Checked against the Window B list (2026-11-11). Present and tested: discovery, J the one client, claims to a Matrix-legal localpart (`[a-z0-9._-]`, 3-80, lower case), reserved names at creation and now at issuance, back-channel logout. Not present: -- **Non-member sign-in.** The gate is `Active` membership, so an account with no membership gets `access_denied`. A "Users" - tier for chat registration, with no vote, is a policy choice not yet made; nothing here writes membership or votes. - **MAS upstream block.** `gamecult-ops` `chat/matrix-auth/config.yaml` has no `upstream_oauth2` (provider ULID, `on_conflict: fail`, `on_backchannel_logout: logout_all`, the redirect URI above); that lives in the ops repo. diff --git a/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs b/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs index 7fce895..1a90c23 100644 --- a/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs +++ b/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs @@ -20,7 +20,7 @@ namespace Bifrost.Web.Features.Oidc; /// public static class OidcEndpoints { - public const string NotActiveDescription = "The account is not an active GameCult member."; + public const string SuspendedDescription = "The account is suspended."; public const string NoIdentityDescription = "The account has no Bifrost identity."; public const string ReservedIdentityDescription = "The account's Bifrost identity is reserved."; @@ -49,9 +49,16 @@ public static class OidcEndpoints } var actor = await actors.GetAsync(http.RequestAborted); - if (actor.UserAccount is null || !actor.IsActiveMember) + // Chat tier: any account that is not suspended may sign in to chat. Membership is neither required nor written; + // every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync). + if (actor.UserAccount is null) { - return Deny(Errors.AccessDenied, NotActiveDescription); + return Deny(Errors.AccessDenied, NoIdentityDescription); + } + + if (actor.Membership?.Status == MembershipStatus.Suspended) + { + return Deny(Errors.AccessDenied, SuspendedDescription); } var account = actor.UserAccount; @@ -90,13 +97,13 @@ public static class OidcEndpoints private static async Task ExchangeAsync(HttpContext http, BifrostDbContext db) { // Only the authorization code grant is enabled, so OpenIddict has refused every other grant already. - // The code's own principal carries the claims chosen at authorize time; membership is read again here, - // because the code outlives the authorize decision (a member suspended since gets no tokens). + // The code's own principal carries the claims chosen at authorize time; suspension is read again here, + // because the code outlives the authorize decision (an account suspended since gets no tokens). var result = await http.AuthenticateAsync(OpenIddictScheme); var subject = result.Principal?.GetClaim(Claims.Subject); - if (!await IsStillActiveMemberAsync(db, subject, http.RequestAborted)) + if (!await IsStillChatEligibleAsync(db, subject, http.RequestAborted)) { - return Deny(Errors.InvalidGrant, NotActiveDescription); + return Deny(Errors.InvalidGrant, SuspendedDescription); } return Results.SignIn(result.Principal!, properties: null, OpenIddictScheme); @@ -110,10 +117,10 @@ public static class OidcEndpoints return Results.Challenge(authenticationSchemes: [OpenIddictScheme]); } - // An access token outlives the authorize decision too: a member suspended since is no longer answered. - if (!await IsStillActiveMemberAsync(db, result.Principal.GetClaim(Claims.Subject), http.RequestAborted)) + // An access token outlives the authorize decision too: an account suspended since is no longer answered. + if (!await IsStillChatEligibleAsync(db, result.Principal.GetClaim(Claims.Subject), http.RequestAborted)) { - return Deny(Errors.InsufficientAccess, NotActiveDescription); + return Deny(Errors.InsufficientAccess, SuspendedDescription); } var claims = new Dictionary { [Claims.Subject] = result.Principal.GetClaim(Claims.Subject) }; @@ -126,11 +133,24 @@ public static class OidcEndpoints return Results.Json(claims); } - /// The one reading of "this subject is still an Active member", shared by the token and userinfo endpoints, the logout reconciler and the fork desk. - internal static async Task IsStillActiveMemberAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken) => - await ActiveMemberIdAsync(db, subject, cancellationToken) is not null; + /// + /// The one reading of "this subject may still chat", shared by the token and userinfo endpoints and the logout reconciler: + /// the account exists and its membership is not Suspended. Membership may be absent, pending or Active. Re-read on every call. + /// + internal static async Task IsStillChatEligibleAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken) + { + if (!Guid.TryParse(subject, out var accountId)) + { + return false; + } - /// The account id of the subject when it is an Active member now, else null. Re-read on every call. + var account = await db.UserAccounts.AsNoTracking() + .Include(x => x.Membership) + .SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken); + return account is not null && account.Membership?.Status != MembershipStatus.Suspended; + } + + /// The account id of the subject when it is an Active member now, else null. The door to the fork desk (cookie surfaces check IsActiveMember); a chat-tier token does not pass it. Re-read on every call. internal static async Task ActiveMemberIdAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken) { if (!Guid.TryParse(subject, out var accountId)) diff --git a/src/Bifrost.Web/Features/Oidc/OidcLogoutReconciler.cs b/src/Bifrost.Web/Features/Oidc/OidcLogoutReconciler.cs index ac6fa72..63df719 100644 --- a/src/Bifrost.Web/Features/Oidc/OidcLogoutReconciler.cs +++ b/src/Bifrost.Web/Features/Oidc/OidcLogoutReconciler.cs @@ -11,8 +11,8 @@ using static OpenIddict.Abstractions.OpenIddictConstants; namespace Bifrost.Web.Features.Oidc; /// -/// Ends the chat sessions of a subject who is no longer an Active member. Each tick it lists the subjects holding valid -/// authorizations of the configured client; for each one the shared active-member reading refuses, it POSTs one signed +/// Ends the chat sessions of a subject who is no longer allowed to chat (suspended, or the account gone). Each tick it lists the subjects holding valid +/// authorizations of the configured client; for each one the shared chat-eligibility reading refuses, it POSTs one signed /// OIDC back-channel logout token to MAS and, only after a 2xx, revokes that subject's authorizations. The /// authorizations table is the queue: nothing is stored, so a restart, a MAS outage or a later-set URI resumes from it. /// Per-subject backoff lives in memory only. One subject's unexpected exception is logged and skipped, never aborting the @@ -127,7 +127,7 @@ public sealed class OidcLogoutReconciler( { await using var scope = scopeFactory.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); - if (await OidcEndpoints.IsStillActiveMemberAsync(db, subject, cancellationToken)) + if (await OidcEndpoints.IsStillChatEligibleAsync(db, subject, cancellationToken)) { _backoff.Remove(subject); return; diff --git a/tests/Bifrost.Web.Tests/OidcIssuerTests.cs b/tests/Bifrost.Web.Tests/OidcIssuerTests.cs index 56f2b9a..68617b8 100644 --- a/tests/Bifrost.Web.Tests/OidcIssuerTests.cs +++ b/tests/Bifrost.Web.Tests/OidcIssuerTests.cs @@ -107,20 +107,74 @@ public sealed class OidcIssuerTests : IClassFixture Assert.Equal("Second Name", second.Claim("name")); } - [Theory] - [InlineData(MembershipStatus.Authenticated)] - [InlineData(MembershipStatus.PendingApproval)] - [InlineData(MembershipStatus.Suspended)] - public async Task A_member_who_is_not_active_is_refused_with_access_denied_and_no_code(MembershipStatus status) + [Fact] + public async Task A_suspended_account_is_refused_with_access_denied_and_no_code() { - var (client, _) = await SignedInAsync(status, "Not Active"); + var (client, _) = await SignedInAsync(MembershipStatus.Suspended, "Suspended One"); var request = NewRequest(); var final = await DriveAsync(client, request); var redirect = AssertRedirectToClient(final, request.State); Assert.Equal("access_denied", redirect["error"]); - Assert.Equal(Bifrost.Web.Features.Oidc.OidcEndpoints.NotActiveDescription, redirect["error_description"]); + Assert.Equal(Bifrost.Web.Features.Oidc.OidcEndpoints.SuspendedDescription, redirect["error_description"]); + Assert.False(redirect.ContainsKey("code")); + } + + [Theory] + [InlineData(MembershipStatus.Authenticated)] + [InlineData(MembershipStatus.PendingApproval)] + public async Task A_non_member_gets_a_chat_only_token_and_writes_no_membership_or_vote(MembershipStatus status) + { + var (client, identity) = await SignedInAsync(status, "Chat Only"); + var accountId = _factory.AccountId(identity); + var before = await _factory.RowCountsAsync(); + + var tokens = await CompleteFlowAsync(client); + + var verified = await ValidateIdTokenAsync(tokens.IdToken, tokens.Request.Nonce); + Assert.Equal(accountId.ToString("D"), verified.Claim("sub")); + Assert.Equal(identity, verified.Claim("preferred_username")); + + // The issuer wrote nothing about membership or votes, and the status is exactly what it was. + Assert.Equal(before, await _factory.RowCountsAsync()); + Assert.Equal(status, await _factory.MembershipStatusAsync(identity)); + Assert.Equal(0, (await _factory.RowCountsAsync()).Votes); + + // Neither the session that signed in to chat nor its token opens a member or governance surface. + foreach (var path in new[] { "/eve/governance/surface", "/api/sealed-motions", "/App" }) + { + using var viaSession = await client.GetAsync(path); + Assert.NotEqual(HttpStatusCode.OK, viaSession.StatusCode); + + using var viaToken = new HttpRequestMessage(HttpMethod.Get, path); + viaToken.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); + using var bearer = await NewClient().SendAsync(viaToken); + Assert.NotEqual(HttpStatusCode.OK, bearer.StatusCode); + } + + using var desk = new HttpRequestMessage(HttpMethod.Get, "/api/desk/forks"); + desk.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); + using var deskResponse = await NewClient().SendAsync(desk); + Assert.NotEqual(HttpStatusCode.OK, deskResponse.StatusCode); + + // Last, because userinfo answers 500 on a .NET 10 runtime (the six known failures), and the rest must still run there. + using var userinfo = await UserInfoAsync(tokens.AccessToken); + Assert.Equal(HttpStatusCode.OK, userinfo.StatusCode); + var info = JsonDocument.Parse(await userinfo.Content.ReadAsStringAsync()).RootElement; + Assert.Equal(["name", "preferred_username", "sub"], info.EnumerateObject().Select(x => x.Name).Order().ToArray()); + } + + [Fact] + public async Task A_chat_tier_account_with_a_reserved_identity_is_still_refused() + { + using var factory = new OidcFixedIdentityFactory("eureka", MembershipStatus.Authenticated); + using var client = factory.CreateClient(ClientOptions()); + await RegisterAsync(client, $"cookie-{Guid.NewGuid():N}"); + var request = NewRequest(); + + var redirect = AssertRedirectToClient(await DriveAsync(client, request), request.State); + Assert.Equal("access_denied", redirect["error"]); Assert.False(redirect.ContainsKey("code")); } @@ -619,11 +673,9 @@ public sealed class OidcIssuerTests : IClassFixture } [Theory] - [InlineData(MembershipStatus.Authenticated)] - [InlineData(MembershipStatus.PendingApproval)] [InlineData(MembershipStatus.Suspended)] [InlineData(null)] - public async Task A_member_no_longer_active_after_authorize_gets_no_tokens(MembershipStatus? status) + public async Task An_account_suspended_or_gone_after_authorize_gets_no_tokens(MembershipStatus? status) { var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Soon Gone"); var request = NewRequest(); @@ -640,11 +692,9 @@ public sealed class OidcIssuerTests : IClassFixture } [Theory] - [InlineData(MembershipStatus.Authenticated)] - [InlineData(MembershipStatus.PendingApproval)] [InlineData(MembershipStatus.Suspended)] [InlineData(null)] - public async Task Userinfo_refuses_an_access_token_whose_member_is_no_longer_active(MembershipStatus? status) + public async Task Userinfo_refuses_an_access_token_whose_account_is_suspended_or_gone(MembershipStatus? status) { var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Soon Gone"); var tokens = await CompleteFlowAsync(client); diff --git a/tests/Bifrost.Web.Tests/OidcLogoutTests.cs b/tests/Bifrost.Web.Tests/OidcLogoutTests.cs index 8aa5d15..c167fc2 100644 --- a/tests/Bifrost.Web.Tests/OidcLogoutTests.cs +++ b/tests/Bifrost.Web.Tests/OidcLogoutTests.cs @@ -37,9 +37,7 @@ public sealed class OidcLogoutTests [Theory] [InlineData(MembershipStatus.Suspended)] - [InlineData(MembershipStatus.PendingApproval)] - [InlineData(MembershipStatus.Authenticated)] - public async Task A_member_who_is_not_active_gets_one_signed_logout_and_loses_the_authorizations(MembershipStatus status) + public async Task A_suspended_account_gets_one_signed_logout_and_loses_the_authorizations(MembershipStatus status) { using var factory = new OidcLogoutFactory(); var (identity, idToken) = await factory.GrantAsync(status); @@ -112,6 +110,23 @@ public sealed class OidcLogoutTests Assert.Equal(before, factory.ValidAuthorizations(activeSubject)); } + [Theory] + [InlineData(MembershipStatus.Authenticated)] + [InlineData(MembershipStatus.PendingApproval)] + public async Task A_chat_tier_non_member_is_never_sent_a_logout_and_keeps_the_authorizations(MembershipStatus status) + { + using var factory = new OidcLogoutFactory(); + var (chat, _) = await factory.GrantAsync(status); + var subject = factory.AccountId(chat).ToString("D"); + var before = factory.ValidAuthorizations(subject); + Assert.True(before > 0); + + await factory.Reconciler.ReconcileOnceAsync(CancellationToken.None); + + Assert.Empty(factory.Mas.LogoutTokens()); + Assert.Equal(before, factory.ValidAuthorizations(subject)); + } + [Fact] public async Task One_subject_that_cannot_be_delivered_does_not_block_another() { diff --git a/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs b/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs index 351ac79..a9b304f 100644 --- a/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs +++ b/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs @@ -179,6 +179,24 @@ public class OidcWebApplicationFactory : TestWebApplicationFactory } } + public async Task MembershipStatusAsync(string identity) + { + using var scope = Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var account = db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity); + return (await db.Memberships.AsNoTracking().SingleOrDefaultAsync(x => x.UserAccountId == account.Id))?.Status; + } + + public sealed record RowCounts(int Accounts, int Memberships, int Votes, int RoleAssignments); + + /// What the issuer must leave alone: accounts, memberships, role grants and votes. + public async Task RowCountsAsync() + { + using var scope = Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return new RowCounts(await db.UserAccounts.CountAsync(), await db.Memberships.CountAsync(), await db.Votes.CountAsync(), await db.RoleAssignments.CountAsync()); + } + /// Sets the membership of the account registered under . public async Task SetMembershipAsync(string identity, MembershipStatus status) { @@ -244,15 +262,15 @@ public sealed class OidcNoIdentityFactory : OidcWebApplicationFactory /// reserved names were refused at creation (or any identity the test needs) reaches the authorize endpoint, since /// registration itself now refuses a reserved name. /// -public sealed class OidcFixedIdentityFactory(string identity) : OidcWebApplicationFactory +public sealed class OidcFixedIdentityFactory(string identity, MembershipStatus status = MembershipStatus.Active) : OidcWebApplicationFactory { protected override void ConfigureActors(IServiceCollection services) { services.RemoveAll(); - services.AddScoped(_ => new FixedIdentity(identity)); + services.AddScoped(_ => new FixedIdentity(identity, status)); } - private sealed class FixedIdentity(string identity) : ICurrentBifrostActorAccessor + private sealed class FixedIdentity(string identity, MembershipStatus status) : ICurrentBifrostActorAccessor { public Task GetAsync(CancellationToken cancellationToken) => Task.FromResult(new CurrentBifrostActor(true, new UserAccount @@ -261,7 +279,7 @@ public sealed class OidcFixedIdentityFactory(string identity) : OidcWebApplicati BifrostIdentity = identity, NormalizedBifrostIdentity = identity, // as given: the guard, not the fixture, must fold case DisplayName = "Fixed Identity", - Membership = new Bifrost.Web.Domain.Membership { Status = MembershipStatus.Active } + Membership = new Bifrost.Web.Domain.Membership { Status = status } })); } } From db91716a3f9d6b5a2200b6b5aa6452a80aa993b1 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 08:15:37 +0000 Subject: [PATCH 006/113] Mouth tail: no ack cursor (acked unaddressed lines are what it exists for), per-room read timeout, tests for the gaps Soul found Co-Authored-By: Claude Sonnet 5.5 --- docs/bridge.md | 6 ++-- tests/persona-matrix-mouth-runtime.test.mjs | 11 ++++++- tests/persona-matrix-mouth.test.mjs | 27 +++++++++++++--- tools/persona-matrix-mouth.mjs | 34 ++++++++++----------- 4 files changed, 51 insertions(+), 27 deletions(-) diff --git a/docs/bridge.md b/docs/bridge.md index a6430d1..b9b35a6 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -221,14 +221,14 @@ Proposed runtime half (follow-up `persona-wakes-on-address-only`): ### Room tail (`chat_pending.v3`, field 2) -The v3 answer is `[persona, deliveries, tail]`. `tail` is a list of recent room lines, oldest first, for a reader that was not woken for them (a scheduled beat). It is built from the same `/messages` read as a delivery's `context`, as her account, with no new endpoint and no new homeserver call per line. A `chat_pending_request.v1` is still answered with the two-field `chat_pending.v2`, and `chat_pending.v3` has not been deployed, so no reader sees the third field before it is ready for it. +The v3 answer is `[persona, deliveries, tail]`. `tail` is a list of recent room lines, oldest first, for a reader that was not woken for them (a scheduled beat). It uses the same room read as a delivery's `context` (the same function, a separate read), as her account, with no new endpoint; the cost is one `/messages` call per speakable room per poll (15 seconds cached), including every DM. A `chat_pending_request.v1` is still answered with the two-field `chat_pending.v2`. `chat_pending.v3` has not been deployed, but a reader that decodes it as a two-field tuple fails on the third element (rmp-serde `LengthMismatch`), so Huginn must accept `tail` (a defaulted field) before this mouth is deployed. | Bound | Rule | |---|---| | Rooms | Only rooms the Persona may speak in: a configured room she has joined, or one of her DMs. The same rule `send` uses (`speakableRoomId`). A room she is in but cannot speak in, and any other room, is absent. | | Lines | A text line outside threads, not an edit, newest `20` per room, newest `60` over all rooms. Trimmed oldest first if the reply byte budget (256 KiB, deliveries first) would be exceeded. | -| Cursor | Only lines past her ack cursor in that room: the origin time of the newest delivery she has acked there (ties by event id). A room she has acked nothing in since the mouth started returns its recent lines, a quiet room included. The cursor is in memory: a restart forgets it and the next tail shows the recent lines again. | -| Read | A room's read is kept 15 seconds, dropped when a sync brings the room news or an ack moves the cursor. A room that cannot be read is logged and absent; the other rooms and the deliveries are unaffected. | +| Cursor | None. The tail is each room's newest lines whether or not they were delivered or acked: a message the wake rule left unaddressed is acked and leaves `pending`, and the tail is where a beat still finds it. A reader removes the lines a delivery already shows (by event id). Her own lines are included. | +| Read | A room's read is kept 15 seconds, dropped when a sync brings the room news. A room that cannot be read within 10 seconds is logged and absent; the other rooms and the deliveries are unaffected. | A line is the 7-field tuple `[room, event_id, at_unix_ms, sender, form, basis, body]`: `room` is the configured alias (the room id for a DM), `form` and `basis` as for a delivery, `body` clipped to 1000 bytes with the same typed text line for media a delivery has (nothing is fetched). `basis` is what Matrix says on the event itself (`direct` in a DM, `tag`, `room`) and nothing the mouth would have to look up, so a reply is nil here: **nil is unproven, not "not for her"**, and a line in a DM is `direct`. Huginn's rule that an `is_direct` delivery wakes with a nil `basis` is unchanged and lives with Huginn; the tail does not feed it. diff --git a/tests/persona-matrix-mouth-runtime.test.mjs b/tests/persona-matrix-mouth-runtime.test.mjs index 7a994c5..e2c9273 100644 --- a/tests/persona-matrix-mouth-runtime.test.mjs +++ b/tests/persona-matrix-mouth-runtime.test.mjs @@ -140,7 +140,7 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a const calls = { acks: [], sends: [], reads: [] }; const mouth = { pendingAfter: after => (after < 7 ? [delivery] : []), - tail: async () => [tailLine], + tail: async () => { if (calls.tailFails) throw new Error("room read failed"); return [tailLine]; }, ack: async through => { calls.acks.push(through); }, read: async request => { calls.reads.push(request); return null; }, send: async request => { calls.sends.push(request); return request.text === "muted" ? { requestId: request.requestId, eventId: null, refusal: "Brake" } : { requestId: request.requestId, eventId: "$sent", refusal: null }; }, @@ -184,6 +184,15 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a assert.deepEqual(v3.deliveries[0], { ...delivery, basis: null, form: "message" }); assert.deepEqual(v3.tail, [tailLine], "the v3 answer carries the room tail"); + calls.tailFails = true; + reply = nextReply(); + put(docs.kinds.pendingRequestV3, "eureka", docs.pendingRequestTuple({ persona: "eureka", afterSeq: 0 })); + document = await reply; + const degraded = docs.parsePendingV3(msgpack.decode(document.payload)); + assert.equal(degraded.deliveries.length, 1, "a tail that throws does not silence the deliveries"); + assert.deepEqual(degraded.tail, []); + calls.tailFails = false; + put(docs.kinds.ack, "eureka:7", docs.ackTuple({ persona: "eureka", throughSeq: 7 })); reply = nextReply(); put(docs.kinds.sendRequest, "req-2", docs.sendRequestTuple({ requestId: "req-2", persona: "eureka", roomAlias: "#operator:gamecult.org", text: "muted" })); diff --git a/tests/persona-matrix-mouth.test.mjs b/tests/persona-matrix-mouth.test.mjs index 5558df3..e4c7731 100644 --- a/tests/persona-matrix-mouth.test.mjs +++ b/tests/persona-matrix-mouth.test.mjs @@ -1528,7 +1528,7 @@ test("room tail: about 60 lines over all rooms, the newest, whatever the room co assert.equal(Math.min(...tail.map(l => l.atUnixMs)), 110, "the oldest kept is the 60th newest of the 120 offered"); }); -test("room tail: lines at or before her ack cursor are gone, later ones stay, and mention basis rides on the line", async () => { +test("room tail: acking a delivery does not hide it, so an unaddressed line she has acked is still found, and mention basis rides on the line", async () => { const events = [ withContent("$a", META, { body: "first" }, 3000), withContent("$b", META, { body: "tag", "m.mentions": { user_ids: [SELF] } }, 3001), @@ -1538,12 +1538,29 @@ test("room tail: lines at or before her ack cursor are gone, later ones stay, an const mouth = mouthFor(hs); await mouth.syncOnce(); const made = await mouth.syncOnce(); - assert.equal(made.length, 2); assert.deepEqual((await mouth.tail()).map(l => [l.eventId, l.basis]), [["$a", null], ["$b", "tag"]]); - await mouth.ack(made[0].seq); - assert.deepEqual((await mouth.tail()).map(l => l.eventId), ["$b"], "unacked past the cursor only"); await mouth.ack(made[1].seq); - assert.deepEqual(await mouth.tail(), []); + assert.equal(mouth.pendingAfter(0).length, 0); + assert.deepEqual((await mouth.tail()).map(l => l.eventId), ["$a", "$b"], "acked lines are the ones no delivery will bring again"); + } finally { await hs.close(); } +}); + +test("room tail: a room that never answers is absent after the timeout and does not hold the others", async () => { + const hs = await fakeHomeserver({ preload: { [OPERATOR]: lines(OPERATOR, 2) }, sync: since => ({ next_batch: since ?? "b0" }) }); + const hang = (url, init) => String(url).includes(encodeURIComponent(ROOM)) && String(url).includes("/messages") ? new Promise(() => {}) : hs.fetch(url, init); + try { + const mouth = mouthFor(hs, { fetch: hang, sendTimeoutMs: 50 }); + await mouth.syncOnce(); + const tail = await mouth.tail(); + assert.deepEqual([...new Set(tail.map(l => l.roomAlias))], [`#operator:${HS_NAME}`]); + } finally { await hs.close(); } +}); + +test("room tail: a mouth that has not started reads no room", async () => { + const hs = await fakeHomeserver({ preload: { [ROOM]: lines(ROOM, 2) }, sync: since => ({ next_batch: since ?? "b0" }) }); + try { + assert.deepEqual(await mouthFor(hs).tail(), []); + assert.equal(hs.seen.filter(r => r.path.includes("/messages")).length, 0); } finally { await hs.close(); } }); diff --git a/tools/persona-matrix-mouth.mjs b/tools/persona-matrix-mouth.mjs index 206fce2..d6b4f94 100644 --- a/tools/persona-matrix-mouth.mjs +++ b/tools/persona-matrix-mouth.mjs @@ -142,8 +142,7 @@ export function createMouth({ let started = false; let lastPresence = null; // 'online' | 'unavailable' | 'offline' | null: command-only, suppresses repeat presence PUTs let activeUntil = 0; // her last sign of life in a turn, plus the grace - const ackedThrough = new Map(); // room id -> { ts, ids }: the newest delivery she has acked there, ids those at exactly that time; the tail is what lies past it - const tailReads = new Map(); // room id -> { at, lines }: a room's tail read, kept TAIL_TTL_MS or until a sync brings the room news or an ack moves the cursor + const tailReads = new Map(); // room id -> { at, lines }: a room's tail read, kept TAIL_TTL_MS or until a sync brings the room news const delivered = new Map(); // event id -> { roomId, roomAlias, seq }: what the mouth handed her, newest last, bounded const readThrough = new Map(); // room id -> { seq, eventId } of the last receipt that landed const readTails = new Map(); // room id -> the read report in flight: reports for one room run one at a time @@ -472,22 +471,18 @@ export function createMouth({ } async function ack(throughSeq) { - for (const d of pending) if (d.seq <= throughSeq) { - const through = ackedThrough.get(d.roomId); - if (!through || d.atUnixMs > through.ts) ackedThrough.set(d.roomId, { ts: d.atUnixMs, ids: new Set([d.eventId]) }); - else if (d.atUnixMs === through.ts) through.ids.add(d.eventId); - } pending = pending.filter(d => d.seq > throughSeq); - tailReads.clear(); images?.acked(throughSeq); await commit(pending.length ? pending[0].seq - 1 : seqCounter); touch(); } - // Her rooms' recent talk, for a reader that was not woken for it: in each room she may speak in, the newest tailPerRoom lines past - // her ack cursor there (a room she has acked nothing in yields its recent lines), the newest tailTotal over all rooms, oldest - // first. From the same /messages read as a delivery's context, as her account, bodies clipped as context lines are. The basis is - // what Matrix says on the event itself (no reply lookup: nil is unproven). A room that cannot be read is logged and absent. + // Her rooms' recent talk, for a reader that was not woken for it: in each room she may speak in, the newest tailPerRoom lines + // whether or not they were delivered or acked (a delivery the wake rule left unaddressed is acked and gone from `pending`; the tail + // is where a beat still finds it, and the reader removes what a delivery already shows), the newest tailTotal over all rooms, + // oldest first. From the same /messages read as a delivery's context, as her account, bodies clipped as context lines are. The + // basis is what Matrix says on the event itself (no reply lookup: nil is unproven). A room that cannot be read in sendTimeoutMs + // is logged and absent, so one stuck room never holds the reply. async function tail() { if (!started) return []; const targets = new Set(); @@ -495,21 +490,24 @@ export function createMouth({ const perRoom = await Promise.all([...targets].map(async roomId => { let read = tailReads.get(roomId); if (!read || now() - read.at >= TAIL_TTL_MS) { - read = { at: now(), lines: roomEvents(roomId).catch(error => { say(`tail for ${roomId} not fetched: ${error.message}`); return null; }) }; + let timer; + const lines = Promise.race([ + roomEvents(roomId), + new Promise((_, fail) => { timer = setTimeout(() => fail(new Error(`no answer in ${sendTimeoutMs} ms`)), sendTimeoutMs); }), + ]).catch(error => { say(`tail for ${roomId} not fetched: ${error.message}`); return null; }).finally(() => clearTimeout(timer)); + read = { at: now(), lines }; tailReads.set(roomId, read); } const events = await read.lines; if (events === null) { if (tailReads.get(roomId) === read) tailReads.delete(roomId); return []; } - const through = ackedThrough.get(roomId); const alias = aliasByRoomId.get(roomId) ?? roomId; const lines = []; - for (const e of events) { - const at = Number.isSafeInteger(e.origin_server_ts) && e.origin_server_ts >= 0 ? e.origin_server_ts : 0; - if (through && (at < through.ts || (at === through.ts && through.ids.has(e.event_id)))) continue; + for (const e of events.slice(-docs.limits.tailPerRoom)) { if (typeof e.event_id !== "string" || e.event_id === "") continue; + const at = Number.isSafeInteger(e.origin_server_ts) && e.origin_server_ts >= 0 ? e.origin_server_ts : 0; lines.push({ roomAlias: alias, eventId: e.event_id, atUnixMs: at, sender: e.sender, form: formOf(e.content), basis: await basisOf(roomId, e, false), text: bodyText(e.content, docs.limits.contextBytes) }); } - return lines.slice(-docs.limits.tailPerRoom); + return lines; })); return perRoom.flat().sort((a, b) => a.atUnixMs - b.atUnixMs).slice(-docs.limits.tailTotal); } From e8722d0abf3c24aa9a1787e3cc88b77f3aaa3aad Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 08:15:38 +0000 Subject: [PATCH 007/113] Mouth: room tail on chat_pending.v3 (#51) --- docs/bridge.md | 19 ++- ...mecult.persona.chat_pending.v3.tag.msgpack | Bin 197 -> 198 bytes ...ecult.persona.chat_pending.v3.tail.msgpack | Bin 0 -> 163 bytes ...na.chat_pending.v3.unproven-notice.msgpack | Bin 153 -> 154 bytes tests/persona-matrix-mouth-runtime.test.mjs | 26 +++- tests/persona-matrix-mouth.test.mjs | 117 ++++++++++++++++++ tools/persona-chat-documents.mjs | 23 +++- tools/persona-matrix-mouth.mjs | 68 ++++++++-- 8 files changed, 236 insertions(+), 17 deletions(-) create mode 100644 tests/fixtures/persona-chat-v5/gamecult.persona.chat_pending.v3.tail.msgpack diff --git a/docs/bridge.md b/docs/bridge.md index 4468988..b9b35a6 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -216,10 +216,25 @@ Proposed runtime half (follow-up `persona-wakes-on-address-only`): 1. Poll with `chat_pending_request.v2` and parse `chat_pending.v3`. 2. A delivery is *addressed* to a Persona when `form == "message"` and either `basis` is `direct`, `tag` or `reply`, or `address::addresses` matches her names or her projects' names on the text. The off-beat wake keeps the sender gate of `heartbeat.rs` `wakes` (the operator or another Mind of the roster): a stranger's tag, `@room` or DM is delivered but wakes no one off the beat. `basis == "room"` is the runtime's policy to weigh; the mouth only reports it. 3. A real-time wake, a live session's tell and the stagger apply to addressed deliveries only. A `notice` or an `edit` never wakes, whatever its basis. -4. A delivery that is not addressed is acked in sequence with the rest, so the position moves (the mouth stops reading at 500 unacked deliveries); it is not lost: Matrix is the record, and the next addressed delivery's `context` (up to 20 lines) and a beat's own room read show it. Reading the tail on a scheduled beat is a runtime read of Matrix, a follow-up of the ruling `wake-reads-room-tail`; the mouth adds no endpoint for it. +4. A delivery that is not addressed is acked in sequence with the rest, so the position moves (the mouth stops reading at 500 unacked deliveries); it is not lost: Matrix is the record, and the next addressed delivery's `context` (up to 20 lines) and a beat's own room read show it. The room tail below gives a scheduled beat those lines without a Matrix read of its own; the mouth adds no endpoint for it. 5. `basis` and `form` are evidence, not authority: a sender's claim is weighed by the runtime's own rule (`address.rs` for names, the sender gate for who may wake her); the mouth reports what the event says and what only Matrix could look up (the author of a reply target). -Golden bytes: `tests/fixtures/persona-chat-v5/`; Huginn pins the same bytes. +### Room tail (`chat_pending.v3`, field 2) + +The v3 answer is `[persona, deliveries, tail]`. `tail` is a list of recent room lines, oldest first, for a reader that was not woken for them (a scheduled beat). It uses the same room read as a delivery's `context` (the same function, a separate read), as her account, with no new endpoint; the cost is one `/messages` call per speakable room per poll (15 seconds cached), including every DM. A `chat_pending_request.v1` is still answered with the two-field `chat_pending.v2`. `chat_pending.v3` has not been deployed, but a reader that decodes it as a two-field tuple fails on the third element (rmp-serde `LengthMismatch`), so Huginn must accept `tail` (a defaulted field) before this mouth is deployed. + +| Bound | Rule | +|---|---| +| Rooms | Only rooms the Persona may speak in: a configured room she has joined, or one of her DMs. The same rule `send` uses (`speakableRoomId`). A room she is in but cannot speak in, and any other room, is absent. | +| Lines | A text line outside threads, not an edit, newest `20` per room, newest `60` over all rooms. Trimmed oldest first if the reply byte budget (256 KiB, deliveries first) would be exceeded. | +| Cursor | None. The tail is each room's newest lines whether or not they were delivered or acked: a message the wake rule left unaddressed is acked and leaves `pending`, and the tail is where a beat still finds it. A reader removes the lines a delivery already shows (by event id). Her own lines are included. | +| Read | A room's read is kept 15 seconds, dropped when a sync brings the room news. A room that cannot be read within 10 seconds is logged and absent; the other rooms and the deliveries are unaffected. | + +A line is the 7-field tuple `[room, event_id, at_unix_ms, sender, form, basis, body]`: `room` is the configured alias (the room id for a DM), `form` and `basis` as for a delivery, `body` clipped to 1000 bytes with the same typed text line for media a delivery has (nothing is fetched). `basis` is what Matrix says on the event itself (`direct` in a DM, `tag`, `room`) and nothing the mouth would have to look up, so a reply is nil here: **nil is unproven, not "not for her"**, and a line in a DM is `direct`. Huginn's rule that an `is_direct` delivery wakes with a nil `basis` is unchanged and lives with Huginn; the tail does not feed it. + +The tail is **data, not instruction**. A line is what a sender typed in a room, and the mouth wakes no one, acks nothing and sends nothing because of it. A reader treats the body as untrusted text and weighs `basis` as evidence, as for a delivery. The tail does not replace a delivery: a message still reaches her as a delivery, with its own `seq`, and only `chat_ack` advances a position. + +Golden bytes: `tests/fixtures/persona-chat-v5/` (`chat_pending.v3.tail` carries two lines); Huginn pins the same bytes. Bifrost admits an observation only when guild, channel, target runtime, canonical repository, Persona, producer, and producer runtime match a preconfigured `bifrost.persona_feedback.target_binding.v0` document in Bifrost's private provider store. That binding also owns source visibility, data classification, and the delivery-store target. Bifrost never infers public visibility from Discord identifiers. It classifies the author using its own `bifrost.discord.actor_link.v0` state: a match yields `linked_governance_feedback`; absence yields `unlinked_social_feedback`. Neither class grants adoption, work, release, or deployment authority. diff --git a/tests/fixtures/persona-chat-v5/gamecult.persona.chat_pending.v3.tag.msgpack b/tests/fixtures/persona-chat-v5/gamecult.persona.chat_pending.v3.tag.msgpack index 006f6cf6f6bbd6d289589bb4ebd1ec33d3ef4b36..6685251d258d7deb362a087216fa725da643e82c 100644 GIT binary patch delta 11 ScmX@gc#M&8@ { test("two clients served at once each get their own answer on their own session", async () => { const mouth = { pendingAfter: () => [], + tail: async () => [], ack: async () => {}, // Slow enough that the two requests are in flight together. send: async request => { await new Promise(r => setTimeout(r, 150)); return { requestId: request.requestId, eventId: `$${request.requestId}`, refusal: null }; }, @@ -138,6 +140,7 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a const calls = { acks: [], sends: [], reads: [] }; const mouth = { pendingAfter: after => (after < 7 ? [delivery] : []), + tail: async () => { if (calls.tailFails) throw new Error("room read failed"); return [tailLine]; }, ack: async through => { calls.acks.push(through); }, read: async request => { calls.reads.push(request); return null; }, send: async request => { calls.sends.push(request); return request.text === "muted" ? { requestId: request.requestId, eventId: null, refusal: "Brake" } : { requestId: request.requestId, eventId: "$sent", refusal: null }; }, @@ -177,7 +180,18 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a put(docs.kinds.pendingRequestV3, "eureka", docs.pendingRequestTuple({ persona: "eureka", afterSeq: 0 })); document = await reply; assert.equal(document.schemaId, docs.kinds.pendingV3, "the kind asked by names the answer"); - assert.deepEqual(docs.parsePendingV3(msgpack.decode(document.payload)).deliveries[0], { ...delivery, basis: null, form: "message" }); + const v3 = docs.parsePendingV3(msgpack.decode(document.payload)); + assert.deepEqual(v3.deliveries[0], { ...delivery, basis: null, form: "message" }); + assert.deepEqual(v3.tail, [tailLine], "the v3 answer carries the room tail"); + + calls.tailFails = true; + reply = nextReply(); + put(docs.kinds.pendingRequestV3, "eureka", docs.pendingRequestTuple({ persona: "eureka", afterSeq: 0 })); + document = await reply; + const degraded = docs.parsePendingV3(msgpack.decode(document.payload)); + assert.equal(degraded.deliveries.length, 1, "a tail that throws does not silence the deliveries"); + assert.deepEqual(degraded.tail, []); + calls.tailFails = false; put(docs.kinds.ack, "eureka:7", docs.ackTuple({ persona: "eureka", throughSeq: 7 })); reply = nextReply(); @@ -322,6 +336,10 @@ const v5Dir = resolve(root, "tests", "fixtures", "persona-chat-v5"); const v5Samples = { "gamecult.persona.chat_pending_request.v2": { tuple: docs.pendingRequestTuple({ persona: "eureka", afterSeq: 3 }), parse: docs.parsePendingRequest }, "gamecult.persona.chat_pending.v3.tag": { tuple: docs.pendingV3Tuple({ persona: "eureka", deliveries: [{ ...delivery, isDirect: false, basis: "tag", form: "message" }] }), parse: docs.parsePendingV3 }, + "gamecult.persona.chat_pending.v3.tail": { tuple: docs.pendingV3Tuple({ persona: "eureka", deliveries: [], tail: [ + { roomAlias: "#operator:gamecult.org", eventId: "$e0", atUnixMs: 1_700_000_000_000, sender: "@meta:gamecult.org", form: "message", basis: null, text: "earlier" }, + { roomAlias: "#operator:gamecult.org", eventId: "$e1", atUnixMs: 1_700_000_001_000, sender: "@meta:gamecult.org", form: "notice", basis: "tag", text: "hello eureka" }, + ] }), parse: docs.parsePendingV3 }, "gamecult.persona.chat_pending.v3.unproven-notice": { tuple: docs.pendingV3Tuple({ persona: "eureka", deliveries: [{ ...delivery, isDirect: false, mentions: [], basis: null, form: "notice" }] }), parse: docs.parsePendingV3 }, }; for (const [name, { tuple, parse }] of Object.entries(v5Samples)) { @@ -331,7 +349,9 @@ for (const [name, { tuple, parse }] of Object.entries(v5Samples)) { if (process.env.UPDATE_FIXTURES === "1") { await mkdir(v5Dir, { recursive: true }); await writeFile(file, bytes); } assert.deepEqual(bytes, await readFile(file), "wire bytes changed: Huginn decodes these fixtures"); assert.deepEqual(parse(msgpack.decode(bytes)), parse(tuple)); - if (name.includes("pending.v3")) assert.equal(msgpack.decode(bytes)[1][0].length, 14); + if (name.includes("pending.v3")) assert.equal(msgpack.decode(bytes).length, 3, "persona, deliveries, tail"); + if (name.endsWith("v3.tag") || name.endsWith("unproven-notice")) assert.equal(msgpack.decode(bytes)[1][0].length, 14); + if (name.endsWith("v3.tail")) assert.equal(msgpack.decode(bytes)[2][0].length, 7); }); } @@ -370,7 +390,7 @@ test("RoomMoved is v2 only, and the v2 documents are strict about arity and newe test("the RUDP endpoint answers a v1 send with the three-field receipt and a v2 send with the four-field one", async () => { const seen = []; - const mouth = { pendingAfter: () => [], ack: async () => {}, send: async request => { + const mouth = { pendingAfter: () => [], tail: async () => [], ack: async () => {}, send: async request => { seen.push(request); return request.basis ? { requestId: request.requestId, eventId: null, refusal: "RoomMoved", newer: ["$a"] } : { requestId: request.requestId, eventId: "$sent", refusal: null, newer: [] }; } }; diff --git a/tests/persona-matrix-mouth.test.mjs b/tests/persona-matrix-mouth.test.mjs index 9458370..e4c7731 100644 --- a/tests/persona-matrix-mouth.test.mjs +++ b/tests/persona-matrix-mouth.test.mjs @@ -1475,3 +1475,120 @@ test("addressing facts: a target that failed is not refetched within a minute, a assert.equal(fetched(), 2, "past the minute: read again"); } finally { await hs.close(); } }); + +// The room tail (docs/bridge.md, "Room tail"): her rooms' recent talk past her ack cursor, bounded, as data on the v3 answer. +const OPERATOR = "!operator:gamecult.test"; +const lines = (room, n, from = 0, sender = META) => Array.from({ length: n }, (_, i) => message(`$${room.slice(1, 4)}${from + i}`, sender, `line ${from + i}`, 10 + from + i)); +async function tailed({ preload, direct, member, events = [], act = async () => {} } = {}) { + const hs = await fakeHomeserver({ preload, direct, member, sync: since => since === null ? { next_batch: "b0" } : { next_batch: "b1", ...joined(events.length ? { [ROOM]: { timeline: { events } } } : {}) } }); + try { + const mouth = mouthFor(hs); + await mouth.syncOnce(); + await act(mouth); + return { tail: await mouth.tail(), mouth, hs }; + } finally { await hs.close(); } +} + +test("room tail: 600 lines in a room keep the newest 20, oldest first", async () => { + const { tail } = await tailed({ preload: { [ROOM]: lines(ROOM, 600) } }); + assert.equal(tail.length, 20); + assert.deepEqual(tail.map(l => l.text), Array.from({ length: 20 }, (_, i) => `line ${580 + i}`)); + assert.deepEqual(Object.keys(tail[0]).sort(), ["atUnixMs", "basis", "eventId", "form", "roomAlias", "sender", "text"]); + assert.equal(tail[0].roomAlias, `#swarm:${HS_NAME}`); + assert.equal(tail[0].sender, META); + assert.equal(tail[0].form, "message"); + assert.equal(tail[0].basis, null, "unproven, not 'not for her'"); +}); + +test("room tail: a quiet room, with nothing delivered, still returns its recent lines", async () => { + const { tail } = await tailed({ preload: { [OPERATOR]: lines(OPERATOR, 3) } }); + assert.deepEqual(tail.map(l => l.text), ["line 0", "line 1", "line 2"]); + assert.ok(tail.every(l => l.roomAlias === `#operator:${HS_NAME}`)); +}); + +test("room tail: a room she is not in the speaking set of is absent, and a DM she holds is present with basis direct", async () => { + const STRANGER = "!stranger:gamecult.test", DM = "!mydm:gamecult.test"; + const { tail } = await tailed({ + preload: { [STRANGER]: lines(STRANGER, 2), [DM]: lines(DM, 2), [ROOM]: lines(ROOM, 1) }, + member: [...Object.values(ROOMS), STRANGER, DM], + direct: { [META]: [DM] }, + }); + assert.deepEqual([...new Set(tail.map(l => l.roomAlias))].sort(), [DM, `#swarm:${HS_NAME}`]); + assert.ok(tail.filter(l => l.roomAlias === DM).every(l => l.basis === "direct")); + assert.ok(!tail.some(l => l.eventId.startsWith("$str"))); +}); + +test("room tail: about 60 lines over all rooms, the newest, whatever the room count", async () => { + const dms = ["!d1:gamecult.test", "!d2:gamecult.test", "!d3:gamecult.test", "!d4:gamecult.test"]; + const preload = { [ROOM]: lines(ROOM, 30, 0), [OPERATOR]: lines(OPERATOR, 30, 30) }; + dms.forEach((dm, i) => { preload[dm] = lines(dm, 30, 60 + 30 * i); }); + const { tail } = await tailed({ preload, direct: { [META]: dms }, member: [...Object.values(ROOMS), ...dms] }); + assert.equal(tail.length, 60); + assert.deepEqual(tail.map(l => l.atUnixMs), tail.map(l => l.atUnixMs).sort((a, b) => a - b), "oldest first"); + assert.equal(Math.min(...tail.map(l => l.atUnixMs)), 110, "the oldest kept is the 60th newest of the 120 offered"); +}); + +test("room tail: acking a delivery does not hide it, so an unaddressed line she has acked is still found, and mention basis rides on the line", async () => { + const events = [ + withContent("$a", META, { body: "first" }, 3000), + withContent("$b", META, { body: "tag", "m.mentions": { user_ids: [SELF] } }, 3001), + ]; + const hs = await fakeHomeserver({ sync: since => since === null ? { next_batch: "b0" } : { next_batch: "b1", ...joined({ [ROOM]: { timeline: { events } } }) } }); + try { + const mouth = mouthFor(hs); + await mouth.syncOnce(); + const made = await mouth.syncOnce(); + assert.deepEqual((await mouth.tail()).map(l => [l.eventId, l.basis]), [["$a", null], ["$b", "tag"]]); + await mouth.ack(made[1].seq); + assert.equal(mouth.pendingAfter(0).length, 0); + assert.deepEqual((await mouth.tail()).map(l => l.eventId), ["$a", "$b"], "acked lines are the ones no delivery will bring again"); + } finally { await hs.close(); } +}); + +test("room tail: a room that never answers is absent after the timeout and does not hold the others", async () => { + const hs = await fakeHomeserver({ preload: { [OPERATOR]: lines(OPERATOR, 2) }, sync: since => ({ next_batch: since ?? "b0" }) }); + const hang = (url, init) => String(url).includes(encodeURIComponent(ROOM)) && String(url).includes("/messages") ? new Promise(() => {}) : hs.fetch(url, init); + try { + const mouth = mouthFor(hs, { fetch: hang, sendTimeoutMs: 50 }); + await mouth.syncOnce(); + const tail = await mouth.tail(); + assert.deepEqual([...new Set(tail.map(l => l.roomAlias))], [`#operator:${HS_NAME}`]); + } finally { await hs.close(); } +}); + +test("room tail: a mouth that has not started reads no room", async () => { + const hs = await fakeHomeserver({ preload: { [ROOM]: lines(ROOM, 2) }, sync: since => ({ next_batch: since ?? "b0" }) }); + try { + assert.deepEqual(await mouthFor(hs).tail(), []); + assert.equal(hs.seen.filter(r => r.path.includes("/messages")).length, 0); + } finally { await hs.close(); } +}); + +test("room tail: a body is clipped like a context line, and an unreadable room is absent without silencing the others", async () => { + const { tail } = await tailed({ preload: { [ROOM]: [message("$big", META, "x".repeat(5000), 10)] } }); + assert.equal(Buffer.byteLength(tail[0].text), docs.limits.contextBytes); + const hs = await fakeHomeserver({ failContext: true, sync: since => ({ next_batch: since ?? "b0" }) }); + try { + const mouth = mouthFor(hs); + await mouth.syncOnce(); + assert.deepEqual(await mouth.tail(), []); + } finally { await hs.close(); } +}); + +test("room tail: only the v3 answer carries it; the v2 answer a v1 request gets is unchanged", async () => { + const { tail } = await tailed({ preload: { [ROOM]: lines(ROOM, 2) } }); + const pack = { encode: v => Buffer.from(JSON.stringify(v)) }; + assert.deepEqual(docs.parsePendingV3(pageOf("eureka", [], pack, () => {}, true, tail)).tail.map(l => l.text), ["line 0", "line 1"]); + const v2 = pageOf("eureka", [], pack, () => {}, false, tail); + assert.equal(v2.length, 2); + assert.deepEqual(docs.parsePending(v2), { persona: "eureka", deliveries: [] }); + assert.throws(() => docs.parsePendingV3(["eureka", []]), /3-field/); +}); + +test("room tail: the reply byte budget trims the oldest tail lines, never a delivery", async () => { + const pack = { encode: v => Buffer.from(JSON.stringify(v)) }; + const big = Array.from({ length: 60 }, (_, i) => ({ roomAlias: "#r:x", eventId: `$${i}`, atUnixMs: i, sender: "@a:x", form: "message", basis: null, text: "y".repeat(5000) })); + const kept = docs.parsePendingV3(pageOf("eureka", [], pack, () => {}, true, big)).tail; + assert.ok(kept.length > 0 && kept.length < 60); + assert.equal(kept.at(-1).eventId, "$59", "the newest survive"); +}); diff --git a/tools/persona-chat-documents.mjs b/tools/persona-chat-documents.mjs index 4867901..e47b7c8 100644 --- a/tools/persona-chat-documents.mjs +++ b/tools/persona-chat-documents.mjs @@ -39,7 +39,7 @@ const maxContext = 20; // Per-delivery bounds, applied where the mouth reads Matrix: the body is bounded like a send, // a context line and a display name are smaller, and a reply is paged to a byte budget. -export const limits = Object.freeze({ textBytes: maxTextBytes, contextBytes: 1000, displayBytes: 256, mentions: 64, replyBytes: 256 * 1024 }); +export const limits = Object.freeze({ textBytes: maxTextBytes, contextBytes: 1000, displayBytes: 256, mentions: 64, replyBytes: 256 * 1024, tailPerRoom: 20, tailTotal: 60 }); // `value` cut to at most `maxBytes` of UTF-8 without splitting a character. export function clip(value, maxBytes) { @@ -237,13 +237,26 @@ export function parsePending(t) { return { persona: text(persona, "persona"), deliveries: deliveries.map(parseDelivery) }; } -export function pendingV3Tuple({ persona, deliveries }) { - return [text(persona, "persona"), deliveries.map(deliveryV3Tuple)]; +// One line of a room's recent talk, newest-unacked: room alias (or room id for a DM), event id, origin time, sender, form, basis, body. +// Data for the reader, never an instruction: no delivery, no wake, no ack position hangs on it. +export function tailLineTuple(l) { + return [text(l.roomAlias, "room"), text(l.eventId, "event_id"), seq(l.atUnixMs, "at_unix_ms"), text(l.sender, "sender"), form(l.form), basis(l.basis ?? null), String(l.text)]; +} +function parseTailLine(t) { + const [roomAlias, eventId, atUnixMs, sender, f, b, body] = tuple(t, 7, "tail_line"); + return { roomAlias: text(roomAlias, "room"), eventId: text(eventId, "event_id"), atUnixMs: seq(atUnixMs, "at_unix_ms"), sender: text(sender, "sender"), form: form(f), basis: basis(b), text: String(body) }; +} + +// The v3 answer: the persona, the deliveries, then the tail (at most tailPerRoom lines a room, tailTotal in all, oldest first). +export function pendingV3Tuple({ persona, deliveries, tail = [] }) { + if (tail.length > limits.tailTotal) throw new Error("chat_pending tail is over the line bound"); + return [text(persona, "persona"), deliveries.map(deliveryV3Tuple), tail.map(tailLineTuple)]; } export function parsePendingV3(t) { - const [persona, deliveries] = tuple(t, 2, "chat_pending_v3"); + const [persona, deliveries, tail] = tuple(t, 3, "chat_pending_v3"); if (!Array.isArray(deliveries)) throw new Error("chat_pending deliveries must be a list"); - return { persona: text(persona, "persona"), deliveries: deliveries.map(parseDeliveryV3) }; + if (!Array.isArray(tail)) throw new Error("chat_pending tail must be a list"); + return { persona: text(persona, "persona"), deliveries: deliveries.map(parseDeliveryV3), tail: tail.map(parseTailLine) }; } // The CultNet document_put_raw envelope every chat_* document travels in. diff --git a/tools/persona-matrix-mouth.mjs b/tools/persona-matrix-mouth.mjs index 439816e..d6b4f94 100644 --- a/tools/persona-matrix-mouth.mjs +++ b/tools/persona-matrix-mouth.mjs @@ -63,6 +63,7 @@ const DELIVERED_INDEX = 4000; // delivered event ids remembered so a read report const DM_SCAN = 200; // joined rooms read when looking for an existing DM with a person const NOT_E2EE = "This room is not end-to-end encrypted: the homeserver can read what is said here."; const dayOf = ms => new Date(ms).toISOString().slice(0, 10); +const TAIL_TTL_MS = 15 * 1000; const HEAD_PAGE = 50; // the room head a gated send reads; also the most ids a RoomMoved receipt names // The kind of an event for a delivery: an edit (m.replace) and an automated notice (m.notice) are not messages anyone is addressed by. @@ -141,6 +142,7 @@ export function createMouth({ let started = false; let lastPresence = null; // 'online' | 'unavailable' | 'offline' | null: command-only, suppresses repeat presence PUTs let activeUntil = 0; // her last sign of life in a turn, plus the grace + const tailReads = new Map(); // room id -> { at, lines }: a room's tail read, kept TAIL_TTL_MS or until a sync brings the room news const delivered = new Map(); // event id -> { roomId, roomAlias, seq }: what the mouth handed her, newest last, bounded const readThrough = new Map(); // room id -> { seq, eventId } of the last receipt that landed const readTails = new Map(); // room id -> the read report in flight: reports for one room run one at a time @@ -209,6 +211,8 @@ export function createMouth({ } } const unjoined = () => joinedAliases.size < rooms.length; + // The rooms this Persona may speak in: a configured room she has joined, or one of her DMs. One rule for send and for the tail. + const speakableRoomId = alias => joinedAliases.has(alias) ? roomIdByAlias.get(alias) : directRooms.has(alias) ? alias : null; // Join the configured rooms the account is not in, only while the brake is released. // One room failing is logged and retried on the next round; it never stops the others. @@ -294,11 +298,11 @@ export function createMouth({ // thread under, an event her account wrote, so her Self run's words count as hers), "room" (an @room mention). In that order; null // when none holds. Her names, her projects' names and the sender's role are the heartbeat's to match (Huginn address.rs), never the // mouth's. A reply target that cannot be read is null and logged: unknown, not "not hers". - async function basisOf(roomId, event) { + async function basisOf(roomId, event, lookup = true) { if (directRooms.has(roomId)) return "direct"; const mentions = event.content["m.mentions"]; if (Array.isArray(mentions?.user_ids) ? mentions.user_ids.includes(selfId) : mentions === undefined && pillFor(event.content.formatted_body)) return "tag"; - if (formOf(event.content) === "message" && await repliesToMe(roomId, event.content["m.relates_to"])) return "reply"; // an edit or a notice wakes no one: no fetch for it + if (lookup && formOf(event.content) === "message" && await repliesToMe(roomId, event.content["m.relates_to"])) return "reply"; // an edit or a notice wakes no one: no fetch for it return mentions?.room === true ? "room" : null; } // A pill is an anchor whose href is exactly her matrix.to link; a longer id, an attribute that merely contains one and a quoted reply do not count. @@ -379,6 +383,7 @@ export function createMouth({ const shown = event.content?.displayname; if (event.type === "m.room.member" && typeof event.state_key === "string" && typeof shown === "string" && shown !== "") displayNames.set(event.state_key, docs.clip(shown, docs.limits.displayBytes)); } + if ((room.timeline?.events ?? []).length > 0) tailReads.delete(roomId); for (const event of room.timeline?.events ?? []) { if (event.type !== "m.room.message" || typeof event.content?.body !== "string") continue; if (typeof event.sender !== "string" || event.sender === "" || typeof event.event_id !== "string" || event.event_id === "") continue; @@ -472,6 +477,41 @@ export function createMouth({ touch(); } + // Her rooms' recent talk, for a reader that was not woken for it: in each room she may speak in, the newest tailPerRoom lines + // whether or not they were delivered or acked (a delivery the wake rule left unaddressed is acked and gone from `pending`; the tail + // is where a beat still finds it, and the reader removes what a delivery already shows), the newest tailTotal over all rooms, + // oldest first. From the same /messages read as a delivery's context, as her account, bodies clipped as context lines are. The + // basis is what Matrix says on the event itself (no reply lookup: nil is unproven). A room that cannot be read in sendTimeoutMs + // is logged and absent, so one stuck room never holds the reply. + async function tail() { + if (!started) return []; + const targets = new Set(); + for (const alias of [...joinedAliases, ...directRooms]) { const id = speakableRoomId(alias); if (id) targets.add(id); } + const perRoom = await Promise.all([...targets].map(async roomId => { + let read = tailReads.get(roomId); + if (!read || now() - read.at >= TAIL_TTL_MS) { + let timer; + const lines = Promise.race([ + roomEvents(roomId), + new Promise((_, fail) => { timer = setTimeout(() => fail(new Error(`no answer in ${sendTimeoutMs} ms`)), sendTimeoutMs); }), + ]).catch(error => { say(`tail for ${roomId} not fetched: ${error.message}`); return null; }).finally(() => clearTimeout(timer)); + read = { at: now(), lines }; + tailReads.set(roomId, read); + } + const events = await read.lines; + if (events === null) { if (tailReads.get(roomId) === read) tailReads.delete(roomId); return []; } + const alias = aliasByRoomId.get(roomId) ?? roomId; + const lines = []; + for (const e of events.slice(-docs.limits.tailPerRoom)) { + if (typeof e.event_id !== "string" || e.event_id === "") continue; + const at = Number.isSafeInteger(e.origin_server_ts) && e.origin_server_ts >= 0 ? e.origin_server_ts : 0; + lines.push({ roomAlias: alias, eventId: e.event_id, atUnixMs: at, sender: e.sender, form: formOf(e.content), basis: await basisOf(roomId, e, false), text: bodyText(e.content, docs.limits.contextBytes) }); + } + return lines; + })); + return perRoom.flat().sort((a, b) => a.atUnixMs - b.atUnixMs).slice(-docs.limits.tailTotal); + } + function pendingAfter(afterSeq) { return pending.filter(d => d.seq > afterSeq).map(d => ({ ...d, context: d.context.map(c => ({ ...c })), mentions: [...d.mentions], image: d.image && { ...d.image } })); } @@ -497,7 +537,7 @@ export function createMouth({ if (typeof text !== "string" || text.trim() === "") return refuse("EmptyText"); try { if (!started || unjoined()) await start(); - const roomId = joinedAliases.has(roomAlias) ? roomIdByAlias.get(roomAlias) : directRooms.has(roomAlias) ? roomAlias : null; + const roomId = speakableRoomId(roomAlias); if (!roomId) return refuse("UnknownRoom"); const result = await gate.run(roomId, async () => { if (basis) { @@ -626,7 +666,7 @@ export function createMouth({ } } - return { start, syncOnce, ack, read, pendingAfter, send, openDirect, run, get userId() { return selfId; }, get pendingCount() { return pending.length; } }; + return { start, syncOnce, ack, read, pendingAfter, tail, send, openDirect, run, get userId() { return selfId; }, get pendingCount() { return pending.length; } }; } // Replace every secret in a message. `secrets` is one string or a list. @@ -671,7 +711,8 @@ export function connectionIdFor(connectionKey) { // The reply to a chat_pending_request: deliveries oldest first, each encoded on its own so one that // will not encode is skipped and logged without silencing the rest, up to the reply byte budget. // The caller acks what it has read and asks again. -export function pageOf(persona, deliveries, msgpack, log = () => {}, v3 = false) { +// A v3 reply also carries `tail` (room lines, oldest first), trimmed oldest first to what the byte budget has left after the deliveries. +export function pageOf(persona, deliveries, msgpack, log = () => {}, v3 = false, tail = []) { const page = []; let bytes = 0; for (const delivery of deliveries) { @@ -684,7 +725,19 @@ export function pageOf(persona, deliveries, msgpack, log = () => {}, v3 = false) page.push(tuple); bytes += size; } - return [persona, page]; + if (!v3) return [persona, page]; + const lines = []; + for (const line of tail.slice().reverse()) { + let tuple, size; + try { tuple = docs.tailLineTuple(line); size = msgpack.encode(tuple).length; } catch (error) { + log(`tail line ${line?.eventId} skipped: ${error?.message ?? error}`); + continue; + } + if (bytes + size > docs.limits.replyBytes) break; + lines.unshift(tuple); + bytes += size; + } + return [persona, page, lines]; } // CultNet RUDP endpoint on loopback, one for every Persona in `mouths` (persona -> mouth). @@ -726,7 +779,8 @@ export async function startChatEndpoint({ mouths, runtime, port, connectionKey, const request = docs.parsePendingRequest(tuple); const mouth = mouths.get(request.persona); if (!mouth) return refuseUnknown(peer, request.persona); - respond(peer, request.persona, v3 ? docs.kinds.pendingV3 : docs.kinds.pending, request.persona, pageOf(request.persona, mouth.pendingAfter(request.afterSeq), msgpack, log, v3)); + const tail = v3 ? await mouth.tail().catch(error => { log(`tail not read: ${error?.message ?? error}`); return []; }) : []; + respond(peer, request.persona, v3 ? docs.kinds.pendingV3 : docs.kinds.pending, request.persona, pageOf(request.persona, mouth.pendingAfter(request.afterSeq), msgpack, log, v3, tail)); } else if (document.schemaId === docs.kinds.ack) { const request = docs.parseAck(tuple); const mouth = mouths.get(request.persona); From fc8242f655af50c4c637ef36660989e5ae78c999 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 08:38:09 +0000 Subject: [PATCH 008/113] Suspension survives sign-in; admin-only Suspend/Unsuspend with a receipt (#53) --- src/Bifrost.Web/Domain/BifrostModels.cs | 3 +- .../Features/Heimdall/HeimdallAuthService.cs | 5 +- .../Membership/MembershipSuspensionService.cs | 79 ++++++++ .../Shared/DashboardSnapshotService.cs | 1 + .../Pages/App/Members/Index.cshtml | 11 +- .../Pages/App/Members/Index.cshtml.cs | 24 ++- src/Bifrost.Web/Program.cs | 1 + .../HeimdallCompletionTests.cs | 39 ++++ .../MembershipSuspensionTests.cs | 179 ++++++++++++++++++ 9 files changed, 337 insertions(+), 5 deletions(-) create mode 100644 src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs create mode 100644 tests/Bifrost.Web.Tests/MembershipSuspensionTests.cs diff --git a/src/Bifrost.Web/Domain/BifrostModels.cs b/src/Bifrost.Web/Domain/BifrostModels.cs index 2f8be41..3cc0506 100644 --- a/src/Bifrost.Web/Domain/BifrostModels.cs +++ b/src/Bifrost.Web/Domain/BifrostModels.cs @@ -363,7 +363,8 @@ public sealed class Membership public sealed class RoleAssignment { - public Guid Id { get; set; } = Guid.NewGuid(); + // Left empty until saved: a key preset on a row added to an already-saved membership makes EF treat it as existing and fail the save. + public Guid Id { get; set; } public Guid MembershipId { get; set; } diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs index 0d39c2f..8d10b53 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs @@ -319,7 +319,8 @@ public sealed class HeimdallAuthService( UserAccountId = userAccount.Id, CreatedAtUtc = now }; - if (grantMemberAccess) + // A suspension is an admin's decision: the claim neither lifts it nor, absent, imposes it. + if (grantMemberAccess && userAccount.Membership.Status != MembershipStatus.Suspended) { userAccount.Membership.Status = MembershipStatus.Active; userAccount.Membership.ApprovedAtUtc ??= now; @@ -332,7 +333,7 @@ public sealed class HeimdallAuthService( userAccount, displayName, cancellationToken); - if (grantMemberAccess) + if (grantMemberAccess && userAccount.Membership!.Status == MembershipStatus.Active) { ApplicationBootstrapper.EnsureRole( userAccount.Membership!, diff --git a/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs b/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs new file mode 100644 index 0000000..cb5626c --- /dev/null +++ b/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs @@ -0,0 +1,79 @@ +using Bifrost.Web.Data; +using Bifrost.Web.Domain; +using Bifrost.Web.Features.Shared; +using Microsoft.EntityFrameworkCore; + +namespace Bifrost.Web.Features.Membership; + +public enum SuspensionOutcome +{ + Done, + NotAdmin, + NoReason, + NoSuchAccount, + NotApplicable, + ProtectedAccount +} + +/// +/// The one place a membership becomes Suspended or stops being. Only a platform admin may call it, every use leaves an audit +/// receipt naming the admin, the account and the reason, and no sign-in path writes or lifts a suspension (Heimdall and GitHub +/// sign-in leave a Suspended membership as it is). Unsuspending restores Active for an account that was once approved, +/// Authenticated for one that never was; a pending request is not remembered. +/// +public sealed class MembershipSuspensionService(BifrostDbContext dbContext, AuditTrailService auditTrailService) +{ + public const int MaxReasonLength = 500; + + public Task SuspendAsync(CurrentBifrostActor actor, Guid userAccountId, string? reason, CancellationToken cancellationToken) => + ChangeAsync(actor, userAccountId, reason, suspend: true, cancellationToken); + + public Task UnsuspendAsync(CurrentBifrostActor actor, Guid userAccountId, string? reason, CancellationToken cancellationToken) => + ChangeAsync(actor, userAccountId, reason, suspend: false, cancellationToken); + + private async Task ChangeAsync(CurrentBifrostActor actor, Guid userAccountId, string? reason, bool suspend, CancellationToken cancellationToken) + { + if (!actor.CanManageMembership || actor.UserAccount is null) + { + return SuspensionOutcome.NotAdmin; + } + + if (string.IsNullOrWhiteSpace(reason)) + { + return SuspensionOutcome.NoReason; + } + + var user = await dbContext.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments).SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken); + if (user?.Membership is not { } membership) + { + return SuspensionOutcome.NoSuchAccount; + } + + // An admin cannot suspend themselves or another platform admin here (the same derivation that makes an actor an admin): + // bootstrap admins are re-promoted to Active at sign-in by configuration, so the suspension would be undone without a receipt. + if (suspend && (user.Id == actor.UserAccount.Id || new CurrentBifrostActor(true, user).IsPlatformAdmin)) + { + return SuspensionOutcome.ProtectedAccount; + } + + if (suspend == (membership.Status == MembershipStatus.Suspended)) + { + return SuspensionOutcome.NotApplicable; + } + + var before = membership.Status; + membership.Status = suspend + ? MembershipStatus.Suspended + : membership.ApprovedAtUtc is null ? MembershipStatus.Authenticated : MembershipStatus.Active; + var clipped = reason.Trim().Length > MaxReasonLength ? reason.Trim()[..MaxReasonLength] : reason.Trim(); + // One save: the status change and its receipt stand or fall together (RecordAsync saves the shared context). + await auditTrailService.RecordAsync( + actor.UserAccount.Id, + nameof(Membership), + membership.Id, + suspend ? "membership.suspended" : "membership.unsuspended", + $"{(suspend ? "Suspended" : "Unsuspended")} {user.DisplayName} ({before} -> {membership.Status}): {clipped}", + cancellationToken); + return SuspensionOutcome.Done; + } +} diff --git a/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs b/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs index 3a31269..cd0d8f2 100644 --- a/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs +++ b/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs @@ -92,6 +92,7 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro var recentActivity = await dbContext.AuditEvents .AsNoTracking() .Include(x => x.ActorUserAccount) + .Where(x => !x.Action.StartsWith("membership.suspended") && !x.Action.StartsWith("membership.unsuspended")) // a reason is for admins, not the member dashboard .OrderByDescending(x => x.OccurredAtUtc) .Take(8) .Select(x => new DashboardActivity( diff --git a/src/Bifrost.Web/Pages/App/Members/Index.cshtml b/src/Bifrost.Web/Pages/App/Members/Index.cshtml index 0d9d546..b4d67e5 100644 --- a/src/Bifrost.Web/Pages/App/Members/Index.cshtml +++ b/src/Bifrost.Web/Pages/App/Members/Index.cshtml @@ -176,7 +176,7 @@ - @if (Model.Actor.CanManageMembership && user.Status != MembershipStatus.Active) + @if (Model.Actor.CanManageMembership && user.Status != MembershipStatus.Active && user.Status != MembershipStatus.Suspended) {
@@ -184,6 +184,15 @@
} + @if (Model.Actor.CanManageMembership) + { +
+ + + +
+ } + @if (Model.Actor.CanManageMembership) {
diff --git a/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs b/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs index 2f385b7..e9b536b 100644 --- a/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs +++ b/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs @@ -1,6 +1,7 @@ using System.ComponentModel.DataAnnotations; 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; @@ -12,6 +13,7 @@ public sealed class IndexModel( BifrostDbContext dbContext, ICurrentBifrostActorAccessor actorAccessor, AuditTrailService auditTrailService, + MembershipSuspensionService suspension, TimeProvider timeProvider) : PageModel { [BindProperty] @@ -102,7 +104,12 @@ public sealed class IndexModel( .ThenInclude(x => x.RoleAssignments) .SingleAsync(x => x.Id == userAccountId, cancellationToken); - user.Membership!.Status = MembershipStatus.Active; + if (user.Membership!.Status == MembershipStatus.Suspended) + { + return RedirectToPage(); // only Unsuspend lifts a suspension + } + + user.Membership.Status = MembershipStatus.Active; user.Membership.ApprovedAtUtc = timeProvider.GetUtcNow(); ApplicationBootstrapper.EnsureRole( user.Membership, @@ -124,6 +131,21 @@ public sealed class IndexModel( return RedirectToPage(); } + public async Task OnPostSuspendAsync(Guid userAccountId, string? reason, CancellationToken cancellationToken) => + await ChangeSuspensionAsync(userAccountId, reason, suspend: true, cancellationToken); + + public async Task OnPostUnsuspendAsync(Guid userAccountId, string? reason, CancellationToken cancellationToken) => + await ChangeSuspensionAsync(userAccountId, reason, suspend: false, cancellationToken); + + private async Task ChangeSuspensionAsync(Guid userAccountId, string? reason, bool suspend, CancellationToken cancellationToken) + { + Actor = await actorAccessor.GetAsync(cancellationToken); + var outcome = suspend + ? await suspension.SuspendAsync(Actor, userAccountId, reason, cancellationToken) + : await suspension.UnsuspendAsync(Actor, userAccountId, reason, cancellationToken); + return outcome == SuspensionOutcome.NotAdmin ? Forbid() : RedirectToPage(); + } + public async Task OnPostToggleRoleAsync(Guid userAccountId, MemberRole role, CancellationToken cancellationToken) { Actor = await actorAccessor.GetAsync(cancellationToken); diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index 2a5ff5f..e19b8d0 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -117,6 +117,7 @@ builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs b/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs index 532f669..afcfcba 100644 --- a/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs +++ b/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Authentication.OAuth; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.WebUtilities; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -864,6 +865,44 @@ public sealed class HeimdallCompletionTests } } + [Fact] + public async Task A_suspended_account_stays_suspended_and_gains_no_role_through_a_sign_in_with_the_member_claim() + { + using var host = new HeimdallHost(); + var accountId = HeimdallShapes.NewAccountId(); + Assert.True((await Genuine(host, await host.StartAsync(member: true), accountId, ["member_access"])).SignedIn); + await host.Db(async db => + { + var account = await db.UserAccounts.Include(x => x.Membership).SingleAsync(x => x.HeimdallAccountId == accountId); + account.Membership!.Status = MembershipStatus.Suspended; + await db.SaveChangesAsync(); + return 0; + }); + + var rolesBefore = (await host.Account(accountId))!.Membership!.RoleAssignments.Count; + var again = await Genuine(host, await host.StartAsync(member: true), accountId, ["member_access"]); + + Assert.True(again.SignedIn); + var after = (await host.Account(accountId))!.Membership!; + Assert.Equal(MembershipStatus.Suspended, after.Status); + Assert.Equal(rolesBefore, after.RoleAssignments.Count); + } + + [Fact] + public async Task A_chat_only_account_that_later_signs_in_with_member_access_becomes_a_member() + { + using var host = new HeimdallHost(); + var accountId = HeimdallShapes.NewAccountId(); + Assert.True((await Genuine(host, await host.StartAsync(member: false), accountId)).SignedIn); + Assert.Equal(MembershipStatus.Authenticated, (await host.Account(accountId))!.Membership!.Status); + + Assert.True((await Genuine(host, await host.StartAsync(member: true), accountId, ["member_access"])).SignedIn); + + var account = (await host.Account(accountId))!; + Assert.Equal(MembershipStatus.Active, account.Membership!.Status); + Assert.Contains(account.Membership.RoleAssignments, x => x.Role == MemberRole.StandardMember); + } + [Fact] public async Task A_token_capability_grants_no_role_to_a_sign_in_that_did_not_ask_for_member_access() { diff --git a/tests/Bifrost.Web.Tests/MembershipSuspensionTests.cs b/tests/Bifrost.Web.Tests/MembershipSuspensionTests.cs new file mode 100644 index 0000000..85e12ca --- /dev/null +++ b/tests/Bifrost.Web.Tests/MembershipSuspensionTests.cs @@ -0,0 +1,179 @@ +using Bifrost.Web.Data; +using Bifrost.Web.Domain; +using Bifrost.Web.Features.Membership; +using Bifrost.Web.Features.Shared; +using Bifrost.Web.Pages.App.Members; +using Bifrost.Web.Tests.Support; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Bifrost.Web.Tests; + +/// A suspension is an admin's decision: only the admin path sets or lifts it, with a receipt, and the members page's Approve cannot lift it. +public sealed class MembershipSuspensionTests : IClassFixture +{ + private readonly TestWebApplicationFactory _factory; + + public MembershipSuspensionTests(TestWebApplicationFactory factory) => _factory = factory; + + private sealed record Seeded(Guid AdminId, Guid MemberId, Guid OrdinaryId, Guid OtherAdminId); + + private async Task SeedAsync(MembershipStatus memberStatus = MembershipStatus.Active, bool approved = true) + { + using var scope = _factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + UserAccount Account(string name, MembershipStatus status, bool admin, bool wasApproved) => new() + { + DisplayName = name, + BifrostIdentity = $"{name}-{Guid.NewGuid():N}"[..20], + NormalizedBifrostIdentity = $"{name}-{Guid.NewGuid():N}"[..20], + Membership = new Bifrost.Web.Domain.Membership + { + Status = status, + IsPlatformAdmin = admin, + ApprovedAtUtc = wasApproved ? DateTimeOffset.UtcNow : null + } + }; + + var admin = Account("admin", MembershipStatus.Active, true, true); + var otherAdmin = Account("admin2", MembershipStatus.Active, true, true); + var member = Account("member", memberStatus, false, approved); + var ordinary = Account("ordinary", MembershipStatus.Active, false, true); + db.UserAccounts.AddRange(admin, otherAdmin, member, ordinary); + await db.SaveChangesAsync(); + return new Seeded(admin.Id, member.Id, ordinary.Id, otherAdmin.Id); + } + + private async Task InScopeAsync(Func> body) + { + using var scope = _factory.Services.CreateScope(); + return await body(scope.ServiceProvider, scope.ServiceProvider.GetRequiredService()); + } + + private Task ActorAsync(Guid id) => InScopeAsync(async (_, db) => + new CurrentBifrostActor(true, await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments).SingleAsync(x => x.Id == id))); + + private Task StatusAsync(Guid id) => InScopeAsync(async (_, db) => + (await db.Memberships.AsNoTracking().SingleAsync(x => x.UserAccountId == id)).Status); + + private Task> AuditAsync(string action) => InScopeAsync((_, db) => + db.AuditEvents.AsNoTracking().Where(x => x.Action == action).ToListAsync()); + + private Task SuspendAsync(Guid by, Guid target, string? reason) => InScopeAsync(async (sp, _) => + await sp.GetRequiredService().SuspendAsync(await ActorAsync(by), target, reason, CancellationToken.None)); + + private Task UnsuspendAsync(Guid by, Guid target, string? reason) => InScopeAsync(async (sp, _) => + await sp.GetRequiredService().UnsuspendAsync(await ActorAsync(by), target, reason, CancellationToken.None)); + + [Fact] + public async Task Only_a_platform_admin_can_suspend_and_the_receipt_names_who_and_why() + { + var seed = await SeedAsync(); + + Assert.Equal(SuspensionOutcome.NotAdmin, await SuspendAsync(seed.OrdinaryId, seed.MemberId, "because")); + Assert.Equal(MembershipStatus.Active, await StatusAsync(seed.MemberId)); + Assert.Equal(SuspensionOutcome.NoReason, await SuspendAsync(seed.AdminId, seed.MemberId, " ")); + Assert.Equal(MembershipStatus.Active, await StatusAsync(seed.MemberId)); + + Assert.Equal(SuspensionOutcome.Done, await SuspendAsync(seed.AdminId, seed.MemberId, "spam in chat")); + Assert.Equal(MembershipStatus.Suspended, await StatusAsync(seed.MemberId)); + var receipt = Assert.Single(await AuditAsync("membership.suspended"), x => x.Detail.Contains("spam in chat")); + Assert.Equal(seed.AdminId, receipt.ActorUserAccountId); + Assert.Contains("Active -> Suspended", receipt.Detail); + } + + [Fact] + public async Task An_admin_cannot_suspend_themselves_or_another_platform_admin() + { + var seed = await SeedAsync(); + + Assert.Equal(SuspensionOutcome.ProtectedAccount, await SuspendAsync(seed.AdminId, seed.AdminId, "oops")); + Assert.Equal(SuspensionOutcome.ProtectedAccount, await SuspendAsync(seed.AdminId, seed.OtherAdminId, "coup")); + Assert.Equal(MembershipStatus.Active, await StatusAsync(seed.AdminId)); + Assert.Equal(MembershipStatus.Active, await StatusAsync(seed.OtherAdminId)); + } + + [Fact] + public async Task A_suspension_reason_does_not_reach_the_member_dashboard_snapshot() + { + var seed = await SeedAsync(); + await SuspendAsync(seed.AdminId, seed.MemberId, "private-reason-canary"); + + var snapshot = await InScopeAsync(async (sp, _) => await sp.GetRequiredService().GetAsync(seed.OrdinaryId, CancellationToken.None)); + + Assert.DoesNotContain(snapshot.RecentActivity, x => x.Detail.Contains("private-reason-canary")); + Assert.Contains(await AuditAsync("membership.suspended"), x => x.Detail.Contains("private-reason-canary")); + } + + [Fact] + public async Task A_role_granted_admin_is_protected_like_a_flagged_one() + { + var seed = await SeedAsync(); + await InScopeAsync(async (_, db) => + { + var membership = await db.Memberships.SingleAsync(x => x.UserAccountId == seed.MemberId); + db.RoleAssignments.Add(new RoleAssignment { MembershipId = membership.Id, Role = MemberRole.PlatformAdmin }); + await db.SaveChangesAsync(); + return 0; + }); + + Assert.Equal(SuspensionOutcome.ProtectedAccount, await SuspendAsync(seed.AdminId, seed.MemberId, "role admin")); + } + + [Theory] + [InlineData(true, MembershipStatus.Active)] + [InlineData(false, MembershipStatus.Authenticated)] + public async Task Unsuspend_works_only_by_the_admin_path_and_with_a_reason(bool approved, MembershipStatus restored) + { + var seed = await SeedAsync(MembershipStatus.Suspended, approved); + + Assert.Equal(SuspensionOutcome.NotAdmin, await UnsuspendAsync(seed.OrdinaryId, seed.MemberId, "please")); + Assert.Equal(SuspensionOutcome.NoReason, await UnsuspendAsync(seed.AdminId, seed.MemberId, null)); + Assert.Equal(MembershipStatus.Suspended, await StatusAsync(seed.MemberId)); + + Assert.Equal(SuspensionOutcome.Done, await UnsuspendAsync(seed.AdminId, seed.MemberId, "appeal upheld")); + Assert.Equal(restored, await StatusAsync(seed.MemberId)); + Assert.Contains(await AuditAsync("membership.unsuspended"), x => x.Detail.Contains("appeal upheld") && x.ActorUserAccountId == seed.AdminId); + Assert.Equal(SuspensionOutcome.NotApplicable, await UnsuspendAsync(seed.AdminId, seed.MemberId, "again")); + } + + [Fact] + public async Task The_members_page_Approve_cannot_lift_a_suspension() + { + var seed = await SeedAsync(MembershipStatus.Suspended); + + var result = await InScopeAsync(async (sp, db) => + { + var page = new IndexModel( + db, new FixedActor(await ActorAsync(seed.AdminId)), sp.GetRequiredService(), + sp.GetRequiredService(), TimeProvider.System); + return await page.OnPostApproveAsync(seed.MemberId, CancellationToken.None); + }); + + Assert.IsType(result); + Assert.Equal(MembershipStatus.Suspended, await StatusAsync(seed.MemberId)); + } + + [Fact] + public async Task The_members_page_suspend_handler_forbids_a_non_admin_and_changes_nothing() + { + var seed = await SeedAsync(); + + var result = await InScopeAsync(async (sp, db) => + { + var page = new IndexModel( + db, new FixedActor(await ActorAsync(seed.OrdinaryId)), sp.GetRequiredService(), + sp.GetRequiredService(), TimeProvider.System); + return await page.OnPostSuspendAsync(seed.MemberId, "nope", CancellationToken.None); + }); + + Assert.IsType(result); + Assert.Equal(MembershipStatus.Active, await StatusAsync(seed.MemberId)); + } + + private sealed class FixedActor(CurrentBifrostActor actor) : ICurrentBifrostActorAccessor + { + public Task GetAsync(CancellationToken cancellationToken) => Task.FromResult(actor); + } +} From 33be966b7dff7fc6bb7443d47ef8f2e2186a83ec Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 10:15:46 +0000 Subject: [PATCH 009/113] Registration gates: proof-of-work CAPTCHA and training-notice consent receipt (#54) --- README.md | 2 +- docs/bridge.md | 2 +- docs/registration-gates.md | 86 ++++ .../Configuration/RegistrationOptions.cs | 31 ++ src/Bifrost.Web/Data/BifrostDbContext.cs | 10 + .../20261111090000_AddConsentReceipts.cs | 40 ++ .../BifrostDbContextModelSnapshot.cs | 37 ++ src/Bifrost.Web/Domain/BifrostModels.cs | 19 + .../Membership/BifrostIdentityService.cs | 8 + src/Bifrost.Web/Features/Oidc/OidcGuard.cs | 25 +- .../RegistrationChallengeService.cs | 137 +++++++ .../Registration/RegistrationRateLimit.cs | 43 ++ .../Features/Registration/TrainingNotice.cs | 17 + .../Features/Shared/ClientAddress.cs | 32 ++ .../Shared/StartupConfigurationValidator.cs | 15 +- src/Bifrost.Web/Program.cs | 80 +++- tests/Bifrost.Web.Tests/DeskOptionsTests.cs | 3 +- tests/Bifrost.Web.Tests/HostTrustTests.cs | 3 +- .../MigrationDiscoveryTests.cs | 1 + tests/Bifrost.Web.Tests/OidcIssuerTests.cs | 2 +- .../PlatformEndpointsTests.cs | 23 +- .../RegistrationGateTests.cs | 367 ++++++++++++++++++ .../RegistrationLimitTests.cs | 239 ++++++++++++ .../ReservedIdentityTests.cs | 10 +- .../Support/OidcLogoutKit.cs | 2 +- .../Support/RegistrationKit.cs | 63 +++ .../Support/TestAuthHandler.cs | 10 + .../Support/TestWebApplicationFactory.cs | 2 + 28 files changed, 1253 insertions(+), 56 deletions(-) create mode 100644 docs/registration-gates.md create mode 100644 src/Bifrost.Web/Configuration/RegistrationOptions.cs create mode 100644 src/Bifrost.Web/Data/Migrations/20261111090000_AddConsentReceipts.cs create mode 100644 src/Bifrost.Web/Features/Registration/RegistrationChallengeService.cs create mode 100644 src/Bifrost.Web/Features/Registration/RegistrationRateLimit.cs create mode 100644 src/Bifrost.Web/Features/Registration/TrainingNotice.cs create mode 100644 src/Bifrost.Web/Features/Shared/ClientAddress.cs create mode 100644 tests/Bifrost.Web.Tests/RegistrationGateTests.cs create mode 100644 tests/Bifrost.Web.Tests/RegistrationLimitTests.cs create mode 100644 tests/Bifrost.Web.Tests/Support/RegistrationKit.cs diff --git a/README.md b/README.md index 0e4ea9d..33302e1 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ For the full staged roadmap, including contribution points, revenue share, patro ## Local Dev Notes - set `GitHubOAuth:ClientId` and `GitHubOAuth:ClientSecret` before using sign-in -- POST `/auth/bifrost/register` with `identity`, optional `displayName`, and optional `returnUrl` to create a Bifrost-native account without OAuth; this signs in as `Authenticated` but does not grant active member access +- POST `/auth/bifrost/register` with `identity`, optional `displayName`, optional `returnUrl`, a solved proof-of-work `challenge` and `nonce` (from `GET /auth/bifrost/challenge`), and `acceptedNoticeVersion` (the `version` from `GET /auth/bifrost/notice`) to create a Bifrost-native account without OAuth; this signs in as `Authenticated` but does not grant active member access - set `Bootstrap:AdminGitHubLogins` with at least one GitHub login for the first active admin path - HTTP bridge ledger configuration (`BIFROST_BRIDGE_BASE_URL` / `BIFROST_BRIDGE_TOKEN`) is removed from live CLI transport. Request-lane, governance, dispatch, and bridge receipts converge on Bifrost-owned `bifrost.crossing_receipt.v1` documents in `.bifrost/bridge-receipts.cc`. - external bridge actions must carry typed CultMesh command provenance such as `BIFROST_CULTMESH_COMMAND_ID`; unreceipted and HTTP-ledger hatches fail closed. diff --git a/docs/bridge.md b/docs/bridge.md index b9b35a6..da23705 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -23,7 +23,7 @@ That means Bifrost owns the operational meaning of the crossing: It does not mean Bifrost should own OAuth sludge. Bifrost is both an identity provider and identity consumer: a GameCult actor should be able to register with Bifrost without OAuth, and that Bifrost identity should be enough to authenticate with most GameCult services. Heimdall owns outside-provider OAuth, linked-account token custody, grants, and signed account claims. Bifrost associates those Heimdall-backed accounts with the Bifrost identity, consumes the permission facts, and decides whether a bridge action is allowed in the Bifrost domain. -The native registration surface is `POST /auth/bifrost/register`. It creates a Bifrost-owned `UserAccount` with `BifrostIdentity` and `NormalizedBifrostIdentity`, signs the caller in with the Bifrost cookie, and leaves membership at `Authenticated`. It does not grant active member access, mint outside-provider tokens, or replace Heimdall's account-link and capability custody. +The native registration surface is `POST /auth/bifrost/register`, which takes `identity`, optional `displayName` and `returnUrl`, a solved proof-of-work `challenge` and `nonce` (from `GET /auth/bifrost/challenge`), and `acceptedNoticeVersion` (from `GET /auth/bifrost/notice`). It creates a Bifrost-owned `UserAccount` with `BifrostIdentity` and `NormalizedBifrostIdentity`, signs the caller in with the Bifrost cookie, and leaves membership at `Authenticated`. It does not grant active member access, mint outside-provider tokens, or replace Heimdall's account-link and capability custody. ## Ownership diff --git a/docs/registration-gates.md b/docs/registration-gates.md new file mode 100644 index 0000000..1b9278a --- /dev/null +++ b/docs/registration-gates.md @@ -0,0 +1,86 @@ +# Public registration gates + +Meta ruled yes to public registration on 2026-11-10. The gates she required: self-hosted CAPTCHA, email verification, +a training-notice consent receipt, rate limits and a brake, reserved names, and new accounts in Users with no vote. +This page scopes the three that did not exist, says where each lives, and records what is built. + +## What exists + +| Gate | Where | State | +| --- | --- | --- | +| Rate limits and brake | `OidcGuardMiddleware` (`docs/oidc-issuer.md`) | Merged. Covers `/connect/*` only, not the register endpoint. | +| Reserved names | `BifrostIdentityService.IsReserved`, 28 names | Merged, at creation and at authorize. | +| Chat tier, no vote | `Authenticated` / `PendingApproval` accounts chat and open no member or governance surface | Merged. | +| Suspension | `MembershipSuspensionService` | Merged. | +| CAPTCHA | `Features/Registration/RegistrationChallengeService` | Built here. | +| Consent receipt | `ConsentReceipt`, `TrainingNotice` | Built here. | +| Email verification | nowhere | Scoped below, not built. | + +The hole these gates close: `POST /auth/bifrost/register` is anonymous, and since the chat tier merged, an +`Authenticated` account it creates can sign in to chat. Before this cut it took an identity name and nothing else. + +## CAPTCHA + +Lives in Bifrost, because the register endpoint is Bifrost's. Heimdall authenticates people through providers and has no +registration form. + +Design: a hashcash proof of work. `GET /auth/bifrost/challenge` returns a Data Protection-protected token (random id and +expiry, five minutes) and a difficulty in bits. The client finds a decimal `nonce` such that +`SHA-256(challenge + ":" + nonce)` has at least that many leading zero bits, and posts both with the registration. The +server verifies the protection, the expiry and the hash, and spends the id once. + +- Self-hosted: no third-party script, request or cookie; nothing to track. +- Accessible: there is nothing to see or hear and nothing to solve by hand. A screen-reader user, a keyboard user and a + script all pass the same way, at the cost of CPU time on the client. +- Cost: difficulty 18 is about 260,000 hashes on average, well under a second natively and a few seconds in browser + JavaScript. It prices a bulk registration run in CPU; it does not stop a determined attacker with CPUs, and it is not a + proof of humanity. The difficulty is embedded in the signed challenge, so a challenge verifies at the difficulty it was issued with. +- Replay: the spent-id set is in memory and bounded (10,000, entries dropped at expiry); a restart forgets it, so a challenge + can be replayed for at most its five-minute life. When the set is full the endpoint refuses rather than grows. One address + cannot fill it alone: `GET /auth/bifrost/challenge` and `POST /auth/bifrost/register` share one per-address budget + (`Bifrost:Registration:Limits`, 10 per minute by default, IPv6 by /64, over budget is 429 with Retry-After). An attacker + with many addresses can still fill the set; that is the accepted bound, the same as oidc-issuer.md. + +Not built: the sign-up form. No registration page exists today; the endpoint is the contract and the only client is a +script. The form (solving in a worker, a `