Repository navigation
feat: add OIDC SSO and admin configuration - #432
Closed
xiandan-erizo wants to merge 23 commits into
Closed
xiandan-erizo wants to merge 23 commits into
xiandan-erizo wants to merge 23 commits into
Conversation
Add a provider-neutral single-IdP OIDC entry point for human authentication while keeping Paca's own JWT session, Global RBAC, personal API keys, agent MCP keys, and ACP bridge tokens completely unchanged. OIDC only proves who the user is; Paca remains the session and authorization authority. Protocol: Authorization Code Flow + PKCE (S256) with OIDC Discovery, driven by coreos/go-oidc. ID tokens are verified for signature/JWKS, issuer, audience, expiry, and nonce. Per-login transactions (state -> nonce/verifier) live in Valkey with a 10-minute TTL and GETDEL single-use consumption, so replayed callback URLs are useless. No IdP token is ever stored in the DB or exposed to the browser or agents; callback errors are generic and carry Referrer-Policy: no-referrer. Identity: external identities are keyed by (issuer, subject) — never by email or username. A new user_external_identities table (migration 000041) binds one identity to one Paca user, with JIT provisioning creating the user and binding in a single transaction. Same-email different-subject never links accounts; colliding emails are dropped. Username candidates derive from the configured claim with collision suffixes and an opaque subject-based fallback. SSO-only accounts: users.password_login_enabled (default true) marks JIT-provisioned users, whose password_hash holds an unknown random value. Password login, change-password, admin reset, and set-token flows all fail closed for these accounts, preventing a password reset from silently opening a second login path. Session issuance is refactored first: auth.Service.Login now delegates to a shared IssueSessionForUser (re-reading the user and role), so password and OIDC login issue identical Paca sessions. Logout still only revokes the Paca token family — no forced IdP logout. Local login stays fully backward compatible and can be hidden and server-side disabled via LOCAL_LOGIN_ENABLED=false (forced back on when OIDC is off). GET /auth/config exposes only display data for the login page; GET /auth/oidc/login and /auth/oidc/callback complete the flow server-side and land the browser back on the web app. Frontend: the login page reads /auth/config, shows a "Continue with <display name>" button when SSO is enabled, hides the password form on SSO-only instances, and surfaces a generic error on ?sso_error=1. i18n keys added across all nine locales. Config fails fast at startup: required issuer/client/secret/redirect, HTTPS enforcement in production, openid scope forced, and JIT default role must exist and never be ADMIN/SUPER_ADMIN. IdP discovery runs at boot so a misconfigured deployment never comes up half-configured. Docs: docs/deployment/oidc-sso.md covers architecture, configuration, and a Keycloak reference setup; .env.example and both compose files pass the new variables through (disabled by default).
Address the review findings on the initial OIDC SSO implementation — three blockers and five should-fixes — without changing the overall architecture. Login CSRF (blocker): the state parameter alone lived in a process-global store with no browser binding, so a callback URL could be completed in any browser it was forwarded to, logging the victim into the attacker's account. /oidc/login now mirrors the state into a short-lived HttpOnly SameSite=Lax cookie scoped to the callback path; the callback only proceeds when the cookie matches the state parameter, and the cookie is cleared on every exit path. Handler tests cover the binding, the mismatch rejection, and the clearing. Dead config (blocker): OIDC_JIT_PROVISION=false rejected unknown identities, yet JIT provisioning is the only supported write path for user_external_identities (no admin-link API exists), so the setting could never produce a working deployment. The switch is removed; JIT is always on and documented as such. It can return when an admin linking API lands. SSO-only lockout (blocker): with LOCAL_LOGIN_ENABLED=false and JIT users never receiving elevated roles, a fresh deployment would have no administrator at all. Bootstrap now refuses to start SSO-only unless at least one ADMIN/SUPER_ADMIN user is already bound to SSO, and the docs spell out the staged rollout (SSO alongside local login first, promote an SSO admin, then disable local login). Concurrent first-login race: a lost (issuer, subject) unique-index race now surfaces as a distinct sentinel and the loser resolves the winner's binding instead of failing the login. Issuer normalization: the loader no longer strips trailing slashes — the issuer is an identifier that must match discovery metadata and ID-token iss claims exactly. Only surrounding whitespace is trimmed. UserInfo: profile/email claims are enriched from the provider's UserInfo endpoint (many standard IdPs only serve them there, not in the ID token), with the returned sub required to match the ID token's subject before anything is merged. Identity stays anchored to the ID token; unreachable UserInfo falls back to ID-token claims. email_verified: only emails the IdP has confirmed (email_verified=true) are written to the user record. IdP timeouts: discovery, code exchange, JWKS fetches, and the UserInfo call all go through a dedicated HTTP client with a 10-second timeout, so a half-dead IdP fails fast instead of hanging startup or requests. Username fallback: the opaque fallback is now derived from SHA-256(issuer NUL subject) instead of the raw subject prefix — the subject is an arbitrary IdP-local string and must never leak into a username.
Five fixes from the follow-up review, again with no scope change. Refresh role staleness (blocker): Refresh() re-read the user but still minted the rotated pair from the OLD token's claims.Username and claims.Role, so a promoted SSO user kept refreshing as USER and — far worse — a demoted ADMIN kept minting ADMIN-claim access tokens for the life of the refresh family (legacy authz grants ADMIN/SUPER_ADMIN PermissionAll). Refresh now issues from the freshly read u.Username/u.Role. Tests cover both directions: promotion picked up at the next refresh, and demotion dropping ADMIN immediately, including on the rotated refresh token so staleness cannot survive rotation. SSO-only guard issuer scoping (blocker): HasSSOUserWithRole counted privileged bindings from ANY issuer, so swapping IdPs (Keycloak-A -> Keycloak-B) let a stale admin binding from the retired provider satisfy the startup guard while nobody could actually administer via the new IdP. The query is now scoped to ei.provider='oidc' AND the currently configured issuer; the repo test pins current-issuer, other-issuer, and deleted-admin behavior. Fixed JIT default role: OIDC_DEFAULT_ROLE only rejected the names ADMIN/SUPER_ADMIN, but Paca global roles are customizable permission sets — a custom role carrying "*" would have handed every JIT user full privileges. The setting is removed; JIT users always get the built-in USER role. Revisit when group→role mapping is designed. UserInfo merge semantics: UserInfo now only fills claims MISSING from the ID token (ID-token values always win, matching the documented behavior), and the username is resolved from the raw UserInfo payload via the configured OIDC_USERNAME_CLAIM — a custom claim (e.g. "nickname") previously only worked from the ID token. New tests pin both behaviors.
Rebased onto upstream master (589987f) which just introduced the Helm chart, and extended it so SSO is configurable on Kubernetes, not just Compose: - values.yaml: api.oidc.{enabled,issuerUrl,clientId,scopes, redirectUrl,displayName,usernameClaim,localLoginEnabled} plus secrets.oidcClientSecret (kept under secrets.* so it lands in the Secret rather than a world-readable Deployment spec); - values.schema.json: schema entries for the new keys; - templates/secret.yaml: emits OIDC_CLIENT_SECRET only when api.oidc.enabled, with a required-message when missing; - templates/api/deployment.yaml: maps the values to the API's env vars (secret via secretKeyRef; issuerUrl/clientId via required); - chart README documents every key, including the staged-rollout constraint the API enforces at startup. Verified with helm template: default render contains no OIDC keys, enabled render emits the full env block with the secret referenced (not inlined), missing issuerUrl/clientId/secret each fail with a clear required-message, and redirectUrl overrides the derived callback URL.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Design
Implements https://github.com/orgs/Paca-AI/discussions/431
Validation
go test ./... -count=1(services/api)bun run test(apps/web): 57 files, 582 testsbun run build(apps/web)helm lint deploy/helm/pacadeploy/helm/paca/tests/render-oidc.shScope and constraints
USER; no email or username account linking