mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 12:41: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).
189 lines
5.5 KiB
Go
189 lines
5.5 KiB
Go
package auth
|
|
|
|
// Seed identifiers and constants used by the Phase 1 migration and the
|
|
// service / handler layers. Centralised here so production code, tests,
|
|
// and migration SQL stay in lockstep on the canonical role / permission
|
|
// names.
|
|
|
|
// DefaultTenantID is the seeded tenant created by migration
|
|
// 000029_rbac.up.sql. Bundle 1 ships single-tenant; every actor_role
|
|
// row carries this tenant_id by default.
|
|
const DefaultTenantID = "t-default"
|
|
|
|
// Seeded role IDs. Stable identifiers used by the migration backfill
|
|
// and the demo-mode synthetic-actor seed.
|
|
const (
|
|
RoleIDAdmin = "r-admin"
|
|
RoleIDOperator = "r-operator"
|
|
RoleIDViewer = "r-viewer"
|
|
RoleIDAgent = "r-agent"
|
|
RoleIDMCP = "r-mcp"
|
|
RoleIDCLI = "r-cli"
|
|
RoleIDAuditor = "r-auditor"
|
|
)
|
|
|
|
// DemoAnonActorID is the synthetic actor used when
|
|
// CERTCTL_AUTH_TYPE=none is configured (the demo path). Phase 1
|
|
// migration seeds the actor + admin role assignment unconditionally;
|
|
// Phase 3 of Bundle 1 wires the middleware to inject this actor into
|
|
// the request context when no-auth mode is active. Reserved system
|
|
// actor: the API rejects mutations / deletions targeting this id.
|
|
const DemoAnonActorID = "actor-demo-anon"
|
|
|
|
// CanonicalPermissions is the canonical Bundle 1 permission catalog,
|
|
// seeded by migration 000029_rbac.up.sql. Bundle 2 extends with
|
|
// auth.session.* and auth.oidc.* permissions (those land in Bundle 2
|
|
// Phase 5's migration).
|
|
//
|
|
// Naming convention: <namespace>.<verb>. Read permissions use
|
|
// `<resource>.read`; mutations use `.create`, `.edit`, `.delete`,
|
|
// `.assign`, `.revoke`, `.use`, `.export`, etc. The catalog is the
|
|
// single source of truth referenced by:
|
|
// - migration 000029_rbac.up.sql (seeds the rows)
|
|
// - service layer (RoleService.Create rejects unknown permissions)
|
|
// - handler layer (auth.RequirePermission perm string)
|
|
var CanonicalPermissions = []string{
|
|
// Certificate lifecycle
|
|
"cert.read",
|
|
"cert.issue",
|
|
"cert.revoke",
|
|
"cert.delete",
|
|
|
|
// Profile management
|
|
"profile.read",
|
|
"profile.edit",
|
|
"profile.delete",
|
|
|
|
// Issuer management
|
|
"issuer.read",
|
|
"issuer.edit",
|
|
"issuer.delete",
|
|
|
|
// Target management
|
|
"target.read",
|
|
"target.edit",
|
|
"target.delete",
|
|
|
|
// Agent management
|
|
"agent.read",
|
|
"agent.edit",
|
|
"agent.retire",
|
|
"agent.heartbeat",
|
|
"agent.job.poll",
|
|
"agent.job.complete",
|
|
"agent.job.report",
|
|
|
|
// Audit access (Phase 8 introduces the auditor split)
|
|
"audit.read",
|
|
"audit.export",
|
|
|
|
// RBAC primitive (Phase 4 surfaces these via /v1/auth/roles)
|
|
"auth.role.list",
|
|
"auth.role.create",
|
|
"auth.role.edit",
|
|
"auth.role.delete",
|
|
"auth.role.assign",
|
|
"auth.role.revoke",
|
|
|
|
// API-key management (Phase 4 + Phase 7 scope-down)
|
|
"auth.key.list",
|
|
"auth.key.create",
|
|
"auth.key.rotate",
|
|
"auth.key.delete",
|
|
|
|
// Bootstrap path (Phase 6)
|
|
"auth.bootstrap.use",
|
|
|
|
// Bundle 1 Phase 3.5: admin-only fine-grained perms for the
|
|
// legacy admin handlers, seeded by migration 000030. Wrapped at
|
|
// the router level via auth.RequirePermission middleware; the
|
|
// in-handler auth.IsAdmin checks have been removed in Phase 3.5.
|
|
"cert.bulk_revoke",
|
|
"crl.admin",
|
|
"scep.admin",
|
|
"est.admin",
|
|
"ca.hierarchy.manage",
|
|
|
|
// Bundle 2 Phase 5 — session + OIDC management permissions
|
|
// seeded by migration 000037. auth.session.list / .revoke gate
|
|
// "list/revoke any session in tenant" (own-session paths bypass
|
|
// the gate via "is path.actor_id == ctx.actor_id?" check at the
|
|
// handler layer); auth.session.list.all gates the all-actors
|
|
// admin view. auth.oidc.{list,create,edit,delete} gates the
|
|
// OIDC-provider-config + group-mapping CRUD endpoints.
|
|
"auth.session.list",
|
|
"auth.session.list.all",
|
|
"auth.session.revoke",
|
|
"auth.oidc.list",
|
|
"auth.oidc.create",
|
|
"auth.oidc.edit",
|
|
"auth.oidc.delete",
|
|
}
|
|
|
|
// DefaultRoles describes the seven default roles seeded by the
|
|
// migration, mapped to the permissions each role holds at global
|
|
// scope. Permissions not in CanonicalPermissions cause the migration
|
|
// to fail-closed.
|
|
var DefaultRoles = map[string][]string{
|
|
RoleIDAdmin: CanonicalPermissions, // admin gets every permission
|
|
|
|
RoleIDOperator: {
|
|
"cert.read", "cert.issue", "cert.revoke", "cert.delete",
|
|
"profile.read", "profile.edit",
|
|
"issuer.read", "issuer.edit",
|
|
"target.read", "target.edit", "target.delete",
|
|
"agent.read", "agent.edit",
|
|
"audit.read",
|
|
},
|
|
|
|
RoleIDViewer: {
|
|
"cert.read",
|
|
"profile.read",
|
|
"issuer.read",
|
|
"target.read",
|
|
"agent.read",
|
|
"audit.read",
|
|
},
|
|
|
|
RoleIDAgent: {
|
|
"cert.read",
|
|
"agent.heartbeat",
|
|
"agent.job.poll",
|
|
"agent.job.complete",
|
|
"agent.job.report",
|
|
},
|
|
|
|
RoleIDMCP: {
|
|
// MCP gets operator-equivalent minus destructive ops.
|
|
// Defense in depth for Claude / IDE integrations where
|
|
// destructive verbs warrant additional scrutiny.
|
|
"cert.read", "cert.issue", "cert.revoke",
|
|
"profile.read", "profile.edit",
|
|
"issuer.read", "issuer.edit",
|
|
"target.read", "target.edit",
|
|
"agent.read",
|
|
"audit.read",
|
|
},
|
|
|
|
RoleIDCLI: {
|
|
// CLI = operator-equivalent. Operators can scope down via
|
|
// `certctl auth keys scope-down` if they want narrower CLI
|
|
// access in production.
|
|
"cert.read", "cert.issue", "cert.revoke", "cert.delete",
|
|
"profile.read", "profile.edit",
|
|
"issuer.read", "issuer.edit",
|
|
"target.read", "target.edit", "target.delete",
|
|
"agent.read", "agent.edit",
|
|
"audit.read",
|
|
"auth.key.list", "auth.key.create", "auth.key.rotate",
|
|
},
|
|
|
|
RoleIDAuditor: {
|
|
// Phase 8 ships the auditor split. Phase 1 reserves the
|
|
// role id + the read-only permission set so subsequent
|
|
// phases don't have to renumber.
|
|
"audit.read",
|
|
"audit.export",
|
|
},
|
|
}
|