diff --git a/.env.example b/.env.example index 09f05d8..6af5d90 100644 --- a/.env.example +++ b/.env.example @@ -30,5 +30,6 @@ GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID= GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID= # GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE=/absolute/path/to/credential +GC_ACCESS_APP_SPOTIVERSE_BACKEND_CALLBACK_URLS= # GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE=/absolute/path/to/credential GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS=yggdrasil-ghostlight diff --git a/AGENTS.md b/AGENTS.md index 639ca18..beb6fed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,8 +26,12 @@ The planned non-shared-by-default layer is: ## Canonical State +- Treat `state/map.yaml` as the canonical current project map. +- Treat `state/scratch.md` as disposable working memory for one bounded subgoal. - Treat `state/evidence.jsonl` as the distilled durable ledger of decisions, verified boundaries, and rejected paths. +- Treat `state/branches.json` as hypothesis tracking, not phase/status prose. +- Treat `notes/fresh-workspace-handoff.md` as the compact re-entry packet. - Treat `docs/architecture.md` as the source-grounded shared architecture note. - Treat `docs/implementation-plan.md` as the forward plan. - Treat `docs/app-profiles/repixelizer.md` and @@ -46,17 +50,75 @@ every absolute path in here rotted the moment it happened. - Repixelizer profile: `docs/app-profiles/repixelizer.md` - StreamPixels profile: `docs/app-profiles/streampixels.md` - Spotiverse profile: `docs/app-profiles/spotiverse.md` +- Handoff summary: `notes/fresh-workspace-handoff.md` +- State CLI: `tools/heimdall_state.py` +- Pre-compaction helper: `tools/heimdall_prepare_compaction.py` + +## Useful Commands + +Both state tools are single-file, standard-library-only Python. They need no +virtualenv and no installed dependencies. Run them with `python` from the repo +root: + +```powershell +python .\tools\heimdall_state.py status +python .\tools\heimdall_state.py add-evidence --type design --status accepted --note "..." +python .\tools\heimdall_prepare_compaction.py +``` + +Verified 2026-09-06 against Python 3.13.15 installed to the user scope; `py -3` +resolves the same interpreter. + +If `python --version` prints an install prompt rather than a version, PATH is +resolving the Microsoft Store alias in `WindowsApps` instead of a real +interpreter, and it will still exit 0 while doing so. Install a real Python and +put it ahead of `WindowsApps` on PATH rather than hunting for some other +interpreter to hard-code here: + +```powershell +winget install --id Python.Python.3.13 --scope user +``` ## Session Bootstrap And Re-entry Protocol On fresh session load: 1. read: + - `state/map.yaml` + - `notes/fresh-workspace-handoff.md` - `docs/architecture.md` - `docs/implementation-plan.md` 2. run: + - `python .\tools\heimdall_state.py status` - `git status --short --branch` - `git log --oneline -5` +3. restate the current next action from persisted state before editing + +After compaction or suspicious continuity loss: + +1. rerun `heimdall_state.py status` +2. reread `state/map.yaml` and `notes/fresh-workspace-handoff.md` +3. treat the persisted next action as authoritative unless fresh evidence + contradicts it + +When the user says to prepare for imminent compaction: + +1. run `tools/heimdall_prepare_compaction.py` +2. update only the state that actually changed +3. rerun the helper +4. commit the completed persistence pass unless the work is deliberately + mid-surgery + +After any major completed pass, assume compaction may be imminent even if the +user did not say so yet: + +1. run `tools/heimdall_prepare_compaction.py` +2. sync only the persistent state that genuinely changed +3. rerun the helper +4. commit the persistence pass before moving on unless the work is + deliberately mid-surgery +5. push the current branch to `origin` after the major pass unless the user + explicitly says not to publish yet ## Operating Discipline @@ -70,17 +132,18 @@ On fresh session load: - Do not let app profiles turn into duplicate copies of the shared architecture. - If the diff grows while the boundary gets blurrier, stop and simplify. +- Before handoff or compaction, sync `state/map.yaml`, refresh + `notes/fresh-workspace-handoff.md`, add distilled evidence when future belief + changed, and make the next action explicit. ## Build And Deploy Target Heimdall runs as the auth authority behind Yggdrasil-hosted nginx at -`heimdall.gamecult.org`, on Linux. `deployment/idunn/recipe.toml` is the target -deployment declaration (untested against live Idunn; Yggdrasil still runs the -hand-written `heimdall.service`). This workstation is Windows and is where the -shell is, not where the artifact runs: a local compile is not evidence about the -Linux release, because toolchain, linker, filesystem semantics and path -handling all differ. Build for the target, or let the deploy path's own builder -do it, and say which one you used. +`heimdall.gamecult.org`, on Linux. Idunn owns the deployment transaction. This +workstation is Windows and is where the shell is, not where the artifact runs: +a local compile is not evidence about the Linux release, because toolchain, +linker, filesystem semantics and path handling all differ. Build for the +target, or let the deploy path's own builder do it, and say which one you used. ## External Context diff --git a/README.md b/README.md index 3104ddd..f0e0a0e 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ The point is painfully simple: - **Problem:** every GameCult app was rebuilding Discord/Patreon login glue. Heimdall centralizes identity authority and keeps app-domain data in the apps. - **Entry points:** - `src/index.ts` and `src/app.ts`: the Fastify service. `src/signing.ts` and `src/claims.ts` issue JWTs and serve `/.well-known/jwks.json`; `src/oauth.ts` and `src/providers.ts` own provider flows. + - `src/verifier.ts`: the local verifier helper an app backend imports to validate Heimdall JWTs without phoning home. - `src/odin-publication.ts` and `plugins/gamecult.heimdall.access`: the redacted Odin/Eve provider advertisement and the `gamecult.heimdall.access` plugin (`docs/eve-access-plugin.md`). - `docs/architecture.md`, `docs/service-contract.md`, `docs/verse-service-contract.md`, `docs/app-profiles/`: the contracts. - `pnpm install`, `pnpm dev`, `pnpm test` (see Dev Commands). @@ -46,8 +47,10 @@ Landed right now: - AES-256-GCM sealing for managed provider tokens at rest - a one-time browser completion exchange kept as fallback for opener `postMessage` handoff -- app profile surfaces for Repixelizer, StreamPixels, Bifrost, and Ghostlight -- signed claim issuance for app-local verification against `/.well-known/jwks.json` +- app profile surfaces for Repixelizer, StreamPixels, and Spotiverse +- signed claim issuance for app-local verification experiments +- a local verifier helper in `src/verifier.ts` so app backends can validate + Heimdall JWTs without phoning home on every guarded request - a read-only Odin/Eve provider advertisement export that names redacted CultCache witness document shapes and paths without touching live secrets - a daemon-owned CultCache boundary witness at `GC_ACCESS_CULTCACHE_PATH` @@ -81,9 +84,9 @@ Canonical docs: - `docs/verse-service-contract.md` - `docs/app-profiles/repixelizer.md` - `docs/app-profiles/streampixels.md` -- `docs/app-profiles/bifrost.md` -- `docs/app-profiles/ghostlight.md` -- `docs/app-profiles/spotiverse.md` (retired restore spec) +- `docs/app-profiles/spotiverse.md` +- `state/map.yaml` +- `notes/fresh-workspace-handoff.md` ## Dev Commands diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index 8179280..48c3577 100644 --- a/deployment/idunn/recipe.toml +++ b/deployment/idunn/recipe.toml @@ -138,16 +138,11 @@ route_required = true optional_environment = [ "CULTMESH_URI_ODIN_RUDP", "GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS", - "GC_ACCESS_APP_BIFROST_RUNTIME_IDS", "GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE", "GC_ACCESS_APP_GHOSTLIGHT_BACKEND_CALLBACK_URLS", "GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS", "GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE", - "GC_ACCESS_APP_REPIXELIZER_BACKEND_CALLBACK_URLS", - "GC_ACCESS_APP_REPIXELIZER_RUNTIME_IDS", "GC_ACCESS_APP_REPIXELIZER_SHARED_SECRET_FILE", - "GC_ACCESS_APP_STREAMPIXELS_BACKEND_CALLBACK_URLS", - "GC_ACCESS_APP_STREAMPIXELS_RUNTIME_IDS", "GC_ACCESS_APP_STREAMPIXELS_SHARED_SECRET_FILE", "GC_ACCESS_APPLY_SCHEMA_ON_STARTUP", "GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT", @@ -161,7 +156,6 @@ optional_environment = [ "GC_ACCESS_PRIVATE_COMMAND_PORT", "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID", "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE", - "GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID", "GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_GOOGLE_CLIENT_ID", "GC_ACCESS_PROVIDER_GOOGLE_CLIENT_SECRET_FILE", @@ -169,13 +163,11 @@ optional_environment = [ "GC_ACCESS_PROVIDER_JOYSTICK_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_PATREON_CLIENT_ID", "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET_FILE", - "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID", "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID", "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID", "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET_FILE", - "GC_ACCESS_REFRESH_TTL_SECONDS", "GC_ACCESS_SESSION_TTL_SECONDS", "GC_ACCESS_SIGNING_KEY_ID", "GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP", @@ -200,7 +192,7 @@ schema_generation = "heimdall-v1" [[state.slots]] id = "service" -relative_path = "cultcache/heimdall.service.cc" +relative_path = "heimdall.service.cc" kind = "cultcache-file" schema = "heimdall.service_state.v1" writer = "process-bound-single-writer" diff --git a/docs/app-profiles/ghostlight.md b/docs/app-profiles/ghostlight.md index 38ad159..58470f4 100644 --- a/docs/app-profiles/ghostlight.md +++ b/docs/app-profiles/ghostlight.md @@ -11,23 +11,14 @@ selection, and every world mutation. - `app_slug`: `ghostlight` - public URL: `https://yggdrasil.gamecult.org/ghostlight/` -- identity providers: Discord and Google -- access rule: Heimdall authenticates; `app_access` is `identity.authenticated`. - Who may play is the Dungeon's account catalog and its one-time invites, not a - Discord role. No Discord role policy is required of begin or refresh, and one - a caller still sends is evaluated by nobody for this app -- starts: every start is app-authenticated (`startRequiresAppCaller`); a public - start without the app secret is `401 app_auth_required` -- first Google sign-in: Google is linked-identity only, so a `sub` no account - holds is refused (`identity_not_linked`) unless the begin carried - `firstLoginGrant: "invite"`, which the Dungeon sends only for an invite its - catalog holds live. The grant mints a Heimdall account for a new `sub`; it - never attaches to or moves an existing account +- identity provider: Discord +- access rule: Ghostlight supplies its configured KLTST Discord-role policy on + the app-authenticated private boundary; Heimdall evaluates the policy and + grants `app_access` only when it succeeds ## Capabilities -- `app_access`: shared capability; every authenticated identity has it, and - admission is the Dungeon's catalog +- `app_access`: shared capability granting entry to the demo - `campaign_play`: hybrid capability; Ghostlight must also prove that the authenticated account owns the selected campaign @@ -36,6 +27,6 @@ plugin stores only an opaque attempt handle. Ghostlight redeems that handle over the encrypted loopback command plane, verifies the resulting `aud=ghostlight` claim against Heimdall JWKS, and establishes app-local campaign authority. Short-lived local access continues without a Heimdall round trip. Scheduled -refresh re-evaluates nothing app-specific; explicit logout +refresh re-evaluates the Ghostlight-owned KLTST role policy; explicit logout revokes both Ghostlight's local session and the matching Heimdall refresh custody record. diff --git a/docs/architecture.md b/docs/architecture.md index 16ea243..956b1db 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -374,9 +374,10 @@ for: only a strong proof whose method the profile lists as an account proof covers the whole account; any other proof covers the one login in `auth_identity_id`. The asserted route trusts the calling app and is bounded by the app secret, a live -bearer for that app, the method allowlist, and a nonce claimed once per session +bearer for that app, the method allowlist, a nonce claimed once per session through `claimOAuthStateUse` (phase `step_up_assert`, no new table or grant; -retained to the session expiry as of the claim, which a refresh may slide past). +retained to the session expiry as of the claim, which a refresh may slide past), +and in-process fixed-window limits (`src/fixed-window.ts`). ### Three nested guards diff --git a/docs/service-contract.md b/docs/service-contract.md index a1c2446..6b77caa 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -83,8 +83,7 @@ Current app slugs: - `repixelizer` - `streampixels` -- `bifrost` -- `ghostlight` +- `spotiverse` Profile fields: @@ -188,10 +187,10 @@ Failure modes: the caller did not authenticate as that app via `x-heimdall-app-secret` (`resolveAppCaller`, `src/app-caller.ts`) -- this applies regardless of `handoff.kind` or app slug; a caller with no policy to attach needs no secret, - unless the app's profile sets `startRequiresAppCaller` (Bifrost and Ghostlight): then + unless the app's profile sets `startRequiresAppCaller` (Bifrost only): then every start for that app, with or without a policy, needs that app's secret. - Bifrost and Ghostlight bind browser completion to a nonce that rides readable - in the signed state's `return_to`, so only the app may mint its own state; apps whose + Bifrost binds browser completion to a nonce that rides readable in the signed + state's `return_to`, so only Bifrost may mint a Bifrost state; apps whose browser starts are public by design leave the flag unset - `401 app_auth_required` also when `mode` is `connect` and the body carries a `connection` (a creator or account target): a connection target is app-backend @@ -237,11 +236,10 @@ Launch note: implemented yet - Repixelizer launch can configure Discord and Patreon on its provider buttons -### Google (OpenID Connect, link-only; mints only under an invite grant) +### Google (OpenID Connect, link-only) -`google` is an identity provider that does not mint an account by itself. It is -a second door into a person who already has one, and a first door only for a -person an app has invited (see the invite grant below). +`google` is an identity provider that never mints an account. It is a second +door into a person who already has one. - Callback redirect URI (register exactly this in the Google Cloud OAuth client): `{GC_ACCESS_BASE_URL}/v1/oauth/google/callback`, which is @@ -258,23 +256,10 @@ person an app has invited (see the invite grant below). - `mode: "link"` needs `Authorization: Bearer ` for the same app; the identity attaches to that token's account and to no other. `mode: "sign_in"` signs in an account the `sub` is already linked to. -- A `sub` no account holds, arriving with `sign_in` and no invite grant, is - refused and mints nothing. A `sub` linked to another account is refused and - never moved. Both audit as `oauth_callback_failed` with error class - `LinkRefusal` and the code `identity_not_linked` or `link_initiator_mismatch`. -- Invite grant. An app whose profile sets `mayGrantFirstLogin` (`bifrost` and `ghostlight`) - may start `mode: "sign_in"` with `firstLoginGrant: "invite"`, saying it has - invited this person. The start must carry that app's own secret: any other - caller, including a public start, is `401 app_auth_required`. An app whose - profile may not grant, any other mode, or any other value is - `400 first_login_grant_refused`. The grant rides only in the signed state - (`first_login_grant`), so nothing a browser sends can set it, and the state - stays single-use. At the callback a `sub` no account holds, under a grant, - mints one account with that identity linked, and audits - `account_minted_by_grant` with `{ provider, appSlug }`. A `sub` an account - already holds signs in to that account exactly as without a grant; the grant - never attaches an identity to an existing account and never moves one. - `mode: "link"` takes no grant and is unchanged. +- A `sub` no account holds, arriving with `sign_in`, is refused and mints + nothing. A `sub` linked to another account is refused and never moved. + Both audit as `oauth_callback_failed` with error class `LinkRefusal` + and the code `identity_not_linked` or `link_initiator_mismatch`. - Link is two-phase. The callback verifies the identity and records a pending link (TTL `completionTtlSeconds`), answering `status: "link_pending"` with a `pendingLinkId` and no session; it writes no linked identity. The app calls @@ -288,7 +273,7 @@ person an app has invited (see the invite grant below). what Discord or Patreon grant. - Configure with `GC_ACCESS_PROVIDER_GOOGLE_CLIENT_ID` and `GC_ACCESS_PROVIDER_GOOGLE_CLIENT_SECRET_FILE`. Admitted to the `bifrost` - and `ghostlight` app profiles only. + app profile only. ### `GET /v1/oauth/{provider}/callback` @@ -912,21 +897,27 @@ Important behavior: - app-local binding, diagnostics, subscription setup, and runtime behavior stay app-owned -### Local verification seam +### Reference local verifier seam Purpose: -- let app backends verify Heimdall Ed25519 JWTs locally against `/.well-known/jwks.json` - instead of calling Heimdall on every guarded request +- give app backends a tiny local verification helper instead of encouraging + per-request Heimdall callbacks -Expected verifier contract: +Current reference helper: -- fetch and cache Heimdall's JWKS by `kid`, bound to Heimdall `issuer` and app slug +- `src/verifier.ts` + +Current helper contract: + +- build the verifier once from Heimdall `issuer`, app slug, and JWKS - verify Ed25519 signature locally by `kid` - reject wrong `iss`, wrong `aud`, malformed claim shape, `nbf` violations, and expired tokens - accept a small clock-skew window for normal same-host reality +This is a reference seam, not a magical shared middleware product yet. + ## Access claim shape Current claim payload fields: @@ -1000,14 +991,6 @@ same result only for the exact same authenticated request; content changes are denied. Completion consumption remains single-use in Heimdall's canonical store. -`heimdall.auth.begin` takes `provider`, `mode`, `returnTo`, an optional -`entitlementPolicy` (accepted for any app, required of none) and an optional -`firstLoginGrant`. Absent or null is no grant; exactly `"invite"` is passed to -the same start gate as the public route (the app's own caller, `sign_in` only, -an app whose profile may grant); any other value is refused before an attempt -is created. Ghostlight sends `"invite"` only for a browser whose invite the -Dungeon's catalog holds live; Heimdall holds no invite records. - Refresh claims are admitted only while their exact persisted session, app/account custody, access revision, and refresh expiry still match. Logout uses the refresh claim as custody proof and atomically advances the persisted diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md new file mode 100644 index 0000000..9d23cf1 --- /dev/null +++ b/notes/fresh-workspace-handoff.md @@ -0,0 +1,272 @@ +# Fresh Workspace Handoff + +This is the re-entry packet for this repo (path: whatever the checkout is; it has moved drives before). + +It is intentionally short. Historical proof belongs in git history and the +distilled `state/evidence.jsonl` ledger; the shared architecture belongs in +`docs/architecture.md`; the forward build order belongs in +`docs/implementation-plan.md`. + +## Rehydrate + +From the repo root: + +```powershell +python .\tools\heimdall_state.py status +Get-Content '.\state\map.yaml' +Get-Content '.\notes\fresh-workspace-handoff.md' +Get-Content '.\docs\architecture.md' +Get-Content '.\docs\implementation-plan.md' +git status --short --branch +git log --oneline -5 +Get-Content '.\state\evidence.jsonl' -Tail 8 +``` + +Do not trust this file for the exact live HEAD. Always check git. + +## Active Work + +Joystick H1 is merged and live (PR GameCult/Heimdall#1; campaign +`joystick:campaign:self`). Next: `joystick:follow_up:h1-joystick-consent-round-trip`, then +StreamPixels S0/S1 (other sessions). Open Heimdall follow-ups, by id: +`joystick:follow_up:cross-process-failed-refresh-marker`, +`joystick:follow_up:connect-start-needs-app-auth`, +`joystick:follow_up:heimdall-idunn-onboarding`, +`joystick:follow_up:joystick-viewer-signin-public-bot`. The Ghostlight KLTST +canaries below stay open, behind them. + +## Current Orientation + +Yggdrasil runs Heimdall `d51fa6b`, hand-deployed 2026-10-19 15:51Z; +gamecult-ops `210a1af` records backup, rollback and provenance. Facts below +about Odin, Ghostlight and CultLib pins were verified at `1086aee` (2026-08-22) +and are not re-verified at `d51fa6b`. + +- At `1086aee01169bf60e8a492b2740db1c6f3e8cabf` Heimdall ran with CultLib + `5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9` +- Heimdall publishes four redacted access records to Odin under unique keys: + `eve:provider:heimdall`, `heimdall:command-boundary`, + `eve:plugin:gamecult.heimdall.access`, and `heimdall:transport-profile` +- Odin `b4f9a2e95f0b41cebdeddc49223781d1d3c7b42a` persists and returns all four; + it does not proxy private commands or receive claims +- Ghostlight `b515ca90c25573005a616244143803b37f2d06ec` resolves the boundary through + Odin and accepted a live canonical anonymous `heimdall.auth.begin`; its unit + has no direct Heimdall endpoint + +- `gamecult.heimdall.access` now has a manifest, advertisement, schemas, + fixtures, executable `describe`/`validate`/`project` ABI, and browser + reference adapter +- Heimdall persists OAuth attempts and serves authenticated + `heimdall.auth.begin` / `heimdall.auth.complete` / `heimdall.auth.refresh` / + `heimdall.auth.logout` through loopback + CultNet/RUDP on port `4101` +- private commands are source-runtime, app-secret, expiry, nonce, and + idempotency bound; their MessagePack payloads and completion claims are + AES-256-GCM wrapped +- the Ghostlight app profile now requires its caller-owned Discord role policy; + Heimdall evaluates it and Ghostlight remains owner of local sessions, + memberships, and campaigns +- refresh verifies the exact persisted session revision before reissuing a + claim; logout expires that session and advances its revision, so a stale or + racing refresh cannot resurrect revoked custody + +- this repo now has a first stateful Heimdall service slice +- the canonical shared architecture lives in `docs/architecture.md` +- the concrete HTTP/JWKS contract lives in `docs/service-contract.md` +- app profiles live under `docs/app-profiles/` +- the key boundary is explicit: + - Heimdall owns OAuth, linking, managed provider credential custody, grants, + entitlement refresh, and signed claim issuance + - app-domain data stays app-owned by default + - host apps verify signed claims locally for routine auth instead of calling + Heimdall on every request +- the landed service now exposes: + - `/.well-known/jwks.json` + - `/.well-known/heimdall-configuration` + - `/v1/oauth/{provider}/start` + - `/v1/oauth/{provider}/callback` + - `/v1/apps/{appSlug}/auth-completions/redeem` + - `/v1/apps/{appSlug}/sessions/refresh` + - `/v1/apps/{appSlug}/managed-credentials/resolve` +- the Discord callback path now performs real code exchange, identity + resolution, auth persistence, entitlement evaluation, audit logging, and + claim issuance for the Repixelizer slice +- browser-style auth handoff now uses a one-time completion code posted back to + the opener, with backend redemption instead of fragment-token handoff +- same-host or Yggdrasil-reachable app integrations can now ask Heimdall to + deliver the auth result directly to an app backend callback endpoint, leaving + the browser with only status/attempt signaling +- signing keys can now load from a persisted file path and bootstrap that file + on first boot when explicitly enabled +- managed provider tokens are now sealed at rest with AES-256-GCM instead of + being dumped into "encrypted" columns raw like an insult +- `src/verifier.ts` now provides a small local JWT verifier seam for app + backends +- Repixelizer has consumed the backend-callback flow in its hosted web layer: + it creates local auth attempts, asks Heimdall to start OAuth, receives the + direct backend callback, verifies Heimdall Ed25519 access tokens locally, and + adopts httpOnly local sessions +- Heimdall is now deployed on Yggdrasil at `https://heimdall.gamecult.org` + behind nginx/TLS with Postgres storage, file-backed signing-key bootstrap, + configured token custody, and public health/discovery/JWKS checks passing +- Repixelizer is now deployed on Yggdrasil at + `https://repixelizer.gamecult.org` with Heimdall mode enabled, Discord and + Patreon as public providers, required access enabled, and queue protection + enabled +- Repixelizer public auth-start returns Discord and Patreon authorization URLs + using the Heimdall callback and Repixelizer backend handoff +- Repixelizer auth now has a refresh path: Heimdall issues signed refresh + tokens with access claims, `/v1/apps/{appSlug}/sessions/refresh` reissues + short-lived access claims, and Discord/Patreon provider tokens refresh inside + Heimdall before entitlement re-evaluation +- Twitch and YouTube now have generic OAuth exchange and identity runtimes +- GitHub is still catalogued, but its callback runtime is not implemented +- StreamPixels now delegates viewer and creator Twitch/YouTube OAuth to + Heimdall, redeems Heimdall completion codes server-side, writes its own + viewer sessions and connector bindings, and resolves current provider access + tokens from Heimdall without storing refresh tokens locally +- Spotiverse now delegates Spotify OAuth to Heimdall. Heimdall has a + `spotiverse` app profile and `spotify` provider runtime; Spotiverse stores a + local Heimdall account binding and resolves current Spotify access through + `/v1/apps/spotiverse/managed-credentials/resolve` without storing provider + refresh tokens. +- Bifrost now has a `bifrost` app profile for Discord/Patreon member access. + Bifrost sends caller-owned KTLST Discord role and Patreon tier policies + through trusted backend-callback OAuth starts; Heimdall owns provider + OAuth/token custody and configured backend callback allowlisting. +- Bifrost patron support sync now reuses Heimdall's existing linked Patreon + identity and membership reader. `POST /v1/apps/bifrost/patron-support/sync` + is app-authenticated, refreshes the stored Patreon credential if needed, + reads active paid Patreon tier evidence, and emits a signed + `RecurringSupportSnapshot` to Bifrost's + `/heimdall/patron-support/events` intake. +- Public Yggdrasil Heimdall has been deployed with the Spotiverse/Spotify code + path, Spotify provider credentials, a Spotiverse shared secret, and an + allowlisted loopback portal callback at + `http://127.0.0.1:18796/auth/heimdall/callback`. +- Heimdall and StreamPixels are deployed on Yggdrasil for the StreamPixels + migration slice; Twitch callback handling has been patched so provider token + `scope` can be either a space-delimited string or an array +- live StreamPixels Twitch sign-in through Heimdall has succeeded on Yggdrasil + and Heimdall audit showed callback success, completion creation, and + completion redemption +- the ignored local `secrets/heimdall-service.env` artifact now has + `GC_ACCESS_PROVIDER_TWITCH_*` and `GC_ACCESS_PROVIDER_YOUTUBE_*` populated + for the StreamPixels migration slice +- the intended first deployment shape is a Heimdall service on Yggdrasil behind + nginx, not an embedded cross-runtime shared library fantasy +- Heimdall now writes a daemon-owned boundary witness store at + `GC_ACCESS_CULTCACHE_PATH` containing provider advertisement, command + boundary, transport profile, and daemon-health summary state +- Heimdall can now publish `heimdall.cultnet-rudp-provider-health` to Idunn + over `cultnet.transport.rudp.v0` when `GC_ACCESS_IDUNN_RUDP_HEALTH` is + configured; HTTP `/healthz`, JWKS, discovery, systemd, and nginx routing + remain compatibility witnesses +- Since `1086aee` Heimdall persists its private + provider-health identity at `/srv/heimdall/keys/provider-health-identity.cc` + and publishes canonical signed health independently of the slower Verse + snapshot cadence. Idunn owns the exact root trust binding, authenticated + admission, lifecycle decision, and redacted public `.cc` projection. +- Odin commit `b4f9a2e95f0b41cebdeddc49223781d1d3c7b42a` retains the RUDP health + reliability cut and registers Heimdall's command-boundary, plugin, and + transport schemas so the typed catalog can persist rather than silently drop + them. Live proof returned all four exact Heimdall records. + +## Critical Doctrine + +- Persistent state is the agent's mind. +- Cut stale architecture notes as ruthlessly as stale code. +- Do not mistake "shared auth" for "shared database." +- Do not mistake "shared auth service" for "every guarded route must call the + mothership." +- If compaction hits before boundary findings are persisted, that work is gone. + Re-gather it instead of pretending continuity happened. + +## Next Real Move + +The Active Work follow-ups first. Everything below is the standing queue. + +Do not continue implementation automatically from a rehydrate-only request. + +The Idunn/swarm health transport cut is live. Do not regress Heimdall to +unsigned `idunn.daemon_health`, merge its private key into Idunn, or make HTTP +health an authority. The next product work is the Bifrost and remaining browser +verification listed below. + +The active Ghostlight deployment cut is complete. The next Ghostlight work is a +real separate-account KLTST completion/refresh/logout canary, followed by the +eight-account Session Zero privacy and actor-binding smoke. Keep port `4101` +loopback-only and treat any claim, token, completion, app secret, or account +state in Odin/CultMesh/browser output as a release-blocking fault. + +If the user asks to continue on Spotiverse, the current next move is the real +browser `/auth/login` flow through public Heimdall. The Yggdrasil SSH tunnel +must include reverse forward +`spotiverse-callback:18796:127.0.0.1:8796`, and local Spotiverse must point at +`https://heimdall.gamecult.org` with the matching `HEIMDALL_APP_SECRET`. Verify +managed credential resolution after login. Spotiverse should not regain local +Spotify OAuth token storage. + +If the user asks to continue on StreamPixels, the current next move is real +browser verification: + +- verify viewer claim/link through `https://streampixels.gamecult.org/auth/connect` +- Twitch viewer sign-in has already passed once; continue with YouTube and + connector attachment verification +- verify creator connector attach from an admin creator session +- confirm StreamPixels persists local profile/connector binding state while + Heimdall retains provider token custody +- if a provider callback fails, inspect Heimdall audit events and StreamPixels + service logs before touching app/domain boundaries + +Repixelizer still needs its real browser OAuth verification: + +- open `https://repixelizer.gamecult.org/app/` +- start Discord sign-in with an account that has the `KLTST` or + Patreon-synced `Inner Sanctum` role, or Patreon sign-in with a currently + entitled tier titled `Inner Sanctum` +- confirm Repixelizer sends its app-owned provider policy in the + backend-callback OAuth start +- confirm Heimdall receives the provider callback and evaluates entitlement +- confirm Repixelizer receives the backend callback, verifies the Heimdall + token, adopts a local httpOnly session, and gates hosted/queue routes +- confirm the Discord authorization URL requests only `identify + guilds.members.read` + +Launch policy is role-gated on purpose: the GameCult Discord can remain public, +but Repixelizer access is limited to members with either `KLTST` or the +Patreon-synced `Inner Sanctum` role. Repixelizer owns that role policy through +its own runtime env and sends it to Heimdall during backend-callback OAuth +start; Heimdall owns provider OAuth mechanics and claim issuance, not the +per-app role list. + +Patreon access is title-gated on the currently entitled tier title +`Inner Sanctum`; do not use currency amount as the durable policy because +currencies are weird little traps. + +Bifrost needs browser verification after deployment: + +- configure Heimdall with + `GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS=https://bifrost.gamecult.org/auth/heimdall/callback` +- configure Heimdall with `GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE`, + `GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT=https://bifrost.gamecult.org/heimdall/patron-support/events`, + and `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE`, each naming a credential + file +- configure Bifrost with `Heimdall__DiscordGuildId`, + `Heimdall__DiscordAllowedRoleIds__0=`, and + `Heimdall__PatreonTierTitle=Inner Sanctum` +- configure Bifrost with the matching `Heimdall__PatronSupportIntakeSecret` +- start Discord sign-in from `https://bifrost.gamecult.org/` with a user that + has the KTLST cult-member role +- start Patreon sign-in with a user that has the configured active tier +- confirm Bifrost creates/updates a local account and active standard + membership while Heimdall keeps provider token custody +- trigger `/v1/apps/bifrost/patron-support/sync` for that linked Heimdall + account and confirm Bifrost records a Patreon recurring-support snapshot + without owning Patreon webhook or token custody + +## Immediate Re-entry Instruction + +After compaction, first rehydrate and reorient from the listed files and git +state. Wait for the user's next instruction unless they explicitly say to +continue. diff --git a/schemas/heimdall.auth_begin_command.v1.schema.json b/schemas/heimdall.auth_begin_command.v1.schema.json index 3ba1879..ca22ccf 100644 --- a/schemas/heimdall.auth_begin_command.v1.schema.json +++ b/schemas/heimdall.auth_begin_command.v1.schema.json @@ -2,12 +2,11 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "heimdall.auth_begin_command.v1", "type": "object", - "required": ["provider", "mode", "returnTo"], + "required": ["provider", "mode", "returnTo", "entitlementPolicy"], "properties": { - "provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick", "google"] }, + "provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick"] }, "mode": { "enum": ["sign_in", "link", "connect"] }, "returnTo": { "type": "string", "format": "uri" }, - "firstLoginGrant": { "enum": ["invite"] }, "entitlementPolicy": { "oneOf": [ { diff --git a/schemas/heimdall.auth_refresh_command.v1.schema.json b/schemas/heimdall.auth_refresh_command.v1.schema.json index 4c86557..4bc4659 100644 --- a/schemas/heimdall.auth_refresh_command.v1.schema.json +++ b/schemas/heimdall.auth_refresh_command.v1.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "heimdall.auth_refresh_command.v1", "type": "object", - "required": ["schema", "refreshToken"], + "required": ["schema", "refreshToken", "entitlementPolicy"], "properties": { "schema": { "const": "heimdall.auth_refresh_command.v1" }, "refreshToken": { "type": "string", "minLength": 1 }, diff --git a/src/app-caller.ts b/src/app-caller.ts index 635d273..59c80a0 100644 --- a/src/app-caller.ts +++ b/src/app-caller.ts @@ -16,24 +16,51 @@ import { timingSafeEqual } from "node:crypto"; import { type AppSlug } from "./contracts.js"; import { type HeimdallConfig } from "./config.js"; -declare const appCallerBrand: unique symbol; +// `{ appSlug }` used to satisfy this type structurally, so any module could +// construct a caller by writing the literal — nothing but grep discipline +// stopped an importer from forging one. The symbol brand stops that at +// compile time, but a cast (`as unknown as AppCaller`) or a JSON round-trip +// defeats a type-level check trivially; nothing enforced it at runtime. The +// module-private WeakSet below is the enforcement: brandCaller registers +// every value it mints, and isAppCaller is the only way a consumer may trust +// one. A forged literal — even one carrying the symbol key by hand — was +// never added to the set and is rejected. +const callerBrand = Symbol("AppCaller"); export interface AppCaller { readonly appSlug: AppSlug; - readonly [appCallerBrand]: true; + readonly [callerBrand]: true; } -function makeCaller(appSlug: AppSlug): AppCaller { - return { appSlug } as AppCaller; +const mintedCallers = new WeakSet(); + +function brandCaller(appSlug: AppSlug): AppCaller { + // Frozen: the brand survives mutation, so without this a legitimately held + // caller for one app could be re-slugged into another and stay branded. + const caller: AppCaller = Object.freeze({ appSlug, [callerBrand]: true as const }); + mintedCallers.add(caller); + return caller; +} + +/** + * The runtime half of the brand. `startOAuthFlow` and `refreshAppSession` + * call this instead of trusting the `AppCaller | null` type alone — a value + * that is not exactly the object `resolveAppCaller` or + * `callerFromOpenedEnvelope` returned is never in the set, regardless of + * shape or cast. + */ +export function isAppCaller(value: unknown): value is AppCaller { + return typeof value === "object" && value !== null && mintedCallers.has(value); } /** * The private command plane already authenticated `appSlug` by opening its * envelope with the app's shared secret and checking sourceRuntimeId before - * calling this. + * ever calling this. It has no header to read, so it cannot go through + * resolveAppCaller; this is the only other place an AppCaller may be minted. */ export function callerFromOpenedEnvelope(appSlug: AppSlug): AppCaller { - return makeCaller(appSlug); + return brandCaller(appSlug); } /** Timing-safe comparator. The only comparator anywhere a shared secret is checked. */ @@ -64,5 +91,5 @@ export function resolveAppCaller( appSlug: AppSlug, headers: Record ): AppCaller | null { - return secretMatches(config.appSharedSecrets[appSlug], getSharedSecretHeader(headers)) ? makeCaller(appSlug) : null; + return secretMatches(config.appSharedSecrets[appSlug], getSharedSecretHeader(headers)) ? brandCaller(appSlug) : null; } diff --git a/src/app-profiles.ts b/src/app-profiles.ts index 8b6a86c..a77f76a 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -3,7 +3,7 @@ import { type CapabilityDefinition, type CapabilityMode, } from "./capability-rules.js"; -import { type AppSlug, type LinkedIdentityInput, type OAuthConnectionBinding, type OAuthMode, type Provider } from "./contracts.js"; +import { type AppSlug, type LinkedIdentityInput, type OAuthConnectionBinding, type OAuthEntitlementPolicy, type OAuthMode, type Provider } from "./contracts.js"; import { entitlementFacts, grantFacts, identityFacts } from "./facts.js"; export type { CapabilityDefinition, CapabilityMode }; @@ -38,6 +38,13 @@ export interface AppProfile { * primitive, not a convenience. Compared by URL origin, not prefix. */ allowedReturnOrigins: readonly string[]; + /** + * Some apps require the caller to supply an entitlement policy of a + * specific kind on every begin/refresh (ghostlight's caller-owned Discord + * role gate). Data instead of a per-slug branch in the private command + * plane; absent for apps with no such requirement. + */ + requiredEntitlementPolicyKind?: OAuthEntitlementPolicy["kind"]; /** * The app binds browser completion to its own pending attempt, and the * binding is the secrecy of the attempt nonce, which rides readable in the @@ -49,14 +56,6 @@ export interface AppProfile { * state. Absent for apps whose browser starts are public by design. */ startRequiresAppCaller?: boolean; - /** - * The app decides who is invited. Its authenticated sign_in start may carry - * `firstLoginGrant: "invite"`, which lets a provider that otherwise requires a - * link (Google) mint the account for an identity no account holds. The grant - * never attaches an identity to an existing account. Absent for every app that - * may not grant. - */ - mayGrantFirstLogin?: true; /** * The app may assert, with its secret and a member's live bearer, that the * member just passed a factor the app itself checked (POST @@ -171,7 +170,6 @@ const bifrostProfile: AppProfile = { managedConnectionProviders: [], allowedReturnOrigins: ["https://bifrost.gamecult.org"], startRequiresAppCaller: true, - mayGrantFirstLogin: true, stepUpAssertion: { methods: ["bifrost-passkey", "bifrost-email-code"] }, // A passkey proves the account; an email code proves an inbox, which is one login's worth at most. identityMoves: { accountProofMethods: ["bifrost-passkey"] }, @@ -188,25 +186,24 @@ const bifrostProfile: AppProfile = { const ghostlightProfile: AppProfile = { slug: "ghostlight", displayName: "Ghostlight Dungeon", - profileVersion: "2026-12-02", - identityProviders: ["discord", "google"], - entitlementSources: [], + profileVersion: "2026-08-22", + identityProviders: ["discord"], + entitlementSources: ["discord"], managedConnectionProviders: [], allowedReturnOrigins: ["https://yggdrasil.gamecult.org"], - startRequiresAppCaller: true, - mayGrantFirstLogin: true, + requiredEntitlementPolicyKind: "discord_role_access", capabilities: [ { key: "app_access", mode: "shared", - summary: "Heimdall authenticated this identity for Ghostlight; who may play is the Dungeon's account catalog.", - anyOf: [identityFacts.authenticated], + summary: "May enter Ghostlight Dungeon after Heimdall verifies the app-supplied GameCult Discord role policy.", + anyOf: gameCultMembership, }, { key: "campaign_play", mode: "hybrid", - summary: "Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership.", - localRequirement: "Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership.", + summary: "May play campaigns owned by the authenticated Ghostlight account.", + localRequirement: "Ghostlight must combine app_access with local campaign ownership.", }, ], }; @@ -286,11 +283,14 @@ export function isAllowedReturnOrigin(profile: AppProfile, returnTo: string): bo } /** - * A connection target names something: non-empty after trimming whitespace. - * The one definition the start gate and the callback mint both use. + * A connection target names something: at least one letter or number that is + * not a default-ignorable code point (the Hangul and Khmer fillers are letters + * that render as nothing). An allowlist, so marks, private-use, unassigned and + * surrogate code points and symbols cannot stand in for a name. The one + * definition the start gate and the callback mint both use. */ export function isUsableConnectionTarget(targetId: string): boolean { - return targetId.trim().length > 0; + return /(?![\p{Default_Ignorable_Code_Point}])[\p{L}\p{N}]/u.test(targetId); } /** diff --git a/src/app.ts b/src/app.ts index 9492f74..b3c7755 100644 --- a/src/app.ts +++ b/src/app.ts @@ -3,7 +3,7 @@ import { deflateRawSync, inflateRawSync } from "node:zlib"; import cookie from "@fastify/cookie"; import cors from "@fastify/cors"; import Fastify, { type FastifyError, type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify"; -import { type AppCaller, resolveAppCaller } from "./app-caller.js"; +import { type AppCaller, isAppCaller, resolveAppCaller } from "./app-caller.js"; import { deliverBackendHandoff, type BackendHandoffPayload } from "./backend-handoff.js"; import { appSlugs, @@ -25,6 +25,7 @@ import { type Provider, } from "./contracts.js"; import { issueAccessClaim, proofCovers, proofTier, signAssertedStepUpClaim, STEP_UP_PROOF_TTL_SECONDS, type IssueAccessClaimInput } from "./claims.js"; +import { FixedWindowBudget, type FixedWindowLimit } from "./fixed-window.js"; import { builtInAppProfiles, getAppProfile, isAllowedReturnOrigin, serializeAppProfile, admitsProviderForMode, callbackMint, isUsableConnectionTarget } from "./app-profiles.js"; import { renderBrowserHandoffPage } from "./browser-handoff.js"; import { consentText, digestOfText, grantViews, GRANTS_PATH, renderConsentPage, renderGrantsPage, type ConsentAsk } from "./consent.js"; @@ -102,7 +103,6 @@ function buildOAuthStateToken(options: { entitlementPolicy: OAuthEntitlementPolicy | undefined; requestedScopes: string[] | undefined; stepUp: boolean | undefined; - firstLoginGrant: "invite" | undefined; keys: ReturnType; }): { token: string; jti: string; expiresAt: string } { const issuedAt = nowEpochSeconds(); @@ -126,7 +126,6 @@ function buildOAuthStateToken(options: { entitlement_policy: options.entitlementPolicy ?? null, requested_scopes: options.requestedScopes ?? null, step_up: options.stepUp ? true : null, - first_login_grant: options.firstLoginGrant ?? null, }; const token = signJwt(payload as unknown as Record, options.keys); @@ -191,8 +190,7 @@ function parseOAuthStatePayload(payload: Record): OAuthStatePay !entitlementPolicyIsValid || !(payload.initiator_account_id === undefined || payload.initiator_account_id === null || typeof payload.initiator_account_id === "string") || !requestedScopesAreValid || - !(payload.step_up === undefined || payload.step_up === null || payload.step_up === true) || - !(payload.first_login_grant === undefined || payload.first_login_grant === null || (payload.first_login_grant === "invite" && payload.mode === "sign_in")) + !(payload.step_up === undefined || payload.step_up === null || payload.step_up === true) ) { return null; } @@ -213,9 +211,6 @@ function parseOAuthStatePayload(payload: Record): OAuthStatePay if (!normalizedPayload.step_up) { normalizedPayload.step_up = null; } - if (!normalizedPayload.first_login_grant) { - normalizedPayload.first_login_grant = null; - } return normalizedPayload; } @@ -748,7 +743,7 @@ export async function startOAuthFlow( return { statusCode: 400, body: { error: "link_initiator_conflict", detail: "initiatingAccountId differs from the bearer's account." } }; } } else { - if (!caller || caller.appSlug !== profile.slug) { + if (!isAppCaller(caller) || caller.appSlug !== profile.slug) { return { statusCode: 401, body: { error: "app_auth_required" } }; } if (!input.initiatingAccountId) { @@ -767,7 +762,7 @@ export async function startOAuthFlow( // sign_in. A provider with no re-authentication parameter is refused here, // at start, so no step-up ever reaches the person without its step. if (input.stepUp) { - if (!caller || caller.appSlug !== profile.slug) { + if (!isAppCaller(caller) || caller.appSlug !== profile.slug) { return { statusCode: 401, body: { error: "app_auth_required" } }; } if (!providerCatalog[provider].stepUpAuthorizationParams) { @@ -828,26 +823,10 @@ export async function startOAuthFlow( if (options?.trustedBrowserAttemptId && handoff.kind === "browser_completion") { handoff = { kind: "browser_completion", attemptId: options.trustedBrowserAttemptId }; } - const requiresAppCaller = - Boolean(entitlementPolicy) || - Boolean(profile.startRequiresAppCaller) || - input.firstLoginGrant !== undefined || - (input.mode === "connect" && input.connection !== undefined); - if (requiresAppCaller && (!caller || caller.appSlug !== profile.slug)) { + if ((entitlementPolicy || profile.startRequiresAppCaller || (input.mode === "connect" && input.connection !== undefined)) && (!isAppCaller(caller) || caller.appSlug !== profile.slug)) { return { statusCode: 401, body: { error: "app_auth_required" } }; } - // A grant is the app's word that it invited this person: the app-caller gate above has already admitted only the profile's own app, - // and a caller without the secret learns nothing about what a grant needs. Here: only a profile that may grant, only on sign_in. - if (input.firstLoginGrant !== undefined) { - if (!(input.firstLoginGrant === "invite" && input.mode === "sign_in" && profile.mayGrantFirstLogin === true)) { - return { - statusCode: 400, - body: { error: "first_login_grant_refused", detail: "firstLoginGrant needs the app's own sign_in start, from an app that may grant." }, - }; - } - } - // After the app-secret gate, so a caller without the secret learns nothing about what a target must look like. if (input.connection !== undefined && !isUsableConnectionTarget(input.connection.targetId)) { return { @@ -886,7 +865,6 @@ export async function startOAuthFlow( entitlementPolicy, requestedScopes: input.requestedScopes, stepUp: input.stepUp, - firstLoginGrant: input.firstLoginGrant, keys, }); return { @@ -973,16 +951,43 @@ async function resolveAccessAccount( return (await resolveBearer(ctx, authorization))?.accountId ?? null; } +/** What an app may spend asserting step-up proofs: per member account, and per calling app. */ +export const STEP_UP_ASSERT_LIMITS: { account: FixedWindowLimit; app: FixedWindowLimit; notPermitted: FixedWindowLimit } = { + account: { max: 10, windowMs: 600_000 }, + app: { max: 120, windowMs: 60_000 }, + // An app whose profile has no grant, holding its own secret: a handful of refusals per window, no more. + notPermitted: { max: 5, windowMs: 60_000 }, +}; + +export interface StepUpAssertBudgets { + account: FixedWindowBudget; + app: FixedWindowBudget; + notPermitted: FixedWindowBudget; +} + +export function createStepUpAssertBudgets(now: () => number = () => Date.now()): StepUpAssertBudgets { + return { + account: new FixedWindowBudget(STEP_UP_ASSERT_LIMITS.account, now), + app: new FixedWindowBudget(STEP_UP_ASSERT_LIMITS.app, now), + notPermitted: new FixedWindowBudget(STEP_UP_ASSERT_LIMITS.notPermitted, now), + }; +} + /** * POST /v1/apps/{app}/step-up. The app says its member just passed a factor * the app checked; Heimdall cannot see the factor, so the word is bounded by * what the route demands: the app's secret AND the member's live bearer for - * that same app, the profile's explicit grant and method allowlist, and a nonce - * spent once per session. Every refusal after the secret verifies is audited - * with a digest of the nonce, never the nonce, the bearer or the secret. + * that same app, the profile's explicit grant and method allowlist, a nonce + * spent once per session, and a rate per account and per app. Every + * refusal after the secret verified is recorded, except that a flood is not: + * a rate-limited refusal is recorded once per window per budget (its first), + * and an app without the grant is recorded once per window; a request without + * the secret writes nothing, since anyone can send one. The audit rows carry a digest of + * the nonce, never the nonce, the bearer or the secret. */ export async function assertStepUp( ctx: Pick, + budgets: StepUpAssertBudgets, appSlug: AppSlug, headers: Record, input: { method: string; nonce: string } @@ -994,25 +999,31 @@ export async function assertStepUp( const permitted = getAppProfile(appSlug)?.stepUpAssertion; let known: { accountId: string; sessionId: string } | undefined; let nonceDigest: string | undefined; - const refuse = async (statusCode: number, error: string, extra: Record = {}): Promise => { + let tripped: string | undefined; + const refuse = async (statusCode: number, error: string, extra: Record = {}, record = true): Promise => { + if (!record) return { statusCode, body: { error, ...extra } }; await store.createAuditEvent({ ...(known ? { accountId: known.accountId, sessionId: known.sessionId } : {}), appSlug, eventType: "step_up_assertion_refused", - eventPayloadJson: { - outcome: "refused", - code: error, - method: permitted?.methods.includes(input.method) ? input.method : null, - nonceDigest: nonceDigest ?? null, - }, + eventPayloadJson: { outcome: "refused", code: error, budget: tripped ?? null, method: permitted?.methods.includes(input.method) ? input.method : null, nonceDigest: nonceDigest ?? null }, createdAt: new Date().toISOString(), }); return { statusCode, body: { error, ...extra } }; }; + // Audit only the first denial of a window: the rows record that a budget tripped, not every request behind it. + const limited = (budget: string, spent: { n: number; retryAfterSeconds: number }, max: number) => { + tripped = budget; + return refuse(429, "step_up_rate_limited", { retryAfterSeconds: spent.retryAfterSeconds }, spent.n === max + 1); + }; if (!permitted) { - return refuse(403, "step_up_assertion_not_permitted", { detail: `${appSlug} may not assert step-up proofs.` }); + const spent = budgets.notPermitted.spend(appSlug); + if (spent.retryAfterSeconds) return limited("notPermitted", spent, STEP_UP_ASSERT_LIMITS.notPermitted.max); + return refuse(403, "step_up_assertion_not_permitted", { detail: `${appSlug} may not assert step-up proofs.` }, spent.n === 1); } + const appSpent = budgets.app.spend(appSlug); + if (appSpent.retryAfterSeconds) return limited("app", appSpent, STEP_UP_ASSERT_LIMITS.app.max); const bearer = await resolveBearer(ctx, headers.authorization as string | undefined); if (!bearer) { @@ -1023,6 +1034,8 @@ export async function assertStepUp( if (bearer.claims.aud !== appSlug) { return refuse(403, "bearer_app_mismatch", { detail: `The access token was not issued to ${appSlug}.` }); } + const accountSpent = budgets.account.spend(bearer.accountId); + if (accountSpent.retryAfterSeconds) return limited("account", accountSpent, STEP_UP_ASSERT_LIMITS.account.max); nonceDigest = createHash("sha256").update(`heimdall-step-up-nonce\0${sessionId}\0${input.nonce}`).digest("hex"); if (!permitted.methods.includes(input.method)) { @@ -1296,7 +1309,7 @@ export async function refreshAppSession( }, }; } - if (entitlementPolicies.length > 0 && (!caller || caller.appSlug !== appSlug)) { + if (entitlementPolicies.length > 0 && (!isAppCaller(caller) || caller.appSlug !== appSlug)) { return { statusCode: 401, body: { error: "app_auth_required" } }; } @@ -1496,7 +1509,6 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { @@ -2135,15 +2142,6 @@ export async function buildApp(options: BuildAppOptions = {}): Promise( "/v1/apps/:appSlug/step-up", { @@ -2760,7 +2759,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { - const result = await assertStepUp({ config, keys, store }, request.params.appSlug, request.headers, request.body); + const result = await assertStepUp({ config, keys, store }, stepUpBudgets, request.params.appSlug, request.headers, request.body); reply.code(result.statusCode).header("cache-control", "no-store"); return result.body; } diff --git a/src/config.ts b/src/config.ts index 3f0461e..39ab96f 100644 --- a/src/config.ts +++ b/src/config.ts @@ -49,53 +49,6 @@ export interface HeimdallConfig { providers: Record; } -/** Secret inputs read via `readSecretInput` (as `NAME_FILE` under Idunn, or legacy plaintext `NAME`). */ -export const SECRET_ENV_NAMES: readonly string[] = [ - "GC_ACCESS_DATABASE_URL", - "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64", - "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET", - ...providers.map((provider) => `GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_SECRET`), - ...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_SHARED_SECRET`), -]; - -const NON_SECRET_ENV_NAMES: readonly string[] = [ - "HOST", - "PORT", - "GAMECULT_IDUNN_CANDIDATE_BIND", - "GAMECULT_IDUNN_PROCESS_WRITE_LEASE", - "GAMECULT_IDUNN_RUNTIME_BUNDLE", - "GC_ACCESS_BASE_URL", - "GC_ACCESS_ISSUER", - "GC_ACCESS_DATA_ROOT", - "GC_ACCESS_STORAGE_BACKEND", - "GC_ACCESS_PRIVATE_COMMAND_HOST", - "GC_ACCESS_PRIVATE_COMMAND_PORT", - "GC_ACCESS_CULTCACHE_PATH", - "GC_ACCESS_IDUNN_DAEMON", - "GC_ACCESS_IDUNN_RUDP_HEALTH", - "GC_ACCESS_IDUNN_HEALTH_CONTRACT", - "GC_ACCESS_PROVIDER_HEALTH_IDENTITY_PATH", - "GC_ACCESS_SESSION_TTL_SECONDS", - "GC_ACCESS_REFRESH_TTL_SECONDS", - "GC_ACCESS_STATE_TTL_SECONDS", - "GC_ACCESS_COMPLETION_TTL_SECONDS", - "GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP", - "GC_ACCESS_APPLY_SCHEMA_ON_STARTUP", - "GC_ACCESS_ODIN_CULTMESH_URI", - "GC_ACCESS_SIGNING_PRIVATE_KEY_PATH", - "GC_ACCESS_SIGNING_KEY_ID", - "GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT", - ...providers.map((provider) => `GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_ID`), - ...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_BACKEND_CALLBACK_URLS`), - ...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_RUNTIME_IDS`), -]; - -/** Canonical environment variable names read by `loadConfig` (using `*_FILE` for secrets). */ -export const ENV_NAMES: readonly string[] = [ - ...NON_SECRET_ENV_NAMES, - ...SECRET_ENV_NAMES.map((name) => `${name}_FILE`), -]; - function trimTrailingSlash(value: string): string { return value.replace(/\/+$/, ""); } diff --git a/src/contracts.ts b/src/contracts.ts index 9fa28f8..78a3a60 100644 --- a/src/contracts.ts +++ b/src/contracts.ts @@ -80,12 +80,6 @@ export interface OAuthStartRequest { entitlementPolicy?: OAuthEntitlementPolicy; /** Sign_in only, app-authenticated: ask the provider for a real re-authentication. Off when absent. */ stepUp?: boolean; - /** - * Sign_in only, from an app whose profile may grant (`mayGrantFirstLogin`): the app has - * invited this person, so a provider that otherwise requires a link may mint the - * first account. Carried in the signed state; never read from a browser. - */ - firstLoginGrant?: "invite"; } export interface OAuthStatePayload { @@ -109,8 +103,6 @@ export interface OAuthStatePayload { requested_scopes: string[] | null; /** The start's step-up request. Signed, so the launch hop reads it here and nowhere else; null when not asked. */ step_up: true | null; - /** The start's first-login grant. Signed, so only the app's own start can set it; null when not granted. */ - first_login_grant: "invite" | null; } export interface LinkedIdentityInput { diff --git a/src/fixed-window.ts b/src/fixed-window.ts new file mode 100644 index 0000000..cfb7f00 --- /dev/null +++ b/src/fixed-window.ts @@ -0,0 +1,49 @@ +// A fixed-window attempt budget per key, held in memory by the process that +// serves the route. It bounds a credentialed caller's rate; it is not a +// security boundary on its own and resets on restart. The clock is injected +// so tests can move it. + +export interface FixedWindowLimit { + max: number; + windowMs: number; +} + +export class FixedWindowBudget { + private readonly windows = new Map(); + + constructor( + private readonly limit: FixedWindowLimit, + private readonly now: () => number = Date.now, + private readonly maxKeys = 4096, + ) {} + + /** + * Spend one attempt for `key`. `n` counts attempts in the window, denied ones + * included, so a caller can act on the first denial (`n === max + 1`) and not + * on the flood behind it. `retryAfterSeconds` is 0 when allowed. + */ + spend(key: string): { n: number; retryAfterSeconds: number } { + const at = this.now(); + let current = this.windows.get(key); + if (!current || at - current.startedAt >= this.limit.windowMs) { + this.sweep(at); + current = { startedAt: at, used: 0 }; + this.windows.set(key, current); + } + current.used += 1; + if (current.used <= this.limit.max) return { n: current.used, retryAfterSeconds: 0 }; + return { n: current.used, retryAfterSeconds: Math.max(1, Math.ceil((current.startedAt + this.limit.windowMs - at) / 1000)) }; + } + + /** Drop turned-over windows once the table is full; if it is still full, the oldest key goes. */ + private sweep(at: number): void { + if (this.windows.size < this.maxKeys) return; + for (const [key, window] of this.windows) { + if (at - window.startedAt >= this.limit.windowMs) this.windows.delete(key); + } + if (this.windows.size >= this.maxKeys) { + const oldest = this.windows.keys().next().value; + if (oldest !== undefined) this.windows.delete(oldest); + } + } +} diff --git a/src/private-command-plane.ts b/src/private-command-plane.ts index fe569d1..8e9fb8d 100644 --- a/src/private-command-plane.ts +++ b/src/private-command-plane.ts @@ -9,6 +9,7 @@ import { import { type FastifyInstance } from "fastify"; import { errorIdentity, getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow, verifyRefreshToken } from "./app.js"; import { callerFromOpenedEnvelope } from "./app-caller.js"; +import { getAppProfile } from "./app-profiles.js"; import { executeHeimdallAccessPlugin, HEIMDALL_ACCESS_PLUGIN_ID, type EvePluginAbiRequest } from "./access-plugin.js"; import { isAppSlug, oauthModes, providers, type AppSlug, type OAuthEntitlementPolicy, type OAuthMode, type Provider } from "./contracts.js"; import { type HeimdallConfig } from "./config.js"; @@ -232,6 +233,7 @@ async function refreshAuth( // handler function the HTTP route uses rather than forging the HTTP header // back at itself. const context = getHeimdallRuntimeContext(app); + await requireEntitlementPolicyIfProfileDemandsIt(appSlug, entitlementPolicy, "refresh"); const result = await refreshAppSession(context, appSlug, callerFromOpenedEnvelope(appSlug), { refreshToken, ...(entitlementPolicy ? { entitlementPolicy } : {}), @@ -266,10 +268,8 @@ async function beginAuth( const returnTo = String(payload.returnTo ?? ""); if (!providers.includes(provider) || !oauthModes.includes(mode) || !returnTo) throw new Error("Auth begin payload is incomplete."); const entitlementPolicy = parseEntitlementPolicy(payload.entitlementPolicy); - // The app's word that it invited this person (the Dungeon holds the invite). Only the literal "invite" is a grant; startOAuthFlow's gate decides whether this app and mode may carry one. - const grant = payload.firstLoginGrant; - if (grant !== undefined && grant !== null && grant !== "invite") throw new Error("Auth begin payload is incomplete."); const store = getHeimdallRuntimeContext(app).store; + await requireEntitlementPolicyIfProfileDemandsIt(appSlug, entitlementPolicy, "authentication"); const now = new Date(); const attempt = await store.createAuthAttempt({ handle: randomUUID(), @@ -292,7 +292,6 @@ async function beginAuth( returnTo, handoff: { kind: "browser_completion" }, ...(entitlementPolicy ? { entitlementPolicy } : {}), - ...(grant === "invite" ? { firstLoginGrant: "invite" as const } : {}), }, { trustedBrowserAttemptId: attempt.handle } ); @@ -388,6 +387,25 @@ function parseEntitlementPolicy(value: unknown): OAuthEntitlementPolicy | undefi return undefined; } +/** + * Ghostlight requires its caller-owned Discord role policy on every begin and + * refresh; that used to be a literal `appSlug === "ghostlight"` branch here. + * The requirement is now data on the app's profile + * (AppProfile.requiredEntitlementPolicyKind), so a future app with the same + * need declares it in its profile instead of adding another branch. + */ +async function requireEntitlementPolicyIfProfileDemandsIt( + appSlug: AppSlug, + entitlementPolicy: OAuthEntitlementPolicy | undefined, + action: "authentication" | "refresh", +): Promise { + const profile = getAppProfile(appSlug); + const requiredKind = profile?.requiredEntitlementPolicyKind; + if (requiredKind && entitlementPolicy?.kind !== requiredKind) { + throw new Error(`${appSlug} ${action} requires its caller-owned ${requiredKind} policy.`); + } +} + function response( request: CultNetOperationRequestMessage, status: string, diff --git a/src/store/index.ts b/src/store/index.ts index 18c52d5..69abbe6 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -32,7 +32,13 @@ export async function createStore(config: HeimdallConfig): Promise undefined); - throw new Error(`Postgres storage could not be prepared (${typeof code === "string" ? code : "error"}); check GC_ACCESS_DATABASE_URL_FILE.`); + // A role that may not create temporary tables is not a bad URL, so that + // refusal names the privilege instead. + const remedy = + code === "SCHEMA_TEMP_PRIVILEGE" + ? "grant the database role TEMPORARY on its database" + : "check GC_ACCESS_DATABASE_URL_FILE"; + throw new Error(`Postgres storage could not be prepared (${typeof code === "string" ? code : "error"}); ${remedy}.`); } return store; diff --git a/src/store/postgres.ts b/src/store/postgres.ts index 6469101..f0da059 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto"; import { Pool, type PoolClient, type QueryResultRow } from "pg"; import { type AppSlug, type HeimdallAuthAttemptStatus, type LinkedIdentityInput, type Provider } from "../contracts.js"; import { decideMove, movedRecord, type MoveFacts } from "./identity-move.js"; -import { CORE_TABLES, CREATE_SCHEMA_SQL } from "./schema.js"; +import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "./schema.js"; import { type CreateAccountInput, type CreateAuthAttemptInput, @@ -411,6 +411,279 @@ function mapAuthAttemptRow(row: AuthAttemptRow): StoredAuthAttempt { return attempt; } +/** + * The AND-ed conditions of a predicate as Postgres prints it, each without a + * pair of parentheses that encloses all of it. Postgres flattens a chain of + * ANDs into one list, so `((a) AND (b) AND (c))` yields `a`, `b`, `c`. An OR, + * or an AND nested under one, stays whole: `((a OR b) AND c)` yields `a OR b` + * and `c`, and `(a OR (b AND c))` yields itself. Quoted text is never split. + */ +export function predicateConditions(printed: string): string[] { + const unwrap = (text: string): string => { + let current = text.trim(); + while (current.startsWith("(") && closingParenthesis(current, 0) === current.length - 1) { + current = current.slice(1, -1).trim(); + } + return current; + }; + const whole = unwrap(printed); + if (whole === "") return []; + const parts: string[] = []; + let depth = 0; + let quote: string | undefined; + let start = 0; + for (let position = 0; position < whole.length; position += 1) { + const character = whole[position]!; + if (quote) { + if (character === quote) quote = undefined; + } else if (character === "'" || character === '"') { + quote = character; + } else if (character === "(") { + depth += 1; + } else if (character === ")") { + depth -= 1; + } else if (depth === 0 && whole.startsWith(" AND ", position)) { + parts.push(whole.slice(start, position)); + start = position + " AND ".length; + position = start - 1; + } + } + parts.push(whole.slice(start)); + return parts.map(unwrap); +} + +/** The index of the parenthesis closing the one at `open`, outside quoted text, or -1. */ +function closingParenthesis(text: string, open: number): number { + let depth = 0; + let quote: string | undefined; + for (let position = open; position < text.length; position += 1) { + const character = text[position]!; + if (quote) { + if (character === quote) quote = undefined; + } else if (character === "'" || character === '"') { + quote = character; + } else if (character === "(") { + depth += 1; + } else if (character === ")") { + depth -= 1; + if (depth === 0) return position; + } + } + return -1; +} + +/** + * Whether an index predicate, as Postgres prints it, keeps exactly the rows + * the declared one (printed the same way) does: the same set of AND-ed + * conditions, ignoring `key_column IS NOT NULL` unless the index treats NULLs + * as equal, since otherwise rows with a NULL key never collide anyway. + */ +export function samePredicate(declared: string, actual: string, keyColumns: string[], nullsNotDistinct: boolean): boolean { + // A key without a predicate must have none: ON CONFLICT cannot infer a + // partial index as its arbiter. + if (predicateConditions(declared).length === 0) return actual.trim() === ""; + const redundant = new Set(nullsNotDistinct ? [] : keyColumns.map((column) => `${column} IS NOT NULL`)); + const conditions = (printed: string) => + [...new Set(predicateConditions(printed).filter((condition) => !redundant.has(condition)))].sort(); + const left = conditions(declared); + const right = conditions(actual); + return left.length === right.length && left.every((condition, index) => condition === right[index]); +} + +/** + * What the store's statements do to each table, and so the privileges its + * database role needs: it reads what it returns or looks up, inserts what it + * creates, updates what it changes or upserts, and deletes two things: + * expired oauth_state_uses rows (which needs SELECT for its WHERE), and the one + * linked_identities row an unlink names (unlinkLinkedIdentity, the only + * delete there; it needs SELECT for its WHERE and for the account's count). + * identity_moves is append-only. moveIdentities is the statement that updates + * linked_identities.account_id (its one writer), sessions, pending_links and + * auth_completions, all of which already hold UPDATE. + * audit_events is written and never read back. + */ +export const STORE_TABLE_PRIVILEGES: Readonly> = { + accounts: ["SELECT", "INSERT", "UPDATE"], + linked_identities: ["SELECT", "INSERT", "UPDATE", "DELETE"], + sessions: ["SELECT", "INSERT", "UPDATE"], + auth_attempts: ["SELECT", "INSERT", "UPDATE"], + private_command_receipts: ["SELECT", "INSERT"], + auth_completions: ["SELECT", "INSERT", "UPDATE"], + pending_links: ["SELECT", "INSERT", "UPDATE"], + oauth_state_uses: ["SELECT", "INSERT", "DELETE"], + capability_grants: ["SELECT", "INSERT"], + entitlement_snapshots: ["SELECT", "INSERT", "UPDATE"], + consent_receipts: ["SELECT", "INSERT"], + identity_moves: ["SELECT", "INSERT"], + audit_events: ["INSERT"], +}; + +/** What a database must hold for a store to serve it; see checkSchemaRequirements. */ +export interface SchemaRequirements { + tables: readonly string[]; + columns: readonly { table: string; column: string; type: string; nullable: boolean }[]; + keys: readonly { table: string; columns: string; predicate: string }[]; + privileges: Readonly>; +} + +/** What Heimdall's store needs, read from its schema and its statements. */ +export const HEIMDALL_SCHEMA_REQUIREMENTS: SchemaRequirements = { + tables: REQUIRED_TABLES, + columns: REQUIRED_COLUMNS, + keys: REQUIRED_KEYS, + privileges: STORE_TABLE_PRIVILEGES, +}; + +/** + * Each required key's predicate as Postgres prints it back (empty for none). + * One simple-protocol round trip on one connection: a transaction that builds + * a temporary copy of each keyed table's declared columns, indexes it with the + * declared predicate, reads the printed form and rolls back. The names and SQL + * come from the requirements, which are constants, never input. A role that + * may not create temporary tables fails with code SCHEMA_TEMP_PRIVILEGE. + */ +export async function printedDeclaredPredicates(pool: Pick, requirements: SchemaRequirements): Promise { + const partial = requirements.keys.flatMap((required, index) => (required.predicate ? [{ ...required, index }] : [])); + if (partial.length === 0) return requirements.keys.map(() => ""); + const statements = partial.flatMap(({ table, columns, predicate, index }) => { + const probe = `heimdall_key_probe_${index}`; + const declared = requirements.columns + .filter((column) => column.table === table) + .map((column) => `${column.column} ${column.type}`) + .join(", "); + return [ + `CREATE TEMP TABLE ${probe} (${declared}) ON COMMIT DROP`, + `CREATE UNIQUE INDEX ${probe}_idx ON ${probe} (${columns}) WHERE ${predicate}`, + ]; + }); + const select = partial + .map(({ index }) => `SELECT ${index} AS key, pg_get_expr(indpred, indrelid) AS predicate FROM pg_index WHERE indexrelid = 'pg_temp.heimdall_key_probe_${index}_idx'::regclass`) + .join(" UNION ALL "); + let results: Array<{ rows: Array<{ key: number; predicate: string }> }>; + try { + results = (await pool.query(["BEGIN", ...statements, select, "ROLLBACK"].join(";\n"))) as unknown as typeof results; + } catch (error) { + if ((error as { code?: unknown }).code === "42501") { + throw Object.assign(new Error("The Heimdall database role may not create temporary tables."), { code: "SCHEMA_TEMP_PRIVILEGE" }); + } + throw error; + } + const printed = results[results.length - 2]!.rows; + return requirements.keys.map((_, index) => printed.find((row) => row.key === index)?.predicate ?? ""); +} + +/** + * Proves that the database can take a store's requests: every required + * table; every column with its declared type, under a deterministic + * collation, and nullable where declared nullable; every unique key; and + * every privilege, held on the table or on each of its columns. A missing or + * altered piece fails with code SCHEMA_MISSING and a missing privilege with + * SCHEMA_PRIVILEGES; neither error names the piece. + * + * A key is met by a unique index on its table that is valid (a failed + * CREATE INDEX CONCURRENTLY or an interrupted DROP INDEX CONCURRENTLY leaves + * one that is not; Postgres never marks an index valid before it is ready), + * immediate (ON CONFLICT refuses a deferrable arbiter), has exactly the key's + * columns as its key columns (INCLUDE columns aside), compares them under + * deterministic collations (a case-insensitive one would merge two + * providers' user ids into one row), and has the key's predicate. A + * predicate matches when both, as Postgres prints them, are the same set of + * AND-ed conditions; a `key_column IS NOT NULL` condition may be absent on + * either side, because a unique index never makes NULL keys collide unless + * it is NULLS NOT DISTINCT. Postgres prints the declared predicates itself + * (printedDeclaredPredicates). + * + * What this does not prove is listed where the schema is: see schema.ts. + */ +export async function checkSchemaRequirements(pool: Pick, requirements: SchemaRequirements): Promise { + const declaredPredicates = await printedDeclaredPredicates(pool, requirements); + const privileges = Object.entries(requirements.privileges).flatMap(([table, wanted]) => + wanted.map((privilege) => ({ table, privilege })) + ); + const result = await pool.query<{ + kind: "missing" | "privilege" | "candidate"; + key: number | null; + predicate: string | null; + nulls_not_distinct: boolean | null; + }>( + ` + SELECT 'missing' AS kind, NULL::int AS key, NULL::text AS predicate, NULL::boolean AS nulls_not_distinct + FROM unnest($1::text[]) AS name WHERE to_regclass(name) IS NULL + UNION ALL + SELECT 'missing', NULL, NULL, NULL + FROM unnest($2::text[], $3::text[], $4::text[], $5::boolean[]) AS required(table_name, column_name, type_name, nullable) + WHERE NOT EXISTS ( + SELECT 1 FROM pg_attribute a + WHERE a.attrelid = to_regclass(required.table_name) + AND a.attname = required.column_name + AND a.attnum > 0 + AND NOT a.attisdropped + AND a.atttypid = to_regtype(required.type_name) + AND (NOT required.nullable OR NOT a.attnotnull) + AND NOT EXISTS (SELECT 1 FROM pg_collation c WHERE c.oid = a.attcollation AND NOT c.collisdeterministic) + ) + UNION ALL + SELECT 'candidate', required.key::int, pg_get_expr(i.indpred, i.indrelid), + coalesce((to_jsonb(i) ->> 'indnullsnotdistinct')::boolean, false) + FROM unnest($6::text[], $7::text[]) WITH ORDINALITY AS required(table_name, columns, key) + JOIN pg_index i ON i.indrelid = to_regclass(required.table_name) + WHERE i.indisunique + AND i.indisvalid + AND i.indimmediate + AND i.indnkeyatts = cardinality(string_to_array(required.columns, ',')) + AND ( + SELECT string_agg(a.attname, ',' ORDER BY a.attname) + FROM unnest(i.indkey::int2[]) WITH ORDINALITY AS key(attnum, position) + JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = key.attnum + WHERE key.position <= i.indnkeyatts + ) = required.columns + AND NOT EXISTS ( + SELECT 1 FROM unnest(i.indcollation::oid[]) WITH ORDINALITY AS key_collation(oid, position) + JOIN pg_collation c ON c.oid = key_collation.oid + WHERE key_collation.position <= i.indnkeyatts AND NOT c.collisdeterministic + ) + UNION ALL + SELECT 'privilege', NULL, NULL, NULL + FROM unnest($8::text[], $9::text[]) AS required(table_name, privilege) + WHERE EXISTS ( + SELECT 1 FROM unnest($2::text[], $3::text[]) AS used(table_name, column_name) + JOIN pg_attribute a ON a.attrelid = to_regclass(used.table_name) AND a.attname = used.column_name AND NOT a.attisdropped + WHERE used.table_name = required.table_name + AND NOT CASE WHEN required.privilege = 'DELETE' + THEN has_table_privilege(a.attrelid, 'DELETE') -- DELETE is a row privilege, never held per column + ELSE has_column_privilege(a.attrelid, a.attnum, required.privilege) END + ) + `, + [ + requirements.tables, + requirements.columns.map((required) => required.table), + requirements.columns.map((required) => required.column), + requirements.columns.map((required) => required.type), + requirements.columns.map((required) => required.nullable), + requirements.keys.map((required) => required.table), + requirements.keys.map((required) => required.columns), + privileges.map((required) => required.table), + privileges.map((required) => required.privilege), + ] + ); + const keyMet = requirements.keys.map((required, index) => + result.rows.some( + (row) => + row.kind === "candidate" && + row.key === index + 1 && + samePredicate(declaredPredicates[index]!, row.predicate ?? "", required.columns.split(","), row.nulls_not_distinct === true) + ) + ); + if (result.rows.some((row) => row.kind === "missing") || keyMet.includes(false)) { + throw Object.assign(new Error("The Heimdall schema is not applied."), { code: "SCHEMA_MISSING" }); + } + if (result.rows.some((row) => row.kind === "privilege")) { + throw Object.assign(new Error("The Heimdall database role lacks a privilege the store needs."), { + code: "SCHEMA_PRIVILEGES", + }); + } +} + export class PostgresStore implements HeimdallStore { constructor(private readonly pool: Pick) {} @@ -418,16 +691,9 @@ export class PostgresStore implements HeimdallStore { await this.pool.query(CREATE_SCHEMA_SQL); } - /** Verifies database connectivity and that the core schema tables exist. */ + /** Proves, before Heimdall serves, that the database can take its requests (checkSchemaRequirements). */ async checkSchema(): Promise { - await this.pool.query("SELECT 1"); - const result = await this.pool.query<{ name: string }>( - "SELECT name FROM unnest($1::text[]) AS name WHERE to_regclass('public.' || name) IS NULL", - [CORE_TABLES] - ); - if (result.rows.length > 0) { - throw Object.assign(new Error("The Heimdall schema is not applied."), { code: "SCHEMA_MISSING" }); - } + await checkSchemaRequirements(this.pool, HEIMDALL_SCHEMA_REQUIREMENTS); } async close(): Promise { diff --git a/src/store/schema.ts b/src/store/schema.ts index b91139f..ff1fcf2 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -253,18 +253,85 @@ CREATE INDEX IF NOT EXISTS audit_events_lookup_idx ON audit_events(account_id, session_id, app_slug, created_at); `; -export const CORE_TABLES = [ - "accounts", - "linked_identities", - "sessions", - "auth_attempts", - "private_command_receipts", - "pending_links", - "auth_completions", - "oauth_state_uses", - "capability_grants", - "entitlement_snapshots", - "consent_receipts", - "identity_moves", - "audit_events", -] as const; +const schemaText = CREATE_SCHEMA_SQL.replace(/\r\n/g, "\n"); +const createdTables = [...schemaText.matchAll(/^CREATE TABLE IF NOT EXISTS (\w+) \(\n([\s\S]*?)\n\);/gm)].map((match) => ({ + table: match[1]!, + lines: match[2]!.split("\n").map((line) => line.trim().replace(/,$/, "")), +})); + +/** Sorted and comma-separated, the form the schema check compares key columns in. */ +function columnList(text: string): string { + return text.split(",").map((column) => column.trim()).sort().join(","); +} + +/** The columns of a `PRIMARY KEY (a, b)` or `UNIQUE(a, b)` line, as a column list. */ +function keyColumns(line: string, keyword: "PRIMARY KEY" | "UNIQUE"): string | undefined { + const match = new RegExp(`^${keyword}\\s*\\(([^)]*)\\)`).exec(line); + return match ? columnList(match[1]!) : undefined; +} + +/* + * What every start must find before it serves, read from the SQL above so the + * two cannot drift. A start that applies the schema checks as well, because + * CREATE ... IF NOT EXISTS leaves a damaged table as it is. Indexes that only + * speed lookups are not required; the unique ones are, by shape, in + * REQUIRED_KEYS. + * + * Out of scope, each able to make a write fail on a database that passes the + * check: CHECK constraints; triggers; row-level security; unique indexes + * beyond the required keys, or stricter than them, including the leftovers of + * an interrupted concurrent index build (a valid extra one refuses rows the + * store expects to write, and even an invalid one that is ready is enforced + * on writes); NOT NULL columns the schema does not declare and that have no + * default, which the store's INSERTs leave out; and SELECT granted column by + * column when a statement reads `SELECT *` or `RETURNING *`, which needs + * SELECT on every column the table has, not only the declared ones. + */ + +/** Every table the schema creates. */ +export const REQUIRED_TABLES = createdTables.map(({ table }) => table); + +/** + * Every column a created table declares and every column the schema adds to + * an existing table, each with its declared type, and whether it is nullable: + * the store reads and writes values as that type, and leaves a nullable + * column null, so a column retyped or made NOT NULL under it fails its writes. + */ +export const REQUIRED_COLUMNS = [ + ...createdTables.flatMap(({ table, lines }) => + lines + .filter((line) => !/^(?:PRIMARY KEY|UNIQUE|FOREIGN KEY)\b/.test(line)) + .map((line) => { + const [, column, type] = /^(\w+) (\w+)/.exec(line)!; + return { table, column: column!, type: type!, nullable: !/\b(?:NOT NULL|PRIMARY KEY)\b/.test(line) }; + }) + ), + ...[...schemaText.matchAll(/^ALTER TABLE (\w+) ADD COLUMN IF NOT EXISTS (\w+) (\w+)([^;]*);/gm)].map((match) => ({ + table: match[1]!, + column: match[2]!, + type: match[3]!, + nullable: !/\b(?:NOT NULL|PRIMARY KEY)\b/.test(match[4]!), + })), +]; + +/** + * Every unique key the schema makes: the primary keys and unique constraints + * of the created tables, and each unique index it creates, with that index's + * predicate as the schema writes it (empty for none). Any index of the right + * shape serves, whatever its name; PostgresStore.checkSchema says what the + * right shape is. + */ +export const REQUIRED_KEYS = [ + ...createdTables.flatMap(({ table, lines }) => + lines.flatMap((line) => { + const columns = + /^(\w+) .*\bPRIMARY KEY\b/.exec(line)?.[1] ?? keyColumns(line, "PRIMARY KEY") ?? keyColumns(line, "UNIQUE"); + return columns ? [{ table, columns, predicate: "" }] : []; + }) + ), + ...[...schemaText.matchAll(/^CREATE UNIQUE INDEX IF NOT EXISTS \w+\s+ON (\w+)\(([^)]*)\)(?:\s+WHERE ([^;]+))?;/gm)].map((match) => ({ + table: match[1]!, + columns: columnList(match[2]!), + predicate: (match[3] ?? "").replace(/\s+/g, " ").trim(), + })), +]; diff --git a/src/verifier.ts b/src/verifier.ts new file mode 100644 index 0000000..81b303a --- /dev/null +++ b/src/verifier.ts @@ -0,0 +1,161 @@ +import { createPublicKey, type KeyObject } from "node:crypto"; +import { isAppSlug, providers, type AccessClaimPayload, type AppSlug, type LinkedIdentityInput, type Provider } from "./contracts.js"; +import { type PublicSigningJwk, verifyJwt } from "./signing.js"; + +export interface HeimdallVerifierOptions { + issuer: string; + appSlug: AppSlug; + jwks: { + keys: PublicSigningJwk[]; + }; + allowedClockSkewSeconds?: number; +} + +export type VerifyAccessTokenResult = + | { + valid: true; + header: Record; + claimSet: AccessClaimPayload; + } + | { + valid: false; + error: string; + }; + +function isLinkedIdentity(value: unknown): value is LinkedIdentityInput { + if (!value || typeof value !== "object") { + return false; + } + + const record = value as Record; + if ( + typeof record.provider !== "string" || + !providers.includes(record.provider as Provider) || + typeof record.providerUserId !== "string" + ) { + return false; + } + + if (record.username !== undefined && typeof record.username !== "string") { + return false; + } + + if (record.displayName !== undefined && typeof record.displayName !== "string") { + return false; + } + + return true; +} + +function parseAccessClaimPayload(payload: Record): AccessClaimPayload | null { + if ( + payload.typ !== "heimdall_access" || + typeof payload.iss !== "string" || + typeof payload.aud !== "string" || + !isAppSlug(payload.aud) || + typeof payload.sub !== "string" || + typeof payload.sid !== "string" || + typeof payload.jti !== "string" || + typeof payload.iat !== "number" || + typeof payload.nbf !== "number" || + typeof payload.exp !== "number" || + typeof payload.account_id !== "string" || + typeof payload.access_revision !== "number" || + !payload.app || + typeof payload.app !== "object" || + typeof (payload.app as Record).slug !== "string" || + !isAppSlug((payload.app as Record).slug) || + typeof (payload.app as Record).profile_version !== "string" || + !Array.isArray(payload.facts) || + !payload.facts.every((fact) => typeof fact === "string") || + !Array.isArray(payload.capabilities) || + !payload.capabilities.every((capability) => typeof capability === "string") || + !Array.isArray(payload.identities) || + !payload.identities.every(isLinkedIdentity) + ) { + return null; + } + + if (payload.display_name !== undefined && typeof payload.display_name !== "string") { + return null; + } + + return payload as unknown as AccessClaimPayload; +} + +function buildKeyIndex(jwks: { keys: PublicSigningJwk[] }): Map { + return new Map( + jwks.keys.map((jwk) => [ + jwk.kid, + createPublicKey({ + key: jwk, + format: "jwk", + }), + ]) + ); +} + +export function createHeimdallAccessTokenVerifier(options: HeimdallVerifierOptions): { + verify(token: string, now?: Date): VerifyAccessTokenResult; +} { + const keyIndex = buildKeyIndex(options.jwks); + const allowedClockSkewSeconds = Math.max(0, Math.trunc(options.allowedClockSkewSeconds ?? 30)); + + return { + verify(token: string, now = new Date()): VerifyAccessTokenResult { + const [encodedHeader] = token.split("."); + if (!encodedHeader) { + return { valid: false, error: "Malformed JWT." }; + } + + let header: Record; + try { + header = JSON.parse(Buffer.from(encodedHeader, "base64url").toString("utf8")) as Record; + } catch { + return { valid: false, error: "Malformed JWT header." }; + } + + if (header.alg !== "EdDSA" || typeof header.kid !== "string") { + return { valid: false, error: "Unsupported JWT signing header." }; + } + + const publicKey = keyIndex.get(header.kid); + if (!publicKey) { + return { valid: false, error: `Unknown signing key id '${header.kid}'.` }; + } + + const verified = verifyJwt(token, publicKey); + if (!verified.valid) { + return verified; + } + + const claimSet = parseAccessClaimPayload(verified.payload); + if (!claimSet) { + return { valid: false, error: "JWT payload is not a valid Heimdall access claim." }; + } + + if (claimSet.iss !== options.issuer) { + return { valid: false, error: "JWT issuer does not match the configured Heimdall issuer." }; + } + + if (claimSet.aud !== options.appSlug || claimSet.app.slug !== options.appSlug) { + return { valid: false, error: "JWT audience does not match the expected app slug." }; + } + + const nowEpochSeconds = Math.floor(now.getTime() / 1000); + if (claimSet.nbf > nowEpochSeconds + allowedClockSkewSeconds) { + return { valid: false, error: "JWT is not valid yet." }; + } + + if (claimSet.exp <= nowEpochSeconds - allowedClockSkewSeconds) { + return { valid: false, error: "JWT has expired." }; + } + + return { + valid: true, + header: verified.header, + claimSet, + }; + }, + }; +} diff --git a/state/branches.json b/state/branches.json new file mode 100644 index 0000000..32cd28f --- /dev/null +++ b/state/branches.json @@ -0,0 +1,26 @@ +{ + "branches": [ + { + "id": "main", + "hypothesis": "A shared Heimdall authority service on Yggdrasil can be reused across hosted experiments if OAuth, sessions, grants, and capability machinery are centralized while app-domain data and routine route authorization stay app-local.", + "status": "active", + "artifacts": [ + "state/map.yaml", + "state/scratch.md", + "state/evidence.jsonl", + "docs/architecture.md", + "docs/implementation-plan.md" + ], + "notes": "Current mainline. Repixelizer is the first auth-blank binding target; StreamPixels is the migration and boundary stress test." + }, + { + "id": "eureka/joystick-h1", + "hypothesis": "One locked refresh primitive plus a Joystick OAuth provider in Heimdall lets StreamPixels ingest Joystick without ever presenting a provider refresh token.", + "status": "accepted", + "artifacts": [ + "state/map.yaml" + ], + "notes": "Merged as PR GameCult/Heimdall#1 (d51fa6b), deployed to Yggdrasil 2026-10-19 15:51Z; gamecult-ops 210a1af. Campaign joystick:campaign:self." + } + ] +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index fa1268b..279b21e 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -41,4 +41,3 @@ {"ts": "2026-11-13T19:10:00+00:00", "type": "design", "status": "accepted", "note": "Changelog 2026-11-13: GET /v1/me/identities lists an account's identities (no credentials, profile or email); POST /v1/me/identities/:id/unlink deletes one with a step-up proof (access claim step_up_at, 600 s, never carried by refresh), refuses the last identity (409), writes revocation receipts when the provider's last identity goes. upsertLinkedIdentity no longer moves an identity between accounts (IdentityHeldElsewhereError; links/confirm 409 identity_linked_elsewhere, callback link_initiator_mismatch). The store role needs DELETE on linked_identities (startup refuses without it): owner-role GRANT at deploy."} {"ts": "2026-11-13T20:01:42+00:00", "type": "design", "status": "accepted", "note": "Changelog 2026-11-13: POST /v1/apps/{app}/step-up (profile grant stepUpAssertion, bifrost only; methods bifrost-passkey, bifrost-email-code). App secret plus the member's live bearer for that app; mints a same-session access token with step_up_at now and new claim step_up_method (exp kept, no refresh, no session write); nonce single-use via oauth_state_uses phase step_up_assert (no schema change), retained to the session expiry as of the claim (a refresh may slide the session past it); in-process rate limits 10 per 600 s per account, 120 per 60 s per app; audit step_up_asserted and step_up_assertion_refused with a nonce digest (429s and not-permitted refusals audited once per window; not-permitted has a 5 per 60 s per-app budget); nonce is base64url 16-128. Provider step-up sign-ins now carry step_up_method provider:; identity_unlinked records stepUpMethod. Heimdall cannot verify the factor: it trusts the calling app. Not deployed; no env, secret or migration. For heimdall-body:follow_up:chat-s7419-7419.", "branch": "heimdall/app-asserted-step-up"} {"ts": "2026-11-14T01:10:00+00:00", "type": "design", "status": "accepted", "note": "Changelog 2026-11-14: POST /v1/apps/{app}/identity-moves (profile grant identityMoves, bifrost only; accountProofMethods bifrost-passkey) and the identity_moves table, the only writer of linked_identities.account_id (moveIdentities, one transaction, accounts locked in id order, shared decideMove on both stores). Access claims gain auth_at and auth_identity_id (sign_in callback only). proofTier is the one freshness rule (unlink reads it; strong 600 s step_up_at, weak 300 s auth_at); proofCovers: only an asserted account-proof method covers a whole account, otherwise the login in auth_identity_id (ruling move-proof-strict-passkey). Moves strip credentials, revoke the source's sessions, expire its pending links and unredeemed completions, write revocation receipts under the source, audit identity_moved; moveId is idempotent (replay answers the stored receipt without proof liveness); a move is reversible once. Not deployed: the owner must apply the identity_moves DDL and GRANT SELECT, INSERT ON identity_moves to the store role before the new build starts (startup refuses SCHEMA_MISSING / SCHEMA_PRIVILEGES otherwise).", "branch": "heimdall/identity-moves"} -{"ts": "2026-12-02T22:23:49+00:00", "type": "design", "status": "accepted", "note": "ghostlight/google-sign-in: ghostlight admits Google, requires the app secret on every start (login-CSRF), accepts firstLoginGrant 'invite' on private-plane begin, app_access = identity.authenticated, no Discord role policy (requiredEntitlementPolicyKind and its guard deleted). Admission is the Dungeon's catalog. Not deployed. Local pnpm test: only pre-existing entrypoint-secrets failure on Windows; StrykerJS not configured, two hand mutants killed."} diff --git a/state/map.yaml b/state/map.yaml new file mode 100644 index 0000000..4aa4d5a --- /dev/null +++ b/state/map.yaml @@ -0,0 +1,130 @@ +project: + name: Heimdall + status: active + phase: streampixels_migration + premise: > + Build Heimdall as one reusable GameCult auth authority service for OAuth, + linked identities, local sessions, grants, and capability claims without + mixing in app-domain audience or product data. + +objective: + primary: > + Create a shared auth authority service that Repixelizer, StreamPixels, and + future GameCult-hosted experiments can consume. + current: > + Publish the Heimdall Eve access plugin and private CultNet authentication + plane, then migrate Ghostlight onto app-local sessions without moving + campaign or membership authority into Heimdall. + +constraints: + - Heimdall owns auth/control-plane authority; app-domain data stays app-owned by default. + - Prefer a same-host Heimdall service on Yggdrasil over duplicated per-app provider stacks. + - Host apps verify signed claims locally for routine guarded routes. + - App profiles stay thin; the shared architecture note owns the main model. + - StreamPixels audience and creator data must not be absorbed into a shared auth store. + +invariants: + - The map is canonical and slow-changing. + - Scratch is temporary and disposable. + - Evidence is durable and distilled; routine activity logs belong in git history and commit messages. + - Heimdall owns OAuth, local sessions, grants, entitlement refresh, capability evaluation, and audit surfaces. + - App-domain data stays with the host app unless there is a deliberate, source-grounded reason to share it. + - Host apps verify signed claims locally and keep resource ownership checks local. + - StreamPixels can reuse shared auth authority without centralizing streamer-audience data. + - Spotiverse consumes Spotify as a Heimdall-managed credential; Spotiverse does not own Spotify refresh-token custody. + - Heimdall's first Odin/Eve daemon boundary publication remains secret-safe: it writes only provider advertisement, command boundary, transport profile, and daemon-health summary state, not per-account auth truth. + - Heimdall owns its persistent provider-health signing identity and signed observations; Idunn owns root-bound admission and the public provider-health projection. Unsigned health is never lifecycle authority. + - Heimdall owns OAuth attempts and completion redemption; the Eve access plugin and browser can project or carry one opaque handle but cannot grant access. + - Private auth commands are app-secret, source-runtime, expiry, nonce, and idempotency bound; sensitive completion claims remain AES-GCM wrapped until the app backend receives them. + - Refresh and logout are exact persisted-session transitions. App/account custody and access revision must match; logout advances the revision and stale refresh cannot recreate the session. + - Persistent state cruft is the same failure class as architecture cruft. + +data_flow: + observe: + - task request + - shared architecture note + - app profile bindings + - current app/runtime seams in Repixelizer and StreamPixels + - Yggdrasil host topology and nginx/service shape + process: + - rehydrate from canonical state + - choose one bounded architecture or implementation slice + - keep auth authority and app-domain data boundaries explicit + - keep routine route auth local after claim verification + - record only belief-changing evidence + - commit or backtrack + cut: + - reject shared-data creep + - reject duplicated auth blobs per app + - reject per-request auth round-trip chatter + +active_subgoals: + - Joystick H1 is merged and live (PR GameCult/Heimdall#1, d51fa6b; campaign joystick:campaign:self). Open follow-ups by id: joystick:follow_up:h1-joystick-consent-round-trip (next), cross-process-failed-refresh-marker, connect-start-needs-app-auth, heimdall-idunn-onboarding, joystick-viewer-signin-public-bot. StreamPixels S0/S1 run in other sessions. + - OPEN, behind the H1 live round-trips: pressure the deployed Ghostlight gamecult.heimdall.access integration with two- and eight-account human canaries. + - Keep the shared architecture explicit and separate from app profiles. + - Preserve the default boundary that app-domain data remains app-owned. + - Align the plan to Heimdall as a Yggdrasil-hosted authority service. + - Publish Heimdall daemon health and boundary state for Idunn/Odin without moving auth truth out of Heimdall. + - Verify the Discord and Patreon Repixelizer auth paths with real provider credentials, stable signing, persistent storage, and live browser callback verification. + - Wire StreamPixels through Heimdall for Twitch/YouTube (Joystick joins under H1) viewer identity and managed creator-provider credentials without moving StreamPixels domain state into Heimdall. + +accepted_design: + - `gamecult.heimdall.access` owns access-gate representation and browser navigation semantics; it has no access-grant or provider-state authority. + - Heimdall's loopback CultNet operation service owns authenticated auth begin/complete commands, while retained HTTP integrations remain supported for existing consumers. + - Ghostlight refresh and logout use the same private CultNet boundary; refresh re-evaluates the caller-owned KLTST policy and logout revokes exact Heimdall session custody. + - `docs/architecture.md` is the canonical shared architecture note. + - `docs/service-contract.md` records the concrete HTTP/JWKS contract of the landed service slice. + - `docs/app-profiles/*.md` are thin app bindings, not duplicate brains. + - Heimdall owns provider OAuth, identity linking, signed local sessions, grants, entitlement refresh, capability evaluation, and audit events. + - Host apps own their domain data, runtime state, and product-specific resources. + - Host apps verify signed claims locally for routine route authorization. + - A shared Heimdall store, if it exists, should hold auth/control-plane truth only. + - Repixelizer is the first auth-blank hosted-app binding. + - StreamPixels is the migration case that proves shared authority must not imply audience-data centralization. + - The first service skeleton is a standalone TypeScript/Fastify app with Ed25519 JWT signing, JWKS discovery, signed OAuth `state`, and app-profile-driven shared capability evaluation. + - The first stateful slice adds durable auth/control-plane storage plus a real Discord callback path for Repixelizer. + - Repixelizer has consumed the Heimdall backend-callback flow in its hosted web layer; Heimdall no longer needs to wait on Repixelizer refactoring before live Discord launch work. + - Heimdall is deployed on Yggdrasil at `https://heimdall.gamecult.org` with nginx/TLS, Postgres storage, file-backed signing-key bootstrap, configured token custody, and passing public health/discovery/JWKS checks. + - Heimdall now issues signed app refresh tokens alongside short-lived access claims and exposes `/v1/apps/{appSlug}/sessions/refresh` so app backends can reissue local claims without restarting provider OAuth. + - Discord and Patreon provider access tokens can refresh inside Heimdall before Repixelizer entitlement re-evaluation. + - Repixelizer is deployed on Yggdrasil at `https://repixelizer.gamecult.org` with `GC_ACCESS_MODE=heimdall`, `GC_ACCESS_ALLOWED_PROVIDERS=discord,patreon`, required access, queue protection enabled, app-owned Discord guild/role policy, and app-owned Patreon tier-title policy sent to Heimdall during backend-callback OAuth start. + - StreamPixels viewer and creator provider OAuth should start through Heimdall; StreamPixels redeems one-time completion codes, owns local profile/connector binding, and resolves current provider access tokens from Heimdall by app-authenticated managed-credential calls. + - Bifrost is a Heimdall app profile for Discord/Patreon member access. Bifrost owns the KTLST Discord role policy and Patreon tier policy; Heimdall owns provider OAuth, token custody, entitlement evaluation, and configured backend callback trust. + - Bifrost patron support sync reuses Heimdall's existing linked Patreon identity and membership reader. Heimdall turns active paid Patreon tier evidence into signed support facts; Bifrost owns point/tier/vote derivation. + - Heimdall's first runtime Verse cut publishes a service-owned CultCache boundary store and optional Idunn RUDP health pulse; full redacted auth-document witness export remains a later pass. + +landed_baseline: + - Heimdall publishes its redacted provider, command boundary, Eve plugin, and transport profile through Odin under globally unique record keys; Ghostlight resolves that boundary instead of owning a direct endpoint. + - Yggdrasil runs Heimdall d51fa6b (hand-deployed 2026-10-19 15:51Z; gamecult-ops 210a1af holds backup, rollback and provenance; prior 1086aee) with CultLib 5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9; live Ghostlight auth.begin through Odin discovery is accepted. + - The Heimdall access plugin, persistent OAuth attempts, encrypted private CultNet commands, conformance fixtures, and browser reference adapter are implemented and locally verified. + - Exact-session refresh validation and logout revocation are implemented; stale or racing refresh cannot resurrect a revoked session. + - Shared architecture extracted into its own repo and renamed to Heimdall. + - Repixelizer and StreamPixels app-profile notes created. + - Repo-local state, handoff, and compaction scaffolding created. + - Initial Heimdall service skeleton landed with discovery, JWKS, OAuth start/callback contract surfaces, and claim issuance scaffolding. + - Durable auth persistence landed for accounts, linked identities, sessions, grants, entitlement snapshots, and audit events. + - The first real provider slice landed for Discord callback exchange, identity resolution, entitlement evaluation, and session/claim issuance for Repixelizer. + - Signing-key persistence/bootstrap, managed token encryption at rest, and a local verifier seam landed for the first real consumer integration pass. + - Direct backend callback handoff landed as the preferred same-host app-consumer path, with browser completion-code exchange retained as fallback. + - Signed session refresh landed for app-facing claims: refresh tokens remain Heimdall-issued, provider refresh tokens remain sealed in Heimdall, and callers can provide app-owned entitlement policies for re-evaluation. + - Repixelizer's hosted web layer now creates Heimdall auth attempts, receives direct backend callbacks, verifies Heimdall Ed25519 access tokens locally, and adopts httpOnly local sessions. + - Heimdall now has generic Twitch and YouTube OAuth callback runtimes plus an app-authenticated managed-credential resolve endpoint for app-owned connector runtimes. + - StreamPixels now starts viewer and creator Twitch/YouTube OAuth through Heimdall, redeems Heimdall completion codes server-side, writes its own viewer sessions and creator connector bindings, and leaves provider refresh-token custody in Heimdall. + - Spotiverse now has a Heimdall app profile and Spotify provider runtime for managed credential custody. + - Bifrost now has a Heimdall app profile for Discord/Patreon member access, and backend callback trust is checked through configured app callback allowlists before legacy app-specific defaults. + - Heimdall exposes `POST /v1/apps/bifrost/patron-support/sync` as an app-authenticated bridge from linked Patreon membership evidence to Bifrost's signed patron support intake endpoint. + - A read-only `gamecult.eve.provider_advertisement.v1` export now advertises Heimdall provider/app surfaces plus redacted CultCache witness document paths for Odin/Eve discovery. + - Heimdall now writes a daemon-owned `GC_ACCESS_CULTCACHE_PATH` boundary store containing provider advertisement, command boundary, transport profile, and daemon-health summary state, and it can publish `heimdall.cultnet-rudp-provider-health` to Idunn over `cultnet.transport.rudp.v0` when configured. + - Heimdall now persists a machine-bound Ed25519 provider-health identity, publishes canonical `idunn.signed_daemon_health.v1` records on an independent sequential pulse loop, and is admitted by Idunn through an exact root trust binding. + +rejected_paths: + - name: per_app_auth_copy_paste + reason: duplicates the same provider/session sludge across every experiment + - name: per_request_auth_round_trip + reason: turns shared auth into a noisy bottleneck instead of local claim verification + - name: shared_user_data_swamp + reason: reusing auth mechanics does not justify centralizing app-domain audience or product data + +current_status: + summary: Yggdrasil runs Heimdall release d51fa6b (hand-deployed 2026-10-19 15:51Z, gamecult-ops 210a1af), which includes Joystick H1 (PR #1). The plugin and encrypted loopback begin, complete, refresh and logout plane, the Odin discovery records and Ghostlight resolution were verified at 1086aee (2026-08-22) and are not re-verified at d51fa6b. + next_action: Run joystick:follow_up:h1-joystick-consent-round-trip, then StreamPixels S0/S1 (other sessions). Still open behind that: separate-account KLTST completion, refresh, logout, privacy, and stale-attempt canaries through the deployed Ghostlight Eve host; keep provider credential rotation on the operator list because prior tool output exposed OAuth secrets. diff --git a/state/scratch.md b/state/scratch.md new file mode 100644 index 0000000..3f84d3b --- /dev/null +++ b/state/scratch.md @@ -0,0 +1,7 @@ +# Scratch + +This file is disposable working memory for the current bounded subgoal. + +## Current Subgoal + +No active scratch subgoal. diff --git a/tests/app.test.ts b/tests/app.test.ts index 3433d42..20a0191 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -318,10 +318,10 @@ describe("Heimdall service", () => { } }); - it("flags only Bifrost's and Ghostlight's profiles", () => { + it("flags only Bifrost's profile", () => { expect( - Object.values(builtInAppProfiles).filter((profile) => profile.startRequiresAppCaller).map((profile) => profile.slug).sort() - ).toEqual(["bifrost", "ghostlight"]); + Object.values(builtInAppProfiles).filter((profile) => profile.startRequiresAppCaller).map((profile) => profile.slug) + ).toEqual(["bifrost"]); }); }); @@ -1440,8 +1440,15 @@ describe("Heimdall service", () => { expect(urls).toEqual([]); }); - const BLANK_TARGETS = [" ", "\t", "\n ", "\u00A0\uFEFF"]; - const NAMING_TARGETS = ["creator-1", " creator-1 ", "Framgång", "42"]; + // Targets made only of whitespace, format characters, controls and the invisible fillers that render as nothing. + const BLANK_TARGETS = [ + " ", "\t", "\n ", "\u200B", "\u00A0\uFEFF", + "\u2800", "\u3164", "\u115F", "\u1160", "\uFFA0", "\u034F", "\u0000", "\u0007", " \u2800\u3164 ", + // Marks, private-use, unassigned and lone-surrogate code points, and the symbols that read as nothing: none is a letter or a number. + "\u0300", "\uE000", "\u0378", "\uD800", "\u{16FE4}", "\u{1D159}", "\u{F0000}", "\u0300\uE000 ", + ]; + // A target is usable when it holds a letter or a number that is not an invisible filler. + const NAMING_TARGETS = ["creator-1", " creator-1 ", "Framgång", "42", "\u2800a\u3164", "\u3164\u0300x"]; describe("a connect start that names a connection target is the app backend's", () => { // The target is app-backend authority: the StreamPixels backend proves the creator-manage session and states the @@ -1512,7 +1519,7 @@ describe("Heimdall service", () => { apps.push(app); for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }]) { - for (const targetId of [" ", "\t\n"]) { + for (const targetId of [" ", "\u2800"]) { const refused = await startFor(app, provider, { kind: "creator", targetId }, headers); expect([refused.statusCode, refused.json()], JSON.stringify(targetId)).toEqual([401, { error: "app_auth_required" }]); } @@ -1524,6 +1531,8 @@ describe("Heimdall service", () => { for (const targetId of BLANK_TARGETS) { expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId }), JSON.stringify(targetId)).toBe("refused"); } + // A visible character among the blanks names a target. + expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId: "\u2800a\u3164" })).toBe("custody_only"); for (const targetId of NAMING_TARGETS) { expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId }), JSON.stringify(targetId)).toBe("custody_only"); } diff --git a/tests/caller-identity-attack-soul-r21.test.ts b/tests/caller-identity-attack-soul-r21.test.ts new file mode 100644 index 0000000..1264a86 --- /dev/null +++ b/tests/caller-identity-attack-soul-r21.test.ts @@ -0,0 +1,620 @@ +// Soul attack probes, third pass: R21.1 (attempt-handle binding), R21.2 +// (runtime AppCaller brand), R21.3 (registered-app path deletion) and the +// partial unique index on auth_completions(app_slug, attempt_id). +// +// Same convention as the other two Soul files: plain `it` is an invariant +// that currently holds; `it.fails` is a hole this branch does not close. +// The "live postgres" block runs only when SOUL_PG_URL names a reachable +// database; it is skipped in the ordinary suite so the suite stays hermetic. +import { encode, decode } from "@msgpack/msgpack"; +import { invokeCultNetOperation } from "cultnet-ts"; +import { Pool } from "pg"; +import { newDb } from "pg-mem"; +import { afterEach, describe, expect, it } from "vitest"; +import { buildApp, getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow } from "../src/app.js"; +import { type AppCaller, isAppCaller, resolveAppCaller } from "../src/app-caller.js"; +import { getAppProfile } from "../src/app-profiles.js"; +import { type HeimdallConfig } from "../src/config.js"; +import { type AppSlug } from "../src/contracts.js"; +import { entitlementFacts } from "../src/facts.js"; +import { type OAuthProviderRuntime } from "../src/oauth.js"; +import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; +import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; +import { InMemoryStore } from "../src/store/index.js"; +import { PostgresStore } from "../src/store/postgres.js"; +import { CREATE_SCHEMA_SQL } from "../src/store/schema.js"; +import { type CreateAuthCompletionInput, type HeimdallStore } from "../src/store/types.js"; +import { launchState, stateOf } from "./oauth-flow.js"; + +const ghostlightSecret = "ghostlight-private-command-secret"; +const resources: Array<{ close(): Promise }> = []; + +afterEach(async () => { + await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); +}); + +function testConfig(overrides: Partial = {}): HeimdallConfig { + return { + serviceName: "heimdall", + host: "127.0.0.1", + port: 4100, + privateCommandHost: "127.0.0.1", + privateCommandPort: 0, + workspaceRoot: "F:/Projects/Heimdall", + dataRoot: "F:/Projects/Heimdall/.heimdall-data", + cultCachePath: "F:/Projects/Heimdall/.heimdall-data/cultcache/test.cc", + publicBaseUrl: "https://heimdall.gamecult.org", + issuer: "https://heimdall.gamecult.org", + daemonId: "yggdrasil-heimdall", + idunnRudpHealth: undefined, + idunnHealthContract: "heimdall.cultnet-rudp-provider-health", + providerHealthIdentityPath: "F:/Projects/Heimdall/.heimdall-data/provider-health-test.cc", + sessionTtlSeconds: 3600, + refreshTtlSeconds: 3600, + stateTtlSeconds: 600, + completionTtlSeconds: 300, + bootstrapSigningPrivateKeyOnMissing: false, + tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), + appSharedSecrets: { repixelizer: "repixelizer-secret", ghostlight: ghostlightSecret }, + appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, + appBackendCallbacks: {}, + storage: { backend: "memory", applySchemaOnStartup: true }, + providers: { + discord: { clientId: "discord-client", clientSecret: "discord-secret" }, + patreon: {}, + github: {}, + twitch: {}, + youtube: {}, + spotify: {}, + joystick: {}, + google: {}, + }, + ...overrides, + }; +} + +// The provider "code" doubles as the identity: code `victim` resolves to +// discord user `victim`, so one runtime plays every party. +function identityByCodeRuntime(): OAuthProviderRuntime { + return { + async exchangeAuthorizationCode({ code }) { + return { accessToken: code, tokenType: "Bearer", scope: ["identify"], raw: {} }; + }, + async resolveIdentity({ accessToken }) { + return { provider: "discord", providerUserId: accessToken, displayName: accessToken, profile: {} }; + }, + async evaluateEntitlements() { + return { facts: [entitlementFacts.appAccess], snapshots: [] }; + }, + }; +} + +async function harness(overrides: Partial = {}) { + const config = testConfig(overrides); + const store = new InMemoryStore(); + const app = await buildApp({ config, store, oauthRuntimes: { discord: identityByCodeRuntime() } }); + resources.push(app); + return { app, store, config }; +} + +type App = Awaited>["app"]; + +async function start(app: App, payload: unknown, headers: Record = {}) { + return app.inject({ method: "POST", url: "/v1/oauth/discord/start", payload: payload as never, headers }); +} + +async function completeAs(app: App, stateToken: string, who: string) { + const { cookie } = await launchState(app, stateToken); + return app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=${who}&state=${encodeURIComponent(stateToken)}`, + headers: { accept: "application/json", cookie }, + }); +} + +function jwtPayload(token: string): Record { + const [, body] = token.split("."); + return JSON.parse(Buffer.from(body ?? "", "base64url").toString("utf8")) as Record; +} + +function planeRequest(operation: string, messageId: string, envelope: HeimdallPrivateEnvelope) { + return { + schemaVersion: "cultnet.operation_request.v0" as const, + messageId, + serviceId: "heimdall.private.commands", + operation, + payloadSchema: "heimdall.private_command_envelope.v1", + payloadEncoding: "messagepack-base64" as const, + payload: Buffer.from(encode(envelope)).toString("base64"), + sourceRuntimeId: "yggdrasil-ghostlight", + }; +} + +async function planeCommand( + endpoint: Parameters[0], + operation: string, + idempotencyKey: string, + payload: Record, +): Promise> { + const contentSchema = operation === "heimdall.auth.begin" ? "heimdall.auth_begin_command.v1" : "heimdall.auth_complete_command.v1"; + const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey, secret: ghostlightSecret, payload }); + const response = await invokeCultNetOperation(endpoint, planeRequest(operation, `msg-${idempotencyKey}`, envelope), { + runtimeId: "yggdrasil-ghostlight", + }); + expect(response.status, JSON.stringify(response.diagnostics)).toBe("accepted"); + const wire = decode(Buffer.from(response.payload, "base64")) as HeimdallPrivateEnvelope; + return openPrivateEnvelope(wire, ghostlightSecret); +} + +async function planeHarness() { + const { app, store, config } = await harness(); + const plane = await startHeimdallPrivateCommandPlane(app, config); + resources.push(plane); + const begin = async (key: string) => + planeCommand(plane.endpoint, "heimdall.auth.begin", key, { + provider: "discord", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, + }); + const complete = async (key: string, handle: string) => planeCommand(plane.endpoint, "heimdall.auth.complete", key, { handle }); + return { app, store, config, begin, complete }; +} + +function completionInput(appSlug: AppSlug, accountId: string, sessionId: string, attemptId?: string): CreateAuthCompletionInput { + const now = new Date(); + return { + ...(attemptId ? { attemptId } : {}), + appSlug, + provider: "discord", + mode: "sign_in", + accountId, + sessionId, + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + createdAt: now.toISOString(), + expiresAt: new Date(now.getTime() + 300_000).toISOString(), + payloadJson: { marker: attemptId ?? "none" }, + }; +} + +// Seeds the account/session rows the FK constraints on auth_completions +// require in postgres; harmless in memory. +async function seedAccountAndSession(store: HeimdallStore, appSlug: AppSlug) { + const now = new Date().toISOString(); + const account = await store.createAccount({ createdAt: now, lastSeenAt: now }); + const session = await store.createSession({ + id: `sess-${account.id}`, + accountId: account.id, + appSlug, + createdAt: now, + lastSeenAt: now, + expiresAt: new Date(Date.now() + 3600_000).toISOString(), + claimsJson: {}, + accessRevision: 0, + }); + return { accountId: account.id, sessionId: session.id }; +} + +describe("R21.1: the attempt handle is unreachable from the public start route", () => { + const legitReturn = "https://yggdrasil.gamecult.org/ghostlight/"; + + it("a well-formed browser_completion attemptId is dropped before the state token is signed", async () => { + const { app, store } = await harness(); + const attempt = await store.createAuthAttempt({ + appSlug: "ghostlight", + provider: "discord", + mode: "sign_in", + returnTo: legitReturn, + createdAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 600_000).toISOString(), + }); + const response = await start(app, { + appSlug: "ghostlight", + mode: "sign_in", + returnTo: legitReturn, + handoff: { kind: "browser_completion", attemptId: attempt.handle }, + }); + expect(response.statusCode, response.body).toBe(201); + expect(response.json().handoff).toEqual({ kind: "browser_completion" }); + const state = jwtPayload(stateOf(response.json())); + expect(state.handoff).toEqual({ kind: "browser_completion" }); + expect(JSON.stringify(state)).not.toContain(attempt.handle); + }); + + // Fastify's default AJV runs with removeAdditional and coerceTypes:"array", + // so `additionalProperties: false` strips unknown keys instead of + // rejecting, and `["h"]` is coerced to "h". The oracle is therefore not + // the status code: it is that the planted value is absent from the + // response's handoff and from the signed state payload. + const planted = "planted-handle-7f3a"; + it.each([ + ["differently-cased key", { kind: "browser_completion", AttemptId: planted }], + ["snake_case key", { kind: "browser_completion", attempt_id: planted }], + ["array value (coerced to a string by AJV)", { kind: "browser_completion", attemptId: [planted] }], + ["object value", { kind: "browser_completion", attemptId: { value: planted } }], + ["nested handoff", { kind: "browser_completion", handoff: { attemptId: planted } }], + ["empty string", { kind: "browser_completion", attemptId: "" }], + ])("a %s attemptId never reaches the state token", async (_label, handoff) => { + const { app } = await harness(); + const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, handoff }); + expect(response.body).not.toContain(planted); + if (response.statusCode === 201) { + expect(response.json().handoff).toEqual({ kind: "browser_completion" }); + expect(jwtPayload(stateOf(response.json())).handoff).toEqual({ kind: "browser_completion" }); + } else { + expect(response.statusCode, response.body).toBe(400); + } + }); + + it("a top-level attemptId / trustedBrowserAttemptId / options field on the body is stripped, never bound", async () => { + const { app } = await harness(); + for (const extra of [{ attemptId: planted }, { trustedBrowserAttemptId: planted }, { options: { trustedBrowserAttemptId: planted } }]) { + const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, ...extra }); + expect(response.statusCode, response.body).toBe(201); + expect(response.body).not.toContain(planted); + expect(jwtPayload(stateOf(response.json())).handoff).toEqual({ kind: "browser_completion" }); + } + }); + + it("startOAuthFlow has exactly two callers and only beginAuth passes the options argument", async () => { + const { readFileSync, readdirSync } = await import("node:fs"); + const { join } = await import("node:path"); + const srcDir = join(process.cwd(), "src"); + const callers: string[] = []; + for (const file of readdirSync(srcDir, { recursive: true }) as string[]) { + if (!file.endsWith(".ts")) continue; + const source = readFileSync(join(srcDir, file), "utf8"); + const calls = source.match(/(? { + const { app, store, begin, complete } = await planeHarness(); + const receipt = await begin("begin-legit"); + expect(receipt.status).toBe("pending"); + const handle = String(receipt.handle); + const navigation = receipt.navigation as { url: string }; + const state = new URL(navigation.url).searchParams.get("state") ?? ""; + expect(jwtPayload(state).handoff).toEqual({ kind: "browser_completion", attemptId: handle }); + + const callback = await completeAs(app, state, "victim"); + expect(callback.statusCode, callback.body).toBe(201); + expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed"); + + const completed = await complete("complete-legit", handle); + expect(completed.status).toBe("authenticated"); + expect(completed.handle).toBe(handle); + expect(completed.accessToken).toEqual(expect.any(String)); + expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("consumed"); + }); + + it("a stranger cannot pre-occupy the app's pending handle so that the victim's own completion collides", async () => { + const { app, store, begin, complete } = await planeHarness(); + const receipt = await begin("begin-victim"); + const handle = String(receipt.handle); + const victimState = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; + + // Attacker names the victim's handle on the public start route, then + // completes as themselves before the victim does. + const attackerStart = await start(app, { + appSlug: "ghostlight", + mode: "sign_in", + returnTo: legitReturn, + handoff: { kind: "browser_completion", attemptId: handle }, + }); + expect(attackerStart.statusCode).toBe(201); + const attackerCallback = await completeAs(app, stateOf(attackerStart.json()), "attacker"); + expect(attackerCallback.statusCode, attackerCallback.body).toBe(201); + expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("pending"); + + // Victim completes; the handle's single unconsumed slot is still free. + const victimCallback = await completeAs(app, victimState, "victim"); + expect(victimCallback.statusCode, victimCallback.body).toBe(201); + const completed = await complete("complete-victim", handle); + expect(completed.status).toBe("authenticated"); + // ...and the tokens are the victim's, not the attacker's. + const claims = jwtPayload(String(completed.accessToken)); + expect(JSON.stringify(claims)).toContain("victim"); + expect(JSON.stringify(claims)).not.toContain("attacker"); + }); + + it("a backend_callback attemptId (the other handoff kind that carries one) never touches an auth attempt", async () => { + const { app, store } = await harness({ appBackendCallbacks: { ghostlight: ["http://127.0.0.1:1/never"] } }); + const attempt = await store.createAuthAttempt({ + appSlug: "ghostlight", + provider: "discord", + mode: "sign_in", + returnTo: legitReturn, + createdAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 600_000).toISOString(), + }); + const response = await start(app, { + appSlug: "ghostlight", + mode: "sign_in", + returnTo: legitReturn, + handoff: { kind: "backend_callback", attemptId: attempt.handle, callbackUrl: "http://127.0.0.1:1/never" }, + }); + expect(response.statusCode, response.body).toBe(201); + // Delivery to port 1 fails; whatever the callback returns, the attempt + // must be untouched and no completion may be bound to it. + await completeAs(app, stateOf(response.json()), "attacker"); + expect((await store.findAuthAttempt("ghostlight", attempt.handle))?.status).toBe("pending"); + expect(await store.consumeAuthCompletionByAttempt("ghostlight", attempt.handle, new Date().toISOString())).toBeNull(); + }); +}); + +describe("R21.2: the WeakSet brand at every consumer", () => { + it("every function that takes an AppCaller checks isAppCaller before reading appSlug", async () => { + const { readFileSync, readdirSync } = await import("node:fs"); + const { join } = await import("node:path"); + const srcDir = join(process.cwd(), "src"); + const consumers: string[] = []; + for (const file of readdirSync(srcDir, { recursive: true }) as string[]) { + if (!file.endsWith(".ts") || file.endsWith("app-caller.ts")) continue; + const source = readFileSync(join(srcDir, file), "utf8"); + const readsSlug = source.match(/caller\.appSlug/g) ?? []; + const guards = source.match(/isAppCaller\(caller\)/g) ?? []; + if (readsSlug.length) consumers.push(`${file}: reads=${readsSlug.length} guards=${guards.length}`); + // Every `caller.appSlug` read is on a line that also carries the guard. + for (const line of source.split("\n")) { + if (line.includes("caller.appSlug")) expect(line, `${file}: ${line.trim()}`).toContain("isAppCaller(caller)"); + } + } + expect(consumers).toEqual(["app.ts: reads=4 guards=4"]); + }); + + it("a caller minted for app A is refused where app B is expected, over HTTP and by direct call", async () => { + const { app, config } = await harness(); + const ctx = getHeimdallRuntimeContext(app); + const repixelizerCaller = resolveAppCaller(config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" }); + expect(isAppCaller(repixelizerCaller)).toBe(true); + + const startResult = await startOAuthFlow(ctx, "discord", repixelizerCaller, { + appSlug: "ghostlight", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, + }); + expect(startResult.statusCode).toBe(401); + expect(startResult.body).toMatchObject({ error: "app_auth_required" }); + + const refreshResult = await refreshAppSession(ctx, "ghostlight", repixelizerCaller, { + refreshToken: "x", + entitlementPolicies: [{ kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }], + }); + expect(refreshResult.statusCode).toBe(401); + + // Over HTTP: repixelizer's real secret on a ghostlight start with policy. + const http = await start( + app, + { + appSlug: "ghostlight", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, + }, + { "x-heimdall-app-secret": "repixelizer-secret" }, + ); + expect(http.statusCode).toBe(401); + }); + + it("symbol-copying, prototype-chaining, Proxy-wrapping and structuredClone forgeries are all refused", async () => { + const { config } = await harness(); + const real = resolveAppCaller(config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" }) as AppCaller; + const [brandSymbol] = Object.getOwnPropertySymbols(real); + expect(brandSymbol).toBeDefined(); + + const symbolCopy = { appSlug: "ghostlight", [brandSymbol as symbol]: true }; + // defineProperty, not assign: `real` is frozen, so shadowing its + // non-writable `appSlug` by assignment throws before the forgery exists. + const chained = Object.defineProperty(Object.create(real) as object, "appSlug", { + value: "ghostlight", + enumerable: true, + }); + const proxied = new Proxy(real, { get: (target, key) => (key === "appSlug" ? "ghostlight" : Reflect.get(target, key)) }); + const spread = { ...real, appSlug: "ghostlight" }; + const cloned = structuredClone({ appSlug: real.appSlug }); + for (const forgery of [symbolCopy, chained, proxied, spread, cloned]) { + expect(isAppCaller(forgery)).toBe(false); + } + // Frozen at mint, so the last forgery the WeakSet could not see is gone: + // a legitimately held caller cannot be re-slugged into another app and + // keep its brand. Modules are strict, so the write throws rather than + // silently no-opping. + expect(Object.isFrozen(real)).toBe(true); + expect(() => { + (real as { appSlug: string }).appSlug = "ghostlight"; + }).toThrow(TypeError); + expect(real.appSlug).toBe("repixelizer"); + expect(isAppCaller(real)).toBe(true); + }); +}); + +async function twoCompletionsForOneHandle(store: HeimdallStore, appSlug: AppSlug = "ghostlight") { + const { accountId, sessionId } = await seedAccountAndSession(store, appSlug); + const results = await Promise.allSettled([ + store.createAuthCompletion(completionInput(appSlug, accountId, sessionId, "handle-1")), + store.createAuthCompletion(completionInput(appSlug, accountId, sessionId, "handle-1")), + ]); + return { results, accountId, sessionId }; +} + +function partialUniqueIndexContract(label: string, makeStore: () => Promise) { + describe(`partial unique index contract: ${label}`, () => { + it("two concurrent completions for one handle: exactly one is minted", async () => { + const store = await makeStore(); + const { results } = await twoCompletionsForOneHandle(store); + const fulfilled = results.filter((r) => r.status === "fulfilled"); + const rejected = results.filter((r) => r.status === "rejected"); + expect(fulfilled).toHaveLength(1); + expect(rejected).toHaveLength(1); + const live = await store.consumeAuthCompletionByAttempt("ghostlight", "handle-1", new Date().toISOString()); + expect(live?.attemptId).toBe("handle-1"); + expect(await store.consumeAuthCompletionByAttempt("ghostlight", "handle-1", new Date().toISOString())).toBeNull(); + }); + + it("the predicate: NULL handles never collide, a consumed handle frees its slot, other apps do not collide", async () => { + const store = await makeStore(); + const g = await seedAccountAndSession(store, "ghostlight"); + const r = await seedAccountAndSession(store, "repixelizer"); + await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId)); + await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId)); + const first = await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "shared")); + await expect(store.createAuthCompletion(completionInput("repixelizer", r.accountId, r.sessionId, "shared"))).resolves.toBeTruthy(); + await expect(store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "shared"))).rejects.toThrow(); + expect(await store.consumeAuthCompletion("ghostlight", first.code, new Date().toISOString())).toBeTruthy(); + const second = await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "shared")); + expect(second.code).not.toBe(first.code); + const byAttempt = await store.consumeAuthCompletionByAttempt("ghostlight", "shared", new Date().toISOString()); + expect(byAttempt?.code).toBe(second.code); + }); + + it("an expired-but-unconsumed completion still occupies the slot (both stores agree; neither frees it)", async () => { + const store = await makeStore(); + const g = await seedAccountAndSession(store, "ghostlight"); + const stale = completionInput("ghostlight", g.accountId, g.sessionId, "stale"); + stale.expiresAt = new Date(Date.now() - 1000).toISOString(); + await store.createAuthCompletion(stale); + expect(await store.consumeAuthCompletionByAttempt("ghostlight", "stale", new Date().toISOString())).toBeNull(); + await expect(store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "stale"))).rejects.toThrow(); + }); + }); +} + +partialUniqueIndexContract("InMemoryStore", async () => new InMemoryStore()); +partialUniqueIndexContract("PostgresStore over pg-mem", async () => { + const adapter = newDb().adapters.createPg(); + const store = new PostgresStore(new adapter.Pool()); + await store.ensureSchema(); + return store; +}); + +describe("duplicate-handle error surfacing through the callback route", () => { + it("a replayed state is refused as already used before any exchange, and leaves the real completion intact", async () => { + const { app, store, begin } = await planeHarness(); + const receipt = await begin("begin-replay"); + const handle = String(receipt.handle); + const state = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; + const { cookie } = await launchState(app, state); + const callbackWith = () => + app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=victim&state=${encodeURIComponent(state)}`, + headers: { accept: "application/json", cookie }, + }); + const first = await callbackWith(); + expect(first.statusCode).toBe(201); + // The state's jti was consumed by the first callback, so the second never + // reaches createAuthCompletion, whose unique index used to be the only + // thing refusing a replay (and whose Postgres 23505 text the route had to + // keep out of the answer). + const replay = await callbackWith(); + expect(replay.statusCode, replay.body).toBe(400); + expect(replay.json()).toEqual({ error: "state_already_used" }); + expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed"); + expect(await store.consumeAuthCompletionByAttempt("ghostlight", handle, new Date().toISOString())).toBeTruthy(); + }); +}); + +describe("R21.3: sync getAppProfile at the seven former resolveAppProfile sites", () => { + it("getAppProfile resolves own keys only, so prototype members are not profiles", () => { + expect(getAppProfile("nope" as AppSlug)).toBeUndefined(); + // Object.hasOwn guards the lookup; a bare `record[key]` index handed these + // back as objects that then serialised as an empty profile. + for (const key of ["constructor", "toString", "__proto__", "hasOwnProperty"]) { + expect(getAppProfile(key as AppSlug), key).toBeUndefined(); + } + }); + + // Was an open hole inherited from main: this is the one route whose params + // schema has no slug enum, and the bare index made `constructor` a 200 `{}` + // because serializeAppProfile(Object) serialises undefined fields. Closed by + // Object.hasOwn in getAppProfile. + it("GET /v1/apps/:appSlug is the one route without the slug enum; a prototype key must still be a 404", async () => { + const { app } = await harness(); + // Null prototype so the "__proto__" key is a key, not a setter. + const statuses: Record = Object.create(null) as Record; + for (const key of ["constructor", "toString", "__proto__", "hasOwnProperty", "valueOf"]) { + const response = await app.inject({ method: "GET", url: `/v1/apps/${key}` }); + statuses[key] = `${response.statusCode} ${response.body.slice(0, 60)}`; + } + process.stdout.write(`\n[soul] GET /v1/apps/: ${JSON.stringify(statuses)}\n`); + expect(statuses).toEqual(Object.fromEntries(Object.keys(statuses).map((key) => [key, expect.stringMatching(/^404 /)]))); + }); + + it("every other appSlug parameter is enum-gated, so an unknown slug is a 400 there and a 404 only on the profile read", async () => { + const { app } = await harness(); + expect((await app.inject({ method: "GET", url: "/v1/apps/nope" })).statusCode).toBe(404); + expect((await start(app, { appSlug: "nope", mode: "sign_in", returnTo: "https://x.example/" })).statusCode).toBe(400); + for (const url of [ + "/v1/apps/nope/auth-completions/redeem", + "/v1/apps/nope/sessions/refresh", + "/v1/apps/nope/patron-support/sync", + "/v1/apps/nope/managed-credentials/resolve", + ]) { + const response = await app.inject({ method: "POST", url, payload: { completionCode: "c", refreshToken: "r", accountId: "a", provider: "discord" } }); + expect(response.statusCode, url).toBe(400); + } + }); + + it("the migration adds attempt_id before the partial index that references it, and drops registered_apps first", () => { + const addColumn = CREATE_SCHEMA_SQL.indexOf("ALTER TABLE auth_completions ADD COLUMN IF NOT EXISTS attempt_id TEXT"); + const dropOldIndex = CREATE_SCHEMA_SQL.indexOf("DROP INDEX IF EXISTS auth_completions_attempt_idx"); + const createIndex = CREATE_SCHEMA_SQL.indexOf("CREATE UNIQUE INDEX IF NOT EXISTS auth_completions_attempt_unconsumed_unique_idx"); + const dropTable = CREATE_SCHEMA_SQL.indexOf("DROP TABLE IF EXISTS registered_apps"); + expect(dropTable).toBeGreaterThanOrEqual(0); + expect(addColumn).toBeGreaterThan(dropTable); + expect(dropOldIndex).toBeGreaterThan(addColumn); + expect(createIndex).toBeGreaterThan(dropOldIndex); + // Statement count, not token count (the comment above the DROP names it too). + expect(CREATE_SCHEMA_SQL.match(/DROP TABLE IF EXISTS registered_apps/g)).toHaveLength(1); + expect(CREATE_SCHEMA_SQL).not.toMatch(/CREATE TABLE[^;]*registered_apps/); + }); + // Re-running ensureSchema on a store built before this branch (table + // present, column absent, old index name) cannot be simulated in pg-mem — + // it rejects CREATE TABLE IF NOT EXISTS on an existing table — so that + // path is proved only by the live block below. +}); + +const livePg = process.env.SOUL_PG_URL; +describe.skipIf(!livePg)("live postgres (SOUL_PG_URL)", () => { + it("real partial index: 23505 names auth_completions_attempt_unconsumed_unique_idx; schema applies twice on a pre-branch store", async () => { + const pool = new Pool({ connectionString: livePg }); + resources.push({ close: () => pool.end() }); + await pool.query(` + DROP SCHEMA public CASCADE; CREATE SCHEMA public; + CREATE TABLE registered_apps (slug TEXT PRIMARY KEY); + CREATE TABLE accounts (id TEXT PRIMARY KEY, created_at TIMESTAMPTZ NOT NULL, last_seen_at TIMESTAMPTZ NOT NULL, display_name TEXT, primary_email TEXT); + CREATE TABLE sessions (id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, app_slug TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, last_seen_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, claims_json JSONB NOT NULL, access_revision INTEGER NOT NULL); + CREATE TABLE auth_completions ( + code TEXT PRIMARY KEY, app_slug TEXT NOT NULL, provider TEXT NOT NULL, mode TEXT NOT NULL, + account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, + return_to TEXT NOT NULL, payload_json JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, consumed_at TIMESTAMPTZ + ); + `); + const store = new PostgresStore(pool); + await store.ensureSchema(); + await store.ensureSchema(); + const tables = await pool.query<{ table_name: string }>("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY 1"); + expect(tables.rows.map((r) => r.table_name)).not.toContain("registered_apps"); + const indexes = await pool.query<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE tablename = 'auth_completions' ORDER BY 1"); + const partial = indexes.rows.find((r) => r.indexdef.includes("auth_completions_attempt_unconsumed_unique_idx")); + expect(partial?.indexdef).toContain("WHERE ((attempt_id IS NOT NULL) AND (consumed_at IS NULL))"); + + const { results } = await twoCompletionsForOneHandle(store); + const rejected = results.find((r): r is PromiseRejectedResult => r.status === "rejected"); + expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1); + const error = rejected?.reason as { code?: string; message?: string }; + expect(error.code).toBe("23505"); + expect(error.message).toContain("auth_completions_attempt_unconsumed_unique_idx"); + // What the callback route's catch would echo as `detail`. + process.stdout.write(`\n[soul live pg] 23505 message: ${error.message}\n`); + }, 30_000); +}); diff --git a/tests/caller-identity-attack-soul.test.ts b/tests/caller-identity-attack-soul.test.ts new file mode 100644 index 0000000..d9b4167 --- /dev/null +++ b/tests/caller-identity-attack-soul.test.ts @@ -0,0 +1,362 @@ +// Soul attack probes for the caller-identity cut, second pass. +// +// Same convention as caller-identity-soul.test.ts: plain `it` is an invariant +// that currently holds; `it.fails` is a hole the cut does not close (vitest +// passes the case while the body fails; close the hole and promote it). +import { afterEach, describe, expect, it } from "vitest"; +import { buildApp, refreshAppSession } from "../src/app.js"; +import { type AppCaller } from "../src/app-caller.js"; +import { builtInAppProfiles, isAllowedReturnOrigin } from "../src/app-profiles.js"; +import { type HeimdallConfig } from "../src/config.js"; +import { entitlementFacts } from "../src/facts.js"; +import { type OAuthProviderRuntime } from "../src/oauth.js"; +import { InMemoryStore } from "../src/store/index.js"; +import { launchState, stateOf } from "./oauth-flow.js"; + +const resources: Array<{ close(): Promise }> = []; + +afterEach(async () => { + await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); +}); + +function testConfig(): HeimdallConfig { + return { + serviceName: "heimdall", + host: "127.0.0.1", + port: 4100, + privateCommandHost: "127.0.0.1", + privateCommandPort: 0, + workspaceRoot: "F:/Projects/Heimdall", + dataRoot: "F:/Projects/Heimdall/.heimdall-data", + cultCachePath: "F:/Projects/Heimdall/.heimdall-data/cultcache/test.cc", + publicBaseUrl: "https://heimdall.gamecult.org", + issuer: "https://heimdall.gamecult.org", + daemonId: "yggdrasil-heimdall", + idunnRudpHealth: undefined, + idunnHealthContract: "heimdall.cultnet-rudp-provider-health", + providerHealthIdentityPath: "F:/Projects/Heimdall/.heimdall-data/provider-health-test.cc", + sessionTtlSeconds: 3600, + refreshTtlSeconds: 3600, + stateTtlSeconds: 600, + completionTtlSeconds: 300, + bootstrapSigningPrivateKeyOnMissing: false, + tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), + appSharedSecrets: { repixelizer: "repixelizer-secret", ghostlight: "ghostlight-secret" }, + appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, + appBackendCallbacks: {}, + storage: { backend: "memory", applySchemaOnStartup: true }, + providers: { + discord: { clientId: "discord-client", clientSecret: "discord-secret" }, + patreon: {}, + github: {}, + twitch: {}, + youtube: {}, + spotify: {}, + joystick: {}, + google: {}, + }, + }; +} + +// The provider "code" doubles as the identity so one runtime can play both +// victim and attacker: code `victim` resolves to discord user `victim`. +function identityByCodeRuntime(): OAuthProviderRuntime { + return { + async exchangeAuthorizationCode({ code }) { + return { accessToken: code, tokenType: "Bearer", scope: ["identify"], raw: {} }; + }, + async resolveIdentity({ accessToken }) { + return { provider: "discord", providerUserId: accessToken, displayName: accessToken, profile: {} }; + }, + async evaluateEntitlements() { + return { facts: [entitlementFacts.appAccess], snapshots: [] }; + }, + }; +} + +async function harness() { + const store = new InMemoryStore(); + const app = await buildApp({ config: testConfig(), store, oauthRuntimes: { discord: identityByCodeRuntime() } }); + resources.push(app); + return { app, store }; +} + +type App = Awaited>["app"]; + +async function start(app: App, payload: Record, headers: Record = {}) { + return app.inject({ method: "POST", url: "/v1/oauth/discord/start", payload, headers }); +} + +async function completeAs(app: App, stateToken: string, who: string) { + const { cookie } = await launchState(app, stateToken); + return app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=${who}&state=${encodeURIComponent(stateToken)}`, + headers: { accept: "application/json", cookie }, + }); +} + +async function redeem(app: App, appSlug: string, completionCode: string) { + return app.inject({ method: "POST", url: `/v1/apps/${appSlug}/auth-completions/redeem`, payload: { completionCode } }); +} + +const uuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +describe("takeover chain: caller-chosen attemptId is never the redemption code", () => { + it("attacker fixes attemptId, victim completes, attemptId does not redeem; the minted code is a fresh uuid v4", async () => { + const { app } = await harness(); + const started = await start(app, { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + handoff: { kind: "browser_completion", attemptId: "attacker-fixed" }, + }); + expect(started.statusCode).toBe(201); + + const callback = await completeAs(app, stateOf(started.json()), "victim"); + expect(callback.statusCode).toBe(201); + const minted = callback.json().completion.code as string; + expect(minted).not.toBe("attacker-fixed"); + expect(minted).toMatch(uuidV4); + + const byAttempt = await redeem(app, "repixelizer", "attacker-fixed"); + expect(byAttempt.statusCode).toBe(410); + expect(byAttempt.json()).toEqual({ error: "invalid_or_expired_completion_code" }); + }); + + it("omitting handoff still mints a uuid v4 code; the attempt handle is absent from the completion", async () => { + const { app, store } = await harness(); + const started = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); + expect(started.statusCode).toBe(201); + const callback = await completeAs(app, stateOf(started.json()), "victim"); + expect(callback.statusCode).toBe(201); + const code = callback.json().completion.code as string; + expect(code).toMatch(uuidV4); + const stored = (store as unknown as { authCompletions: Map }).authCompletions.get(code); + expect(stored?.attemptId).toBeUndefined(); + }); + + it("handoff.kind backend_callback with an attemptId is refused unless the callbackUrl is configured", async () => { + const { app } = await harness(); + const started = await start(app, { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + handoff: { kind: "backend_callback", attemptId: "attacker-fixed", callbackUrl: "https://attacker.example/cb" }, + }); + expect(started.statusCode).toBe(400); + expect(started.json().error).toBe("untrusted_backend_callback"); + }); + + it("an unknown handoff.kind is rejected by the schema", async () => { + const { app } = await harness(); + const started = await start(app, { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + handoff: { kind: "evil", attemptId: "attacker-fixed" }, + }); + expect(started.statusCode).toBe(400); + }); + + it("attemptId set to a real victim completion code does not let the attacker's flow touch the victim's completion", async () => { + const { app } = await harness(); + const victimStart = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); + const victimCallback = await completeAs(app, stateOf(victimStart.json()), "victim"); + const victimCode = victimCallback.json().completion.code as string; + + const attackerStart = await start(app, { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + handoff: { kind: "browser_completion", attemptId: victimCode }, + }); + const attackerCallback = await completeAs(app, stateOf(attackerStart.json()), "attacker"); + expect(attackerCallback.statusCode).toBe(201); + expect(attackerCallback.json().completion.code).not.toBe(victimCode); + + // The victim's code still redeems the victim, once. + const first = await redeem(app, "repixelizer", victimCode); + expect(first.statusCode).toBe(201); + expect(first.json().account.displayName).toBe("victim"); + }); + + it("the redeem route is unauthenticated, so the code is the whole secret: 122 bits of CSPRNG, distinct across mints", async () => { + const store = new InMemoryStore(); + const codes = new Set(); + for (let i = 0; i < 200; i += 1) { + const completion = await store.createAuthCompletion({ + appSlug: "repixelizer", + provider: "discord", + mode: "sign_in", + accountId: "a", + sessionId: "s", + returnTo: "https://repixelizer.gamecult.org/app/", + createdAt: "2026-01-01T00:00:00.000Z", + expiresAt: "2999-01-01T00:00:00.000Z", + payloadJson: {}, + }); + expect(completion.code).toMatch(uuidV4); + codes.add(completion.code); + } + expect(codes.size).toBe(200); + }); +}); + +describe("consumeAuthCompletion: single-use, scoped, expiring", () => { + it("a code redeems exactly once under concurrent redemption, and never for another app", async () => { + const { app } = await harness(); + const started = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); + const callback = await completeAs(app, stateOf(started.json()), "victim"); + const code = callback.json().completion.code as string; + + const crossApp = await redeem(app, "bifrost", code); + expect(crossApp.statusCode).toBe(410); + + const results = await Promise.all([redeem(app, "repixelizer", code), redeem(app, "repixelizer", code), redeem(app, "repixelizer", code)]); + expect(results.map((r) => r.statusCode).sort()).toEqual([201, 410, 410]); + }); + + it("an expired completion is not consumable, by code or by attempt", async () => { + const store = new InMemoryStore(); + const completion = await store.createAuthCompletion({ + attemptId: "h1", + appSlug: "repixelizer", + provider: "discord", + mode: "sign_in", + accountId: "a", + sessionId: "s", + returnTo: "https://repixelizer.gamecult.org/app/", + createdAt: "2026-01-01T00:00:00.000Z", + expiresAt: "2026-01-01T00:05:00.000Z", + payloadJson: {}, + }); + expect(await store.consumeAuthCompletion("repixelizer", completion.code, "2026-01-01T00:05:00.000Z")).toBeNull(); + expect(await store.consumeAuthCompletionByAttempt("repixelizer", "h1", "2026-01-01T00:05:00.000Z")).toBeNull(); + expect(await store.consumeAuthCompletionByAttempt("bifrost", "h1", "2026-01-01T00:04:00.000Z")).toBeNull(); + expect(await store.consumeAuthCompletionByAttempt("repixelizer", "h1", "2026-01-01T00:04:00.000Z")).not.toBeNull(); + expect(await store.consumeAuthCompletionByAttempt("repixelizer", "h1", "2026-01-01T00:04:00.000Z")).toBeNull(); + }); +}); + +describe("attempt-handle binding: the public start route may attach a completion to any attempt", () => { + // Closed (R21.1). The private plane creates attempt H for its app and later + // redeems by handle (consumeAuthCompletionByAttempt). handoff.attemptId is + // no longer read from the request body at all (normalizeOAuthHandoff always + // returns a bare `{ kind: "browser_completion" }` for a public caller); the + // only path by which an attempt handle reaches the signed state token is + // `startOAuthFlow`'s `trustedBrowserAttemptId` option, which only + // `beginAuth` (private-command-plane.ts) can set, from the handle it just + // minted server-side. A value that never crosses the public boundary cannot + // be chosen by a stranger, so a public flow carrying H as body JSON now has + // no effect on H at all. + it("a public flow carrying the app's attempt handle must not complete that attempt", async () => { + const { app, store } = await harness(); + const attempt = await store.createAuthAttempt({ + appSlug: "ghostlight", + provider: "discord", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + createdAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 600_000).toISOString(), + }); + + const attackerStart = await start(app, { + appSlug: "ghostlight", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + handoff: { kind: "browser_completion", attemptId: attempt.handle }, + }); + expect(attackerStart.statusCode).toBe(201); + await completeAs(app, stateOf(attackerStart.json()), "attacker"); + + const after = await store.findAuthAttempt("ghostlight", attempt.handle); + expect(after?.status).toBe("pending"); + const bound = await store.consumeAuthCompletionByAttempt("ghostlight", attempt.handle, new Date().toISOString()); + expect(bound).toBeNull(); + }); +}); + +describe("isAllowedReturnOrigin: origin comparison, not string matching", () => { + const profile = builtInAppProfiles.repixelizer; + // Narrow rather than cast: the lookup is Partial-typed, and a missing + // built-in should fail this suite loudly instead of being asserted away. + if (!profile) { + throw new Error("built-in repixelizer profile is missing"); + } + const rejected = [ + "https://repixelizer.gamecult.org.evil.com/", + "https://evil.com/?x=https://repixelizer.gamecult.org", + "https://repixelizer.gamecult.org@evil.com/", + "https://evil.com#https://repixelizer.gamecult.org", + "//repixelizer.gamecult.org/app/", + "http://repixelizer.gamecult.org/app/", + "https://repixelizer.gamecult.org:8443/app/", + "https://repixelizer.gamecult.org./app/", + "https://xn--repixelizer-gamecult.org/", + "javascript:alert(1)", + "data:text/html,hi", + "not a url", + "", + "https://repixelizer.gamecult.org.", + "https://repixelizer.gamecult.orgx/", + "https://sub.repixelizer.gamecult.org/", + ]; + it.each(rejected)("rejects %s", (returnTo) => { + expect(isAllowedReturnOrigin(profile, returnTo)).toBe(false); + }); + + // Accepted variants are all the same origin after WHATWG normalisation; + // they are listed so a future "fix" that switches to string comparison + // shows up as a behaviour change here rather than silently in production. + const acceptedSameOrigin = [ + "https://repixelizer.gamecult.org", + "https://repixelizer.gamecult.org/app/", + "https://REPIXELIZER.GameCult.org/app/", + "https://repixelizer.gamecult.org:443/app/", + "https:/\\repixelizer.gamecult.org/app/", + "https://user:pw@repixelizer.gamecult.org/app/", + "https://repixelizer.gamecult.org/app/?returnTo=https://evil.com", + ]; + it.each(acceptedSameOrigin)("accepts %s (same origin after URL parsing)", (returnTo) => { + expect(new URL(returnTo).origin).toBe("https://repixelizer.gamecult.org"); + expect(isAllowedReturnOrigin(profile, returnTo)).toBe(true); + }); + + it("an empty allowlist denies everything rather than passing vacuously", () => { + expect(isAllowedReturnOrigin({ ...profile, allowedReturnOrigins: [] }, "https://repixelizer.gamecult.org/")).toBe(false); + }); + + // The registered-app path this test covered (seedRegisteredApp, + // resolveAppProfile's non-built-in branch) was deleted in R21.3: every HTTP + // route already enumerates the four built-in slugs in its own JSON schema, + // so a registered row could never be reached over HTTP in the first place. + // An unknown slug is now refused by that schema directly. + it("an unknown appSlug cannot start a flow through HTTP at all (slug enum)", async () => { + const { app } = await harness(); + const started = await start(app, { appSlug: "newapp", mode: "sign_in", returnTo: "https://anything.example/" }); + expect(started.statusCode).toBe(400); + }); +}); + +describe("AppCaller brand: enforced by a module-private WeakSet (R21.2)", () => { + // Closed. brandCaller (app-caller.ts) registers every AppCaller it mints in + // a WeakSet that never leaves the module; isAppCaller is the only way a + // consumer may trust one, and startOAuthFlow / refreshAppSession now call + // it instead of trusting the AppCaller | null type alone. A forged literal + // — even one carrying the callerBrand symbol key by hand — was never added + // to the set and is rejected regardless of shape or cast. + it("a forged caller literal is refused at runtime", async () => { + const { app } = await harness(); + const context = (app as unknown as { heimdallContext: Parameters[0] }).heimdallContext; + const forged = { appSlug: "repixelizer" } as unknown as AppCaller; + const result = await refreshAppSession(context, "repixelizer", forged, { + refreshToken: "not-a-token", + entitlementPolicies: [{ kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }], + } as never); + // With a forged caller the request gets past the caller gate and fails + // later on the bogus refresh token (401 invalid_refresh_token / similar); + // a runtime brand check would return app_auth_required here. + expect(result.body).toMatchObject({ error: "app_auth_required" }); + }); +}); diff --git a/tests/caller-identity-soul.test.ts b/tests/caller-identity-soul.test.ts new file mode 100644 index 0000000..d66f652 --- /dev/null +++ b/tests/caller-identity-soul.test.ts @@ -0,0 +1,295 @@ +// Soul falsification probes for the caller-identity cut (epiphany/heimdall-caller-identity). +// +// Two kinds of test live here: +// - plain `it(...)`: an invariant the cut claims and that currently holds. +// - `it.fails(...)`: an invariant the cut does NOT yet enforce. vitest passes +// the case while the body fails; when someone closes the hole the case +// flips to a real failure and must be promoted to a plain `it`. +import { readFileSync, readdirSync } from "node:fs"; +import { join } from "node:path"; +import { encode } from "@msgpack/msgpack"; +import { invokeCultNetOperation } from "cultnet-ts"; +import { afterEach, describe, expect, it } from "vitest"; +import { buildApp, refreshAppSession, startOAuthFlow } from "../src/app.js"; +import { callerFromOpenedEnvelope, secretMatches } from "../src/app-caller.js"; +import { type HeimdallConfig } from "../src/config.js"; +import { entitlementFacts } from "../src/facts.js"; +import { type OAuthProviderRuntime } from "../src/oauth.js"; +import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; +import { sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; +import { InMemoryStore } from "../src/store/index.js"; +import { launchFlow } from "./oauth-flow.js"; + +const ghostlightSecret = "ghostlight-private-command-secret"; +const resources: Array<{ close(): Promise }> = []; + +afterEach(async () => { + await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); +}); + +function testConfig(): HeimdallConfig { + return { + serviceName: "heimdall", + host: "127.0.0.1", + port: 4100, + privateCommandHost: "127.0.0.1", + privateCommandPort: 0, + workspaceRoot: "F:/Projects/Heimdall", + dataRoot: "F:/Projects/Heimdall/.heimdall-data", + cultCachePath: "F:/Projects/Heimdall/.heimdall-data/cultcache/test.cc", + publicBaseUrl: "https://heimdall.gamecult.org", + issuer: "https://heimdall.gamecult.org", + daemonId: "yggdrasil-heimdall", + idunnRudpHealth: undefined, + idunnHealthContract: "heimdall.cultnet-rudp-provider-health", + providerHealthIdentityPath: "F:/Projects/Heimdall/.heimdall-data/provider-health-test.cc", + sessionTtlSeconds: 3600, + refreshTtlSeconds: 3600, + stateTtlSeconds: 600, + completionTtlSeconds: 300, + bootstrapSigningPrivateKeyOnMissing: false, + tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), + appSharedSecrets: { repixelizer: "repixelizer-secret", ghostlight: ghostlightSecret }, + appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, + appBackendCallbacks: {}, + storage: { backend: "memory", applySchemaOnStartup: true }, + providers: { + discord: { clientId: "discord-client", clientSecret: "discord-secret" }, + patreon: {}, + github: {}, + twitch: {}, + youtube: {}, + spotify: {}, + joystick: {}, + google: {}, + }, + }; +} + +function mockDiscordRuntime(): OAuthProviderRuntime { + return { + async exchangeAuthorizationCode() { + return { accessToken: "provider-access", tokenType: "Bearer", scope: ["identify"], raw: {} }; + }, + async resolveIdentity() { + return { provider: "discord", providerUserId: "discord-victim", displayName: "Victim", profile: {} }; + }, + async evaluateEntitlements() { + return { facts: [entitlementFacts.appAccess], snapshots: [] }; + }, + }; +} + +describe("caller identity: unauthenticated mint paths", () => { + // Item 1 (closed). The completion code used to be chosen by whoever started + // the flow (handoff.attemptId became the completion code verbatim, + // src/app.ts createAuthCompletion `code: handoff.attemptId`), and + // auth-completions/redeem takes no app secret. An unauthenticated party + // could therefore fix the code, get a victim to finish provider login on + // the authorization URL, and redeem the victim's signed access + refresh + // tokens. The store now always mints the code itself; attemptId is kept + // only as a separate correlation field the browser may carry. + it("a client-chosen attemptId must not be redeemable for signed tokens without app auth", async () => { + const app = await buildApp({ config: testConfig(), oauthRuntimes: { discord: mockDiscordRuntime() } }); + resources.push(app); + + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + handoff: { kind: "browser_completion", attemptId: "attacker-fixed-code" }, + }, + // no x-heimdall-app-secret + }); + expect(start.statusCode).toBe(201); + + const flow = await launchFlow(app, start.json()); + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=victim-code&state=${encodeURIComponent(flow.state)}`, + headers: { accept: "text/html", cookie: flow.cookie }, + }); + expect(callback.statusCode).toBe(200); + + const redeem = await app.inject({ + method: "POST", + url: "/v1/apps/repixelizer/auth-completions/redeem", + payload: { completionCode: "attacker-fixed-code" }, + // still no x-heimdall-app-secret + }); + + // The invariant the cut claims: the caller-chosen code is never minted, + // so it can never be redeemed. + expect(redeem.statusCode).not.toBe(201); + expect(redeem.json().accessToken).toBeUndefined(); + }); + + // Item 2 (closed). returnTo used to be validated only as `format: uri`. The + // success page postMessages the completion payload to + // new URL(returnTo).origin and links to returnTo with the code in the + // fragment (src/browser-handoff.ts), so an unlisted origin was an + // exfiltration primitive. startOAuthFlow now refuses any returnTo whose + // origin is not in the app profile's allowedReturnOrigins. + it("an unauthenticated start must not accept an arbitrary returnTo origin", async () => { + const app = await buildApp({ config: testConfig(), oauthRuntimes: { discord: mockDiscordRuntime() } }); + resources.push(app); + + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://attacker.example/collect" }, + }); + + expect(start.statusCode).not.toBe(201); + }); + + it("refuses to mint on refresh when the caller supplies policy without app auth", async () => { + const app = await buildApp({ config: testConfig(), oauthRuntimes: { discord: mockDiscordRuntime() } }); + resources.push(app); + const context = (app as unknown as { heimdallContext: Parameters[0] }).heimdallContext; + const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }; + + const nullCaller = await refreshAppSession(context, "repixelizer", null, { + refreshToken: "irrelevant", + entitlementPolicy: policy, + } as Parameters[3]); + expect(nullCaller).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); + + const wrongApp = await refreshAppSession(context, "repixelizer", callerFromOpenedEnvelope("ghostlight"), { + refreshToken: "irrelevant", + entitlementPolicy: policy, + } as Parameters[3]); + expect(wrongApp).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); + + const nullStart = await startOAuthFlow(context, "discord", null, { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + entitlementPolicy: policy, + } as Parameters[3]); + expect(nullStart).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); + }); +}); + +describe("caller identity: single authority", () => { + // Item 2. Source tripwire: the header may be read in exactly one module, + // and the per-app secret table may be read only by the two envelope + // openers (HTTP header comparator, private-plane HMAC/AES-GCM opener). + const srcRoot = join(__dirname, "..", "src"); + const sources = readdirSync(srcRoot) + .filter((name) => name.endsWith(".ts")) + .map((name) => [name, readFileSync(join(srcRoot, name), "utf8")] as const); + + it("x-heimdall-app-secret is read only in app-caller.ts", () => { + const readers = sources + .filter(([, text]) => /headers\[\s*["']x-heimdall-app-secret["']\s*\]/.test(text)) + .map(([name]) => name); + expect(readers).toEqual(["app-caller.ts"]); + }); + + it("appSharedSecrets is read only by the HTTP comparator and the private-plane envelope opener", () => { + const readers = sources + .filter(([, text]) => /appSharedSecrets\s*[\[.]/.test(text)) + .map(([name]) => name) + .sort(); + expect(readers).toEqual(["app-caller.ts", "private-command-plane.ts"]); + }); + + it("no source file compares a shared secret with ===", () => { + const offenders = sources + .filter(([, text]) => /[sS]ecret\w*\s*===|===\s*\w*[sS]ecret/.test(text)) + .map(([name]) => name); + expect(offenders).toEqual([]); + }); + + it("AppCaller literals are constructed nowhere; AppCaller is a branded type", () => { + // Item 3 (closed). `{ appSlug }` used to satisfy AppCaller structurally, + // so the private plane (after openPrivateEnvelope + sourceRuntimeId) + // constructed the literal directly — nothing but grep discipline stopped + // any other importer from doing the same. AppCaller is now branded with + // an unexported symbol, and the private plane gets its caller from + // app-caller.ts's callerFromOpenedEnvelope, the same way the HTTP path + // gets its caller from resolveAppCaller. No file may construct the + // literal at all anymore. + const forgers = sources + .filter(([name, text]) => name !== "app-caller.ts" && /(startOAuthFlow|refreshAppSession)\([^;]*\{\s*appSlug\s*\}/s.test(text)) + .map(([name]) => name); + expect(forgers).toEqual([]); + }); +}); + +describe("caller identity: timing-safe comparator", () => { + // Item 4. + it("secretMatches rejects mismatches of any length and both empty sides", () => { + expect(secretMatches("abc", "abd")).toBe(false); + expect(secretMatches("abc", "abcd")).toBe(false); + expect(secretMatches("abc", "")).toBe(false); + expect(secretMatches(undefined, "abc")).toBe(false); + expect(secretMatches("abc", undefined)).toBe(false); + expect(secretMatches("", "")).toBe(false); + expect(secretMatches("abc", "abc")).toBe(true); + }); + + it("app-caller.ts is the only HTTP-side importer of timingSafeEqual", () => { + const srcRoot = join(__dirname, "..", "src"); + const importers = readdirSync(srcRoot) + .filter((name) => name.endsWith(".ts")) + .filter((name) => /timingSafeEqual/.test(readFileSync(join(srcRoot, name), "utf8"))) + .sort(); + expect(importers).toEqual(["app-caller.ts", "private-command-security.ts"]); + }); +}); + +describe("caller identity: private plane envelope authority", () => { + // Item 3. A correctly sealed envelope from the wrong sourceRuntimeId must + // be refused before beginAuth constructs an AppCaller: no auth attempt may + // be created. + it("refuses a valid envelope from an unconfigured runtime before any attempt is created", async () => { + const config = testConfig(); + const store = new InMemoryStore(); + const app = await buildApp({ config, store, oauthRuntimes: { discord: mockDiscordRuntime() } }); + resources.push(app); + const plane = await startHeimdallPrivateCommandPlane(app, config); + resources.push(plane); + + const envelope = sealPrivateEnvelope({ + appSlug: "ghostlight", + operation: "heimdall.auth.begin", + contentSchema: "heimdall.auth_begin_command.v1", + idempotencyKey: "soul-begin-1", + secret: ghostlightSecret, + payload: { + provider: "discord", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, + }, + }); + + const response = await invokeCultNetOperation( + plane.endpoint, + request("heimdall.auth.begin", "soul-wrong-runtime", envelope, "not-ghostlight"), + { runtimeId: "not-ghostlight" } + ); + expect(response.status).toBe("denied"); + + const internals = store as unknown as { authAttempts: Map }; + expect(internals.authAttempts.size).toBe(0); + }, 20_000); +}); + +function request(operation: string, messageId: string, envelope: HeimdallPrivateEnvelope, sourceRuntimeId: string) { + return { + schemaVersion: "cultnet.operation_request.v0" as const, + messageId, + serviceId: "heimdall.private.commands", + operation, + payloadSchema: "heimdall.private_command_envelope.v1", + payloadEncoding: "messagepack-base64" as const, + payload: Buffer.from(encode(envelope)).toString("base64"), + sourceRuntimeId, + }; +} diff --git a/tests/caller-identity.test.ts b/tests/caller-identity.test.ts deleted file mode 100644 index 12e24f8..0000000 --- a/tests/caller-identity.test.ts +++ /dev/null @@ -1,266 +0,0 @@ -import { encode, decode } from "@msgpack/msgpack"; -import { invokeCultNetOperation } from "cultnet-ts"; -import { afterEach, describe, expect, it } from "vitest"; -import { buildApp, getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow } from "../src/app.js"; -import { callerFromOpenedEnvelope, resolveAppCaller, secretMatches } from "../src/app-caller.js"; -import { type HeimdallConfig } from "../src/config.js"; -import { entitlementFacts } from "../src/facts.js"; -import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; -import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; -import { InMemoryStore } from "../src/store/index.js"; -import { createTestConfig, launchFlow, launchState } from "./oauth-flow.js"; - -const ghostlightSecret = "ghostlight-private-command-secret"; -const resources: Array<{ close(): Promise }> = []; - -afterEach(async () => { - await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); -}); - -function callerTestConfig(): HeimdallConfig { - const base = createTestConfig(); - return { - ...base, - privateCommandHost: "127.0.0.1", - privateCommandPort: 0, - appSharedSecrets: { - ...base.appSharedSecrets, - ghostlight: ghostlightSecret, - }, - appRuntimeIds: { - ghostlight: ["yggdrasil-ghostlight"], - }, - }; -} - -function identityByCodeRuntime(): OAuthProviderRuntime { - return { - async exchangeAuthorizationCode({ code }) { - return { accessToken: code, tokenType: "Bearer", scope: ["identify"], raw: {} }; - }, - async resolveIdentity({ accessToken }) { - return { provider: "discord", providerUserId: accessToken, displayName: accessToken, profile: {} }; - }, - async evaluateEntitlements() { - return { facts: [entitlementFacts.appAccess], snapshots: [] }; - }, - }; -} - -async function createHarness() { - const config = callerTestConfig(); - const store = new InMemoryStore(); - const app = await buildApp({ config, store, oauthRuntimes: { discord: identityByCodeRuntime() } }); - resources.push(app); - return { app, store, config }; -} - -function jwtPayload(token: string): Record { - const [, body] = token.split("."); - return JSON.parse(Buffer.from(body ?? "", "base64url").toString("utf8")) as Record; -} - -describe("caller identity and secret comparison", () => { - it("secretMatches rejects mismatches of any length and empty/missing inputs", () => { - expect(secretMatches("abc", "abd")).toBe(false); - expect(secretMatches("abc", "abcd")).toBe(false); - expect(secretMatches("abc", "")).toBe(false); - expect(secretMatches(undefined, "abc")).toBe(false); - expect(secretMatches("abc", undefined)).toBe(false); - expect(secretMatches("", "")).toBe(false); - expect(secretMatches("abc", "abc")).toBe(true); - }); - - it("refuses missing or wrong secrets on startRequiresAppCaller and policy routes", async () => { - const { app, config } = await createHarness(); - const ctx = getHeimdallRuntimeContext(app); - - for (const headers of [undefined, {}, { "x-heimdall-app-secret": "wrong-secret" }, { "x-heimdall-app-secret": "repixelizer-secret" }]) { - const response = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - ...(headers ? { headers } : {}), - payload: { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - }, - }); - expect([response.statusCode, response.json().error]).toEqual([401, "app_auth_required"]); - } - - const repixelizerCaller = resolveAppCaller(config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" }); - expect(repixelizerCaller?.appSlug).toBe("repixelizer"); - - const policy = { kind: "discord_role_access" as const, guildId: "g", allowedRoleIds: ["r"] }; - expect(await startOAuthFlow(ctx, "discord", null, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - entitlementPolicy: policy, - })).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); - - expect(await refreshAppSession(ctx, "repixelizer", callerFromOpenedEnvelope("ghostlight"), { - refreshToken: "irrelevant", - entitlementPolicies: [policy], - })).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); - }); - - it("drops caller-supplied attemptId on HTTP starts and rejects untrusted returnTo origins", async () => { - const { app } = await createHarness(); - - const untrustedReturn = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://attacker.example/collect" }, - }); - expect(untrustedReturn.statusCode).toBe(400); - - const start = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - payload: { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "browser_completion", attemptId: "attacker-fixed-code" }, - }, - }); - expect(start.statusCode).toBe(201); - expect(start.json().handoff).toEqual({ kind: "browser_completion" }); - - const flow = await launchFlow(app, start.json()); - const callback = await app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=victim&state=${encodeURIComponent(flow.state)}`, - headers: { accept: "application/json", cookie: flow.cookie }, - }); - expect(callback.statusCode).toBe(201); - const mintedCode = callback.json().completion.code as string; - expect(mintedCode).not.toBe("attacker-fixed-code"); - - const byAttempt = await app.inject({ - method: "POST", - url: "/v1/apps/repixelizer/auth-completions/redeem", - payload: { completionCode: "attacker-fixed-code" }, - }); - expect(byAttempt.statusCode).toBe(410); - - const crossApp = await app.inject({ - method: "POST", - url: "/v1/apps/bifrost/auth-completions/redeem", - payload: { completionCode: mintedCode }, - }); - expect(crossApp.statusCode).toBe(410); - }); - - it("returns 404 for unknown and prototype keys on GET /v1/apps/:appSlug", async () => { - const { app } = await createHarness(); - for (const key of ["nope", "constructor", "toString", "__proto__", "hasOwnProperty"]) { - const response = await app.inject({ method: "GET", url: `/v1/apps/${key}` }); - expect(response.statusCode, key).toBe(404); - } - }); -}); - -describe("private command plane caller authentication", () => { - function envelopeRequest(operation: string, messageId: string, envelope: HeimdallPrivateEnvelope, sourceRuntimeId: string) { - return { - schemaVersion: "cultnet.operation_request.v0" as const, - messageId, - serviceId: "heimdall.private.commands", - operation, - payloadSchema: "heimdall.private_command_envelope.v1", - payloadEncoding: "messagepack-base64" as const, - payload: Buffer.from(encode(envelope)).toString("base64"), - sourceRuntimeId, - }; - } - - it("refuses an unconfigured sourceRuntimeId before creating an auth attempt", async () => { - const { app, store, config } = await createHarness(); - const plane = await startHeimdallPrivateCommandPlane(app, config); - resources.push(plane); - - const envelope = sealPrivateEnvelope({ - appSlug: "ghostlight", - operation: "heimdall.auth.begin", - contentSchema: "heimdall.auth_begin_command.v1", - idempotencyKey: "wrong-runtime-begin", - secret: ghostlightSecret, - payload: { - provider: "discord", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - }, - }); - - const response = await invokeCultNetOperation( - plane.endpoint, - envelopeRequest("heimdall.auth.begin", "msg-wrong-runtime", envelope, "not-ghostlight"), - { runtimeId: "not-ghostlight" } - ); - expect(response.status).toBe("denied"); - expect((store as unknown as { authAttempts: Map }).authAttempts.size).toBe(0); - }, 20_000); - - it("binds server-minted attempt handle on begin, correlates callback, and redeems on complete", async () => { - const { app, store, config } = await createHarness(); - const plane = await startHeimdallPrivateCommandPlane(app, config); - resources.push(plane); - - const beginEnvelope = sealPrivateEnvelope({ - appSlug: "ghostlight", - operation: "heimdall.auth.begin", - contentSchema: "heimdall.auth_begin_command.v1", - idempotencyKey: "legit-begin", - secret: ghostlightSecret, - payload: { - provider: "discord", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - }, - }); - const beginResponse = await invokeCultNetOperation( - plane.endpoint, - envelopeRequest("heimdall.auth.begin", "msg-begin", beginEnvelope, "yggdrasil-ghostlight"), - { runtimeId: "yggdrasil-ghostlight" } - ); - expect(beginResponse.status).toBe("accepted"); - const receipt = openPrivateEnvelope(decode(Buffer.from(beginResponse.payload, "base64")) as HeimdallPrivateEnvelope, ghostlightSecret); - expect(receipt.status).toBe("pending"); - - const handle = String(receipt.handle); - const state = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; - expect(jwtPayload(state).handoff).toEqual({ kind: "browser_completion", attemptId: handle }); - - const { cookie } = await launchState(app, state); - const callback = await app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=victim&state=${encodeURIComponent(state)}`, - headers: { accept: "application/json", cookie }, - }); - expect(callback.statusCode).toBe(201); - expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed"); - - const completeEnvelope = sealPrivateEnvelope({ - appSlug: "ghostlight", - operation: "heimdall.auth.complete", - contentSchema: "heimdall.auth_complete_command.v1", - idempotencyKey: "legit-complete", - secret: ghostlightSecret, - payload: { handle }, - }); - const completeResponse = await invokeCultNetOperation( - plane.endpoint, - envelopeRequest("heimdall.auth.complete", "msg-complete", completeEnvelope, "yggdrasil-ghostlight"), - { runtimeId: "yggdrasil-ghostlight" } - ); - expect(completeResponse.status).toBe("accepted"); - const completed = openPrivateEnvelope(decode(Buffer.from(completeResponse.payload, "base64")) as HeimdallPrivateEnvelope, ghostlightSecret); - expect(completed.status).toBe("authenticated"); - expect(completed.accessToken).toEqual(expect.any(String)); - expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("consumed"); - }, 20_000); -}); diff --git a/tests/entrypoint-secrets.test.ts b/tests/entrypoint-secrets.test.ts index 6d14f54..941c8c5 100644 --- a/tests/entrypoint-secrets.test.ts +++ b/tests/entrypoint-secrets.test.ts @@ -1,61 +1,65 @@ import { spawn } from "node:child_process"; -import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; -import { createServer } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { afterAll, describe, expect, it } from "vitest"; +// A secret must never reach a terminal. Under Idunn, Heimdall's stderr goes to +// the journal and the install script tails the journal to the operator's +// terminal, so the layer that matters is the process's own output, not an +// error's message. These cases run the real entrypoint with canary values in +// the places a misbinding puts secrets, and fail on any byte of the canary +// anywhere on stdout or stderr: in a message, an error cause, an error +// property, or anything else Node chooses to print. + const repoRoot = fileURLToPath(new URL("..", import.meta.url)); const tsxCli = createRequire(import.meta.url).resolve("tsx/cli"); const scratch = mkdtempSync(join(tmpdir(), "heimdall-entrypoint-")); -chmodSync(scratch, 0o755); const CANARY = "CANARY"; afterAll(() => { rmSync(scratch, { recursive: true, force: true }); }); -function secretFile(name: string, contents: string): string { - const filePath = join(scratch, name); - writeFileSync(filePath, contents); - return filePath; +function file(name: string, contents: string): string { + const path = join(scratch, name); + writeFileSync(path, contents); + return path; } -function reserveLoopbackPort(): Promise { - return new Promise((resolve, reject) => { - const server = createServer(); - server.once("error", reject); - server.listen(0, "127.0.0.1", () => { - const address = server.address(); - if (!address || typeof address === "string") { - server.close(() => reject(new Error("Expected numeric ephemeral port"))); - return; - } - const { port } = address; - server.close((err) => (err ? reject(err) : resolve(port))); - }); - }); +interface Run { + code: number | null; + signal: NodeJS.Signals | null; + output: string; } -function killProcessTree(child: ReturnType): void { - if (process.platform !== "win32" && child.pid) { - try { - process.kill(-child.pid, "SIGKILL"); - return; - } catch { - // fall through if already exited - } - } - child.kill("SIGKILL"); +interface Identity { + uid: number; + gid: number; } -function runEntrypoint(name: string, env: Record): Promise<{ code: number | null; signal: NodeJS.Signals | null; output: string }> { +/** + * Who can be denied a read. Root reads a mode-000 file, so a read failure is + * only reachable as another user: the process itself when it is not root, or + * else the checkout's owner, who can still load the entrypoint. A string is + * the reason no such user exists here. + */ +function nonRootReader(): Identity | "self" | string { + if (process.platform === "win32") return "file modes do not deny reads on Windows"; + if (process.getuid?.() !== 0) return "self"; + const owner = statSync(repoRoot); + if (owner.uid === 0) return "running as root in a root-owned checkout, so no other user can load the entrypoint"; + return { uid: owner.uid, gid: owner.gid }; +} + +/** Runs `tsx src/index.ts` with only the given environment, merging stdout and stderr. */ +function runEntrypoint(name: string, env: Record, identity?: Identity): Promise { return new Promise((resolve, reject) => { const child = spawn(process.execPath, [tsxCli, "src/index.ts"], { cwd: repoRoot, - detached: process.platform !== "win32", + ...identity, env: { PATH: process.env.PATH ?? "", HOME: scratch, @@ -69,7 +73,8 @@ function runEntrypoint(name: string, env: Record): Promise<{ cod let output = ""; child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString("utf8"))); child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString("utf8"))); - const timer = setTimeout(() => killProcessTree(child), 30_000); + // A case that fails to fail would start serving; stop it rather than hang. + const timer = setTimeout(() => child.kill("SIGKILL"), 30_000); child.on("error", reject); child.on("close", (code, signal) => { clearTimeout(timer); @@ -78,90 +83,171 @@ function runEntrypoint(name: string, env: Record): Promise<{ cod }); } -function canaryTokenKey(): string { - return `${CANARY}key`.padEnd(43, "A") + "="; +/** A base64 value that decodes to exactly 32 bytes and still carries the canary. */ +function canaryTokenKey(tag: string): string { + return `${CANARY}${tag}`.padEnd(43, "A") + "="; } -describe("entrypoint startup and secret redaction smoke checks", () => { - it("startup failure redacts configured secrets from stdout and stderr", async () => { - const run = await runEntrypoint("redact", { +interface Case { + name: string; + env: () => Record; + /** Something the failure must say, so a case cannot pass by never reaching its path. */ + expect: RegExp; + /** Run the entrypoint as a user a file mode can refuse. */ + nonRoot?: true; +} + +const cases: Case[] = [ + { + name: "a URL bound into an absolute _FILE slot", + env: () => ({ GC_ACCESS_DATABASE_URL_FILE: `/postgres://heimdall:${CANARY}url@db/heimdall` }), + expect: /GC_ACCESS_DATABASE_URL_FILE could not be read \(ENOENT\)/, + }, + { + name: "a _FILE path under a regular file", + env: () => ({ GC_ACCESS_DATABASE_URL_FILE: join(file("plain", "x"), `${CANARY}notdir`) }), + expect: /GC_ACCESS_DATABASE_URL_FILE could not be read \(ENOTDIR\)/, + }, + { + name: "a secret bound into a relative _FILE slot", + env: () => ({ GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE: `${CANARY}relative-secret` }), + expect: /GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE is not an absolute path/, + }, + { + name: "a secret bound both ways", + env: () => ({ + GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET: `${CANARY}plain`, + GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE: file("both", `${CANARY}file\n`), + }), + expect: /GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET and GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE are both set/, + }, + { + name: "a blank secret file", + env: () => ({ GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE: join(scratch, "blank") }), + expect: /GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE is empty/, + }, + { + name: "a token key that decodes short", + env: () => ({ GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: file("short-key", `${CANARY}shortkey\n`) }), + expect: /GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE must decode to exactly 32 bytes/, + }, + { + name: "a database URL with an unusable port", + env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-port", `postgres://heimdall:${CANARY}port@db:notaport/heimdall\n`) }), + expect: /Postgres storage could not be prepared \(ERR_INVALID_URL\)/, + }, + { + name: "a database URL that does not parse", + env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-parse", `postgres://heimdall:${CANARY} parse@[bad/heimdall\n`) }), + expect: /Postgres storage could not be prepared \(E[A-Z_]+\)/, + }, + { + name: "a database URL with a broken percent escape", + env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-percent", `postgres://heimdall:${CANARY}%zz@127.0.0.1:1/heimdall\n`) }), + expect: /Postgres storage could not be prepared \(ECONNREFUSED\)/, + }, + { + name: "a database that refuses the connection", + env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-refused", `postgres://heimdall:${CANARY}refused@127.0.0.1:1/heimdall\n`) }), + expect: /Postgres storage could not be prepared \(ECONNREFUSED\)/, + }, + { + // A password holding an unescaped delimiter moves part of it into the + // host, and the resolver's error names the host. + name: "a database host that does not resolve", + env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-host", `postgres://heimdall:pw@${CANARY}host.invalid/heimdall\n`) }), + expect: /Postgres storage could not be prepared \(E[A-Z_]+\)/, + }, + { + // A start that does not apply the schema still connects, so a misbound URL + // fails at startup rather than in a request's error answer. + name: "a database host that does not resolve, on a start that does not apply the schema", + env: () => ({ + GC_ACCESS_APPLY_SCHEMA_ON_STARTUP: "0", + GC_ACCESS_DATABASE_URL_FILE: file("db-host-noapply", `postgres://heimdall:pw@${CANARY}host.invalid/heimdall\n`), + }), + expect: /Postgres storage could not be prepared \(E[A-Z_]+\)/, + }, + { + name: "private key text bound to the signing key path", + env: () => ({ + GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: `-----BEGIN PRIVATE KEY-----\n${CANARY}pem\n-----END PRIVATE KEY-----\n`, + }), + expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH is not an absolute path/, + }, + { + name: "a signing key path that names no file", + env: () => ({ GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: join(scratch, `${CANARY}missing-key`) }), + expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH names no file \(ENOENT\)/, + }, + { + name: "a signing key file that is not a key", + env: () => ({ GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: file("not-a-key", `${CANARY}notakey\n`) }), + expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH does not hold a usable private key/, + }, + { + name: "a signing key file its reader may not read", + env: () => { + const key = file(`${CANARY}locked-key`, `${CANARY}pem\n`); + chmodSync(key, 0o000); + const dataRoot = join(scratch, "locked-key-data"); + mkdirSync(dataRoot, { recursive: true }); + chmodSync(dataRoot, 0o777); + return { GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: key, GC_ACCESS_DATA_ROOT: dataRoot }; + }, + expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH could not be read \(EACCES\)/, + nonRoot: true, + }, + { + name: "a signing key path that is a directory", + env: () => { + const dir = join(scratch, "key-dir"); + mkdirSync(dir, { recursive: true }); + return { GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: dir }; + }, + expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH could not be read \(EISDIR\)/, + }, + { + name: "a bootstrapped signing key whose directory cannot be created", + env: () => ({ + GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: join(file("key-parent", "x"), `${CANARY}dir`, "key.pem"), + GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP: "1", + }), + expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH could not be created \(ENOTDIR\)/, + }, + { + // Every secret is configured and valid, and startup fails afterwards, in + // the entrypoint's own catch: the one place that holds the whole config. + name: "a listen failure with every secret configured", + env: () => ({ HOST: "203.0.113.1", - GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: secretFile("token-key", `${canaryTokenKey()}\n`), - GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: secretFile("bifrost-secret", `${CANARY}bifrost\n`), - GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE: secretFile("github-secret", `${CANARY}github\n`), - }); + GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: file("listen-key", `${canaryTokenKey("key")}\n`), + GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE: file("listen-patron", `${CANARY}patron\n`), + GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE: file("listen-github", `${CANARY}github\n`), + GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: file("listen-bifrost", `${CANARY}bifrost\n`), + }), + expect: /Heimdall failed to start/, + }, +]; - expect(run.signal).toBeNull(); - expect(run.code).not.toBe(0); - expect(run.output).toMatch(/Heimdall failed to start/); - expect(run.output).not.toContain(CANARY); - }, 45_000); +describe("the entrypoint never prints a secret", () => { + writeFileSync(join(scratch, "blank"), " \n"); + // mkdtemp makes the scratch directory private to its creator; a non-root + // reader must still reach the files a case names inside it. + chmodSync(scratch, 0o755); + const reader = nonRootReader(); - it("missing required config fails cleanly", async () => { - const run = await runEntrypoint("missing-base-url", { - GAMECULT_IDUNN_CANDIDATE_BIND: "127.0.0.1:4100", - }); + for (const testCase of cases) { + const skipReason = testCase.nonRoot && typeof reader === "string" && reader !== "self" ? reader : undefined; + const title = `refuses ${testCase.name} without printing the canary${skipReason ? ` (skipped: ${skipReason})` : ""}`; + it.skipIf(skipReason !== undefined)(title, async () => { + const identity = testCase.nonRoot && typeof reader === "object" ? reader : undefined; + const run = await runEntrypoint(testCase.name.replace(/\W+/g, "-"), testCase.env(), identity); - expect(run.signal).toBeNull(); - expect(run.code).not.toBe(0); - expect(run.output).toMatch(/GC_ACCESS_BASE_URL is required when GAMECULT_IDUNN_CANDIDATE_BIND is set/); - }, 45_000); - - it("valid config starts and serves /healthz without printing configured secrets", async () => { - const port = await reserveLoopbackPort(); - const child = spawn(process.execPath, [tsxCli, "src/index.ts"], { - cwd: repoRoot, - detached: process.platform !== "win32", - env: { - PATH: process.env.PATH ?? "", - HOME: scratch, - GC_ACCESS_DATA_ROOT: join(scratch, "data-valid"), - HOST: "127.0.0.1", - PORT: String(port), - GC_ACCESS_PRIVATE_COMMAND_PORT: "0", - GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: secretFile("valid-token-key", `${canaryTokenKey()}\n`), - GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: secretFile("valid-bifrost", `${CANARY}bifrost\n`), - GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID: "discord-client-id", - GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE: secretFile("valid-discord", `${CANARY}discord\n`), - }, - stdio: ["ignore", "pipe", "pipe"], - }); - - let buf = ""; - let exited: number | null | undefined; - const closed = new Promise((resolve) => { - child.stdout.on("data", (chunk: Buffer) => (buf += chunk.toString("utf8"))); - child.stderr.on("data", (chunk: Buffer) => (buf += chunk.toString("utf8"))); - child.on("close", (code) => { - exited = code; - resolve(); - }); - }); - - try { - const deadline = Date.now() + 25_000; - let health: { ok?: boolean; service?: string } | undefined; - while (Date.now() < deadline && exited === undefined) { - try { - const response = await fetch(`http://127.0.0.1:${port}/healthz`); - if (response.ok) { - health = (await response.json()) as { ok?: boolean; service?: string }; - break; - } - } catch { - // listener not ready yet - } - await new Promise((resolve) => setTimeout(resolve, 100)); - } - - expect(health, `Expected /healthz to respond 200; exited=${exited}; output:\n${buf}`).toMatchObject({ - ok: true, - service: "heimdall", - }); - expect(buf).not.toContain(CANARY); - } finally { - killProcessTree(child); - await closed; - } - }, 45_000); + expect(run.signal, "the process must stop by itself").toBeNull(); + expect(run.code, "startup must fail").not.toBe(0); + expect(run.output).toMatch(testCase.expect); + expect(run.output.includes(CANARY), "no byte of the canary may reach the terminal").toBe(false); + }, 45_000); + } }); diff --git a/tests/google-link.test.ts b/tests/google-link.test.ts index a196b59..4a1fc6d 100644 --- a/tests/google-link.test.ts +++ b/tests/google-link.test.ts @@ -1,25 +1,18 @@ import { createHash, createSign, generateKeyPairSync } from "node:crypto"; import { afterEach, describe, expect, it, vi } from "vitest"; import { type FastifyInstance } from "fastify"; -import { decode, encode } from "@msgpack/msgpack"; -import { invokeCultNetOperation } from "cultnet-ts"; import { buildApp } from "../src/app.js"; import { loadConfig, type HeimdallConfig } from "../src/config.js"; import { resetGoogleJwksCache } from "../src/google-oidc.js"; import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; -import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; -import { decodeJwt } from "../src/signing.js"; import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js"; import { launchFlow, launchWithRedirect, stateOf, type LaunchedFlow } from "./oauth-flow.js"; const CLIENT_ID = "google-client"; -const GHOSTLIGHT_SECRET = "ghostlight-private-command-secret"; const REDIRECT = "https://heimdall.gamecult.org/v1/oauth/google/callback"; const rsa = generateKeyPairSync("rsa", { modulusLength: 2048 }); const originalFetch = globalThis.fetch; const apps: FastifyInstance[] = []; -const planes: Array<{ close(): Promise }> = []; function config(): HeimdallConfig { const base = loadConfig({ @@ -32,10 +25,7 @@ function config(): HeimdallConfig { storage: { backend: "memory", applySchemaOnStartup: true }, tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), bootstrapSigningPrivateKeyOnMissing: true, - privateCommandHost: "127.0.0.1", - privateCommandPort: 0, - appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret", repixelizer: "repixelizer-secret", ghostlight: GHOSTLIGHT_SECRET }, - appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, + appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret" }, providers: { ...base.providers, google: { clientId: CLIENT_ID, clientSecret: "google-secret" }, @@ -195,7 +185,6 @@ async function linkGoogle(app: FastifyInstance, token: string, claims?: Record { globalThis.fetch = originalFetch; resetGoogleJwksCache(); - while (planes.length) await planes.pop()?.close(); while (apps.length) await apps.pop()?.close(); }); @@ -546,317 +535,3 @@ describe("Google as a Heimdall OIDC provider", () => { expect(accountCount(store)).toBe(1); }); }); - -describe("an invite grant lets Bifrost's sign-in start mint the first Google account", () => { - const RETURN = "https://bifrost.gamecult.org/auth/heimdall/complete"; - - function startGrant(app: FastifyInstance, extra: Record = {}, headers: Record = BIFROST_APP) { - return app.inject({ - method: "POST", - url: "/v1/oauth/google/start", - headers, - payload: { appSlug: "bifrost", mode: "sign_in", returnTo: RETURN, firstLoginGrant: "invite", ...extra }, - }); - } - - async function googleCallback(app: FastifyInstance, start: { json(): never }, claims?: Record) { - const flow = await launchWithRedirect(app, start.json()); - fakeGoogle({ nonceFrom: () => flow.url.searchParams.get("nonce") ?? undefined, ...(claims ? { claims } : {}) }); - return { flow, done: await callbackGoogle(app, flow) }; - } - - const auditEvents = (store: InMemoryStore) => - [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; - - it("google_first_login_without_grant_refused: no grant, identity_not_linked, nothing minted", async () => { - const { app, store } = await build(); - const start = await startGoogle(app, undefined, "sign_in"); - const { done } = await googleCallback(app, start); - expect([done.statusCode, done.json().error]).toEqual([403, "identity_not_linked"]); - expect(accountCount(store)).toBe(0); - }); - - it("google_first_login_with_bifrost_grant_mints: one account, the identity linked to it, audited", async () => { - const { app, store } = await build(); - const start = await startGrant(app); - expect(start.statusCode).toBe(201); - const { done } = await googleCallback(app, start); - expect(done.statusCode).toBe(201); - expect(accountCount(store)).toBe(1); - expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(done.json().account.id); - const minted = auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant"); - expect(minted.map((e) => e.eventPayloadJson)).toEqual([{ provider: "google", appSlug: "bifrost" }]); - }); - - it("a granted state is single-use: replaying the callback mints nothing more", async () => { - const { app, store } = await build(); - const start = await startGrant(app); - const { flow } = await googleCallback(app, start); - const again = await callbackGoogle(app, flow); - expect(again.statusCode).toBeGreaterThanOrEqual(400); - expect(accountCount(store)).toBe(1); - }); - - it("grant_from_other_app_refused: an app whose profile may not grant gets first_login_grant_refused", async () => { - const { app, store } = await build(); - const res = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - headers: { "x-heimdall-app-secret": "repixelizer-secret" }, - payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" }, - }); - expect([res.statusCode, res.json().error]).toEqual([400, "first_login_grant_refused"]); - // Another app's secret on Bifrost's start is no Bifrost caller. - const other = await startGrant(app, {}, { "x-heimdall-app-secret": "repixelizer-secret" }); - expect(other.statusCode).toBe(401); - expect(accountCount(store)).toBe(0); - }); - - it("grant_without_app_caller_refused: a public start with firstLoginGrant is refused", async () => { - const { app, store } = await build(); - for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }]) { - const res = await startGrant(app, {}, headers); - expect(res.statusCode, JSON.stringify(headers)).toBeGreaterThanOrEqual(400); - expect(res.json().authorizationUrl).toBeUndefined(); - } - // An app that does not require a caller is still refused: a grant is a start only the app itself may make. - const open = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" }, - }); - expect([open.statusCode, open.json().error]).toEqual([401, "app_auth_required"]); - expect(accountCount(store)).toBe(0); - }); - - it("refuses a grant on link mode and a grant value other than invite", async () => { - const { app } = await build(); - const { accessToken } = await signInWithDiscord(app); - const link = await app.inject({ - method: "POST", - url: "/v1/oauth/google/start", - headers: { ...BIFROST_APP, authorization: `Bearer ${accessToken}` }, - payload: { appSlug: "bifrost", mode: "link", returnTo: RETURN, firstLoginGrant: "invite" }, - }); - expect([link.statusCode, link.json().error]).toEqual([400, "first_login_grant_refused"]); - expect((await startGrant(app, { firstLoginGrant: "admin" })).statusCode).toBe(400); - }); - - it("grant_ignored_for_existing_account: a Google identity already held signs in to its account, no second account", async () => { - const { app, store } = await build(); - const { accessToken, accountId } = await signInWithDiscord(app); - await linkGoogle(app, accessToken); - const start = await startGrant(app); - const { done } = await googleCallback(app, start); - expect(done.statusCode).toBe(201); - expect(done.json().account.id).toBe(accountId); - expect(accountCount(store)).toBe(1); - expect(auditEvents(store).some((e) => e.eventType === "account_minted_by_grant")).toBe(false); - }); - - it("a grant never attaches an identity to an existing account: a new sub mints its own account and an held sub is never moved", async () => { - const store = new InMemoryStore(); - const first = await build(store, "discord-1"); - const a = await signInWithDiscord(first.app, "discord-1"); - await linkGoogle(first.app, a.accessToken); - const second = await build(store, "discord-2"); - const b = await signInWithDiscord(second.app, "discord-2"); - const start = await startGrant(second.app); - const { done } = await googleCallback(second.app, start, { sub: "g-sub-new" }); - expect(done.statusCode).toBe(201); - expect(done.json().account.id).not.toBe(a.accountId); - expect(done.json().account.id).not.toBe(b.accountId); - expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(a.accountId); - expect((await store.findStoredLinkedIdentity("google", "g-sub-new"))?.accountId).toBe(done.json().account.id); - }); - - it("grant_tampered_state_refused: a first_login_grant added to a signed state fails verification", async () => { - const { app, store } = await build(); - const plain = await startGoogle(app, undefined, "sign_in"); - const [head, body, sig] = stateOf(plain.json()).split("."); - const payload = JSON.parse(Buffer.from(body!, "base64url").toString()); - const forged = [head, Buffer.from(JSON.stringify({ ...payload, first_login_grant: "invite" })).toString("base64url"), sig].join("."); - const launched = await app.inject({ method: "GET", url: `/v1/oauth/google/launch?state=${encodeURIComponent(forged)}` }); - expect(launched.statusCode).toBe(400); - expect(launched.headers.location).toBeUndefined(); - const cb = await app.inject({ method: "GET", url: `/v1/oauth/google/callback?code=g-code&state=${encodeURIComponent(forged)}` }); - expect(cb.statusCode).toBeGreaterThanOrEqual(400); - expect(accountCount(store)).toBe(0); - }); -}); - -describe("ghostlight admits Google over the private command plane, and the Dungeon's invite is the only grant", () => { - const RETURN = "https://yggdrasil.gamecult.org/ghostlight/"; - let seq = 0; - - async function buildGhostlight() { - const store = new InMemoryStore(); - const cfg = config(); - const app = await buildApp({ config: cfg, store, oauthRuntimes: { discord: discordRuntime("discord-1", "Person") } }); - apps.push(app); - const plane = await startHeimdallPrivateCommandPlane(app, cfg); - planes.push(plane); - return { app, store, plane }; - } - - /** One sealed command to the plane as Ghostlight's own runtime; the opened receipt, or the transport status when refused. */ - async function command(plane: { endpoint: string }, operation: string, contentSchema: string, payload: Record) { - const id = `gl-${++seq}`; - const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey: id, secret: GHOSTLIGHT_SECRET, payload }); - const response = await invokeCultNetOperation( - plane.endpoint, - { - schemaVersion: "cultnet.operation_request.v0" as const, - messageId: id, - serviceId: "heimdall.private.commands", - operation, - payloadSchema: "heimdall.private_command_envelope.v1", - payloadEncoding: "messagepack-base64" as const, - payload: Buffer.from(encode(envelope)).toString("base64"), - sourceRuntimeId: "yggdrasil-ghostlight", - }, - { runtimeId: "yggdrasil-ghostlight" } - ); - if (response.status !== "accepted") return { status: response.status, receipt: undefined }; - const wire = decode(Buffer.from(response.payload, "base64")) as HeimdallPrivateEnvelope; - return { status: response.status, receipt: openPrivateEnvelope(wire, GHOSTLIGHT_SECRET) as Record }; - } - - const begin = (plane: { endpoint: string }, payload: Record) => - command(plane, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", { mode: "sign_in", returnTo: RETURN, ...payload }); - const complete = (plane: { endpoint: string }, handle: unknown) => - command(plane, "heimdall.auth.complete", "heimdall.auth_complete_command.v1", { handle }); - - /** Begin google as Ghostlight, walk the browser to Google and back, and return the callback answer plus the attempt handle. */ - async function googleSignIn(app: FastifyInstance, plane: { endpoint: string }, payload: Record, claims?: Record) { - const started = await begin(plane, { provider: "google", ...payload }); - expect(started.status).toBe("accepted"); - const receipt = started.receipt as { handle: string; navigation: { url: string } }; - const flow = await launchWithRedirect(app, { authorizationUrl: receipt.navigation.url }); - fakeGoogle({ nonceFrom: () => flow.url.searchParams.get("nonce") ?? undefined, ...(claims ? { claims } : {}) }); - return { handle: receipt.handle, done: await callbackGoogle(app, flow) }; - } - - const auditEvents = (store: InMemoryStore) => - [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; - const attemptCount = (store: InMemoryStore) => (store as unknown as { authAttempts: Map }).authAttempts.size; - const capabilitiesOf = (receipt: Record | undefined) => - decodeJwt(String(receipt?.accessToken)).payload.capabilities as string[]; - - it("a first Google sign-in under the Dungeon's invite grant mints one account, audits it, and the claim carries app_access", async () => { - const { app, store, plane } = await buildGhostlight(); - const { handle, done } = await googleSignIn(app, plane, { firstLoginGrant: "invite" }); - expect(done.statusCode, done.body).toBe(201); - expect(accountCount(store)).toBe(1); - const minted = auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant"); - expect(minted.map((e) => e.eventPayloadJson)).toEqual([{ provider: "google", appSlug: "ghostlight" }]); - const completion = (await complete(plane, handle)).receipt; - expect(completion).toMatchObject({ status: "authenticated", handle }); - expect(capabilitiesOf(completion)).toContain("app_access"); - }); - - it("a first Google sign-in with no live grant is refused identity_not_linked and mints nothing", async () => { - const { app, store, plane } = await buildGhostlight(); - for (const extra of [{}, { firstLoginGrant: null }]) { - const { handle, done } = await googleSignIn(app, plane, extra); - expect([done.statusCode, done.json().error]).toEqual([403, "identity_not_linked"]); - expect(auditEvents(store).some((e) => e.eventType === "account_minted_by_grant")).toBe(false); - expect((await complete(plane, handle)).receipt?.status).toBe("denied"); - } - expect(accountCount(store)).toBe(0); - }); - - it("a returning Google identity signs in to its own account with or without the grant, and the grant attaches nothing", async () => { - const { app, store, plane } = await buildGhostlight(); - const first = await googleSignIn(app, plane, { firstLoginGrant: "invite" }); - const accountId = first.done.json().account.id; - for (const extra of [{}, { firstLoginGrant: "invite" }]) { - const again = await googleSignIn(app, plane, extra); - expect(again.done.statusCode, again.done.body).toBe(201); - expect(again.done.json().account.id).toBe(accountId); - } - // A different Google subject under the grant is its own new account; the held one is never moved. - const other = await googleSignIn(app, plane, { firstLoginGrant: "invite" }, { sub: "g-sub-2" }); - expect(other.done.json().account.id).not.toBe(accountId); - expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(accountId); - expect(accountCount(store)).toBe(2); - expect(auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant")).toHaveLength(2); - }); - - it("discord begins and refreshes with no entitlement policy, and the claim carries app_access", async () => { - const { app, plane } = await buildGhostlight(); - const started = await begin(plane, { provider: "discord" }); - expect(started.status).toBe("accepted"); - const receipt = started.receipt as { handle: string; navigation: { url: string } }; - const flow = await launchFlow(app, { authorizationUrl: receipt.navigation.url }); - const callback = await app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(flow.state)}`, - headers: { cookie: flow.cookie }, - }); - expect(callback.statusCode, callback.body).toBe(201); - const completion = (await complete(plane, receipt.handle)).receipt; - expect(completion?.status).toBe("authenticated"); - expect(capabilitiesOf(completion)).toContain("app_access"); - const refreshed = await command(plane, "heimdall.auth.refresh", "heimdall.auth_refresh_command.v1", { refreshToken: completion?.refreshToken }); - expect(refreshed.receipt).toMatchObject({ schema: "heimdall.auth_refresh_receipt.v1", status: "authenticated" }); - expect(capabilitiesOf(refreshed.receipt)).toContain("app_access"); - }); - - it("a public ghostlight start, with no secret or the wrong one, is refused app_auth_required for every provider", async () => { - const { app, store } = await buildGhostlight(); - for (const provider of ["google", "discord"]) { - for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }, { "x-heimdall-app-secret": "bifrost-secret" }]) { - const res = await app.inject({ - method: "POST", - url: `/v1/oauth/${provider}/start`, - headers, - payload: { appSlug: "ghostlight", mode: "sign_in", returnTo: RETURN }, - }); - expect([res.statusCode, res.json().error], `${provider} ${JSON.stringify(headers)}`).toEqual([401, "app_auth_required"]); - expect(res.json().authorizationUrl).toBeUndefined(); - } - } - // The same start with a grant is no easier without the app's secret. - const granted = await app.inject({ - method: "POST", - url: "/v1/oauth/google/start", - payload: { appSlug: "ghostlight", mode: "sign_in", returnTo: RETURN, firstLoginGrant: "invite" }, - }); - expect([granted.statusCode, granted.json().error]).toEqual([401, "app_auth_required"]); - expect(accountCount(store)).toBe(0); - expect(attemptCount(store)).toBe(0); - }); - - it("a begin whose firstLoginGrant is anything but 'invite' is refused before any attempt or state is minted", async () => { - const { plane, store } = await buildGhostlight(); - for (const bad of ["yes", "admin", true, 1, {}]) { - const res = await begin(plane, { provider: "google", firstLoginGrant: bad }); - expect(res.status, JSON.stringify(bad)).not.toBe("accepted"); - } - expect(attemptCount(store)).toBe(0); - }); - - it("a grant on link mode is refused by startOAuthFlow's gate, not smuggled past it", async () => { - const { plane } = await buildGhostlight(); - const res = await begin(plane, { provider: "google", mode: "link", firstLoginGrant: "invite" }); - expect(res.status).not.toBe("accepted"); - }); - - it("other apps are unchanged: repixelizer's public start still opens and its grant is still first_login_grant_refused", async () => { - const { app } = await buildGhostlight(); - const open = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }, - }); - expect(open.statusCode).toBe(201); - const granted = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - headers: { "x-heimdall-app-secret": "repixelizer-secret" }, - payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" }, - }); - expect([granted.statusCode, granted.json().error]).toEqual([400, "first_login_grant_refused"]); - }); -}); diff --git a/tests/private-command-diagnostics.test.ts b/tests/private-command-diagnostics.test.ts index 6db634e..4e62c3d 100644 --- a/tests/private-command-diagnostics.test.ts +++ b/tests/private-command-diagnostics.test.ts @@ -14,7 +14,7 @@ import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope import { InMemoryStore } from "../src/store/index.js"; import { launchState } from "./oauth-flow.js"; -const secret = "bifrost-private-command-secret"; +const secret = "ghostlight-private-command-secret"; const resources: Array<{ close(): Promise }> = []; afterEach(async () => { vi.unstubAllGlobals(); @@ -29,24 +29,24 @@ function config(): HeimdallConfig { idunnRudpHealth: undefined, idunnHealthContract: "heimdall.cultnet-rudp-provider-health", providerHealthIdentityPath: "/tmp/.hd/p.cc", sessionTtlSeconds: 3600, refreshTtlSeconds: 3600, stateTtlSeconds: 600, completionTtlSeconds: 300, bootstrapSigningPrivateKeyOnMissing: false, tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), - appSharedSecrets: { bifrost: secret }, appRuntimeIds: { bifrost: ["bifrost-runtime"] }, appBackendCallbacks: {}, + appSharedSecrets: { ghostlight: secret }, appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, appBackendCallbacks: {}, storage: { backend: "memory", applySchemaOnStartup: true }, providers: { discord: { clientId: "discord-client", clientSecret: "discord-secret" }, patreon: {}, github: {}, twitch: {}, youtube: {}, spotify: {}, joystick: {}, google: {} }, } as HeimdallConfig; } async function command(endpoint: unknown, operation: string, contentSchema: string, key: string, payload: Record) { - const envelope = sealPrivateEnvelope({ appSlug: "bifrost", operation, contentSchema, idempotencyKey: key, secret, payload }); + const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey: key, secret, payload }); return invokeCultNetOperation(endpoint as never, { schemaVersion: "cultnet.operation_request.v0", messageId: `m-${key}`, serviceId: "heimdall.private.commands", operation, payloadSchema: "heimdall.private_command_envelope.v1", payloadEncoding: "messagepack-base64", - payload: Buffer.from(encode(envelope)).toString("base64"), sourceRuntimeId: "bifrost-runtime", - } as never, { runtimeId: "bifrost-runtime" }); + payload: Buffer.from(encode(envelope)).toString("base64"), sourceRuntimeId: "yggdrasil-ghostlight", + } as never, { runtimeId: "yggdrasil-ghostlight" }); } const open = (reply: { payload: string }) => openPrivateEnvelope(decode(Buffer.from(reply.payload, "base64")) as HeimdallPrivateEnvelope, secret); -/** A signed-in Bifrost session, then a refresh whose provider answer is `refreshAnswer`. */ +/** A signed-in Ghostlight session, then a refresh whose provider answer is `refreshAnswer`. */ async function refreshAgainst(refreshAnswer: () => Response) { let refreshing = false; vi.stubGlobal("fetch", async (url: string | URL, init?: RequestInit) => { @@ -72,7 +72,7 @@ async function refreshAgainst(refreshAnswer: () => Response) { resources.push(plane); const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }; const begin = open(await command(plane.endpoint, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", "k1", - { provider: "discord", mode: "sign_in", returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete", entitlementPolicy: policy })); + { provider: "discord", mode: "sign_in", returnTo: "https://yggdrasil.gamecult.org/ghostlight/", entitlementPolicy: policy })); const state = new URL(String((begin.navigation as { url: string }).url)).searchParams.get("state")!; const { cookie } = await launchState(app, state); const callback = await app.inject({ @@ -133,7 +133,7 @@ it("keeps the completion code out of the audit trail when the plane redeems by a resources.push(plane); const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }; const begin = open(await command(plane.endpoint, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", "k1", - { provider: "discord", mode: "sign_in", returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete", entitlementPolicy: policy })); + { provider: "discord", mode: "sign_in", returnTo: "https://yggdrasil.gamecult.org/ghostlight/", entitlementPolicy: policy })); const state = new URL(String((begin.navigation as { url: string }).url)).searchParams.get("state")!; const { cookie } = await launchState(app, state); const callback = await app.inject({ diff --git a/tests/recipe-secrets.test.ts b/tests/recipe-secrets.test.ts index 88be61d..ea144c5 100644 --- a/tests/recipe-secrets.test.ts +++ b/tests/recipe-secrets.test.ts @@ -1,67 +1,228 @@ import { readFileSync } from "node:fs"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { appProfiles } from "../src/app-profiles.js"; -import { ENV_NAMES, SECRET_ENV_NAMES } from "../src/config.js"; -import { providers } from "../src/contracts.js"; +import { appSlugs, providers } from "../src/contracts.js"; import { providerCatalog } from "../src/providers.js"; -const recipe = readFileSync(new URL("../deployment/idunn/recipe.toml", import.meta.url), "utf8").replace(/\r\n/g, "\n"); +// The Idunn recipe decides which environment names a binding may set, and +// Idunn refuses any other. So the recipe is where "a secret is only ever a +// file" is enforced for a deployment: a plaintext secret name declared here +// can carry the secret into the binding, the unit and every plan. +const recipe = readFileSync(new URL("../deployment/idunn/recipe.toml", import.meta.url), "utf8"); + +/** The names in one `KEY = [ "A", "B" ]` array of the given TOML text. */ function stringArray(text: string, key: string): string[] { const match = new RegExp(`^${key}\\s*=\\s*\\[([^\\]]*)\\]`, "m").exec(text); return match ? [...match[1]!.matchAll(/"([^"]+)"/g)].map((name) => name[1]!) : []; } -const serviceSection = /^\[service\]\n([\s\S]*?)(?=^\[)/m.exec(recipe)?.[1] ?? ""; -const serviceNames = new Set([ +const serviceSection = /^\[service\]\n([\s\S]*?)(?=^\[)/m.exec(recipe.replace(/\r\n/g, "\n"))?.[1] ?? ""; +const serviceNames = [ ...stringArray(serviceSection, "optional_environment"), ...stringArray(serviceSection, "required_environment"), -]); -const everyDeclaredName = new Set( - [...recipe.matchAll(/^\w+_environment\s*=\s*\[([^\]]*)\]/gm)].flatMap( - (match) => [...match[1]!.matchAll(/"([^"]+)"/g)].map((name) => name[1]!) - ) +]; +const everyDeclaredName = [...recipe.replace(/\r\n/g, "\n").matchAll(/^\w+_environment\s*=\s*\[([^\]]*)\]/gm)].flatMap( + (match) => [...match[1]!.matchAll(/"([^"]+)"/g)].map((name) => name[1]!) ); +// The secrets Heimdall reads are observed, not read from the source: the real +// loadConfig runs against an environment that records every name it looks +// up. readSecretInput looks up `NAME_FILE` for each secret, so every `_FILE` +// lookup names one, however the call is spelled and whatever list computes +// the name. The recorder also stands in for process.env, both while config.ts +// is imported (freshly, so a copy of process.env taken at module load is the +// recorder too) and during every call. +// +// A read made from a copy of the environment ({ ...env }, Object.entries) +// cannot be seen, so copying or enumerating it is recorded and fails below. +// +// A secret read only on a branch some value opens is reached by running +// loadConfig over many environments, until no run reads a new name: every +// secret found so far set in plaintext; then each name read so far set to +// each probe value (a few shapes, plus every string literal in config.ts); +// then every name at once, each set to a value loadConfig accepted for it +// alone; and every combined run again as Idunn starts Heimdall, with the +// recipe's service arguments and a candidate socket with its base URL, a +// pair loadConfig refuses one name at a time. A run that throws still counts +// the reads it made first. +// +// Known limit: a read gated on a value that is none of the probe values and +// not accepted alone in combination with the others stays unseen. +const configSource = readFileSync(new URL("../src/config.ts", import.meta.url), "utf8"); +const probeValues = [ + ...new Set(["1", "true", "/probe/path", "127.0.0.1:4100", "https://probe.test", ...[...configSource.matchAll(/"([^"\\\r\n]+)"/g)].map((m) => m[1]!)]), +]; + +const recorder = { values: {} as Record, names: new Set(), enumerated: false }; +const recordingEnv = new Proxy({} as NodeJS.ProcessEnv, { + get(_target, name) { + if (typeof name !== "string") return undefined; + recorder.names.add(name); + return recorder.values[name]; + }, + has(_target, name) { + if (typeof name !== "string") return false; + recorder.names.add(name); + return name in recorder.values; + }, + ownKeys() { + recorder.enumerated = true; + return []; + }, + getOwnPropertyDescriptor() { + recorder.enumerated = true; + return undefined; + }, +}); + +async function withRecordingProcessEnv(run: () => T | Promise): Promise { + const processEnv = process.env; + process.env = recordingEnv; + try { + return await run(); + } finally { + process.env = processEnv; + } +} + +/** + * How Idunn starts Heimdall: the recipe's [service] arguments after the + * entry script, each binding given a probe value, and the environment an + * Idunn candidate always has (a loopback socket, which requires the base URL). + */ +const recipeArguments = [...(/^\[service\][\s\S]*?^arguments = \[([\s\S]*?)^\]/m.exec(recipe.replace(/\r\n/g, "\n"))?.[1] ?? "").matchAll( + /\{ kind = "(literal|binding)", (?:value|name) = "([^"]+)" \}/g +)].map((match) => (match[1] === "literal" ? match[2]! : "/probe/idunn-binding")); +const idunnArgv = recipeArguments.slice(1); +const idunnEnv = { GAMECULT_IDUNN_CANDIDATE_BIND: "127.0.0.1:4100", GC_ACCESS_BASE_URL: "https://probe.test" }; + +vi.resetModules(); +const { loadConfig } = await withRecordingProcessEnv(() => import("../src/config.js")); + +/** The names one loadConfig run reads under `values`, and whether it accepted them. */ +async function readsOf( + values: Readonly>, + argv: readonly string[] = [] +): Promise<{ names: Set; accepted: boolean }> { + recorder.values = { ...values }; + recorder.names = new Set(); + let accepted = true; + await withRecordingProcessEnv(() => { + try { + loadConfig(recordingEnv, argv); + } catch { + accepted = false; // the reads before the refusal still count + } + }); + return { names: recorder.names, accepted }; +} + +async function exploreLoadConfig(): Promise<{ names: Set; enumerated: boolean }> { + const names = new Set(); + recorder.enumerated = false; + const secretsOf = () => [...names].filter((name) => name.endsWith("_FILE")).map((name) => name.slice(0, -"_FILE".length)); + for (let grew = true; grew; ) { + const before = names.size; + const secrets = Object.fromEntries(secretsOf().map((name) => [name, "probe-secret"])); + const settable = [...names].filter((name) => !name.endsWith("_FILE") && !(name in secrets)); + const accepted = new Map(); + const keep = (run: { names: Set }) => run.names.forEach((name) => names.add(name)); + keep(await readsOf({})); + keep(await readsOf(secrets)); + keep(await readsOf({ ...secrets, ...idunnEnv }, idunnArgv)); + for (const name of settable) { + for (const value of probeValues) { + const run = await readsOf({ ...secrets, [name]: value }); + keep(run); + if (run.accepted) accepted.set(name, [...(accepted.get(name) ?? []), value]); + } + } + const widest = Math.max(0, ...[...accepted.values()].map((values) => values.length)); + for (let round = 0; round < widest; round += 1) { + const together = Object.fromEntries([...accepted].map(([name, values]) => [name, values[round % values.length]!])); + keep(await readsOf({ ...secrets, ...together })); + keep(await readsOf({ ...secrets, ...together, ...idunnEnv }, idunnArgv)); + } + grew = names.size > before; + } + return { names, enumerated: recorder.enumerated }; +} + +const explored = await exploreLoadConfig(); + +/** Secrets Heimdall reads through readSecretInput, by their plaintext name. */ +const secretNames = [...explored.names] + .filter((name) => name.endsWith("_FILE")) + .map((name) => name.slice(0, -"_FILE".length)); + const secretShaped = /SECRET|PASSWORD|PASSPHRASE|TOKEN|API_KEY|PRIVATE_KEY|ENCRYPTION_KEY|SALT|CREDENTIAL|DATABASE_URL|_DSN|_PEM|HMAC/; +/** Secret-shaped names that hold no secret, each for its own reason. */ const notSecrets = new Set([ + // A path to the signing key file, which Heimdall reads (or creates) itself. "GC_ACCESS_SIGNING_PRIVATE_KEY_PATH", + // A flag: create that file on first boot. "GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP", ]); -const neverBound = new Set([ - "HOST", - "PORT", - "GC_ACCESS_DATA_ROOT", - "GC_ACCESS_CULTCACHE_PATH", - "GC_ACCESS_PROVIDER_HEALTH_IDENTITY_PATH", - "GC_ACCESS_IDUNN_DAEMON", -]); - describe("Idunn recipe secret declarations", () => { - it("declares every expected _FILE secret and never binds plaintext secrets", () => { - const expectedSecretFiles = new Set([ - ...SECRET_ENV_NAMES.map((name) => `${name}_FILE`), - ...providers.map((provider) => providerCatalog[provider].clientSecretEnv), - ...Object.values(appProfiles).map((profile) => `GC_ACCESS_APP_${profile.slug.toUpperCase()}_SHARED_SECRET_FILE`), - ]); + it("reads the service's declared environment", () => { + expect(serviceNames).toContain("GC_ACCESS_DATABASE_URL_FILE"); + expect(serviceNames).toContain("GC_ACCESS_BASE_URL"); + }); - const missingSecretFiles = [...expectedSecretFiles].filter((name) => !serviceNames.has(name)); - expect(missingSecretFiles).toEqual([]); - - const boundPlaintext = SECRET_ENV_NAMES.filter((name) => everyDeclaredName.has(name)); - expect(boundPlaintext).toEqual([]); - - const secretShapedPlaintext = [...everyDeclaredName].filter( + it("declares no secret-shaped name except as a _FILE credential path", () => { + const plaintext = everyDeclaredName.filter( (name) => secretShaped.test(name) && !name.endsWith("_FILE") && !notSecrets.has(name) ); - expect(secretShapedPlaintext).toEqual([]); + expect(plaintext).toEqual([]); }); - it("declares every config ENV_NAME except host-fixed exclusions", () => { - const undeclared = ENV_NAMES.filter((name) => !everyDeclaredName.has(name) && !neverBound.has(name)); - expect(undeclared).toEqual([]); + it("starts the exploration the way the recipe starts Heimdall", async () => { + expect(idunnArgv).toEqual(["--state-root", "/probe/idunn-binding"]); + expect(serviceNames).toEqual(expect.arrayContaining(Object.keys(idunnEnv))); + expect((await readsOf({ ...idunnEnv }, idunnArgv)).accepted).toBe(true); + }); + + it("reads the environment only by name, never by copying or enumerating it", () => { + expect(explored.enumerated).toBe(false); + }); + + it("sees every secret loadConfig reads, across the provider and app lists", () => { + expect(secretNames).toEqual( + expect.arrayContaining([ + "GC_ACCESS_DATABASE_URL", + "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64", + "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET", + ...providers.map((provider) => `GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_SECRET`), + ...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_SHARED_SECRET`), + ]) + ); + }); + + it("declares none of the secrets Heimdall reads under its plaintext name", () => { + for (const name of secretNames) { + expect(everyDeclaredName).not.toContain(name); + } + }); + + it("declares every provider client-secret file the witness publishes", () => { + for (const provider of providers) { + expect(serviceNames).toContain(providerCatalog[provider].clientSecretEnv); + } + }); + + it("declares the shared-secret file of every app profile the witness publishes", () => { + for (const profile of Object.values(appProfiles)) { + expect(serviceNames).toContain(`GC_ACCESS_APP_${profile.slug.toUpperCase()}_SHARED_SECRET_FILE`); + } + }); + + it("declares the _FILE of every secret Heimdall reads", () => { + for (const name of secretNames) { + expect(serviceNames).toContain(`${name}_FILE`); + } }); }); diff --git a/tests/step-up-assertion.test.ts b/tests/step-up-assertion.test.ts index 7ed66e2..f064e00 100644 --- a/tests/step-up-assertion.test.ts +++ b/tests/step-up-assertion.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; -import { buildApp } from "../src/app.js"; +import { buildApp, STEP_UP_ASSERT_LIMITS } from "../src/app.js"; import { builtInAppProfiles } from "../src/app-profiles.js"; import { issueAccessClaim } from "../src/claims.js"; import { type Provider } from "../src/contracts.js"; @@ -312,6 +312,85 @@ describe("the method and the nonce", () => { }); }); +describe("rate limits", () => { + it("trips per account, leaves other accounts alone, and turns over with the window", async () => { + const r = await rig(); + const m = await member(r); + const other = await member(r); + vi.useFakeTimers({ toFake: ["Date"] }); + for (let i = 0; i < STEP_UP_ASSERT_LIMITS.account.max; i += 1) { + expect((await assertStepUp(r, { token: m.token, nonce: nonce(`r${i}`) })).statusCode, `attempt ${i}`).toBe(201); + } + const tripped = await assertStepUp(r, { token: m.token, nonce: nonce("over") }); + expect(refused(tripped)).toEqual([429, "step_up_rate_limited"]); + expect(tripped.json().retryAfterSeconds).toBeGreaterThan(0); + expect(tripped.json()).not.toHaveProperty("accessToken"); + expect((await assertStepUp(r, { token: other.token })).statusCode).toBe(201); + vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.account.windowMs + 1000); + expect((await assertStepUp(r, { token: m.token, nonce: nonce("after") })).statusCode).toBe(201); + // The tripped attempt did not spend its nonce. + expect((await assertStepUp(r, { token: m.token, nonce: nonce("over") })).statusCode).toBe(201); + }); + + it("trips per app across accounts, counting attempts that failed their bearer", async () => { + const r = await rig(); + const m = await member(r); + vi.useFakeTimers({ toFake: ["Date"] }); + for (let i = 0; i < STEP_UP_ASSERT_LIMITS.app.max; i += 1) { + expect((await assertStepUp(r, { token: "garbage", nonce: nonce(`g${i}`) })).statusCode).toBe(401); + } + expect(refused(await assertStepUp(r, { token: m.token }))).toEqual([429, "step_up_rate_limited"]); + vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.app.windowMs + 1000); + expect((await assertStepUp(r, { token: m.token })).statusCode).toBe(201); + }); +}); + +describe("flood handling", () => { + it("the not-permitted budget is per app: one app's flood neither blocks bifrost's own call nor another ungranted app's first refusal", async () => { + const r = await rig(); + const sp = await member(r, "streampixels"); + const rp = await member(r, "repixelizer"); + const b = await member(r); + const as = (app: string, appSecret: string, token: string, i: number) => assertStepUp(r, { app, headers: { "x-heimdall-app-secret": appSecret }, token, nonce: nonce(`i${i}`) }); + for (let i = 0; i < 50; i += 1) await as("streampixels", "streampixels-secret", sp.token, i); + expect((await as("streampixels", "streampixels-secret", sp.token, 99)).statusCode).toBe(429); + expect(refused(await as("repixelizer", "repixelizer-secret", rp.token, 1))).toEqual([403, "step_up_assertion_not_permitted"]); + expect((await assertStepUp(r, { token: b.token })).statusCode).toBe(201); + }); + + it("a flood is not an audit flood: an app without the grant is audited once per window, a tripped budget once per window", async () => { + const r = await rig(); + const sp = await member(r, "streampixels"); + vi.useFakeTimers({ toFake: ["Date"] }); + const codes: Record = {}; + for (let i = 0; i < 500; i += 1) { + const res = await assertStepUp(r, { app: "streampixels", headers: { "x-heimdall-app-secret": "streampixels-secret" }, token: sp.token, nonce: nonce(`f${i}`) }); + codes[res.statusCode] = (codes[res.statusCode] ?? 0) + 1; + } + expect(codes).toEqual({ 403: STEP_UP_ASSERT_LIMITS.notPermitted.max, 429: 500 - STEP_UP_ASSERT_LIMITS.notPermitted.max }); + const rows = (code: string) => auditOf(r, "step_up_assertion_refused").filter((e) => e.eventPayloadJson.code === code); + expect(rows("step_up_assertion_not_permitted")).toHaveLength(1); + expect(rows("step_up_rate_limited")).toHaveLength(1); + expect(rows("step_up_rate_limited")[0]!.eventPayloadJson.budget).toBe("notPermitted"); + vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.notPermitted.windowMs + 1000); + await assertStepUp(r, { app: "streampixels", headers: { "x-heimdall-app-secret": "streampixels-secret" }, token: sp.token }); + expect(rows("step_up_assertion_not_permitted")).toHaveLength(2); + + // The same for the granted app's per-app and per-account budgets. + const m = await member(r); + const before = r.audit.length; + for (let i = 0; i < 300; i += 1) await assertStepUp(r, { token: "garbage", nonce: nonce(`g${i}`) }); + expect(r.audit.length - before, "garbage-bearer refusals up to the budget, then one row for the trip").toBe(STEP_UP_ASSERT_LIMITS.app.max + 1); + vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.app.windowMs + 1000); + const mark = r.audit.length; + for (let i = 0; i < 30; i += 1) await assertStepUp(r, { token: m.token, nonce: nonce(`a${i}`) }); + const accountRows = r.audit.slice(mark); + expect(accountRows.filter((e) => e.eventType === "step_up_asserted")).toHaveLength(STEP_UP_ASSERT_LIMITS.account.max); + const trips = accountRows.filter((e) => e.eventPayloadJson.code === "step_up_rate_limited"); + expect(trips.map((e) => e.eventPayloadJson.budget)).toEqual(["account"]); + }); +}); + describe("receipts", () => { it("records every assertion and every post-secret refusal with account, app, session, method, outcome and time, and nothing secret", async () => { const r = await rig(); diff --git a/tests/store.test.ts b/tests/store.test.ts index fda8a9f..03b869a 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -4,13 +4,22 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { newDb } from "pg-mem"; import { type HeimdallConfig } from "../src/config.js"; import { createStore, IdentityHeldElsewhereError, InMemoryStore, type HeimdallStore } from "../src/store/index.js"; -import { createPostgresStore, PostgresStore } from "../src/store/postgres.js"; +import { + createPostgresStore, + PostgresStore, + checkSchemaRequirements, + HEIMDALL_SCHEMA_REQUIREMENTS, + predicateConditions, + printedDeclaredPredicates, + samePredicate, + STORE_TABLE_PRIVILEGES, +} from "../src/store/postgres.js"; import { OAUTH_STATE_PRUNE_BATCH, OAUTH_STATE_PRUNE_MARGIN_MS, OAUTH_STATE_SKEW_MS, } from "../src/store/types.js"; -import { CORE_TABLES, CREATE_SCHEMA_SQL } from "../src/store/schema.js"; +import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "../src/store/schema.js"; describe("PostgresStore", () => { it("round-trips core auth records through postgres", async () => { @@ -459,40 +468,81 @@ describe("createPostgresStore", () => { }); describe("PostgresStore.checkSchema", () => { - it("runs connectivity check and verifies core tables exist", async () => { - const queries: Array<{ sql: string; params: unknown[] | undefined }> = []; - const store = new PostgresStore({ - query: async (sql: string, params?: unknown[]) => { - queries.push({ sql, params }); - return { rows: [], rowCount: 0 }; - }, - end: async () => {}, - connect: async () => ({}), - } as unknown as Pool); - - await expect(store.checkSchema()).resolves.toBeUndefined(); - expect(queries).toHaveLength(2); - expect(queries[0]!.sql).toBe("SELECT 1"); - expect(queries[1]!.sql).toContain("to_regclass('public.' || name) IS NULL"); - expect(queries[1]!.params).toEqual([CORE_TABLES]); - const declaredTables = Array.from( - CREATE_SCHEMA_SQL.matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/g), - (m) => m[1]!, + it("derives every table, typed column and unique key from the schema", () => { + expect(REQUIRED_TABLES).toEqual([ + "accounts", + "linked_identities", + "sessions", + "auth_attempts", + "private_command_receipts", + "pending_links", + "auth_completions", + "oauth_state_uses", + "capability_grants", + "entitlement_snapshots", + "consent_receipts", + "identity_moves", + "audit_events", + ]); + expect(REQUIRED_COLUMNS).toHaveLength(121); + expect(REQUIRED_COLUMNS).toEqual( + expect.arrayContaining([ + { table: "auth_completions", column: "code", type: "TEXT", nullable: false }, + { table: "sessions", column: "access_revision", type: "INTEGER", nullable: false }, + { table: "linked_identities", column: "profile_json", type: "JSONB", nullable: false }, + { table: "linked_identities", column: "username", type: "TEXT", nullable: true }, + { table: "entitlement_snapshots", column: "is_allowed", type: "BOOLEAN", nullable: false }, + { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, + ]) + ); + expect(REQUIRED_KEYS).toHaveLength(19); + expect(REQUIRED_KEYS).toEqual( + expect.arrayContaining([ + { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, + { table: "private_command_receipts", columns: "app_slug,idempotency_key", predicate: "" }, + { table: "oauth_state_uses", columns: "jti,phase", predicate: "" }, + { table: "consent_receipts", columns: "revokes_receipt_id", predicate: "revokes_receipt_id IS NOT NULL" }, + { table: "consent_receipts", columns: "account_id,id", predicate: "" }, + { table: "identity_moves", columns: "reverses_move_id", predicate: "reverses_move_id IS NOT NULL" }, + { table: "entitlement_snapshots", columns: "account_id,provider,scope", predicate: "" }, + { table: "auth_completions", columns: "app_slug,attempt_id", predicate: "attempt_id IS NOT NULL AND consumed_at IS NULL" }, + ]) ); - expect([...CORE_TABLES].sort()).toEqual([...declaredTables].sort()); }); - it("throws SCHEMA_MISSING when any core table is missing", async () => { - const store = new PostgresStore({ - query: async (sql: string) => { - if (sql === "SELECT 1") return { rows: [], rowCount: 0 }; - return { rows: [{ name: "consent_receipts" }], rowCount: 1 }; - }, - end: async () => {}, - connect: async () => ({}), - } as unknown as Pool); + // Soul pass 6: stripping parentheses and case merged predicates of + // different meaning. These are Postgres's own printed forms. + it("splits a printed predicate only at its top-level ANDs", () => { + expect(predicateConditions("((a OR b) AND c)")).toEqual(["a OR b", "c"]); + expect(predicateConditions("(a OR (b AND c))")).toEqual(["a OR (b AND c)"]); + expect(predicateConditions("((attempt_id IS NOT NULL) AND (consumed_at IS NULL))")).toEqual([ + "attempt_id IS NOT NULL", + "consumed_at IS NULL", + ]); + expect(predicateConditions("(s = 'x AND (y'::text)")).toEqual(["s = 'x AND (y'::text"]); + expect(predicateConditions('(("odd AND (name" IS NULL) AND b)')).toEqual(['"odd AND (name" IS NULL', "b"]); + expect(predicateConditions("")).toEqual([]); + }); - await expect(store.checkSchema()).rejects.toMatchObject({ code: "SCHEMA_MISSING" }); + it("matches predicates by their conditions, never by case or by dropping structure", () => { + const keys = ["app_slug", "attempt_id"]; + expect(samePredicate("((a OR b) AND c)", "(a OR (b AND c))", keys, false)).toBe(false); + expect(samePredicate("(s = 'Pending'::text)", "(s = 'pending'::text)", keys, false)).toBe(false); + expect(samePredicate("((a) AND (b))", "((b) AND (a))", keys, false)).toBe(true); + expect(samePredicate("((a) AND (b))", "((a) AND (b) AND (c))", keys, false)).toBe(false); + }); + + it("lets a key column's IS NOT NULL be absent only where NULL keys cannot collide", () => { + const keys = ["app_slug", "attempt_id"]; + const declared = "((attempt_id IS NOT NULL) AND (consumed_at IS NULL))"; + expect(samePredicate(declared, "(consumed_at IS NULL)", keys, false)).toBe(true); + expect(samePredicate(declared, "(consumed_at IS NULL)", keys, true)).toBe(false); + expect(samePredicate(declared, "((consumed_at IS NULL) AND (other IS NOT NULL))", keys, false)).toBe(false); + }); + + it("requires a key without a predicate to have none", () => { + expect(samePredicate("", "", ["id"], false)).toBe(true); + expect(samePredicate("", "(id IS NOT NULL)", ["id"], false)).toBe(false); }); }); @@ -839,10 +889,12 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD return { name, owner }; } - /** Grants the app role standard DML on all core tables. */ - async function grantAppRole(owner: Pool): Promise { + /** Grants the app role exactly `privileges`, per table, and nothing else. */ + async function grant(owner: Pool, privileges: Readonly>): Promise { await owner.query(`GRANT USAGE ON SCHEMA public TO ${role}`); - await owner.query(`GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO ${role}`); + for (const [table, wanted] of Object.entries(privileges)) { + if (wanted.length > 0) await owner.query(`GRANT ${wanted.join(", ")} ON ${table} TO ${role}`); + } } /** @@ -881,9 +933,9 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD expect(await start(urlFor(name), true)).toBe("started"); }); - it("serves every store operation as the app role", async () => { + it("serves every store operation with exactly the privileges it checks for", async () => { const { name, owner } = await appliedDatabase(); - await grantAppRole(owner); + await grant(owner, STORE_TABLE_PRIVILEGES); expect(await start(urlFor(name, role, rolePassword), false)).toBe("started"); const pool = fixturePool(urlFor(name, role, rolePassword)); @@ -897,6 +949,44 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD expect([...called].sort()).toEqual(offered.sort()); }); + it("refuses each privilege taken away, and the store needs each one", async () => { + const pairs = Object.entries(STORE_TABLE_PRIVILEGES).flatMap(([table, wanted]) => wanted.map((privilege) => ({ table, privilege }))); + expect(Object.keys(STORE_TABLE_PRIVILEGES).sort()).toEqual([...REQUIRED_TABLES].sort()); + for (const { table, privilege } of pairs) { + const { name, owner } = await appliedDatabase(); + await grant(owner, { ...STORE_TABLE_PRIVILEGES, [table]: STORE_TABLE_PRIVILEGES[table]!.filter((p) => p !== privilege) }); + + const message = await start(urlFor(name, role, rolePassword), false); + expect(message, `${table} without ${privilege}`).toBe(refusal("SCHEMA_PRIVILEGES")); + expect(message).not.toContain("CANARY"); + + const pool = fixturePool(urlFor(name, role, rolePassword)); + const failure = await exerciseStore(new PostgresStore(pool)).then( + () => undefined, + (error: unknown) => (error as { code?: string }).code + ); + await pool.end(); + expect(failure, `the store runs without ${privilege} on ${table}, so the check need not ask for it`).toBe("42501"); + for (const step of cleanup.splice(0).reverse()) await step(); + } + }); + + it("startup refuses a role that lacks DELETE on linked_identities", async () => { + expect(STORE_TABLE_PRIVILEGES.linked_identities).toContain("DELETE"); + const { name, owner } = await appliedDatabase(); + await grant(owner, { ...STORE_TABLE_PRIVILEGES, linked_identities: ["SELECT", "INSERT", "UPDATE"] }); + expect(await start(urlFor(name, role, rolePassword), false)).toBe(refusal("SCHEMA_PRIVILEGES")); + }); + + it("startup refuses a role that lacks INSERT or SELECT on identity_moves", async () => { + expect(STORE_TABLE_PRIVILEGES.identity_moves).toEqual(["SELECT", "INSERT"]); + for (const [kept, dropped] of [[["SELECT"], "INSERT"], [["INSERT"], "SELECT"]] as const) { + const { name, owner } = await appliedDatabase(); + await grant(owner, { ...STORE_TABLE_PRIVILEGES, identity_moves: kept }); + expect(await start(urlFor(name, role, rolePassword), false), `without ${dropped}`).toBe(refusal("SCHEMA_PRIVILEGES")); + } + }); + it("on real Postgres: the move contract holds", async () => { const { owner } = await appliedDatabase(); await exerciseMoveContract(new PostgresStore(owner)); @@ -1063,7 +1153,7 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD it("the step_up_assert nonce claim is single-use under the store's own role, and independent of the other phases", async () => { const { name, owner } = await appliedDatabase(); - await grantAppRole(owner); + await grant(owner, STORE_TABLE_PRIVILEGES); const pool = fixturePool(urlFor(name, role, rolePassword)); cleanup.push(async () => { await pool.end(); @@ -1077,8 +1167,7 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD it("a role without DELETE still claims, and leaves the old records", async () => { const { name, owner } = await appliedDatabase(); - await grantAppRole(owner); - await owner.query(`REVOKE DELETE ON oauth_state_uses FROM ${role}`); + await grant(owner, { ...STORE_TABLE_PRIVILEGES, oauth_state_uses: ["SELECT", "INSERT"] }); await seed(owner, "old"); const pool = fixturePool(urlFor(name, role, rolePassword)); cleanup.push(async () => { @@ -1092,15 +1181,223 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD it("refuses to apply the schema as a role that may not, and closes the store", async () => { const { name, owner } = await appliedDatabase(); - await grantAppRole(owner); + await grant(owner, STORE_TABLE_PRIVILEGES); expect(await start(urlFor(name, role, rolePassword), true)).toBe(refusal("42501")); }); + it("prints each declared predicate exactly as Postgres prints the applied index's", async () => { + const { owner } = await appliedDatabase(); + const printed = await printedDeclaredPredicates(owner, HEIMDALL_SCHEMA_REQUIREMENTS); + const appliedByIndex = { + auth_completions_attempt_unconsumed_unique_idx: "auth_completions", + consent_receipts_revokes_unique_idx: "consent_receipts", + identity_moves_reverses_unique_idx: "identity_moves", + }; + const partialKeys = REQUIRED_KEYS.flatMap((key, index) => (key.predicate === "" ? [] : [{ key, index }])); + expect(partialKeys.map(({ key }) => key.table).sort()).toEqual(Object.values(appliedByIndex).sort()); + for (const [indexName, table] of Object.entries(appliedByIndex)) { + const applied = await owner.query<{ predicate: string }>( + "SELECT pg_get_expr(indpred, indrelid) AS predicate FROM pg_index WHERE indexrelid = $1::regclass", + [indexName] + ); + const { index } = partialKeys.find(({ key }) => key.table === table)!; + expect(printed[index], indexName).toBe(applied.rows[0]!.predicate); + } + expect(printed.filter((predicate) => predicate !== "")).toHaveLength(partialKeys.length); + }); + it("refuses to boot with consent_receipts missing when the schema is not applied on startup", async () => { const { name, owner } = await appliedDatabase(); await owner.query("DROP TABLE consent_receipts"); expect(await start(urlFor(name), false)).toBe(refusal("SCHEMA_MISSING")); }); + + it("refuses a table whose primary key was dropped, even after applying the schema", async () => { + const { name, owner } = await appliedDatabase(); + await owner.query("ALTER TABLE auth_completions DROP CONSTRAINT auth_completions_pkey"); + + expect(await start(urlFor(name), false)).toBe(refusal("SCHEMA_MISSING")); + expect(await start(urlFor(name), true)).toBe(refusal("SCHEMA_MISSING")); + }); + + it("serves every store operation with each privilege granted column by column", async () => { + const { name, owner } = await appliedDatabase(); + await owner.query(`GRANT USAGE ON SCHEMA public TO ${role}`); + for (const [table, wanted] of Object.entries(STORE_TABLE_PRIVILEGES)) { + const columns = REQUIRED_COLUMNS.filter((column) => column.table === table).map((column) => column.column).join(", "); + for (const privilege of wanted) { + // DELETE removes rows and cannot be granted per column. + await owner.query(privilege === "DELETE" ? `GRANT DELETE ON ${table} TO ${role}` : `GRANT ${privilege} (${columns}) ON ${table} TO ${role}`); + } + } + + expect(await start(urlFor(name, role, rolePassword), false)).toBe("started"); + const pool = fixturePool(urlFor(name, role, rolePassword)); + cleanup.push(async () => { + await pool.end(); + }); + await exerciseStore(new PostgresStore(pool)); + }); + + it("refuses a privilege missing on one column of another table", async () => { + const { name, owner } = await appliedDatabase(); + await grant(owner, { ...STORE_TABLE_PRIVILEGES, auth_completions: [] }); + const columns = REQUIRED_COLUMNS.filter((column) => column.table === "auth_completions" && column.column !== "attempt_id") + .map((column) => column.column) + .join(", "); + for (const privilege of STORE_TABLE_PRIVILEGES.auth_completions!) { + await owner.query(`GRANT ${privilege} (${columns}) ON auth_completions TO ${role}`); + } + + expect(await start(urlFor(name, role, rolePassword), false)).toBe(refusal("SCHEMA_PRIVILEGES")); + }); + + it("names the TEMPORARY privilege when the role may not create temporary tables", async () => { + const { name, owner } = await appliedDatabase(); + await grant(owner, STORE_TABLE_PRIVILEGES); + await owner.query(`REVOKE TEMPORARY ON DATABASE ${name} FROM PUBLIC`); + + expect(await start(urlFor(name, role, rolePassword), false)).toBe( + "Postgres storage could not be prepared (SCHEMA_TEMP_PRIVILEGE); grant the database role TEMPORARY on its database." + ); + }); + + // The schema's own predicate splits into the same conditions raw or + // printed, so only a predicate whose printed form differs (a literal gains + // its cast) shows that the check compares Postgres's printing. + it("matches a declared predicate that Postgres prints differently from how it is written", async () => { + const { owner } = await appliedDatabase(); + await owner.query("CREATE TABLE predicate_probe (id INTEGER NOT NULL, state TEXT, attempts INTEGER)"); + await owner.query("CREATE UNIQUE INDEX predicate_probe_live ON predicate_probe (id) WHERE state = 'live' AND attempts > 0"); + const requirements = { + tables: ["predicate_probe"], + columns: [ + { table: "predicate_probe", column: "id", type: "INTEGER", nullable: false }, + { table: "predicate_probe", column: "state", type: "TEXT", nullable: true }, + { table: "predicate_probe", column: "attempts", type: "INTEGER", nullable: true }, + ], + keys: [{ table: "predicate_probe", columns: "id", predicate: "state = 'live' AND attempts > 0" }], + privileges: {}, + }; + + expect((await printedDeclaredPredicates(owner, requirements))[0]).toBe("((state = 'live'::text) AND (attempts > 0))"); + await expect(checkSchemaRequirements(owner, requirements)).resolves.toBeUndefined(); + }); + + it("refuses a privilege held on only some of a table's columns", async () => { + const { name, owner } = await appliedDatabase(); + await grant(owner, { ...STORE_TABLE_PRIVILEGES, audit_events: [] }); + await owner.query(`GRANT INSERT (id) ON audit_events TO ${role}`); + + expect(await start(urlFor(name, role, rolePassword), false)).toBe(refusal("SCHEMA_PRIVILEGES")); + }); + + // Each damage below leaves a database whose shape still resembles the + // schema but on which a store write fails or R21.1 no longer holds. A step + // starting with "!" is expected to fail and leave its mark (a failed + // CREATE INDEX CONCURRENTLY leaves an invalid index behind). + const seedDuplicates = [ + "INSERT INTO accounts VALUES ('acc', now(), now(), null, null)", + "INSERT INTO sessions VALUES ('s', 'acc', 'ghostlight', now(), now(), now() + interval '1 hour', '{}', 1)", + ]; + it.each([ + ["a key made DEFERRABLE (ON CONFLICT refuses it as an arbiter)", + ["ALTER TABLE private_command_receipts DROP CONSTRAINT private_command_receipts_pkey", "ALTER TABLE private_command_receipts ADD PRIMARY KEY (app_slug, idempotency_key) DEFERRABLE INITIALLY IMMEDIATE"]], + ["a key narrowed to one column, the other only INCLUDEd", + ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_include ON linked_identities(provider) INCLUDE (provider_user_id)"]], + ["a key widened by an expression column", + ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_expr ON linked_identities(provider, provider_user_id, lower(username))"]], + ["a key replaced by a partial one", + ["ALTER TABLE entitlement_snapshots DROP CONSTRAINT entitlement_snapshots_account_id_provider_scope_key", "CREATE UNIQUE INDEX es_partial ON entitlement_snapshots(account_id, provider, scope) WHERE is_allowed"]], + ["a key replaced by a plain index on the same columns", + ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE INDEX li_plain ON linked_identities(provider, provider_user_id)"]], + ["a key replaced by one on other columns of the same count", + ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_other ON linked_identities(provider, username)"]], + ["a key left only as an invalid index by a failed concurrent build", + [...seedDuplicates, + "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", + "INSERT INTO linked_identities (id, account_id, provider, provider_user_id, created_at, updated_at) VALUES ('l1', 'acc', 'youtube', 'dup', now(), now()), ('l2', 'acc', 'youtube', 'dup', now(), now())", + "!CREATE UNIQUE INDEX CONCURRENTLY li_ccnew ON linked_identities(provider, provider_user_id)", + "DELETE FROM linked_identities WHERE id = 'l2'"]], + ["the attempt index left invalid over duplicate attempts by a failed concurrent build", + [...seedDuplicates, + "DROP INDEX auth_completions_attempt_unconsumed_unique_idx", + "INSERT INTO auth_completions (code, attempt_id, app_slug, provider, mode, account_id, session_id, return_to, payload_json, created_at, expires_at) VALUES ('c1', 'att', 'ghostlight', 'discord', 'sign_in', 'acc', 's', 'https://x/', '{}', now(), now() + interval '1 hour'), ('c2', 'att', 'ghostlight', 'discord', 'sign_in', 'acc', 's', 'https://x/', '{}', now(), now() + interval '1 hour')", + "!CREATE UNIQUE INDEX CONCURRENTLY auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE attempt_id IS NOT NULL AND consumed_at IS NULL"]], + // An interrupted DROP INDEX CONCURRENTLY leaves an index ready but not + // valid; the fixture sets that state directly (the admin role may). + ["a key left only as an index that is ready but not valid", + ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", + "CREATE UNIQUE INDEX li_half_dropped ON linked_identities(provider, provider_user_id)", + "UPDATE pg_index SET indisvalid = false WHERE indexrelid = 'li_half_dropped'::regclass"]], + ["a key's first column compared under a case-insensitive collation", + ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", + "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", + "CREATE UNIQUE INDEX li_ci_first ON linked_identities(provider COLLATE heimdall_ci, provider_user_id)"]], + // Soul pass 7: the key index compares under "C", but the column itself is + // case-insensitive, so the store's own lookups by provider_user_id match + // other users' ids. + ["a column declared under a case-insensitive collation, its key index under C", + ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", + "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", + "ALTER TABLE linked_identities ALTER COLUMN provider_user_id TYPE text COLLATE heimdall_ci", + 'CREATE UNIQUE INDEX li_c ON linked_identities(provider, provider_user_id COLLATE "C")']], + ["a key compared under a case-insensitive collation (two users' ids become one row)", + ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", + "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", + "CREATE UNIQUE INDEX li_ci ON linked_identities(provider, provider_user_id COLLATE heimdall_ci)"]], + ["the attempt index replaced by a plain one of the same name", + ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id)"]], + ["the attempt index made unique on every row (no predicate)", + ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id)"]], + ["the attempt index given another predicate", + ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE attempt_id IS NOT NULL"]], + ["the attempt index narrowed by an extra condition", + ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE attempt_id IS NOT NULL AND consumed_at IS NULL AND app_slug <> 'ghostlight'"]], + ["the attempt index with a condition ORed into its predicate", + ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE (attempt_id IS NOT NULL OR app_slug = 'x') AND consumed_at IS NULL"]], + ["the attempt index made NULLS NOT DISTINCT without excluding NULL attempts", + ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) NULLS NOT DISTINCT WHERE consumed_at IS NULL"]], + ["a column retyped", ["ALTER TABLE sessions ALTER COLUMN access_revision TYPE TEXT"]], + ["a created table's column dropped", ["ALTER TABLE auth_completions DROP COLUMN mode"]], + ["NOT NULL added to a column the store leaves null", ["ALTER TABLE auth_completions ALTER COLUMN attempt_id SET NOT NULL"]], + ["NOT NULL added to a nullable column of another table", + ["UPDATE linked_identities SET username = ''", "ALTER TABLE linked_identities ALTER COLUMN username SET NOT NULL"]], + ])("refuses %s", async (_damage, steps) => { + const { name, owner } = await appliedDatabase(); + for (const step of steps) { + if (step.startsWith("!")) await expect(owner.query(step.slice(1))).rejects.toBeDefined(); + else await owner.query(step); + } + + expect(await start(urlFor(name), false)).toBe(refusal("SCHEMA_MISSING")); + }); + + // Each change below leaves a database the store serves exactly as before. + it.each([ + ["a key index that carries extra INCLUDE columns", + ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_covering ON linked_identities(provider, provider_user_id) INCLUDE (username)"]], + ["the attempt index under another name", ["ALTER INDEX auth_completions_attempt_unconsumed_unique_idx RENAME TO attempt_idx_renamed"]], + ["the attempt index's conditions in the other order", + ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX attempt_reordered ON auth_completions(app_slug, attempt_id) WHERE consumed_at IS NULL AND attempt_id IS NOT NULL"]], + // NULL attempt ids never collide in a unique index that treats NULLs as + // distinct (the default), so dropping that condition keeps the same rows unique. + ["the attempt index without its redundant attempt_id IS NOT NULL", + ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX attempt_unconsumed ON auth_completions(app_slug, attempt_id) WHERE consumed_at IS NULL"]], + ["a lookup index dropped", ["DROP INDEX audit_events_lookup_idx", "DROP INDEX auth_completions_lookup_idx"]], + // Only a key's own columns decide which rows collide; an INCLUDEd column's + // collation does not, whatever it is. + ["a key index that INCLUDEs an undeclared case-insensitive column", + ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", + "ALTER TABLE linked_identities ADD COLUMN operator_note text COLLATE heimdall_ci", + "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", + "CREATE UNIQUE INDEX li_note ON linked_identities(provider, provider_user_id) INCLUDE (operator_note)"]], + ])("accepts %s", async (_change, steps) => { + const { name, owner } = await appliedDatabase(); + for (const step of steps) await owner.query(step); + + expect(await start(urlFor(name), false)).toBe("started"); + }); }); diff --git a/tools/heimdall_prepare_compaction.py b/tools/heimdall_prepare_compaction.py new file mode 100644 index 0000000..c273586 --- /dev/null +++ b/tools/heimdall_prepare_compaction.py @@ -0,0 +1,328 @@ +from __future__ import annotations + +import argparse +import json +import re +import subprocess +from dataclasses import dataclass +from pathlib import Path +from typing import Any + + +ROOT = Path(__file__).resolve().parents[1] +STATE_DIR = ROOT / "state" +NOTES_DIR = ROOT / "notes" +DOCS_DIR = ROOT / "docs" + +MAP_PATH = STATE_DIR / "map.yaml" +SCRATCH_PATH = STATE_DIR / "scratch.md" +BRANCHES_PATH = STATE_DIR / "branches.json" +EVIDENCE_PATH = STATE_DIR / "evidence.jsonl" +HANDOFF_PATH = NOTES_DIR / "fresh-workspace-handoff.md" +ARCH_PATH = DOCS_DIR / "architecture.md" +PLAN_PATH = DOCS_DIR / "implementation-plan.md" +AGENTS_PATH = ROOT / "AGENTS.md" + + +@dataclass +class Finding: + level: str + message: str + + +def read_text(path: Path) -> str: + return path.read_text(encoding="utf-8") + + +def run_git(args: list[str]) -> str: + completed = subprocess.run( + ["git", *args], + cwd=ROOT, + check=True, + capture_output=True, + text=True, + ) + return completed.stdout.strip() + + +def extract_map_field(name: str) -> str | None: + prefix = f" {name}:" + for line in read_text(MAP_PATH).splitlines(): + if line.startswith(prefix): + return line.split(":", 1)[1].strip() + return None + + +def extract_active_subgoals() -> list[str]: + lines = read_text(MAP_PATH).splitlines() + results: list[str] = [] + in_section = False + for line in lines: + if not in_section: + if line.strip() == "active_subgoals:": + in_section = True + continue + if line.startswith(" - "): + results.append(line[4:].strip()) + continue + if line and not line.startswith(" "): + break + return results + + +def current_scratch_subgoal() -> str | None: + lines = read_text(SCRATCH_PATH).splitlines() + for index, line in enumerate(lines): + if line.strip() != "## Current Subgoal": + continue + for candidate in lines[index + 1 :]: + stripped = candidate.strip() + if stripped: + return stripped + return None + + +def load_evidence() -> list[dict[str, Any]]: + records: list[dict[str, Any]] = [] + for line_number, line in enumerate(read_text(EVIDENCE_PATH).splitlines(), start=1): + if not line.strip(): + continue + try: + record = json.loads(line) + except json.JSONDecodeError as exc: + raise ValueError(f"evidence line {line_number} is invalid JSON: {exc}") from exc + if not isinstance(record, dict): + raise ValueError(f"evidence line {line_number} is not a JSON object") + records.append(record) + return records + + +def load_branches() -> dict[str, Any]: + data = json.loads(read_text(BRANCHES_PATH)) + if not isinstance(data, dict): + raise ValueError("branches.json must be a JSON object") + branches = data.get("branches") + if not isinstance(branches, list): + raise ValueError("branches.json must contain a branches list") + return data + + +def add_required_file_checks(findings: list[Finding]) -> None: + for path in [ + MAP_PATH, + SCRATCH_PATH, + BRANCHES_PATH, + EVIDENCE_PATH, + HANDOFF_PATH, + ARCH_PATH, + PLAN_PATH, + AGENTS_PATH, + ]: + if path.exists(): + findings.append(Finding("ok", f"found {path.relative_to(ROOT)}")) + else: + findings.append(Finding("error", f"missing {path.relative_to(ROOT)}")) + + +def add_content_checks(findings: list[Finding]) -> tuple[list[dict[str, Any]], dict[str, Any]]: + evidence: list[dict[str, Any]] = [] + branches: dict[str, Any] = {} + + summary = extract_map_field("summary") + next_action = extract_map_field("next_action") + if summary: + findings.append(Finding("ok", "state/map.yaml has current_status.summary")) + else: + findings.append(Finding("error", "state/map.yaml is missing current_status.summary")) + if next_action: + findings.append(Finding("ok", "state/map.yaml has current_status.next_action")) + else: + findings.append(Finding("error", "state/map.yaml is missing current_status.next_action")) + + subgoals = extract_active_subgoals() + if subgoals: + findings.append(Finding("ok", f"state/map.yaml has {len(subgoals)} active subgoal(s)")) + else: + findings.append(Finding("warn", "state/map.yaml has no active_subgoals entries")) + + scratch_subgoal = current_scratch_subgoal() + if scratch_subgoal == "No active scratch subgoal.": + findings.append(Finding("ok", "state/scratch.md has no stale active scratch subgoal")) + elif scratch_subgoal: + findings.append(Finding("warn", f"state/scratch.md has active scratch subgoal: {scratch_subgoal}")) + else: + findings.append(Finding("warn", "state/scratch.md has no Current Subgoal value")) + + try: + evidence = load_evidence() + findings.append(Finding("ok", f"state/evidence.jsonl parses ({len(evidence)} record(s))")) + except ValueError as exc: + findings.append(Finding("error", str(exc))) + + if EVIDENCE_PATH.exists() and EVIDENCE_PATH.stat().st_size > 25_000: + findings.append(Finding("warn", "state/evidence.jsonl is larger than 25 KB; consider distillation")) + + try: + branches = load_branches() + active = [ + branch + for branch in branches.get("branches", []) + if isinstance(branch, dict) and branch.get("status") == "active" + ] + findings.append(Finding("ok", f"state/branches.json parses ({len(active)} active branch(es))")) + except (json.JSONDecodeError, ValueError) as exc: + findings.append(Finding("error", f"branches.json parse failed: {exc}")) + + return evidence, branches + + +def add_handoff_checks(findings: list[Finding]) -> None: + text = read_text(HANDOFF_PATH) + stale_branch = re.search(r"Current branch before .*ahead \d+", text) + stale_head = re.search(r"Current HEAD before .*\b[0-9a-f]{7,40}\b", text) + if stale_branch or stale_head: + findings.append(Finding("error", "handoff embeds an exact branch or HEAD snapshot; use git commands instead")) + else: + findings.append(Finding("ok", "handoff avoids exact branch/HEAD snapshots")) + + required_phrases = [ + "Do not continue implementation automatically from a rehydrate-only request.", + "Do not trust this file for the exact live HEAD.", + "Immediate Re-entry Instruction", + ] + for phrase in required_phrases: + if phrase in text: + findings.append(Finding("ok", f"handoff contains: {phrase}")) + else: + findings.append(Finding("warn", f"handoff missing: {phrase}")) + + +def add_agents_checks(findings: list[Finding]) -> None: + text = read_text(AGENTS_PATH) + if "heimdall_prepare_compaction.py" in text: + findings.append(Finding("ok", "AGENTS.md tells agents to use the compaction helper")) + else: + findings.append(Finding("error", "AGENTS.md does not mention tools/heimdall_prepare_compaction.py")) + if "prepare for imminent compaction" in text.lower(): + findings.append(Finding("ok", "AGENTS.md names the imminent-compaction trigger")) + else: + findings.append(Finding("warn", "AGENTS.md does not name the imminent-compaction trigger phrase")) + + +def add_git_checks(findings: list[Finding]) -> tuple[str, str]: + status = run_git(["status", "--short", "--branch"]) + log = run_git(["log", "--oneline", "-5"]) + dirty_lines = [line for line in status.splitlines()[1:] if line.strip()] + if dirty_lines: + findings.append(Finding("warn", "git worktree has uncommitted changes; commit or explain before compaction")) + else: + findings.append(Finding("ok", "git worktree is clean")) + return status, log + + +def render_report(findings: list[Finding], status: str, log: str, evidence: list[dict[str, Any]]) -> str: + summary = extract_map_field("summary") or "(missing)" + next_action = extract_map_field("next_action") or "(missing)" + subgoals = extract_active_subgoals() + + counts = { + "ok": sum(1 for finding in findings if finding.level == "ok"), + "warn": sum(1 for finding in findings if finding.level == "warn"), + "error": sum(1 for finding in findings if finding.level == "error"), + } + + lines = [ + "Heimdall pre-compaction persistence check", + f"Workspace: {ROOT}", + f"Findings: {counts['ok']} ok, {counts['warn']} warn, {counts['error']} error", + "", + "Git status:", + status, + "", + "Recent commits:", + log, + "", + f"Summary: {summary}", + f"Next action: {next_action}", + ] + if subgoals: + lines.append("Active subgoals:") + lines.extend(f"- {item}" for item in subgoals) + if evidence: + latest = evidence[-1] + lines.extend( + [ + "", + "Latest distilled evidence:", + f"- {latest.get('ts', '(missing ts)')} {latest.get('type', '(missing type)')}/{latest.get('status', '(missing status)')}: {latest.get('note', '(missing note)')}", + ] + ) + + lines.append("") + lines.append("Findings:") + for finding in findings: + lines.append(f"[{finding.level.upper()}] {finding.message}") + + lines.extend( + [ + "", + "Pre-compaction checklist:", + "- Update state/map.yaml only if current understanding changed.", + "- Refresh notes/fresh-workspace-handoff.md if re-entry instructions changed.", + "- Add distilled evidence only for a belief-changing lesson, verification, rejected path, or scar.", + "- Keep exact branch/HEAD out of handoff prose; git commands own volatile truth.", + "- Commit completed persistence changes, or state why the worktree must stay dirty.", + "- Re-run this helper after edits before yielding to compaction.", + ] + ) + return "\n".join(lines) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Audit Heimdall persistent state before imminent compaction." + ) + parser.add_argument( + "--strict", + action="store_true", + help="Exit nonzero on warnings as well as errors.", + ) + return parser + + +def main() -> int: + args = build_parser().parse_args() + findings: list[Finding] = [] + evidence: list[dict[str, Any]] = [] + + add_required_file_checks(findings) + try: + evidence, _branches = add_content_checks(findings) + except OSError as exc: + findings.append(Finding("error", f"state content check failed: {exc}")) + try: + add_handoff_checks(findings) + except OSError as exc: + findings.append(Finding("error", f"handoff check failed: {exc}")) + try: + add_agents_checks(findings) + except OSError as exc: + findings.append(Finding("error", f"AGENTS check failed: {exc}")) + try: + status, log = add_git_checks(findings) + except (OSError, subprocess.CalledProcessError) as exc: + findings.append(Finding("error", f"git check failed: {exc}")) + status = "(git status unavailable)" + log = "(git log unavailable)" + + print(render_report(findings, status, log, evidence)) + + has_error = any(finding.level == "error" for finding in findings) + has_warning = any(finding.level == "warn" for finding in findings) + if has_error or (args.strict and has_warning): + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/heimdall_state.py b/tools/heimdall_state.py new file mode 100644 index 0000000..d4aa50a --- /dev/null +++ b/tools/heimdall_state.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +import argparse +import json +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +ROOT = Path(__file__).resolve().parents[1] +STATE_DIR = ROOT / "state" +MAP_PATH = STATE_DIR / "map.yaml" +BRANCHES_PATH = STATE_DIR / "branches.json" +EVIDENCE_PATH = STATE_DIR / "evidence.jsonl" + + +def read_text(path: Path) -> str: + return path.read_text(encoding="utf-8") + + +def write_text(path: Path, content: str) -> None: + path.write_text(content, encoding="utf-8") + + +def load_branches() -> dict[str, Any]: + return json.loads(read_text(BRANCHES_PATH)) + + +def save_branches(data: dict[str, Any]) -> None: + write_text(BRANCHES_PATH, json.dumps(data, indent=2) + "\n") + + +def append_evidence(record: dict[str, Any]) -> None: + with EVIDENCE_PATH.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record, ensure_ascii=True) + "\n") + + +def utc_stamp() -> str: + return datetime.now(timezone.utc).replace(microsecond=0).isoformat() + + +def extract_map_field(name: str) -> str | None: + prefix = f" {name}:" + for line in read_text(MAP_PATH).splitlines(): + if line.startswith(prefix): + return line.split(":", 1)[1].strip() + return None + + +def extract_active_subgoals() -> list[str]: + lines = read_text(MAP_PATH).splitlines() + results: list[str] = [] + in_section = False + for line in lines: + if not in_section: + if line.strip() == "active_subgoals:": + in_section = True + continue + if line.startswith(" - "): + results.append(line[4:].strip()) + continue + if line and not line.startswith(" "): + break + return results + + +def cmd_status(_: argparse.Namespace) -> int: + branches = load_branches().get("branches", []) + active = [branch for branch in branches if branch.get("status") == "active"] + summary = extract_map_field("summary") or "(missing)" + next_action = extract_map_field("next_action") or "(missing)" + subgoals = extract_active_subgoals() + + print(f"Workspace: {ROOT}") + print(f"Summary: {summary}") + print(f"Next action: {next_action}") + print(f"Active branches: {len(active)} / {len(branches)}") + if subgoals: + print("Active subgoals:") + for item in subgoals: + print(f"- {item}") + return 0 + + +def cmd_add_evidence(args: argparse.Namespace) -> int: + record: dict[str, Any] = { + "ts": utc_stamp(), + "type": args.type, + "status": args.status, + "note": args.note, + } + if args.branch: + record["branch"] = args.branch + append_evidence(record) + print("Appended evidence record.") + return 0 + + +def cmd_add_branch(args: argparse.Namespace) -> int: + data = load_branches() + branches = data.setdefault("branches", []) + if any(branch.get("id") == args.id for branch in branches): + raise SystemExit(f"Branch '{args.id}' already exists.") + branches.append( + { + "id": args.id, + "hypothesis": args.hypothesis, + "status": "active", + "artifacts": args.artifact or [], + "notes": args.note or "", + } + ) + save_branches(data) + print(f"Added branch '{args.id}'.") + return 0 + + +def cmd_close_branch(args: argparse.Namespace) -> int: + data = load_branches() + for branch in data.get("branches", []): + if branch.get("id") != args.id: + continue + branch["status"] = args.status + if args.note: + branch["notes"] = args.note + save_branches(data) + print(f"Updated branch '{args.id}' to status '{args.status}'.") + return 0 + raise SystemExit(f"Branch '{args.id}' was not found.") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Inspect and update Heimdall persistent state files." + ) + subparsers = parser.add_subparsers(dest="command", required=True) + + status_parser = subparsers.add_parser("status", help="Show a compact state summary.") + status_parser.set_defaults(func=cmd_status) + + evidence_parser = subparsers.add_parser( + "add-evidence", help="Append one distilled JSONL evidence record." + ) + evidence_parser.add_argument("--type", required=True) + evidence_parser.add_argument("--status", required=True) + evidence_parser.add_argument("--note", required=True) + evidence_parser.add_argument("--branch") + evidence_parser.set_defaults(func=cmd_add_evidence) + + add_branch_parser = subparsers.add_parser( + "add-branch", help="Create a new active branch entry." + ) + add_branch_parser.add_argument("--id", required=True) + add_branch_parser.add_argument("--hypothesis", required=True) + add_branch_parser.add_argument("--artifact", action="append") + add_branch_parser.add_argument("--note") + add_branch_parser.set_defaults(func=cmd_add_branch) + + close_branch_parser = subparsers.add_parser( + "close-branch", help="Close an existing branch." + ) + close_branch_parser.add_argument("--id", required=True) + close_branch_parser.add_argument( + "--status", required=True, choices=["accepted", "rejected", "archived"] + ) + close_branch_parser.add_argument("--note") + close_branch_parser.set_defaults(func=cmd_close_branch) + + return parser + + +def main() -> int: + parser = build_parser() + args = parser.parse_args() + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main())