mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 11:11:30 +00:00
9c679a5960
pre-login store, OpenID Connect Back-Channel Logout 1.0, cookieAuth
scheme, 7 new auth permissions, CI guard, handler tests
Phase 5 of the bundle puts the Phase 3 OIDC service + Phase 4 session
service on the wire. 13 HTTP endpoints split into three logical groups:
Public OIDC handshake (auth-exempt; protocol-mediated):
GET /auth/oidc/login?provider=<id> -> 302 to IdP authorization URL
+ sets certctl_oidc_pending cookie
(10-min TTL, Path=/auth/oidc/,
SameSite=Lax)
GET /auth/oidc/callback?code=...&state=... -> consume pre-login row,
run Phase 3's 11-step token
validation, mint post-login
session, 302 to dashboard
POST /auth/oidc/back-channel-logout -> OpenID Connect BCL 1.0 — IdP
POSTs logout_token JWT; certctl
validates signature against IdP
JWKS via Phase 3 alg allow-list,
required claims (iss/aud/iat/jti/
events; exactly one of sub/sid;
nonce ABSENT per spec §2.4),
revokes matching sessions,
returns 200 with
Cache-Control: no-store
POST /auth/logout -> revoke caller's session
Session management (RBAC-gated auth.session.*):
GET /api/v1/auth/sessions -> auth.session.list (own / all)
DELETE /api/v1/auth/sessions/{id} -> auth.session.revoke (own bypass)
OIDC provider + group-mapping CRUD (RBAC-gated auth.oidc.*):
GET /api/v1/auth/oidc/providers -> auth.oidc.list
POST /api/v1/auth/oidc/providers -> auth.oidc.create
(client_secret encrypted
at rest via
internal/crypto.EncryptIfKeySet)
PUT /api/v1/auth/oidc/providers/{id} -> auth.oidc.edit
DELETE /api/v1/auth/oidc/providers/{id} -> auth.oidc.delete
(refused via
ErrOIDCProviderInUse → 409
when users authenticated
via this provider)
POST /api/v1/auth/oidc/providers/{id}/refresh -> auth.oidc.edit
(re-runs IdP downgrade
defense via
OIDCService.RefreshKeys)
GET /api/v1/auth/oidc/group-mappings -> auth.oidc.list
POST /api/v1/auth/oidc/group-mappings -> auth.oidc.edit
DELETE /api/v1/auth/oidc/group-mappings/{id} -> auth.oidc.edit
Migration 000037 ships:
- oidc_pre_login_sessions table (10-min absolute TTL, FK CASCADE on
oidc_provider_id, FK RESTRICT on signing_key_id; index on
absolute_expires_at for the GC sweep);
- 7 new permissions seeded into r-admin only:
auth.session.list, auth.session.list.all, auth.session.revoke,
auth.oidc.list, auth.oidc.create, auth.oidc.edit, auth.oidc.delete
CanonicalPermissions extended in lockstep at internal/domain/auth/
validate.go.
Pre-login machinery:
- internal/repository/oidc.go gains PreLoginRepository interface +
PreLoginSession struct + ErrPreLoginNotFound / ErrPreLoginExpired
sentinels.
- internal/repository/postgres/oidc_prelogin.go ships the impl;
LookupAndConsume uses DELETE ... RETURNING for atomic single-use.
- internal/auth/oidc/prelogin.go is the PreLoginAdapter that bridges
the OIDC service's Phase 3 PreLoginStore interface to the new
repository, signing the cookie value under the active
SessionSigningKey via the same v1.<id>.<key>.<HMAC> wire format
Phase 4 uses for post-login cookies. Defense-in-depth: the
pre-login `pl-` prefix is enforced by ParseCookieValue(prefix);
a stolen pre-login cookie cannot be replayed against the
post-login Validate path (pinned by
TestService_Validate_RejectsPreLoginCookieAtPostLoginGate).
Session package extension:
- internal/auth/session/service.go gains exported SignCookieValue,
ParseCookieValue (with caller-supplied id-1 prefix), ComputeCookieHMAC,
DecryptKeyMaterial wrappers so the OIDC pre-login adapter shares
the same length-prefixed HMAC math without code duplication.
- parseCookie no longer hardcodes the `ses-` prefix check (moved to
Validate as defense-in-depth; pre-login cookie verification uses
the `pl-` prefix via ParseCookieValue).
Cookie attributes (all Phase 5 endpoints honor CERTCTL_SESSION_SAMESITE
+ Secure=true via SessionCookieAttrs from Phase 4 config):
- certctl_oidc_pending: Path=/auth/oidc/, MaxAge=600s, SameSite=Lax
(cannot be Strict because the IdP-initiated callback is a top-level
navigation from a different origin).
- certctl_session: Path=/, Expires=8h, SameSite=Lax|Strict, HttpOnly.
- certctl_csrf: Path=/, Expires=8h, HttpOnly=false (intentional —
GUI must read it to echo into X-CSRF-Token header).
Audit logging on every mutating operation (event_category="auth"):
auth.oidc_login_succeeded / failed / unmapped_groups
auth.oidc_back_channel_logout / failed
auth.session_revoked
auth.oidc_provider_{created,updated,deleted,refreshed}
auth.group_mapping_{added,removed}
OpenAPI updates:
- cookieAuth security scheme added to api/openapi.yaml under
components.securitySchemes (apiKey / cookie / certctl_session).
- The 13 Phase 5 routes are added to SpecParityExceptions with a
deferral note: full per-endpoint OpenAPI rows land in a follow-on
commit alongside the GUI work (Phase 8) so the ergonomic shape can
be validated against the live GUI client.
CI guard: scripts/ci-guards/N-bundle-2-security-empty-preserved.sh
asserts api/openapi.yaml has ≥ 14 'security: []' occurrences (the
pre-Bundle-2 baseline). Reducing the count below 14 would silently
force a Bearer-or-cookie requirement onto an endpoint that legitimately
runs without certctl-issued credentials; the guard fires before that
regression lands.
Handler tests (internal/api/handler/auth_session_oidc_test.go):
- All 6 prompt-mandated negative cases:
BCL with missing events claim -> 400
BCL with nonce present -> 400 (per spec §2.4)
BCL with sig signed by an unknown key -> 400
Callback with replayed state -> 400
Callback with PKCE verifier mismatch -> 400
Callback with expired pre-login row -> 400
- Plus happy paths for every endpoint, edge cases (missing-cookie,
duplicate-name, in-use-409, wrong-tenant), and the Helper-function
coverage (peekIssuer, classifyOIDCFailure, defaultIfBlank,
defaultIntIfZero, clientIPFromRequest, encryptClientSecret).
Coverage on internal/api/handler/auth_session_oidc.go: 80.9% per-function
(above the Phase 5 spec's ≥ 80% floor).
Server wiring (cmd/server/main.go):
Wired AFTER sessionService (Phase 4) so the OIDC PreLoginAdapter can
sign pre-login cookies under the active SessionSigningKey:
oidcProviderRepo + oidcMappingRepo + oidcUserRepo + oidcPreLoginRepo
-> preLoginAdapter -> oidcService -> authSessionOIDCHandler.
sessionMinterAdapter shim bridges *session.Service.Create to the
oidcsvc.SessionMinter port the OIDC service consumes.
Router wiring (internal/api/router/router.go):
4 public OIDC routes via direct r.mux.Handle (auth-exempt; pinned in
AuthExemptRouterRoutes); 9 RBAC-gated routes via r.Register +
rbacGate(checker, perm, h). Routes only register when
reg.AuthSessionOIDC != nil so pre-Phase-5 builds skip the block
entirely.
Verifications: gofmt clean, go vet clean across all touched packages,
go test -short -count=1 green across internal/api/handler (74 tests +
new Phase 5 batch), internal/api/router (parity + auth-exempt
allowlist), internal/auth/oidc + session (no regressions), full domain
+ scheduler + config sweeps green, ci-guard
N-bundle-2-security-empty-preserved.sh green (17 ≥ 14 baseline).
130 lines
6.1 KiB
PL/PgSQL
130 lines
6.1 KiB
PL/PgSQL
-- 000037_oidc_phase5.up.sql
|
|
-- Auth Bundle 2 / Phase 5: HTTP handler surface.
|
|
--
|
|
-- Two things land here:
|
|
--
|
|
-- 1. oidc_pre_login_sessions table — short-lived rows holding the
|
|
-- OIDC state + nonce + PKCE verifier across the IdP redirect.
|
|
-- Distinct from the sessions table because the schema for sessions
|
|
-- doesn't carry OIDC-specific columns and bolting them on would
|
|
-- bloat every row. 10-minute absolute TTL; GC sweep deletes
|
|
-- expired rows alongside the post-login session GC sweep.
|
|
--
|
|
-- Cookie name `certctl_oidc_pending` (Path=/auth/oidc/) carries the
|
|
-- same v1.<id>.<signing_key_id>.<HMAC-SHA256> wire format as the
|
|
-- post-login cookie. The signing key is the active SessionSigningKey
|
|
-- so we don't need a separate key lifecycle for pre-login cookies.
|
|
--
|
|
-- 2. Seven new permissions extending the canonical catalogue:
|
|
-- auth.session.list — list one's own sessions
|
|
-- auth.session.list.all — list every session in the tenant (admin)
|
|
-- auth.session.revoke — revoke a session that isn't yours
|
|
-- auth.oidc.list — list OIDC providers + group mappings
|
|
-- auth.oidc.create — register a new OIDC provider
|
|
-- auth.oidc.edit — update OIDC provider config / mappings
|
|
-- auth.oidc.delete — delete OIDC provider (only when no
|
|
-- users have authenticated via it)
|
|
-- Granted to r-admin only by default. Operators who want session
|
|
-- revocation across actors granted to r-operator can add the row
|
|
-- via the role-permission API after migration.
|
|
--
|
|
-- All operations idempotent. Wrapped in a single transaction.
|
|
|
|
BEGIN;
|
|
|
|
-- =============================================================================
|
|
-- oidc_pre_login_sessions table
|
|
-- =============================================================================
|
|
|
|
CREATE TABLE IF NOT EXISTS oidc_pre_login_sessions (
|
|
-- id is the prefix-`pl-` opaque identifier signed into the cookie.
|
|
-- Format on the wire: v1.pl-<base64url>.sk-<base64url>.<base64url HMAC>.
|
|
id TEXT PRIMARY KEY,
|
|
|
|
tenant_id TEXT NOT NULL DEFAULT 't-default'
|
|
REFERENCES tenants(id) ON DELETE CASCADE,
|
|
|
|
-- The signing key id pinning which SessionSigningKey row signed
|
|
-- the cookie. Validation re-derives the HMAC against this key.
|
|
signing_key_id TEXT NOT NULL
|
|
REFERENCES session_signing_keys(id) ON DELETE RESTRICT,
|
|
|
|
-- The OIDC provider being authenticated against. References
|
|
-- oidc_providers(id) with ON DELETE CASCADE so deleting a provider
|
|
-- mid-handshake invalidates in-flight pre-login rows. (Provider
|
|
-- deletion is itself gated on no users having authenticated via
|
|
-- the provider; this is the second-line defense.)
|
|
oidc_provider_id TEXT NOT NULL
|
|
REFERENCES oidc_providers(id) ON DELETE CASCADE,
|
|
|
|
-- OIDC state: 32 random bytes base64url-no-pad. Constant-time
|
|
-- compared at callback against the IdP-returned state param.
|
|
state TEXT NOT NULL,
|
|
|
|
-- OIDC nonce: 32 random bytes base64url-no-pad. Constant-time
|
|
-- compared at callback against the ID token's nonce claim.
|
|
nonce TEXT NOT NULL,
|
|
|
|
-- PKCE-S256 verifier: 43-128 chars base64url-no-pad. Sent to the
|
|
-- IdP token endpoint to prove possession of the original challenge.
|
|
pkce_verifier TEXT NOT NULL,
|
|
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
-- Phase 5 spec: 10-minute absolute TTL. The GC sweep treats this
|
|
-- as the cutoff (rows older than 10 minutes are deleted).
|
|
absolute_expires_at TIMESTAMPTZ NOT NULL DEFAULT (NOW() + INTERVAL '10 minutes'),
|
|
|
|
CONSTRAINT oidc_pre_login_expiry_after_created
|
|
CHECK (absolute_expires_at > created_at)
|
|
);
|
|
|
|
-- Index for the GC sweep — `WHERE absolute_expires_at < NOW()` hot path.
|
|
CREATE INDEX IF NOT EXISTS idx_oidc_pre_login_expires
|
|
ON oidc_pre_login_sessions (absolute_expires_at);
|
|
|
|
-- Index for the lookup-by-provider hot path (admin "active pending logins"
|
|
-- surface, optional Phase 8 GUI extension).
|
|
CREATE INDEX IF NOT EXISTS idx_oidc_pre_login_provider
|
|
ON oidc_pre_login_sessions (oidc_provider_id);
|
|
|
|
-- =============================================================================
|
|
-- Seven new permissions extending the Bundle 1 catalogue.
|
|
-- =============================================================================
|
|
|
|
INSERT INTO permissions (id, name, namespace) VALUES
|
|
('p-auth-session-list', 'auth.session.list', 'auth.session'),
|
|
('p-auth-session-list-all', 'auth.session.list.all', 'auth.session'),
|
|
('p-auth-session-revoke', 'auth.session.revoke', 'auth.session'),
|
|
('p-auth-oidc-list', 'auth.oidc.list', 'auth.oidc'),
|
|
('p-auth-oidc-create', 'auth.oidc.create', 'auth.oidc'),
|
|
('p-auth-oidc-edit', 'auth.oidc.edit', 'auth.oidc'),
|
|
('p-auth-oidc-delete', 'auth.oidc.delete', 'auth.oidc')
|
|
ON CONFLICT (id) DO NOTHING;
|
|
|
|
-- Grant all seven to r-admin (and only r-admin by default). The
|
|
-- role-permission API can hand auth.session.revoke to r-operator
|
|
-- post-deploy if the operator wants their support staff to revoke
|
|
-- sessions; we ship locked-down by default.
|
|
INSERT INTO role_permissions (role_id, permission_id, scope_type, scope_id)
|
|
SELECT 'r-admin', id, 'global', NULL
|
|
FROM permissions
|
|
WHERE id IN (
|
|
'p-auth-session-list',
|
|
'p-auth-session-list-all',
|
|
'p-auth-session-revoke',
|
|
'p-auth-oidc-list',
|
|
'p-auth-oidc-create',
|
|
'p-auth-oidc-edit',
|
|
'p-auth-oidc-delete'
|
|
)
|
|
ON CONFLICT (role_id, permission_id, scope_type, scope_id) DO NOTHING;
|
|
|
|
-- Every actor who has been federated-authenticated needs to list AND
|
|
-- revoke their OWN session. That gate is encoded at the handler layer
|
|
-- via "is the actor_id in the path the caller's actor_id?" rather
|
|
-- than via a permission, since granting `auth.session.list` to
|
|
-- everyone would be tantamount to making it a no-op. The handler
|
|
-- pattern: `if path.id == ctx.actor_id { allow } else { require(auth.session.revoke) }`.
|
|
|
|
COMMIT;
|