Skip to content

Phase B2: OIDC client registry, signing keys and discovery #2016

Closed

Description

@neuromechanist

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

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 of 0112_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_hash and previous_secret_expires_at, redirect_uris (JSON array, 1 to 10), allowed_scopes, allowed_grants (JSON subsets of authorization_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_reservations and cap_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 one next and one current.
  • shared/oidc.ts (import-free): scope catalogue (openid, profile, email, orcid, nemar.account, offline_access, compute.read, compute.reserve, compute.submit, compute.stats) with compute.stats marked 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 is API_BASE_URL trimmed of a trailing slash; oidcEnabled(env) is true only when OIDC_SECRET is at least 32 characters. Add the optional OIDC_SECRET binding and list it in the secrets comment of backend/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 with encrypt() from services/encryption.ts under OIDC_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 (next becomes current only if at least 24 hours old unless forced, current becomes retired, a new next is made; rotating an empty table creates current and next). Cache decrypted keys in module scope.
  • backend/src/services/oidc-clients.ts: validation (redirect URIs exact, https only, loopback http only when isNonProductionEnv, no fragment, no wildcard, no userinfo; first_party refused when any redirect host is a partner host or not a NEMAR-run host; scopes within the catalogue; compute.stats only with client_credentials; logout URI https), secret generation (256-bit, shown once), hashing with hashApiKey, constant-time verification honouring the previous secret until its expiry.
  • backend/src/routes/oidc-discovery.ts, mounted in backend/src/index.ts next to the Neurobagel mount: both documents answer 404 unless oidcEnabled and the request's hostname equals the issuer's and the path has no /nemar prefix (export this as an oidcSurface middleware that Phase B4: OIDC token, userinfo, revocation and introspection #2018 and Phase B5: OIDC revocation cascades and back-channel logout #2019 reuse on every /oauth and owner route) (the worker mounts api at both / and /nemar; resolveHostRoute forks 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_endpoint is APP_BASE_URL plus /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.ts with registerOidcAdminRoutes(admin), each behind ownerMiddleware: 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 via auditLogStatement, shape only. Register in routes/admin/index.ts; pin handlers in test/admin-route-inventory.unit.test.ts.
  • CLI: src/commands/admin-oidc.ts (new Command("oidc"), subgroups clients add|list|show|rotate-secret|disable and keys list|rotate, every command --json, an "Exit codes:" help block), src/lib/api/oidc.ts (add to MODULE_EXPORTS in test/api-export-surface.unit.test.ts), registered after repullCommand in src/commands/admin.ts. Add client_secret to the debug-log redaction in src/lib/debug-log.ts.

Tests (write these first)

  1. Discovery and JWKS answer on the issuer host only: 404 on the data host, on /nemar/.well-known/..., on another hostname, and when OIDC_SECRET is absent. Mutation: remove the hostname check.
  2. The JWKS holds no private member and carries next and current; a JWT signed by the service verifies with crypto.subtle against the published key; a wrong OIDC_SECRET cannot decrypt the stored key.
  3. Rotation state machine and both partial unique indexes, including the 24 hour rule and --force.
  4. Client validation refuses each bad redirect (wildcard, fragment, http in production, a partner host with first_party); the secret is shown once, the database holds only its hash, rotation keeps the old secret valid until the grace ends.
  5. Every owner route refuses a non-owner admin (403) and an anonymous call (401).
  6. CLI end to end against a Bun.serve of the real routes over freshDb (template test/admin-repull-auto-cli.test.ts); --json stdout 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_URL and 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_SECRET is 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

  1. added
    feature
    on Nov 4, 2026
  2. neuromechanist commented on Nov 4, 2026

    @neuromechanist
    ContributorAuthor

    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.

    • A client is treated as first-party only when EVERY registered redirect URI is on a NEMAR web origin (not merely when none is on a partner host); a client with any other redirect is third-party and always shows the consent page.
    • Discovery and the JWKS document live on the API host permanently (ADR 0119); exempt both from maintenanceMode and from the rate limiter, and test it.
  3. neuromechanist commented on Nov 4, 2026

    @neuromechanist
    ContributorAuthor

    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 prefix nmo_cs_; a revoked signing-key state with nemar admin oidc keys revoke; first-party means an https host on nemar.org (loopback and website previews only outside production); a forced rotation within 6 minutes of publication needs --emergency. The OIDC_SECRET Worker 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_SECRET and the rotation procedure (a docs pull request), and the first-party and consent wording on the design page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurehpc

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions