Repository navigation
Phase B2: OIDC client registry, signing keys and discovery - #2033
Conversation
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR2033Version: 🤖 Updated on each push. |
|
Review triage, driver, 2026-11-04. Round 1 was a three-reviewer panel (contract and types, tests and errors, comments and simplification) plus a focused Opus security read; round 2 was the Opus delta on the fix commits. Every accepted finding is fixed on this branch and was checked against its test; the advisor's required changes were each re-verified. Deferred or handled elsewhere, with the reason:
Open for the repository owner before this epic reaches |
873206d
into
feature/issue-2014-epic-oidc-provider
* Phase B1: ADR 0119, partner hosts, __Host- cookie and OIDC subject (#2031) * docs: ADR 0119, NEMAR as an OIDC provider * feat: exclude partner hosts from origin checks * feat: __Host- session cookie behind a flag * feat: users.oidc_subject and owner lookup * feat: reserve the nmu_ username prefix * docs: refresh compute notes for ADR 0119 * docs: ADR 0119 notes the single legacy clear * docs: ADR 0119 names the cookie exposure * docs: correct stale session cookie docblocks * fix: brand OidcSubject, correct shared docblocks * docs: say who deletes TOLERATED_GAPS entry * feat: __Host- names for the ORCID flow cookies * feat: reversible flag, slide and sign-out rules * test: name-aware session cookie in live tests * docs: ADR 0119 states the cookie principle * docs: refresh stale cookie comments, 0120 notes * fix: sign-out cascades for every carried account * docs: ADR 0119 rule 9 matches the Context * fix: name every account in the sign-out log * Phase B2: OIDC client registry, signing keys and discovery (#2033) * Add the OIDC scope, token and id vocabulary * Add migration 0121 for OIDC clients and keys * Add OIDC config and signing key service * Amend ADR 0119 rule 8: first-party needs NEMAR hosts * Serve OIDC discovery and keys on the issuer host * Add owner routes for OIDC clients and keys * Declare OIDC_SECRET as a Worker secret * Add nemar admin oidc commands * Retype OIDC vocabulary and share encoders * Add revoked key state and unique active names * Harden OIDC key rotation and add revocation * Tighten OIDC client registration rules * Close OIDC surface bypasses and cached errors * Add keys revoke and emergency rotation to the CLI * Record OIDC key and client decisions in ADR 0119 * Note what the key set cache depends on * Use router path, add --emergency, ADR note * Phase B3: OIDC authorization and consent (#2036) * Add the OIDC authorization wire contract * Add migration 0122 for OIDC grants and codes * Add the OIDC sign-in rule and ORCID proof * Add OIDC authorization and consent service * Add a per-account OIDC authorize budget * Serve OIDC authorize and consent routes * Add OIDC consent, rule and error copy * Record phase B3 rules in ADR 0119 * Correct the OIDC error copy comment * Treat an empty request parameter as omitted * Pin the OIDC authorize cap in the caps table * Mint a fresh session at every ORCID sign-in * Link an ORCID iD only from a __Host- session * Give OIDC codes a row id and strict times * Refuse a redirect query naming code or state * Move ID token reading into its own module * Sign the reauth marker, guard the caller * Show the redirect host on the consent screen * Say the authorization routes need the flag * Record round-1 authorization rules in ADR 0119 * Start an ORCID link only from the POST route * State the flag-off ORCID link residual * Phase B4: OIDC token, userinfo, revocation and introspection (#2042) * Add oidc_tokens table (migration 0123) * Add OIDC token, userinfo, revoke, introspect * Refuse OIDC tokens on every non-OIDC route * Add the oauth-ip rate limit bucket * Name the nemar.account claims in discovery * Test token statements, router and bearer * Use a plain string in the bearer test * Let the statement decide the refresh token * Record token rules 13 and 14 in ADR 0119 * Note the /oauth routes beside the cookie flag * Revoke on any second presentation of a code * Make the access expiry index partial * Revoke a refresh token's siblings on rotation * Revoke a used code only after PKCE matches * Serve userinfo and introspection in read-only * Seed owner-only data in the allowlist test * Bare bearer challenge, userinfo scope pinned * Omit token_type for a refresh token; type user * Test the content type and a late reuse * Scan the constant-time comparisons * Test database and signing faults * Test trimming, form decoding, grant binding * Correct the surface and bearer docblocks * Record round-1 token rules in ADR 0119 * Let the lost claim detect a code's replay * Refuse a retry once the first child was used * Exempt only POST in read-only maintenance * Record round-2 token rules in ADR 0119 * Correct the ADR 0119 index line * Test the grace's time limit on its own * Phase B5: OIDC revocation cascades and back-channel logout (#2045) * Add oidc_logout_deliveries (migration 0124) The intent row of a back-channel logout, and the closed words of an ending: reasons, statuses, error classes and the retry schedule. Tested on bun:sqlite and Miniflare D1; d1-check passes. * End OIDC grants in every credential cascade One cascade module (oidcEndStatements) is added to the batch of admin revoke, the owner soft delete and its sweep, ORCID unlink and relink, a kind change away from person, the owner end-account route and the client disable. It queues the logouts, revokes the tokens and grants and deletes unused codes. Role demotion, key revocation and sign-out are deliberate non-paths with tests. Tested through the real routes; each caller mutation-checked; caller count held by a source scan. * Send back-channel logouts after a cascade The sender signs a logout+jwt and posts it to the client's registered https address after the batch commits (waitUntil), never following a redirect, with a 5 second timeout, no answer body read and no credential. 5xx and network errors retry at 1m, 5m, 30m, 2h and 12h from a production-only 30 minute tick. A dev worker sends only to loopback or OIDC_LOGOUT_DEV_HOSTS and records the rest as fenced. Owner list view added. * Add end-account and logout-deliveries commands nemar admin oidc end-account (the manual merge step and incident tool) and logout-deliveries, and the disable command now reports what it revoked. * Run the cascade statements on Miniflare D1 Every cascade and delivery store statement, as the real functions build it, runs on D1 itself, where bun:sqlite accepts SQL that D1 refuses. * Record the OIDC cascade and logout in ADR 0119 Rule 12 gains the cascade function, its order, filters and caller list, rule 15 the delivery, token, request and fence, with consequences and open questions. Index line, AGENTS.md and implementation notes updated; wording pinned by test. * Refuse a loopback host with a trailing dot localhost. names localhost; the production address check now strips trailing dots before testing the host. Tested for production and dev. * Document the kind change and the dev hosts var The kind route comment names the grants it now ends; wrangler documents the absent OIDC_LOGOUT_DEV_HOSTS var; a userinfo test expects a disabled client's token row to be revoked. * Retry throttled logouts, close the class list A 408 or 429 is retried on the same six-attempt schedule with the class http_throttled; Retry-After is only a lower bound for the wait, capped at 12 hours, and only for those two. last_error_class is now a closed list in the unreleased migration, held equal as a set to the vocabulary for reason, status and class. * Prune finished logout deliveries in the tick The production tick deletes sent and fenced deliveries after 30 days and failed ones after 180, at most 500 a tick and after its delivery work, and never a pending row. The windows are named defaults in shared/oidc.ts for the owner to set before the first client registers. Dev has no tick and is not pruned. * Log a database fault in the first attempt attemptDueLogouts never throws, so the catch after it was dead and a fault in the first attempt (or the sweep's) left no trace. The tally is now logged as a count and the error's class, never its text, an address, a token or a subject. * Agree on a trailing dot and test the fence isLoopbackHost and isLocalOrLiteral fold a trailing dot, so registration of a logout or redirect address and the sender's check at send time agree. Tests: production ignores OIDC_LOGOUT_DEV_HOSTS for a local host that the list names, a stored address that is no longer sendable is recorded address_refused through the sender, dotted forms in the registry and verdict tables. * Test the lease, unreported and the pins Claimed-never-recorded attempts are taken up again when the lease lapses and failed as unreported once all six are used; the claim's two-minute lease is read from the database and pinned above the 5 second timeout; the timeout window is tight; the token-store reason test no longer feeds one list through itself. * Hold the cascade callers by every reference The caller scan now resolves import bindings of the cascade module (named, aliased, namespace, destructured, alias chains) and flags every other use outside it as a stray: a value, a raw SQL constant, a dynamic import, a re-export, a default import, a namespace element access, a module-level reference. Each way is planted and shown caught. * Correct the end-account text, tighten types The end-account question no longer says the person is asked again at every client (a first-party client does not ask), and the help says to pair the command with a revocation, deletion or kind change for a merge loser. The reason is a z.enum that never echoes a value, an unsent delivery's status and class are a typed pair, the soft delete and sweep paths get the restore test, and the stand-in reports the cause of an openssl failure. * Record the round-1 rulings in ADR 0119 Rule 12 says a new path adds to OIDC_END_CALLERS and to the docs and private lists only when it runs their statements, that only the sweep is guarded, and that a merge loser's end-account is paired with a revocation, deletion or kind change. Rule 15 decides throttling with Retry-After, unreported, the owner routes without the cookie flag, and retention; open points updated. * Drop kind change from the merge-loser steps A kind change away from person ends only the person_proven_orcid grants, and a non-person account still meets active_account, so it cuts no merge loser off. The end-account help and ADR 0119 rule 12 now say to run end-account and then revoke or delete the loser, and why in that order. Tested: kind change keeps active_account grants and signs in again; the merge procedure through the real routes; wording pins fail on the old text. * Cap a Retry-After of any length A run of 11 or more digits was read as no Retry-After, so a partner asking for the longest wait got the shortest. parseRetryAfter now accepts any run of digits and caps digits and dates at 12 hours; the cap lives there and recordOf only takes the longer of it and the schedule. Tested: 12, 25 and 400 digits through the sender and a pure parser table; restoring the 10-digit limit fails both. * Correct the delivery span and failed help With Retry-After capped at 12 hours, a failed row's last attempt can come about 63 hours after its creation, not under a day: the retention comment, ADR rule 15 and its consequences now say within three days, derived from the constants and pinned by a test. The logout-deliveries help now lists what is final and what is retried, read from a table of every status from 200 to 599 through the real sender. * Flag an exported alias of the cascade The caller scan saw no call and no value in export const endIt = oidcEndStatements, so a caller in another file could hide behind it. An alias whose name is exported by its declaration (const, let, var, a destructured pattern, a namespace member, a later assignment to an exported let) is now a stray, reported once. Both headers say a call that never runs, or whose result is discarded, passes the scan. Tested with the real scanner on planted source; removing the check fails it. * Phase B6: OIDC end-to-end test (S0, S1) (#2048) * Pin relying-party libraries for the OIDC test * Add OIDC end-to-end test with a real library * Declare OIDC token error words once * Check the token error type at compile time * Scope e2e hooks and add verifier controls * Pin openid-client 6.8.9 * Amend ADR 0119 on key re-encryption * Narrow the key recovery to current and next * List every verifier control in the e2e header * Guard the e2e hooks against failed setup * Phase B6: OIDC conformance rig and run (S4, S5) (#2049) * Add the conformance plan configurations * Add the conformance rig and its pre-flight * Pin the conformance suite images by digest * Add the OIDC conformance workflow * Accept a redirect as the suite being up * Run the suite scripts in their local mode * Let every Basic module run to its outcome * Give the rig a client for each purpose * Record the approved deviations and skips * Stop the rig and pin Python before upload * Test the expected files and workflow limits * Give each plan its own expected failures * Expect both client_secret_post failures * Accept a combined decision in the PKCE check * Say what the exported results copy * Log each authorization error the rig answers * Check the authorization errors before upload * Wait for the rig to exit before upload * Bound the suite start and lower the Basic limit * Say the suite goes on after the secret check * Test the PKCE refusal, scopes and the pre-flight * Test the authorization check and stop step * Fail on malformed authorization lines * Match strictly and report a missing log * Test the check's entry point and its step * Log a rule refusal as access_denied * Read an error in the redirect fragment * Count authorization requests against their lines * Test each kind of authorization line * Kill a rig that ignores the stop * State the residual risk of a global allowed set * Fix the tier claims in two OIDC test headers (#2053) * Claim the unit-pure tier in two OIDC headers * Fix OIDC test header wording * Add a process CI tier and move the two OIDC process tests into it (#2056) * Route CI TIER: process files out of unit-pure Add scripts/ci/process-files.sh, which lists the files whose header claims the process tier, and have unit-pure-files.sh skip them. The routing test reads the new pattern from the script. Tested: bun test test/ci-tier-routing.unit.test.ts. * Add the process-tier CI job One job, on the unit-pure trigger, that runs the files process-files.sh lists and refuses an empty list. No secrets, no sharding. Tested: routing test; actionlint shows only the three SC2086 notes already present on the base. * Move the two OIDC process tests to the process tier oidc-conformance-rig and oidc-e2e now claim CI TIER: process, with the reason stated. The routing test asserts they are listed by process-files.sh and absent from the unit-pure list. Tested: routing test; both files run on their own. * Run the process tier in the deploy gate The pure list skips process files, so test-gate gains a step that runs scripts/ci/process-files.sh with the same empty-list refusal. The routing test asserts the gate runs it. Tested: routing test, both OIDC files, actionlint, typecheck, lint. * Give the OIDC alias scan test 60 s (#2052) * Reword the OIDC compute-spend consent sentence (#2057) * Reword the OIDC compute-spend consent sentence * Update ADR 0119 consent screen wording * Remove the temporary conformance push trigger (#2059)
Phase B2 of the compute program's OpenID Connect (OIDC) epic (#2014), issue #2016. After this phase the owner can register OIDC clients and manage signing keys with
nemar admin oidc, and the API publishes a discovery document and a JSON Web Key Set (JWKS) on its own host only. No sign-in works yet. This pull request was reviewed by a Sonnet panel and an Opus security read, and the second half of the commit list answers that review.What the phase adds
0121_oidc_clients_and_keys.sql:oidc_clientsandoidc_signing_keys, a header comment per column, every CHECK TRUE or FALSE (never NULL), no foreign key, partial unique indexes allowing onenextand onecurrentkey. Checked against real D1 and bun:sqlite.shared/oidc.ts(import-free): the scope catalogue (compute.statsmachine-only), grants, sign-in rules, consent modes, token prefixes and lifetimes from Architecture Decision Record (ADR) 0119, identifier formats, endpoint paths.shared/contract/oidc-admin.ts: lenient zod wire shapes (no closed schema); an unknown request field is refused by name at the route.services/oidc-config.ts: the issuer isAPI_BASE_URLtrimmed of trailing slashes and nothing derived from a request; the provider is on only with anOIDC_SECRETof at least 32 characters;onOidcSurface; the discovery document.services/oidc-keys.ts: P-256 keys, the private half encrypted underOIDC_SECRET, ES256 signing (ECDSA over P-256 with SHA-256), the JWKS built from an allow-list of public members, rotation as one batch whose partial unique indexes are the lock.services/oidc-clients.ts: registration rules, 256-bit client secrets shown once and kept as a hash, constant-time verification that honours the previous secret until its grace ends.routes/oidc-discovery.ts:GET /.well-known/openid-configurationandGET /oauth/jwks, 404 unlessoidcSurfacepasses (exported for Phase B4: OIDC token, userinfo, revocation and introspection #2018 and Phase B5: OIDC revocation cascades and back-channel logout #2019), exempt from the maintenance mode and the rate limiter.routes/admin/oidc.ts: owner routes behind oneuse("/oidc/*", ownerMiddleware, oidcSurface, no-store); audit rows byauditLogStatement, shape only.nemar admin oidc clients add|list|show|rotate-secret|disableandkeys list|rotate|revoke, every command--json, an "Exit codes:" block each;client_secretis redacted from the debug log.OIDC_SECRET: an optional binding, listed in the secrets comment ofbackend/wrangler-sccn.toml, never a[vars]entry (a test pins it).Round 1: what changed after review
Security (Opus read):
isFirstPartyRedirect(uri, env)inservices/oidc-clients.ts, exported for phase B3: https only,nemar.orgor a subdomain, never a partner host, the default port, no user information; a loopback address (any port, http or https) and a website preview count only outside production. It replaces the cross-origin predicateisNemarWebOrigin, which admits loopback and previews everywhere. Every host class is tested in production and outside it, and an unset or unknownENVIRONMENTis production.new URL(raw).href === raw. That one comparison refuses a scheme with no slashes, upper-case schemes and hosts, dot segments however spelled, an explicit default port, a missing path, an ideographic full stop, look-alike letters, and the invisible and bidirectional format characters (table-driven, with a control that canonical addresses pass). A bare origin such ashttps://example.orgmust now be writtenhttps://example.org/.key_unreadable(409) and no change when the key was encrypted under anotherOIDC_SECRET; the same check guardscurrentwhen only anextkey is made. The decrypted key must also match the public key published for its row, so a ciphertext swapped between rows cannot sign under the wrongkid.authorization_codegrant (a client-credentials-only client may hold only machine scopes),refresh_tokenneedsauthorization_code, andoffline_accessandrefresh_tokencome together. Typedinvalid_bodyrefusals name the field./nemarexclusion bypass is closed: the surface test now decodes the path (up to three times) as a router does, so/%6eemar/...,/%6Eemar/...,/n%65mar/...and double or triple encodings are 404 for discovery, the JWKS and every owner route, tested through the real Worker.UNIQUE constraint failed: oidc_signing_keys.state) is a rotationconflict; a CHECK or another table's or column's violation is thrown. Tested with a database whose batch throws the message D1 gives.Cache-Control: public, max-age=300and the open CORS (cross-origin resource sharing) header only on a 200: a key set that could not be read is a 500 with neither. The JWKS builder now fails loudly (500) when thecurrentornextkey's public half is malformed instead of publishing a shorter set; a malformed retired key is logged and skipped.signJwttakes the token type (typ, defaultJWT) for phase B5'slogout+jwttoken.response_modes_supported: ["query"]; a back-channel logout address in production may not be a loopback host or an IP literal; client names are unique among active clients, ignoring case (409client_name_taken, enforced by a partial unique index and a pre-check);clients addsuggestsclients listafter a network error, because a retried create registers a second client whose secret nobody holds.Tests and correctness (Sonnet panel):
test/admin-oidc-cli.test.tscallssetDefaultTimeout(30_000)(one test makes 28 CLI spawns); it passes alone with the default settings.kid = ? AND state = .... The reviewers showed no test pinned the state conditions; I found the scenario in which they matter, and each now has a test. Two rotations (or a rotation and a revocation) finishing between a slow writer's read and its write would otherwise rewrite a key into a state its stamps forbid and fail as a CHECK violation (a 500) instead of a cleanconflict; the header comment says so.ClientInputcarries typed unions for the sign-in rule and the consent mode (as consttuples inshared/oidc.ts), with membership checks invalidateClientInput(a typed refusal, not a 500 from the table's CHECK).oidcDiscoveryRouteshas a route-inventory pin (exactly two documents, three handlers each, no wildcard, the surface check first by reference), and the admin inventory pins the new routes.Docs, wording and structure:
oidc-clients.tsdocblock, the refusal message, the CLI help): a client with a non-NEMAR redirect does not "always show consent". It never skips the consent screen and follows itsconsent_mode(ask_onceby default, oralways). The refusal now reads "first_party is refused ... Register the client without first_party and it is a third-party client".API_BASE_URL; staging ishttps://api-test.nemar.org; any other host answers 404) and leaves the not-decided list and the index; the keys' life (including the new states), the client secret prefix and the consequence of changingOIDC_SECRETare recorded; a test holds these statements. Status staysproposed.shared/oidc.tsare interpolated in the CLI help and messages and in the route messages (grace default and maximum, the 24 hours, the 7 days, the scope and grant lists, the redirect limit, the id formats). The unusedOIDC_CLIENT_STATUSESandOIDC_KEY_STATESare deleted;services/oidc-encoding.tsholds the onerandomHexandtoBase64Url; onerenderTableserves the CLI; the logout-address refusal has its own message and a comment on whystartsWith("https://")stays.Decisions applied, owner's veto still open
nmo_cs_plus 43 base64url characters, so a secret scanner can find one. Verification is by hash of the whole string; nothing else depends on the prefix. In ADR 0119 rule 4.revokedsigning-key state exists from the first release (a CHECK cannot be changed in place, so a later state would be a table rebuild).POST /admin/oidc/keys/:kid/revokeandnemar admin oidc keys revoke <kid>withdraw a retired key; the current and next keys are refused (rotate first); a revoked key is never published; the CLI asks first (--yesanswers); audited. This was proportionate, so it is the full feature and not only the CHECK.allowed_scopesmay hold up to 20 names (the catalogue has 10), and a test holds the catalogue to that cap, so "a new scope needs no migration" is true.private_jwk_encryptedis NULL-able forretiredandrevokedkeys only (a CHECK), so private halves can be wiped later. Nothing wipes them yet.keys rotate --forcerefuses while the next key is under 6 minutes old unless the CLI got--emergency(a flag of its own, not--yes, which only answers confirmation prompts; the request carriesemergency, and the Worker reads it only together withforce). A key published a moment ago may not be in a client's cached key set, so tokens signed with it can fail verification there for up to about 5 minutes; the help says so, and the audit row records the emergency.Gates (final lines)
bun run typecheck:tsc --noEmit && tsc --noEmit -p backend, no errors.bun run lint:biome check src/, Checked 179 files, No fixes applied.bunx biome checkon every file this branch touches: Checked 36 files, No fixes applied. The whole commandbunx biome check backend/src shared src teststill reports Found 42 errors and Found 29 warnings, identical at the phase B1 commit and in files this branch does not touch.oidc-*backend suites,test/adr-0119-wording.unit.test.ts, the admin route inventory, the API export surface, help tiers, debug-log redaction, contract schemas, ADR index, maintenance and cross-origin suites).test/admin-oidc-cli.test.tsalone, default settings: 38 pass, 0 fail, 18.39 s.bun run migrations:d1-checkalone: All migrations applied on real D1. Catalog matches bun:sqlite (166 objects, 50 tables). OK.bun testis the driver's. The previous full run (before this round) had 3 failures unrelated to this branch: a copy-parity test that compares against a local website checkout, and two timeouts under the load of the run that pass alone.Not verified, and deferred
WeakMapkeyed byenv.DB. Under workerd (Miniflare) a Worker is handed the sameenv.DBobject on every request of an isolate, whichbackend/test/oidc-jwks-memo-identity.test.tspins; whether the deployed edge does the same is unverified until the dev Worker has served traffic. If not, it is a no-op that costs one read per request.encrypt()anddecrypt()(100,000 iterations) on a real Worker is not measured. Decrypted keys are cached per isolate, so it is paid once per key, but a cold isolate pays it on its first signature.OIDC_SECRETwith a version on each row (Phase B6: Sign in with NEMAR docs and conformance #2020); the token endpoint's use ofverifyClientSecret(Phase B4: OIDC token, userinfo, revocation and introspection #2018); an account-kind check on owner routes (pre-existing for every owner route).OIDC_SECRETleaves no CLI way back (a rotation refuses withkey_unreadable, and revoke refuses the current and next keys), so recovery means removing the unreadable key rows by hand before a rotation can make a new pair; the runbook (Phase B6: Sign in with NEMAR docs and conformance #2020) carries that procedure and the re-encryption path.OIDC_SECRETis set nowhere; the owner sets it, and it must differ fromENCRYPTION_KEYand be random (for exampleopenssl rand -base64 48), now said in the secrets comment.Deviations from the issue
oidcSurfaceas well asownerMiddleware, so they are 404 off the issuer's host and under/nemar; the CLI says why on that 404.claims_supportedlists no claim fornemar.account(ADR 0119 names none); the userinfo phase names them.request_uri_parameter_supportedandresponse_modes_supportedin discovery, a 168-hour maximum grace,disableandrevokeasking first, and the JWKS cache.