feat(oidc): backend-mediated OIDC login + session cookies + cli config

Adds the OpenID Connect login flow Dialectic.Frontend will drive. Pattern
mirrors Fabric.Backend.Center: SPA → /api/auth/oidc/start → IdP →
/api/auth/oidc/callback → 302 to SPA with one-time ticket in URL fragment
→ SPA POST /api/auth/oidc/exchange → HttpOnly session cookie set.

What's added:

  - internal/oidc/service.go — runtime OIDC service:
    * BuildAuthorizeURL (PKCE S256 + random state, 10min ttl)
    * HandleCallback (token exchange + ID token verify + ticket mint, 60s ttl)
    * ExchangeTicket (ticket → session JWT, HS256 24h)
    * VerifySession (cookie validation)
    * GetConfig/SetConfig with sync.Map-backed state/ticket stores
    * SweepExpired (call from background goroutine; clears stale entries)
  - internal/db/migrations/004_oidc_config.sql — single-row oidc_config
    table (issuer/client_id/client_secret/redirect_uri/post_login_redirect/
    scopes/enabled). Runtime-mutable via dialectic-cli.
  - internal/httpapi/handlers/auth.go — 5 endpoints:
    GET  /api/auth/oidc/status   — { enabled }
    GET  /api/auth/oidc/start    — 302 to IdP
    GET  /api/auth/oidc/callback — IdP returns; we 302 to SPA with ticket
    POST /api/auth/oidc/exchange — ticket → cookie + user
    GET  /api/auth/me            — current session user (401 if anon)
    POST /api/auth/logout        — clears cookie
  - internal/auth: replaces the OIDCBrowser Phase-2C stub with one that
    reads the session cookie via SessionVerifier; keeps dev-bypass
    behind cfg.OIDCOnly gate (set OIDC_ONLY=true in prod to disable
    dev-bypass entirely)
  - cmd/dialectic-cli/main.go — new binary; subcommand
    'config oidc [--issuer ... --client-id ... --client-secret ...
                  --callback-url ... --enabled true|false]'
    Runs against same DB the backend uses; reachable via
    'docker exec dialectic-backend dialectic-cli config oidc ...'
  - Dockerfile: build both binaries; put on PATH for docker exec

Config:

  - SESSION_SIGNING_KEY env: required in prod, ephemeral random in dev.
    HS256 secret for session JWTs. Stable across restarts (rotation
    invalidates every session — kill switch).
  - OIDC_ONLY env: 'true' disables the dev-bypass path entirely; use
    in prod once OIDC is configured.
  - OIDC_ISSUER + OIDC_CLIENT_ID env are no longer required at boot —
    they're advisory bootstrap values for the oidc_config DB row.

Deps:
  - github.com/coreos/go-oidc/v3 (discovery + JWKS verify)
  - golang.org/x/oauth2 (token exchange + PKCE)
  - github.com/golang-jwt/jwt/v5 (session JWT)
  - Bumped go.mod toolchain to 1.25.

Pairs with Dialectic.Frontend (next commit) which removes the
/agents/:id admin page and adds the login button + /oidc/callback
SPA route + AuthProvider that talks to these new endpoints.
This commit is contained in:
h z
2026-05-24 01:40:36 +01:00
parent 0b16b52ee7
commit 2463129dbd
11 changed files with 949 additions and 33 deletions

View File

@@ -2,6 +2,7 @@ package httpapi
import (
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
@@ -12,13 +13,28 @@ import (
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/auth"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/config"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/httpapi/handlers"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/oidc"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/store"
)
// sessionVerifierAdapter wires internal/oidc.Service into auth's
// SessionVerifier interface (which uses auth.SessionClaims to stay
// import-cycle-free).
type sessionVerifierAdapter struct{ s *oidc.Service }
func (a sessionVerifierAdapter) VerifySession(raw string) (*auth.SessionClaims, error) {
c, err := a.s.VerifySession(raw)
if err != nil {
return nil, err
}
return &auth.SessionClaims{Sub: c.Sub, Email: c.Email, Name: c.Name}, nil
}
// Mount returns the root router with all v2 endpoints wired. Owners of
// individual middleware chains:
//
// - /api/healthz : public (no auth)
// - /api/auth/* : OIDC login flow + session
// - /api/topics : mixed — list/get optional auth (anon
// sees public only); create requires CallerAgent or CallerUser
// - /api/topics/{id}/signups : agent-only (CallerAgent)
@@ -27,7 +43,7 @@ import (
// same route by being "optional auth" — if either succeeds, Caller is
// attached; otherwise the handler sees anonymous and decides whether
// to 401 or fall through to public behavior.
func Mount(cfg *config.Config, db *sqlx.DB, version string) http.Handler {
func Mount(cfg *config.Config, db *sqlx.DB, oidcSvc *oidc.Service, version string) http.Handler {
r := chi.NewRouter()
// Boilerplate middleware — these run on every request.
@@ -45,10 +61,12 @@ func Mount(cfg *config.Config, db *sqlx.DB, version string) http.Handler {
MaxAge: 300,
}))
verifier := sessionVerifierAdapter{s: oidcSvc}
// Auth middlewares — composed as "try agent, then user, else pass anonymous".
optionalAuth := optionalAuthChain(db, cfg)
optionalAuth := optionalAuthChain(db, cfg, verifier)
requireAgent := auth.AgentAPIKey(db, cfg.AgentAPIKeyPepper) // strict bearer
requireAnyAuth := requireAnyAuthChain(db, cfg)
requireAnyAuth := requireAnyAuthChain(db, cfg, verifier)
// Handler instances.
topicStore := store.NewTopicStore(db)
@@ -64,11 +82,32 @@ func Mount(cfg *config.Config, db *sqlx.DB, version string) http.Handler {
argsH := handlers.NewArgumentsHandler(topicStore, campStore, roundStore, argStore)
verdictH := handlers.NewVerdictHandler(topicStore, campStore, verdictStore)
adminH := handlers.NewAdminHandler(db, cfg.AgentAPIKeyPepper, cfg.DialecticAdminAPIKey)
// Cookie Secure: in prod nginx terminates TLS upstream, so requests
// hit the backend over plain HTTP. Setting Secure=true on the
// cookie would prevent the browser from sending it back. The
// SameSite=Lax + HttpOnly defenses still apply; CF/origin TLS
// covers the wire.
authH := handlers.NewAuthHandler(oidcSvc, "dialectic_session", false)
// Routes.
r.Route("/api", func(r chi.Router) {
r.Get("/healthz", health.Healthz)
// OIDC login flow + session — public endpoints (no auth
// middleware; they ARE the auth surface).
r.Get("/auth/oidc/status", authH.Status)
r.Get("/auth/oidc/start", authH.Start)
r.Get("/auth/oidc/callback", authH.Callback)
r.Post("/auth/oidc/exchange", authH.Exchange)
// /auth/me + /auth/logout need an authenticated session to be
// meaningful, but /auth/me returns 401 cleanly so SPA can call
// it on mount as a "who am i" probe.
r.Group(func(r chi.Router) {
r.Use(optionalAuth)
r.Get("/auth/me", authH.Me)
r.Post("/auth/logout", authH.Logout)
})
// Topics: list+get optional-auth (visibility-gated by handler);
// create+visibility-flip require any auth.
r.Group(func(r chi.Router) {
@@ -111,9 +150,9 @@ func Mount(cfg *config.Config, db *sqlx.DB, version string) http.Handler {
// optionalAuthChain: if either auth method succeeds, attach Caller;
// otherwise let the request through anonymous. Handlers decide what
// to do with anonymous (typically: serve public subset, hide private).
func optionalAuthChain(db *sqlx.DB, cfg *config.Config) func(http.Handler) http.Handler {
func optionalAuthChain(db *sqlx.DB, cfg *config.Config, verifier auth.SessionVerifier) func(http.Handler) http.Handler {
agent := auth.AgentAPIKey(db, cfg.AgentAPIKeyPepper)
oidc := auth.OIDCBrowser(cfg.IsDev(), cfg.OIDCDevBypassToken)
oidcMw := auth.OIDCBrowser(verifier, cfg.IsDev(), cfg.OIDCDevBypassToken, cfg.OIDCOnly)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Bearer present → try agent path; on success it ServeHTTPs next.
@@ -127,12 +166,13 @@ func optionalAuthChain(db *sqlx.DB, cfg *config.Config) func(http.Handler) http.
if rw.status != http.StatusUnauthorized {
return
}
// reset captured state and try anon path (since OIDC
// won't apply if there's no cookie / bypass header)
}
if r.Header.Get("x-dev-bypass") != "" {
// Try OIDC (session cookie) — always (no header gate needed,
// cookie presence is implicit) so an authenticated browser
// always gets its identity attached.
if hasSession(r) || r.Header.Get("x-dev-bypass") != "" {
rw := &captureWriter{ResponseWriter: w}
oidc(next).ServeHTTP(rw, r)
oidcMw(next).ServeHTTP(rw, r)
if rw.status != http.StatusUnauthorized {
return
}
@@ -144,9 +184,9 @@ func optionalAuthChain(db *sqlx.DB, cfg *config.Config) func(http.Handler) http.
}
// requireAnyAuthChain: 401 if neither agent nor user auth succeeds.
func requireAnyAuthChain(db *sqlx.DB, cfg *config.Config) func(http.Handler) http.Handler {
func requireAnyAuthChain(db *sqlx.DB, cfg *config.Config, verifier auth.SessionVerifier) func(http.Handler) http.Handler {
agent := auth.AgentAPIKey(db, cfg.AgentAPIKeyPepper)
oidc := auth.OIDCBrowser(cfg.IsDev(), cfg.OIDCDevBypassToken)
oidcMw := auth.OIDCBrowser(verifier, cfg.IsDev(), cfg.OIDCDevBypassToken, cfg.OIDCOnly)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("authorization") != "" {
@@ -156,11 +196,16 @@ func requireAnyAuthChain(db *sqlx.DB, cfg *config.Config) func(http.Handler) htt
return
}
}
oidc(next).ServeHTTP(w, r)
oidcMw(next).ServeHTTP(w, r)
})
}
}
func hasSession(r *http.Request) bool {
c, err := r.Cookie("dialectic_session")
return err == nil && c != nil && strings.TrimSpace(c.Value) != ""
}
// captureWriter records the status so the optional-auth chain can
// distinguish "401 from inner middleware (try next)" from "actual
// response from handler (deliver)". Body bytes are passed through