Repository navigation
Description
Goal
After this phase the owner can register OIDC clients and manage signing keys with nemar admin oidc, and the API publishes a correct discovery document and JSON Web Key Set (JWKS) on its own host only.
No sign-in works yet.
Routing
- Readiness: ready
- Implementer: Sonnet
- Opus checkpoint: none
- Depends on: Phase B1: ADR 0119, partner hosts, __Host- cookie and OIDC subject #2015 ; Unblocks: Phase B3: OIDC authorization and consent #2017, Phase B4: OIDC token, userinfo, revocation and introspection #2018
- Repository and base branch: nemarOrg/nemar-cli, epic branch
Scope
In: migration 0121, discovery, JWKS, ES256 signing, owner routes, the CLI, the OIDC_SECRET binding.
Out: authorization (#2017), tokens (#2018), revocation on disable (#2019; here disable only sets the status).
Design references
Design section 3 (Endpoints, Clients, Tokens); ADR 0119.
Changes
backend/src/db/migrations/0121_oidc_clients_and_keys.sql(style of0112_upstream_repull_automatic.sql: header comment per column, CHECKs never NULL, no cascading foreign keys).oidc_clients:id,client_id(oc_plus 24 hex, unique),name,secret_hash,previous_secret_hashandprevious_secret_expires_at,redirect_uris(JSON array, 1 to 10),allowed_scopes,allowed_grants(JSON subsets ofauthorization_code,refresh_token,client_credentials),sign_in_rule(active_account|person_proven_orcid),first_party(0|1),consent_mode(ask_once|always),backchannel_logout_uri(nullable),audience,introspection_audiences(JSON),cap_open_reservationsandcap_su_per_day(nullable, enforced by the compute epics),status(active|disabled),disabled_at,created_by, timestamps.oidc_signing_keys:kid(16 hex, primary key),alg(ES256),state(next|current|retired),public_jwk,private_jwk_encrypted,created_at,promoted_at,retired_at, with partial unique indexes allowing onenextand onecurrent.shared/oidc.ts(import-free): scope catalogue (openid,profile,email,orcid,nemar.account,offline_access,compute.read,compute.reserve,compute.submit,compute.stats) withcompute.statsmarked machine-only, token prefixes and lifetimes from ADR 0119.shared/contract/oidc-admin.ts: zod wire shapes for the owner routes.backend/src/services/oidc-config.ts: issuer isAPI_BASE_URLtrimmed of a trailing slash;oidcEnabled(env)is true only whenOIDC_SECRETis at least 32 characters. Add the optionalOIDC_SECRETbinding and list it in the secrets comment ofbackend/wrangler-sccn.toml(the owner sets it; an agent never does).backend/src/services/oidc-keys.ts: generate P-256 keys, encrypt the private JWK withencrypt()fromservices/encryption.tsunderOIDC_SECRET, sign a JWT as ES256 (WebCrypto's output is already the JOSE r||s form), build the JWKS (next, current, and retired keys for 7 days; never a private member), rotate (nextbecomescurrentonly if at least 24 hours old unless forced,currentbecomesretired, a newnextis made; rotating an empty table createscurrentandnext). Cache decrypted keys in module scope.backend/src/services/oidc-clients.ts: validation (redirect URIs exact,httpsonly, loopbackhttponly whenisNonProductionEnv, no fragment, no wildcard, no userinfo;first_partyrefused when any redirect host is a partner host or not a NEMAR-run host; scopes within the catalogue;compute.statsonly withclient_credentials; logout URIhttps), secret generation (256-bit, shown once), hashing withhashApiKey, constant-time verification honouring the previous secret until its expiry.backend/src/routes/oidc-discovery.ts, mounted inbackend/src/index.tsnext to the Neurobagel mount: both documents answer 404 unlessoidcEnabledand the request's hostname equals the issuer's and the path has no/nemarprefix (export this as anoidcSurfacemiddleware that Phase B4: OIDC token, userinfo, revocation and introspection #2018 and Phase B5: OIDC revocation cascades and back-channel logout #2019 reuse on every/oauthand owner route) (the worker mountsapiat both/and/nemar;resolveHostRouteforks data, zarr and mcp hosts before this). Headers:Access-Control-Allow-Origin: *,Cache-Control: public, max-age=300. Discovery lists the issuer, the endpoints (authorization_endpointisAPP_BASE_URLplus/oauth/authorize),response_types_supported: ["code"],id_token_signing_alg_values_supported: ["ES256"],token_endpoint_auth_methods_supported: ["client_secret_basic"],code_challenge_methods_supported: ["S256"], grants, scopes, claims,authorization_response_iss_parameter_supported,backchannel_logout_supported,request_parameter_supported: false.backend/src/routes/admin/oidc.tswithregisterOidcAdminRoutes(admin), each behindownerMiddleware:POST /oidc/clients,GET /oidc/clients,GET /oidc/clients/:client_id,POST /oidc/clients/:client_id/rotate-secret(graceHours, default 24),POST /oidc/clients/:client_id/disable,GET /oidc/keys,POST /oidc/keys/rotate. Audit rows viaauditLogStatement, shape only. Register inroutes/admin/index.ts; pin handlers intest/admin-route-inventory.unit.test.ts.- CLI:
src/commands/admin-oidc.ts(new Command("oidc"), subgroupsclients add|list|show|rotate-secret|disableandkeys list|rotate, every command--json, an "Exit codes:" help block),src/lib/api/oidc.ts(add toMODULE_EXPORTSintest/api-export-surface.unit.test.ts), registered afterrepullCommandinsrc/commands/admin.ts. Addclient_secretto the debug-log redaction insrc/lib/debug-log.ts.
Tests (write these first)
- Discovery and JWKS answer on the issuer host only: 404 on the data host, on
/nemar/.well-known/..., on another hostname, and whenOIDC_SECRETis absent. Mutation: remove the hostname check. - The JWKS holds no private member and carries next and current; a JWT signed by the service verifies with
crypto.subtleagainst the published key; a wrongOIDC_SECRETcannot decrypt the stored key. - Rotation state machine and both partial unique indexes, including the 24 hour rule and
--force. - Client validation refuses each bad redirect (wildcard, fragment,
httpin production, a partner host withfirst_party); the secret is shown once, the database holds only its hash, rotation keeps the old secret valid until the grace ends. - Every owner route refuses a non-owner admin (403) and an anonymous call (401).
- CLI end to end against a
Bun.serveof the real routes overfreshDb(templatetest/admin-repull-auto-cli.test.ts);--jsonstdout is pure JSON.
Acceptance criteria
- An owner can add a client, list it, rotate its secret and disable it from the CLI.
- Discovery is served only from the issuer host and matches the ADR.
- Signing keys rotate and no private key is ever exposed.
Gates
bun run typecheck, bun run lint, bunx biome check backend/src shared src test, the new tests plus test/admin-route-inventory.unit.test.ts, test/api-export-surface.unit.test.ts, test/help-tiers.unit.test.ts, bun run migrations:d1-check, full bun test.
Rules that bite here
- The issuer is
API_BASE_URLand nothing derived from a request (ADR 0119). - Never log or return a secret, a private JWK or a hashed value; secrets appear once, in the creating response.
- D1 limits: GLOB patterns at most 50 characters.
Escalate to the owner if
OIDC_SECRETis needed on a real worker (the owner sets it) or the key rotation interval should differ from 24 hours.
When merged
Add OIDC_SECRET and the rotation procedure to the gated admin/operations/systems-inventory; the full runbook is #2020.
Activity
neuromechanist commentedon Nov 4, 2026
Driver amendment, 2026-11-04, from the phase B1 Opus checkpoint (PR #2031). This comment is part of the phase brief; where it differs from the body above, this comment wins.
maintenanceModeand from the rate limiter, and test it.neuromechanist commentedon Nov 4, 2026
Merged into the epic branch by #2033 (squash
873206d1), 2026-11-04, after a three-reviewer panel, a focused Opus security read and its delta; every accepted finding fixed (triage on the pull request). Gates: 612 targeted tests, the CLI suite alone under the default timeout (38), typecheck, lint and the D1 migration check pass; the full CI run is the epic gate.Decisions this phase applied, owner veto still open (ADR 0119 stays
proposed): client secrets carry the prefixnmo_cs_; arevokedsigning-key state withnemar admin oidc keys revoke; first-party means an https host onnemar.org(loopback and website previews only outside production); a forced rotation within 6 minutes of publication needs--emergency. TheOIDC_SECRETWorker secret is not set anywhere: the owner sets it (random, different from the encryption key; changing it later makes every stored signing key unreadable); until it exists every OIDC surface answers 404.Still owed from this phase's "When merged" step: the gated systems-inventory page with
OIDC_SECRETand the rotation procedure (a docs pull request), and the first-party and consent wording on the design page.