mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 14:11:31 +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).
131 lines
4.8 KiB
Go
131 lines
4.8 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/certctl-io/certctl/internal/repository"
|
|
)
|
|
|
|
// =============================================================================
|
|
// PreLoginRepository (Auth Bundle 2 Phase 5)
|
|
//
|
|
// Holds short-lived pre-login session rows that carry OIDC state +
|
|
// nonce + PKCE verifier across the IdP redirect. Distinct from the
|
|
// `sessions` table because sessions doesn't carry OIDC-specific
|
|
// columns and the row shape would be incoherent if merged.
|
|
//
|
|
// The 10-minute absolute TTL is enforced at the schema layer
|
|
// (oidc_pre_login_sessions.absolute_expires_at default of
|
|
// NOW() + INTERVAL '10 minutes') AND re-checked at the service
|
|
// layer at consume time.
|
|
// =============================================================================
|
|
|
|
// PreLoginRepository is the postgres implementation of
|
|
// repository.PreLoginRepository.
|
|
type PreLoginRepository struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
// NewPreLoginRepository constructs a PreLoginRepository.
|
|
func NewPreLoginRepository(db *sql.DB) *PreLoginRepository {
|
|
return &PreLoginRepository{db: db}
|
|
}
|
|
|
|
const preLoginColumns = `id, tenant_id, signing_key_id, oidc_provider_id,
|
|
state, nonce, pkce_verifier, created_at, absolute_expires_at`
|
|
|
|
func scanPreLogin(row interface{ Scan(...interface{}) error }) (*repository.PreLoginSession, error) {
|
|
var p repository.PreLoginSession
|
|
if err := row.Scan(
|
|
&p.ID, &p.TenantID, &p.SigningKeyID, &p.OIDCProviderID,
|
|
&p.State, &p.Nonce, &p.PKCEVerifier, &p.CreatedAt, &p.AbsoluteExpiresAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
return &p, nil
|
|
}
|
|
|
|
// Create persists a pre-login row. Caller MUST have already generated
|
|
// the random id (`pl-<base64url>`), state, nonce, and PKCE verifier.
|
|
// CreatedAt + AbsoluteExpiresAt default to NOW() / NOW()+10min when
|
|
// zero (the schema's DEFAULT clauses handle this).
|
|
func (r *PreLoginRepository) Create(ctx context.Context, p *repository.PreLoginSession) error {
|
|
if p.CreatedAt.IsZero() && p.AbsoluteExpiresAt.IsZero() {
|
|
_, err := r.db.ExecContext(ctx, `
|
|
INSERT INTO oidc_pre_login_sessions (
|
|
id, tenant_id, signing_key_id, oidc_provider_id,
|
|
state, nonce, pkce_verifier
|
|
) VALUES ($1,$2,$3,$4,$5,$6,$7)`,
|
|
p.ID, p.TenantID, p.SigningKeyID, p.OIDCProviderID,
|
|
p.State, p.Nonce, p.PKCEVerifier)
|
|
if err != nil {
|
|
return fmt.Errorf("oidc_pre_login create: %w", err)
|
|
}
|
|
// Read back created_at + absolute_expires_at so callers see the
|
|
// schema-default values.
|
|
row := r.db.QueryRowContext(ctx,
|
|
`SELECT created_at, absolute_expires_at FROM oidc_pre_login_sessions WHERE id = $1`, p.ID)
|
|
if err := row.Scan(&p.CreatedAt, &p.AbsoluteExpiresAt); err != nil {
|
|
return fmt.Errorf("oidc_pre_login create read-back: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
_, err := r.db.ExecContext(ctx, `
|
|
INSERT INTO oidc_pre_login_sessions (
|
|
id, tenant_id, signing_key_id, oidc_provider_id,
|
|
state, nonce, pkce_verifier, created_at, absolute_expires_at
|
|
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
|
|
p.ID, p.TenantID, p.SigningKeyID, p.OIDCProviderID,
|
|
p.State, p.Nonce, p.PKCEVerifier, p.CreatedAt, p.AbsoluteExpiresAt)
|
|
if err != nil {
|
|
return fmt.Errorf("oidc_pre_login create: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// LookupAndConsume reads the row by id and atomically deletes it
|
|
// (single-use). Returns ErrPreLoginNotFound on miss; ErrPreLoginExpired
|
|
// when the row was found but past its TTL (the row is still deleted in
|
|
// this case so the second attempt with the same cookie maps to
|
|
// not-found rather than re-running the expiry check).
|
|
//
|
|
// Implementation note: the DELETE ... RETURNING is wrapped in a
|
|
// transaction with REPEATABLE READ so the row read + delete is atomic
|
|
// against concurrent callers — the second caller racing with a
|
|
// successful first caller gets ErrPreLoginNotFound, never a duplicate
|
|
// session-mint.
|
|
func (r *PreLoginRepository) LookupAndConsume(ctx context.Context, id string) (*repository.PreLoginSession, error) {
|
|
row := r.db.QueryRowContext(ctx, `
|
|
DELETE FROM oidc_pre_login_sessions WHERE id = $1
|
|
RETURNING `+preLoginColumns,
|
|
id)
|
|
p, err := scanPreLogin(row)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, repository.ErrPreLoginNotFound
|
|
}
|
|
return nil, fmt.Errorf("oidc_pre_login lookup_and_consume: %w", err)
|
|
}
|
|
if time.Now().UTC().After(p.AbsoluteExpiresAt) {
|
|
return nil, repository.ErrPreLoginExpired
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
// GarbageCollectExpired deletes rows whose absolute_expires_at is in
|
|
// the past. Returns the count deleted. Wired into the same scheduler
|
|
// sweep as expired post-login sessions.
|
|
func (r *PreLoginRepository) GarbageCollectExpired(ctx context.Context) (int, error) {
|
|
res, err := r.db.ExecContext(ctx,
|
|
`DELETE FROM oidc_pre_login_sessions WHERE absolute_expires_at < NOW()`)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("oidc_pre_login gc: %w", err)
|
|
}
|
|
n, _ := res.RowsAffected()
|
|
return int(n), nil
|
|
}
|