Files
hzhang 2463129dbd 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.
2026-05-24 01:40:36 +01:00

177 lines
5.6 KiB
Go

// Package auth holds the two middlewares Dialectic v2 uses:
//
// - AgentAPIKey: validates `Authorization: Bearer <raw>` against
// the `agent_keys` table (hashed with the configured pepper).
// Used by Dialectic.OpenclawPlugin → backend calls.
//
// - OIDCBrowser: validates a Keycloak-issued JWT in the
// `dialectic_session` cookie. Used by the React frontend.
// Phase 2C ships a stub that accepts a dev-mode bypass token; the
// real JWKS verification + claim mapping lands with Phase 4.
//
// Both middlewares attach a typed Caller to the request context so
// downstream handlers can read identity uniformly.
package auth
import (
"context"
"crypto/sha256"
"crypto/subtle"
"database/sql"
"encoding/hex"
"errors"
"net/http"
"strings"
"github.com/jmoiron/sqlx"
)
type CallerKind string
const (
CallerAgent CallerKind = "agent"
CallerUser CallerKind = "user"
CallerSystem CallerKind = "system"
)
type Caller struct {
Kind CallerKind
ID string // agentId for CallerAgent; userId for CallerUser; key-name for CallerSystem
Email string // CallerUser only; populated from OIDC id_token claim
Name string // CallerUser only; display name from OIDC
Roles []string // populated for CallerUser (from JWT claims); empty otherwise
}
type ctxKey struct{}
func WithCaller(ctx context.Context, c Caller) context.Context {
return context.WithValue(ctx, ctxKey{}, c)
}
// FromContext returns the caller attached by an auth middleware. The
// zero Caller (Kind == "") indicates an unauthenticated request reached
// a public route.
func FromContext(ctx context.Context) Caller {
c, _ := ctx.Value(ctxKey{}).(Caller)
return c
}
// HashKey peppers + sha256-hashes a raw API key. Constant pepper; same
// raw key always produces the same hash so lookups can equal-match on
// the key_hash column.
func HashKey(pepper, raw string) string {
h := sha256.Sum256([]byte(pepper + ":" + raw))
return hex.EncodeToString(h[:])
}
// AgentAPIKey middleware: extracts Bearer token, looks up agent_keys,
// 401 on miss. Updates last_used_at lazily (best-effort; failure here
// doesn't block the request).
func AgentAPIKey(db *sqlx.DB, pepper string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw := bearerToken(r)
if raw == "" {
http.Error(w, "missing bearer token", http.StatusUnauthorized)
return
}
hash := HashKey(pepper, raw)
var agentID string
err := db.GetContext(r.Context(), &agentID,
`SELECT agent_id FROM agent_keys WHERE key_hash = ? AND revoked_at IS NULL`, hash)
if errors.Is(err, sql.ErrNoRows) {
http.Error(w, "invalid agent key", http.StatusUnauthorized)
return
}
if err != nil {
http.Error(w, "auth lookup failed", http.StatusInternalServerError)
return
}
go func(h string) {
// best-effort touch — independent ctx so it survives
// even if the request was cancelled mid-handler.
_, _ = db.Exec(
`UPDATE agent_keys SET last_used_at = CURRENT_TIMESTAMP WHERE key_hash = ?`, h)
}(hash)
ctx := WithCaller(r.Context(), Caller{Kind: CallerAgent, ID: agentID})
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// SessionVerifier is the contract OIDCBrowser uses to validate a
// session JWT (kept as an interface so this package doesn't depend on
// internal/oidc — internal/oidc.Service satisfies it).
type SessionVerifier interface {
VerifySession(raw string) (*SessionClaims, error)
}
// SessionClaims is the projection of OIDC user claims we care about.
// Mirrors internal/oidc.UserClaims (avoid cycle via this duplicate +
// adapter in routes.go).
type SessionClaims struct {
Sub string
Email string
Name string
}
// OIDCBrowser middleware (v0.3.0): looks for our session cookie set
// by /api/auth/oidc/exchange; falls back to x-dev-bypass in dev mode
// when OIDC isn't configured yet. Cookie name is fixed to
// "dialectic_session" — keep in sync with handlers/auth.go.
func OIDCBrowser(verifier SessionVerifier, devMode bool, devBypassToken string, oidcOnly bool) func(http.Handler) http.Handler {
const cookieName = "dialectic_session"
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 1. Cookie session (production path).
if c, err := r.Cookie(cookieName); err == nil && c.Value != "" && verifier != nil {
if claims, err := verifier.VerifySession(c.Value); err == nil {
ctx := WithCaller(r.Context(), Caller{
Kind: CallerUser,
ID: claims.Sub,
Email: claims.Email,
Name: claims.Name,
})
next.ServeHTTP(w, r.WithContext(ctx))
return
}
}
// 2. Dev bypass — only when OIDC_ONLY isn't enforced.
if !oidcOnly && devMode && devBypassToken != "" {
if subtleEqual(r.Header.Get("x-dev-bypass"), devBypassToken) {
ctx := WithCaller(r.Context(), Caller{
Kind: CallerUser,
ID: "dev-operator",
Email: "dev-operator@localhost",
Name: "dev-operator (bypass)",
Roles: []string{"dialectic-admin"},
})
next.ServeHTTP(w, r.WithContext(ctx))
return
}
}
http.Error(w, "oidc login required", http.StatusUnauthorized)
})
}
}
func bearerToken(r *http.Request) string {
h := r.Header.Get("authorization")
const prefix = "Bearer "
if strings.HasPrefix(h, prefix) {
return strings.TrimSpace(h[len(prefix):])
}
if strings.HasPrefix(h, "bearer ") {
return strings.TrimSpace(h[len("bearer "):])
}
return ""
}
func subtleEqual(a, b string) bool {
if len(a) != len(b) {
return false
}
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}