Stage 1: /api/auth/exchange/k8s for service-principal JWTs #32

Merged
romaine-life-app[bot] merged 1 commit from service-token-exchange into main 2026-05-16 15:16:58 -07:00
romaine-life-app[bot] commented 2026-05-16 14:17:18 -07:00 (Migrated from github.com)

Summary

Stage 1 of nelsong6/tank-operator#486 — auth-side only.

Adds POST /api/auth/exchange/k8s: session pods (today: tank-operator) POST their projected SA token and receive a normal auth.romaine.life JWT with role=service. The JWT is shape-compatible with human JWTs (same JWKS, iss, aud) so any app that already verifies auth.romaine.life tokens can accept service callers by extending its role gate to include service — no JWKS/verifier surgery needed.

This PR is independently coherent: the endpoint is live and verified by tests, but no in-cluster caller exists yet. Stage 2 (tank-operator role-gate widening + new session-creation handlers) and Stage 4 (atomic cutover of requireInternalCaller SA-TokenReview path) will land cross-repo against this contract.

What's in here

  • POST /api/auth/exchange/k8s — reuses the existing verifyK8sSAToken (refactored to accept env-driven {audience, allowlist} so the admin and service paths share one verifier). Audience pinned to https://auth.romaine.life per K8S_SERVICE_AUDIENCE; (namespace, serviceAccount) pinned per K8S_SERVICE_SA_ALLOWLIST.
  • Synthetic email domain. pod-<session-id>@service.tank.romaine.life. DNS-owned, never MX-served. RESERVED_SERVICE_EMAIL_DOMAINS in src/synthetic-email.ts is the registry — new consumers add one entry here and one row in NAMESPACE_TO_CONSUMER (both required by construction; buildServiceEmail refuses unregistered consumers).
  • Reserved-domain guard. databaseHooks.user.create.before in src/auth.ts refuses any IdP-sourced user-create whose email is in a reserved domain. Defense-in-depth against a Microsoft/Google IdP returning an email that collides with our synthetic namespace. Admin console POST /admin/users gets the same check.
  • Service user upsert. Idempotent on userId = svc:<consumer>:<session-id> (deterministic, prefix-namespaced so it cannot collide with a human UUID). Inserted directly via Drizzle to intentionally bypass the reserved-domain hook above — that hook exists to block humans, not the exchange that owns the namespace.
  • JWT mint via auth.api.signJWT. Better Auth's /sign-jwt endpoint is exposed only programmatically (no HTTP path). Uses the same JWKS-stored keypair, same iss, same aud, same kid rotation behavior as the human path. Default TTL 15 min (Better Auth's expirationTime default). Extra actor_email claim carries the human owner.
  • Pod-annotation lookup. src/k8s-pod.ts does a single GET against kubernetes.default.svc using the in-cluster SA token. Trusts the cluster CA via NODE_EXTRA_CA_CERTS so native fetch works without pulling in undici / @kubernetes/client-node.
  • Cross-namespace RBAC. k8s/templates/rbac-service-consumers.yaml scaffolds a Role + RoleBinding granting pods/get to (auth/auth) in each namespace listed under k8sOidc.serviceConsumerNamespaces. Scoped strictly to pods get — minimum surface for the lookup, no list/watch.

What's NOT in here (deferred to later stages)

  • Stage 2/4 cutover lives on tank-operator + mcp-tank-operator and depends on this endpoint being deployed first.
  • Stage 5 observability — nelsong6/auth doesn't currently expose Prometheus; adding a metrics surface is its own scoped lift. Until then, exchange failures surface via console.error and the structured reason in the response body (denied_token | denied_allowlist | denied_unbound_pod | denied_unknown_namespace | denied_annotation_missing | denied_pod_lookup_failed | error_jwt_mint | error_internal).
  • Stage 6 quota lives on tank-operator (per-sub and per-actor_email ceilings on create_session); auth doesn't gate that.

Test plan

  • npm run typecheck — clean
  • npm run build — clean
  • npm test — 42/42 passing (existing 28 + 14 new across synthetic-email, k8s-pod, service-exchange helpers)
  • npm run check:static-slot-origins — clean
  • helm template auth k8s/ — renders; new env vars and cross-namespace RBAC present
  • Manual smoke: deploy to auth, exchange a real session-pod SA token, verify the returned JWT validates against /api/auth/jwks and carries role=service + actor_email (post-merge, paired with the Stage 3 session-pod bootstrap)

Migration policy

No legacy auth shape is being retired in this PR — the new endpoint is additive. The retirement of requireInternalCaller's raw SA-TokenReview path on tank-operator's /api/internal/sessions/* is Stage 4 and lands atomically with the mcp-tank-operator switchover per #486.

## Summary Stage 1 of [nelsong6/tank-operator#486](https://github.com/nelsong6/tank-operator/issues/486) — auth-side only. Adds `POST /api/auth/exchange/k8s`: session pods (today: tank-operator) POST their projected SA token and receive a normal auth.romaine.life JWT with `role=service`. The JWT is shape-compatible with human JWTs (same JWKS, `iss`, `aud`) so any app that already verifies auth.romaine.life tokens can accept service callers by extending its role gate to include `service` — no JWKS/verifier surgery needed. This PR is independently coherent: the endpoint is live and verified by tests, but no in-cluster caller exists yet. Stage 2 (tank-operator role-gate widening + new session-creation handlers) and Stage 4 (atomic cutover of `requireInternalCaller` SA-TokenReview path) will land cross-repo against this contract. ## What's in here - `POST /api/auth/exchange/k8s` — reuses the existing `verifyK8sSAToken` (refactored to accept env-driven `{audience, allowlist}` so the admin and service paths share one verifier). Audience pinned to `https://auth.romaine.life` per `K8S_SERVICE_AUDIENCE`; `(namespace, serviceAccount)` pinned per `K8S_SERVICE_SA_ALLOWLIST`. - **Synthetic email domain.** `pod-<session-id>@service.tank.romaine.life`. DNS-owned, never MX-served. `RESERVED_SERVICE_EMAIL_DOMAINS` in `src/synthetic-email.ts` is the registry — new consumers add one entry here and one row in `NAMESPACE_TO_CONSUMER` (both required by construction; `buildServiceEmail` refuses unregistered consumers). - **Reserved-domain guard.** `databaseHooks.user.create.before` in `src/auth.ts` refuses any IdP-sourced user-create whose email is in a reserved domain. Defense-in-depth against a Microsoft/Google IdP returning an email that collides with our synthetic namespace. Admin console `POST /admin/users` gets the same check. - **Service user upsert.** Idempotent on `userId = svc:<consumer>:<session-id>` (deterministic, prefix-namespaced so it cannot collide with a human UUID). Inserted directly via Drizzle to intentionally bypass the reserved-domain hook above — that hook exists to block humans, not the exchange that owns the namespace. - **JWT mint via `auth.api.signJWT`.** Better Auth's `/sign-jwt` endpoint is exposed only programmatically (no HTTP path). Uses the same JWKS-stored keypair, same `iss`, same `aud`, same `kid` rotation behavior as the human path. Default TTL 15 min (Better Auth's `expirationTime` default). Extra `actor_email` claim carries the human owner. - **Pod-annotation lookup.** `src/k8s-pod.ts` does a single GET against `kubernetes.default.svc` using the in-cluster SA token. Trusts the cluster CA via `NODE_EXTRA_CA_CERTS` so native fetch works without pulling in `undici` / `@kubernetes/client-node`. - **Cross-namespace RBAC.** `k8s/templates/rbac-service-consumers.yaml` scaffolds a Role + RoleBinding granting `pods/get` to (`auth/auth`) in each namespace listed under `k8sOidc.serviceConsumerNamespaces`. Scoped strictly to `pods get` — minimum surface for the lookup, no list/watch. ## What's NOT in here (deferred to later stages) - **Stage 2/4 cutover** lives on tank-operator + mcp-tank-operator and depends on this endpoint being deployed first. - **Stage 5 observability** — `nelsong6/auth` doesn't currently expose Prometheus; adding a metrics surface is its own scoped lift. Until then, exchange failures surface via `console.error` and the structured `reason` in the response body (`denied_token | denied_allowlist | denied_unbound_pod | denied_unknown_namespace | denied_annotation_missing | denied_pod_lookup_failed | error_jwt_mint | error_internal`). - **Stage 6 quota** lives on tank-operator (per-`sub` and per-`actor_email` ceilings on `create_session`); auth doesn't gate that. ## Test plan - [x] `npm run typecheck` — clean - [x] `npm run build` — clean - [x] `npm test` — 42/42 passing (existing 28 + 14 new across synthetic-email, k8s-pod, service-exchange helpers) - [x] `npm run check:static-slot-origins` — clean - [x] `helm template auth k8s/` — renders; new env vars and cross-namespace RBAC present - [ ] Manual smoke: deploy to auth, exchange a real session-pod SA token, verify the returned JWT validates against `/api/auth/jwks` and carries `role=service` + `actor_email` (post-merge, paired with the Stage 3 session-pod bootstrap) ## Migration policy No legacy auth shape is being retired in this PR — the new endpoint is additive. The retirement of `requireInternalCaller`'s raw SA-TokenReview path on tank-operator's `/api/internal/sessions/*` is **Stage 4** and lands atomically with the mcp-tank-operator switchover per [#486](https://github.com/nelsong6/tank-operator/issues/486).
Sign in to join this conversation.
No description provided.