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

@@ -37,6 +37,8 @@ const (
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
}
@@ -98,28 +100,58 @@ func AgentAPIKey(db *sqlx.DB, pepper string) func(http.Handler) http.Handler {
}
}
// OIDCBrowser middleware (Phase 2C stub):
// - Dev mode + `x-dev-bypass: <token>` header → admit as a fake user.
// - Otherwise: 401 with a hint pointing to the (not-yet-wired)
// Keycloak redirect path. The real JWKS-verifying middleware lands
// when the frontend is wired up; until then, browser callers can
// only reach the API via the dev bypass.
func OIDCBrowser(devMode bool, devBypassToken string) func(http.Handler) http.Handler {
// 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) {
if devMode && devBypassToken != "" {
// 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
}
}
// Production path goes through Keycloak — Phase 4.
http.Error(w, "oidc login required (Phase 4: not yet wired)", http.StatusUnauthorized)
http.Error(w, "oidc login required", http.StatusUnauthorized)
})
}
}

View File

@@ -63,9 +63,26 @@ type Config struct {
// https://auth.hangman-lab.top/realms/hangman-lab
// Phase 2C ships this as configured-but-not-verified; Phase 4 wires
// real JWKS validation.
// OIDC env-bootstrap values — used to seed the oidc_config DB row
// at first boot if it's empty. Runtime mutation goes through the
// dialectic-cli `config oidc ...` subcommand → updates the DB row.
// Env-only mode is fine for greenfield deploys; once the DB row is
// populated and enabled, env values become advisory.
OIDCIssuer string
OIDCClientID string
// OIDC_ONLY: when "true", disables the dev-bypass auth path on
// every browser-facing route. Use this in prod once the OIDC
// realm + client are configured so a leaked dev token can't
// authenticate anyone. Defaults false (dev/sim convenience).
OIDCOnly bool
// SessionSigningKey: HS256 secret for the session JWT we mint on
// /api/auth/oidc/exchange. MUST be stable across restarts (rotating
// invalidates every logged-in user — that's the desired side
// effect for emergency revocation). Random hex, ≥ 32 bytes.
SessionSigningKey string
// (Removed Aug 2026: all Fabric coupling — FabricSystemAPIKey,
// FabricGuildBaseURL, FabricAnnounceChannelID, FabricBotBearerToken.
// Backend no longer broadcasts lifecycle events to Fabric. The
@@ -95,6 +112,8 @@ func LoadFromEnv() (*Config, error) {
DialecticAdminAPIKey: os.Getenv("DIALECTIC_ADMIN_API_KEY"),
OIDCIssuer: os.Getenv("OIDC_ISSUER"),
OIDCClientID: os.Getenv("OIDC_CLIENT_ID"),
OIDCOnly: os.Getenv("OIDC_ONLY") == "true",
SessionSigningKey: os.Getenv("SESSION_SIGNING_KEY"),
}
if d := os.Getenv("ORCHESTRATOR_TICK_INTERVAL"); d != "" {
if parsed, err := time.ParseDuration(d); err == nil {
@@ -114,12 +133,14 @@ func LoadFromEnv() (*Config, error) {
if c.AgentAPIKeyPepper == "" {
missing = append(missing, "AGENT_API_KEY_PEPPER")
}
if c.OIDCIssuer == "" {
missing = append(missing, "OIDC_ISSUER")
}
if c.OIDCClientID == "" {
missing = append(missing, "OIDC_CLIENT_ID")
if c.SessionSigningKey == "" {
missing = append(missing, "SESSION_SIGNING_KEY")
}
// OIDC_ISSUER + OIDC_CLIENT_ID are no longer required env at
// boot — they're optional bootstrap values for the oidc_config
// DB row (mutated via cli). If you start prod without them and
// without configuring via cli, the SPA will see OIDC disabled +
// every browser-facing route stays 401.
if len(missing) > 0 {
return nil, fmt.Errorf("prod mode requires env: %s", strings.Join(missing, ", "))
}

View File

@@ -0,0 +1,23 @@
-- OIDC config: single-row table holding the runtime-mutable
-- OpenID Connect provider settings. Updated via the dialectic-cli
-- `config oidc` subcommand, NOT via env. Env-only config (OIDCIssuer /
-- OIDCClientID in config.go) is kept as fallback for first-boot
-- bootstrap but the DB row wins when present + enabled.
--
-- Mirrors Fabric.Backend.Center's oidc_configs table — same fields,
-- same semantics. One row enforced by id='singleton'.
CREATE TABLE oidc_config (
id VARCHAR(16) NOT NULL PRIMARY KEY DEFAULT 'singleton',
issuer VARCHAR(255) NOT NULL DEFAULT '',
client_id VARCHAR(255) NOT NULL DEFAULT '',
client_secret TEXT NOT NULL,
redirect_uri VARCHAR(255) NOT NULL DEFAULT '',
post_login_redirect VARCHAR(255) NOT NULL DEFAULT '',
scopes VARCHAR(255) NOT NULL DEFAULT 'openid email profile',
enabled TINYINT(1) NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO oidc_config (id, client_secret) VALUES ('singleton', '');

View File

@@ -0,0 +1,145 @@
package handlers
import (
"encoding/json"
"errors"
"net/http"
"net/url"
"strings"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/auth"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/oidc"
)
// AuthHandler implements OIDC login + session endpoints. Mirrors
// Fabric.Backend.Center's OidcController surface:
//
// GET /api/auth/oidc/status — { enabled }; SPA polls before showing Login
// GET /api/auth/oidc/start — 302 to IdP authorize URL
// GET /api/auth/oidc/callback — IdP redirects here; we 302 to SPA with #oidc_ticket
// POST /api/auth/oidc/exchange — SPA trades ticket for session cookie + user
// GET /api/auth/me — current session user (401 if anon)
// POST /api/auth/logout — clears the session cookie
type AuthHandler struct {
oidc *oidc.Service
cookieName string
secure bool
}
func NewAuthHandler(svc *oidc.Service, cookieName string, secure bool) *AuthHandler {
if cookieName == "" {
cookieName = "dialectic_session"
}
return &AuthHandler{oidc: svc, cookieName: cookieName, secure: secure}
}
func (h *AuthHandler) Status(w http.ResponseWriter, r *http.Request) {
enabled, err := h.oidc.IsEnabled(r.Context())
if err != nil {
http.Error(w, "oidc status: "+err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, http.StatusOK, map[string]any{"enabled": enabled})
}
func (h *AuthHandler) Start(w http.ResponseWriter, r *http.Request) {
u, err := h.oidc.BuildAuthorizeURL(r.Context())
if err != nil {
http.Error(w, "oidc start: "+err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, u, http.StatusFound)
}
func (h *AuthHandler) Callback(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")
ticket, redirect, err := h.oidc.HandleCallback(r.Context(), code, state)
if err != nil {
// Bounce to the SPA with an error fragment so the user sees
// something useful instead of a 500 page mid-login.
c, _ := h.oidc.GetConfig(r.Context())
base := "/"
if c != nil && c.PostLoginRedirect != "" {
base = c.PostLoginRedirect
}
sep := "#"
if strings.Contains(base, "#") {
sep = "&"
}
http.Redirect(w, r, base+sep+"oidc_error="+url.QueryEscape(err.Error()), http.StatusFound)
return
}
sep := "#"
if strings.Contains(redirect, "#") {
sep = "&"
}
http.Redirect(w, r, redirect+sep+"oidc_ticket="+url.QueryEscape(ticket), http.StatusFound)
}
type exchangeBody struct {
Ticket string `json:"ticket"`
}
func (h *AuthHandler) Exchange(w http.ResponseWriter, r *http.Request) {
var b exchangeBody
if err := json.NewDecoder(r.Body).Decode(&b); err != nil {
http.Error(w, "bad body", http.StatusBadRequest)
return
}
jwtStr, exp, user, err := h.oidc.ExchangeTicket(b.Ticket)
if err != nil {
http.Error(w, "exchange: "+err.Error(), http.StatusUnauthorized)
return
}
// HTTP-only session cookie. SameSite=Lax so it survives the OIDC
// redirect chain; Secure when behind HTTPS (always in prod).
http.SetCookie(w, &http.Cookie{
Name: h.cookieName,
Value: jwtStr,
Path: "/",
Expires: exp,
HttpOnly: true,
Secure: h.secure,
SameSite: http.SameSiteLaxMode,
})
writeJSON(w, http.StatusOK, map[string]any{
"user": map[string]any{
"id": user.Sub,
"email": user.Email,
"name": user.Name,
},
"expires_at": exp,
})
}
func (h *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
caller := auth.FromContext(r.Context())
if caller.Kind == "" {
http.Error(w, "not authenticated", http.StatusUnauthorized)
return
}
writeJSON(w, http.StatusOK, map[string]any{
"id": caller.ID,
"email": caller.Email,
"name": caller.Name,
})
}
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
// Clear the cookie by setting an expired one with the same name + path.
http.SetCookie(w, &http.Cookie{
Name: h.cookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
Secure: h.secure,
SameSite: http.SameSiteLaxMode,
})
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// silence unused errors import if no upstream calls — keep so future
// handlers can build typed error responses.
var _ = errors.New

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

451
internal/oidc/service.go Normal file
View File

@@ -0,0 +1,451 @@
// Package oidc implements the runtime-configurable OpenID Connect login
// flow for Dialectic. Mirrors Fabric.Backend.Center's pattern:
//
// 1. Browser hits GET /api/auth/oidc/start
// 2. We 302 to the IdP authorize endpoint (PKCE + state)
// 3. IdP redirects back to /api/auth/oidc/callback?code=...&state=...
// 4. We exchange the code for tokens, verify the ID token, mint a
// one-time "ticket" (short random string), and 302 to the SPA at
// the post-login redirect with the ticket in the URL fragment.
// 5. SPA POSTs the ticket to /api/auth/oidc/exchange and gets a
// session JWT set as an HTTP-only cookie.
//
// Why a ticket vs cookie at callback: the callback URL gets logged by
// every nginx / cloudflare in the path. A short-lived ticket that we
// then trade for a real cookie is much safer than putting the session
// JWT in the callback URL.
//
// Storage:
// - config persisted to oidc_config (single-row table; mutated by
// `dialectic-cli config oidc ...`).
// - state + PKCE verifier kept in-memory (sync.Map keyed by state;
// entries expire after 10 min). Single-instance backend is OK with
// in-memory; multi-instance would need a shared store (DB or redis).
// - tickets also in-memory, 60s ttl.
//
// Session JWT:
// - HS256, signed with cfg.SystemAPIKey OR a dedicated SessionSigningKey
// env (latter is cleaner — see config.go).
// - 24h ttl, cookie HttpOnly + Secure + SameSite=Lax + path=/.
// - Claims: sub (user_id), email, name, exp.
package oidc
import (
"context"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"net/url"
"strings"
"sync"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/golang-jwt/jwt/v5"
"github.com/jmoiron/sqlx"
"golang.org/x/oauth2"
)
type Config struct {
Issuer string `db:"issuer"`
ClientID string `db:"client_id"`
ClientSecret string `db:"client_secret"`
RedirectURI string `db:"redirect_uri"`
PostLoginRedirect string `db:"post_login_redirect"`
Scopes string `db:"scopes"` // space-separated
Enabled bool `db:"enabled"`
}
type Service struct {
db *sqlx.DB
sessionSecret []byte
sessionTTL time.Duration
state sync.Map // state -> *stateEntry
tickets sync.Map // ticket -> *ticketEntry
cachedProvider *oidc.Provider
cachedProviderAt time.Time
cachedIssuer string
mu sync.Mutex
}
type stateEntry struct {
verifier string
expiresAt time.Time
postRedir string // the eventual SPA URL to bounce to
}
type ticketEntry struct {
userID string
email string
name string
expiresAt time.Time
}
// NewService wires the OIDC service. sessionSecret is the HS256 signing
// key for session JWTs — must be a stable per-deployment secret (>= 32
// bytes random). sessionTTL is how long the cookie stays valid (default
// 24h is fine for a dashboard).
func NewService(db *sqlx.DB, sessionSecret []byte, sessionTTL time.Duration) *Service {
if sessionTTL <= 0 {
sessionTTL = 24 * time.Hour
}
return &Service{
db: db,
sessionSecret: sessionSecret,
sessionTTL: sessionTTL,
}
}
// IsEnabled returns true iff a fully-configured + flag-on OIDC config
// is in the DB. Safe to call frequently — direct DB hit, no cache (the
// SPA polls this on every load).
func (s *Service) IsEnabled(ctx context.Context) (bool, error) {
c, err := s.GetConfig(ctx)
if err != nil {
return false, err
}
if c == nil {
return false, nil
}
return c.Enabled && c.Issuer != "" && c.ClientID != "" && c.RedirectURI != "", nil
}
func (s *Service) GetConfig(ctx context.Context) (*Config, error) {
var c Config
err := s.db.GetContext(ctx, &c, `SELECT issuer, client_id, client_secret, redirect_uri, post_login_redirect, scopes, enabled FROM oidc_config WHERE id='singleton'`)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &c, nil
}
// SetConfig mutates only the fields present in patch (non-nil pointer).
// Pass &"" to clear a string; pass nil to leave unchanged. Enabled is
// the only field where false has a meaning distinct from "unchanged"
// so use a pointer.
type ConfigPatch struct {
Issuer *string
ClientID *string
ClientSecret *string
RedirectURI *string
PostLoginRedirect *string
Scopes *string
Enabled *bool
}
func (s *Service) SetConfig(ctx context.Context, p ConfigPatch) (*Config, error) {
// Read-modify-write under a tx so two concurrent CLI invocations
// don't lose updates.
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return nil, err
}
defer func() { _ = tx.Rollback() }()
var c Config
if err := tx.GetContext(ctx, &c, `SELECT issuer, client_id, client_secret, redirect_uri, post_login_redirect, scopes, enabled FROM oidc_config WHERE id='singleton' FOR UPDATE`); err != nil {
return nil, err
}
if p.Issuer != nil {
c.Issuer = *p.Issuer
}
if p.ClientID != nil {
c.ClientID = *p.ClientID
}
if p.ClientSecret != nil {
c.ClientSecret = *p.ClientSecret
}
if p.RedirectURI != nil {
c.RedirectURI = *p.RedirectURI
}
if p.PostLoginRedirect != nil {
c.PostLoginRedirect = *p.PostLoginRedirect
}
if p.Scopes != nil {
c.Scopes = *p.Scopes
}
if p.Enabled != nil {
c.Enabled = *p.Enabled
}
if _, err := tx.ExecContext(ctx,
`UPDATE oidc_config SET issuer=?, client_id=?, client_secret=?, redirect_uri=?, post_login_redirect=?, scopes=?, enabled=? WHERE id='singleton'`,
c.Issuer, c.ClientID, c.ClientSecret, c.RedirectURI, c.PostLoginRedirect, c.Scopes, c.Enabled,
); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, err
}
// Bust provider cache — the issuer might have changed.
s.mu.Lock()
s.cachedProvider = nil
s.cachedIssuer = ""
s.mu.Unlock()
return &c, nil
}
// provider returns a cached *oidc.Provider; cache invalidates when the
// issuer changes (SetConfig clears it) or after 1 hour (defensive
// against stale JWKS cache).
func (s *Service) provider(ctx context.Context, issuer string) (*oidc.Provider, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.cachedProvider != nil && s.cachedIssuer == issuer && time.Since(s.cachedProviderAt) < time.Hour {
return s.cachedProvider, nil
}
p, err := oidc.NewProvider(ctx, issuer)
if err != nil {
return nil, fmt.Errorf("oidc discovery for %s: %w", issuer, err)
}
s.cachedProvider = p
s.cachedIssuer = issuer
s.cachedProviderAt = time.Now()
return p, nil
}
// BuildAuthorizeURL generates the IdP authorize URL + remembers the
// PKCE verifier + state. Caller redirects the browser to the URL.
func (s *Service) BuildAuthorizeURL(ctx context.Context) (string, error) {
c, err := s.GetConfig(ctx)
if err != nil {
return "", err
}
if c == nil || !c.Enabled {
return "", errors.New("oidc not enabled")
}
if c.Issuer == "" || c.ClientID == "" || c.RedirectURI == "" {
return "", errors.New("oidc config incomplete (need issuer + client_id + redirect_uri)")
}
p, err := s.provider(ctx, c.Issuer)
if err != nil {
return "", err
}
verifier := randomBase64URL(48)
challenge := pkceS256(verifier)
state := randomBase64URL(24)
s.state.Store(state, &stateEntry{
verifier: verifier,
expiresAt: time.Now().Add(10 * time.Minute),
postRedir: c.PostLoginRedirect,
})
cfg := oauth2.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
Endpoint: p.Endpoint(),
RedirectURL: c.RedirectURI,
Scopes: strings.Fields(c.Scopes),
}
return cfg.AuthCodeURL(state,
oauth2.AccessTypeOnline,
oauth2.SetAuthURLParam("code_challenge", challenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
), nil
}
// HandleCallback exchanges the code for tokens, verifies the ID token,
// mints a one-time ticket, and returns the ticket + post-login redirect.
// Caller (HTTP handler) 302's the browser there with the ticket in the
// URL fragment.
func (s *Service) HandleCallback(ctx context.Context, code, state string) (ticket, redirect string, err error) {
if code == "" || state == "" {
return "", "", errors.New("missing code or state")
}
v, ok := s.state.LoadAndDelete(state)
if !ok {
return "", "", errors.New("unknown state (expired or replay)")
}
entry := v.(*stateEntry)
if time.Now().After(entry.expiresAt) {
return "", "", errors.New("state expired")
}
c, err := s.GetConfig(ctx)
if err != nil || c == nil || !c.Enabled {
return "", "", errors.New("oidc not enabled")
}
p, err := s.provider(ctx, c.Issuer)
if err != nil {
return "", "", err
}
cfg := oauth2.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
Endpoint: p.Endpoint(),
RedirectURL: c.RedirectURI,
Scopes: strings.Fields(c.Scopes),
}
tok, err := cfg.Exchange(ctx, code,
oauth2.SetAuthURLParam("code_verifier", entry.verifier),
)
if err != nil {
return "", "", fmt.Errorf("token exchange: %w", err)
}
rawID, ok := tok.Extra("id_token").(string)
if !ok || rawID == "" {
return "", "", errors.New("no id_token in response")
}
verifier := p.Verifier(&oidc.Config{ClientID: c.ClientID})
idTok, err := verifier.Verify(ctx, rawID)
if err != nil {
return "", "", fmt.Errorf("id_token verify: %w", err)
}
var claims struct {
Sub string `json:"sub"`
Email string `json:"email"`
PreferredUsername string `json:"preferred_username"`
Name string `json:"name"`
}
if err := idTok.Claims(&claims); err != nil {
return "", "", fmt.Errorf("claims decode: %w", err)
}
// Pick the most useful display name.
displayName := claims.Name
if displayName == "" {
displayName = claims.PreferredUsername
}
if displayName == "" {
displayName = claims.Email
}
if claims.Sub == "" {
return "", "", errors.New("id_token missing sub claim")
}
// Mint one-time ticket (60s, single-use).
t := randomBase64URL(32)
s.tickets.Store(t, &ticketEntry{
userID: claims.Sub,
email: claims.Email,
name: displayName,
expiresAt: time.Now().Add(60 * time.Second),
})
redirect = entry.postRedir
if redirect == "" {
redirect = "/"
}
return t, redirect, nil
}
// ExchangeTicket validates the ticket and returns a signed session JWT
// + its expiry. Single-use; deleted on first read regardless of result.
func (s *Service) ExchangeTicket(ticket string) (jwt string, expiresAt time.Time, user UserClaims, err error) {
if ticket == "" {
err = errors.New("missing ticket")
return
}
v, ok := s.tickets.LoadAndDelete(ticket)
if !ok {
err = errors.New("unknown ticket (expired, used, or invalid)")
return
}
entry := v.(*ticketEntry)
if time.Now().After(entry.expiresAt) {
err = errors.New("ticket expired")
return
}
user = UserClaims{
Sub: entry.userID,
Email: entry.email,
Name: entry.name,
}
expiresAt = time.Now().Add(s.sessionTTL)
jwt, err = s.signSession(user, expiresAt)
return
}
// UserClaims is what a session cookie carries. Kept tiny: sub + email
// + name. Anything heavier (roles, group memberships) should hit
// /api/auth/me which can re-derive on demand.
type UserClaims struct {
Sub string `json:"sub"`
Email string `json:"email"`
Name string `json:"name"`
}
func (s *Service) signSession(u UserClaims, expiresAt time.Time) (string, error) {
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": u.Sub,
"email": u.Email,
"name": u.Name,
"exp": expiresAt.Unix(),
})
return tok.SignedString(s.sessionSecret)
}
// VerifySession parses a session JWT and returns the claims if valid.
// Used by auth middleware.
func (s *Service) VerifySession(raw string) (*UserClaims, error) {
tok, err := jwt.Parse(raw, func(t *jwt.Token) (any, error) {
if t.Method != jwt.SigningMethodHS256 {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return s.sessionSecret, nil
})
if err != nil {
return nil, err
}
claims, ok := tok.Claims.(jwt.MapClaims)
if !ok || !tok.Valid {
return nil, errors.New("invalid token")
}
sub, _ := claims["sub"].(string)
email, _ := claims["email"].(string)
name, _ := claims["name"].(string)
if sub == "" {
return nil, errors.New("token missing sub")
}
return &UserClaims{Sub: sub, Email: email, Name: name}, nil
}
// SweepExpired removes expired state + ticket entries. Call from a
// background goroutine every ~1min so the maps don't grow unbounded
// on a forever-running process.
func (s *Service) SweepExpired() {
now := time.Now()
s.state.Range(func(k, v any) bool {
if e, ok := v.(*stateEntry); ok && now.After(e.expiresAt) {
s.state.Delete(k)
}
return true
})
s.tickets.Range(func(k, v any) bool {
if e, ok := v.(*ticketEntry); ok && now.After(e.expiresAt) {
s.tickets.Delete(k)
}
return true
})
}
// randomBase64URL returns a URL-safe random string of the given byte length
// (so the resulting string is ~1.3x longer after base64). Panics on
// crypto/rand failure (the process is doomed anyway).
func randomBase64URL(n int) string {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
panic("rand: " + err.Error())
}
return base64.RawURLEncoding.EncodeToString(b)
}
// pkceS256 returns the BASE64URL(SHA256(verifier)) PKCE code challenge.
func pkceS256(verifier string) string {
h := sha256.Sum256([]byte(verifier))
return base64.RawURLEncoding.EncodeToString(h[:])
}
// hashCallbackHint is a tiny utility for logging callback errors
// without dumping the raw URL (which may contain tokens). Not used in
// hot path; here so callers can build observability later.
func hashCallbackHint(u *url.URL) string {
if u == nil {
return ""
}
h := sha256.Sum256([]byte(u.Path + "?" + u.RawQuery))
return hex.EncodeToString(h[:6])
}
// silence unused — keep available for future logging.
var _ = hashCallbackHint