diff --git a/Dockerfile b/Dockerfile index 3e3eb92..791baff 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,10 @@ # syntax=docker/dockerfile:1.7 -# Dialectic.Backend.Go — multi-stage build (compile static binary, run on distroless). +# Dialectic.Backend.Go — multi-stage build. +# Compiles two binaries: +# - dialectic-backend (ENTRYPOINT — long-running HTTP server) +# - dialectic-cli (operator subcommands; reach via docker exec) -FROM golang:1.23-bookworm AS build +FROM golang:1.25-bookworm AS build WORKDIR /src COPY go.mod go.sum ./ RUN go mod download @@ -9,11 +12,18 @@ COPY . . ARG VERSION=dev RUN CGO_ENABLED=0 GOOS=linux go build \ -ldflags="-s -w -X main.Version=${VERSION}" \ - -o /out/dialectic-backend . + -o /out/dialectic-backend . \ + && CGO_ENABLED=0 GOOS=linux go build \ + -ldflags="-s -w" \ + -o /out/dialectic-cli ./cmd/dialectic-cli FROM gcr.io/distroless/static-debian12:nonroot WORKDIR /app COPY --from=build /out/dialectic-backend /app/dialectic-backend +COPY --from=build /out/dialectic-cli /app/dialectic-cli +# Put both on PATH so `docker exec dialectic-backend dialectic-cli ...` +# just works without typing /app/. +ENV PATH="/app:${PATH}" EXPOSE 8090 USER nonroot:nonroot ENTRYPOINT ["/app/dialectic-backend"] diff --git a/cmd/dialectic-cli/main.go b/cmd/dialectic-cli/main.go new file mode 100644 index 0000000..d65e861 --- /dev/null +++ b/cmd/dialectic-cli/main.go @@ -0,0 +1,145 @@ +// dialectic-cli — operator/admin commands for the running Dialectic +// backend. Reads the same DB the backend reads + writes; takes no +// HTTP path so it can run inside the same container as the backend +// (docker exec dialectic-backend dialectic-cli ...) or against the +// same DB from anywhere with credentials. +// +// Subcommands today: +// +// dialectic-cli config oidc [--issuer URL] [--client-id ID] +// [--client-secret S] [--callback-url URL] +// [--post-login-redirect URL] +// [--scopes "openid email profile"] +// [--enabled true|false] +// [--show-secret] +// +// Pattern mirrors Fabric.Backend.Center's `node dist/cli.js config oidc`. +// Only the flags you pass mutate; others stay unchanged. Default print +// masks client_secret (use --show-secret to reveal — local audit only, +// never paste output into chat). +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + "time" + + "git.hangman-lab.top/hzhang/Dialectic.Backend/internal/config" + "git.hangman-lab.top/hzhang/Dialectic.Backend/internal/db" + "git.hangman-lab.top/hzhang/Dialectic.Backend/internal/oidc" +) + +func main() { + if len(os.Args) < 3 { + usage() + } + subject := os.Args[1] + action := os.Args[2] + args := os.Args[3:] + + if subject != "config" || action != "oidc" { + usage() + } + + patch := oidc.ConfigPatch{} + showSecret := false + for i := 0; i < len(args); i++ { + switch args[i] { + case "--issuer": + patch.Issuer = strArg(args, &i) + case "--client-id": + patch.ClientID = strArg(args, &i) + case "--client-secret": + patch.ClientSecret = strArg(args, &i) + case "--callback-url": + patch.RedirectURI = strArg(args, &i) + case "--post-login-redirect": + patch.PostLoginRedirect = strArg(args, &i) + case "--scopes": + patch.Scopes = strArg(args, &i) + case "--enabled": + v := strArg(args, &i) + b := v != nil && *v == "true" + patch.Enabled = &b + case "--show-secret": + showSecret = true + default: + fmt.Fprintf(os.Stderr, "unknown flag: %s\n", args[i]) + usage() + } + } + + cfg, err := config.LoadFromEnv() + check("config", err) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + conn, err := db.Open(ctx, cfg.DSN()) + check("db", err) + defer conn.Close() + // Don't auto-run migrations from the CLI — the backend container's + // startup is the canonical migration driver. The CLI assumes the + // table is already in place. + signingKey := []byte(cfg.SessionSigningKey) + if len(signingKey) == 0 { + signingKey = []byte("cli-only-irrelevant") + } + svc := oidc.NewService(conn, signingKey, 24*time.Hour) + + updated, err := svc.SetConfig(ctx, patch) + check("set config", err) + + out := map[string]any{ + "issuer": updated.Issuer, + "client_id": updated.ClientID, + "redirect_uri": updated.RedirectURI, + "post_login_redirect": updated.PostLoginRedirect, + "scopes": updated.Scopes, + "enabled": updated.Enabled, + } + if showSecret { + out["client_secret"] = updated.ClientSecret + } else if updated.ClientSecret != "" { + out["client_secret"] = "***set***" + } else { + out["client_secret"] = "" + } + b, _ := json.MarshalIndent(map[string]any{"ok": true, "config": out}, "", " ") + fmt.Println(string(b)) +} + +func strArg(args []string, i *int) *string { + if *i+1 >= len(args) { + fmt.Fprintf(os.Stderr, "%s requires a value\n", args[*i]) + os.Exit(1) + } + *i++ + v := args[*i] + return &v +} + +func check(label string, err error) { + if err != nil { + fmt.Fprintf(os.Stderr, "%s: %v\n", label, err) + os.Exit(1) + } +} + +func usage() { + fmt.Fprintln(os.Stderr, `Usage: + dialectic-cli config oidc [--issuer ] [--client-id ] + [--client-secret ] [--callback-url ] + [--post-login-redirect ] + [--scopes "openid email profile"] + [--enabled true|false] [--show-secret] + +Sets only the flags you pass; leaves the rest unchanged. Prints the +post-update config with client_secret masked unless --show-secret. + +Reads the same DB env as the backend (DB_HOST/PORT/USER/PASSWORD/NAME). +Run inside the backend container via: + docker exec dialectic-backend dialectic-cli config oidc ... +`) + os.Exit(1) +} diff --git a/go.mod b/go.mod index 4cf4ee0..a85aec5 100644 --- a/go.mod +++ b/go.mod @@ -1,13 +1,19 @@ module git.hangman-lab.top/hzhang/Dialectic.Backend -go 1.23 +go 1.25.0 require ( + github.com/coreos/go-oidc/v3 v3.18.0 github.com/go-chi/chi/v5 v5.1.0 github.com/go-chi/cors v1.2.1 github.com/go-sql-driver/mysql v1.8.1 + github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 github.com/jmoiron/sqlx v1.4.0 + golang.org/x/oauth2 v0.36.0 ) -require filippo.io/edwards25519 v1.1.0 // indirect +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/go-jose/go-jose/v4 v4.1.4 // indirect +) diff --git a/go.sum b/go.sum index b26d9bb..c6866cc 100644 --- a/go.sum +++ b/go.sum @@ -1,11 +1,17 @@ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/coreos/go-oidc/v3 v3.18.0 h1:V9orjXynvu5wiC9SemFTWnG4F45v403aIcjWo0d41+A= +github.com/coreos/go-oidc/v3 v3.18.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw= github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4= github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= @@ -14,3 +20,5 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 01b02b3..bd18acf 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -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: ` 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) }) } } diff --git a/internal/config/config.go b/internal/config/config.go index d4e6750..cdcb6e4 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -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, ", ")) } diff --git a/internal/db/migrations/004_oidc_config.sql b/internal/db/migrations/004_oidc_config.sql new file mode 100644 index 0000000..c00f38f --- /dev/null +++ b/internal/db/migrations/004_oidc_config.sql @@ -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', ''); diff --git a/internal/httpapi/handlers/auth.go b/internal/httpapi/handlers/auth.go new file mode 100644 index 0000000..7503e32 --- /dev/null +++ b/internal/httpapi/handlers/auth.go @@ -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 diff --git a/internal/httpapi/routes.go b/internal/httpapi/routes.go index 24485e5..f840fb4 100644 --- a/internal/httpapi/routes.go +++ b/internal/httpapi/routes.go @@ -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 diff --git a/internal/oidc/service.go b/internal/oidc/service.go new file mode 100644 index 0000000..5ee4ada --- /dev/null +++ b/internal/oidc/service.go @@ -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 diff --git a/main.go b/main.go index f1158cd..707f190 100644 --- a/main.go +++ b/main.go @@ -20,6 +20,7 @@ import ( "git.hangman-lab.top/hzhang/Dialectic.Backend/internal/config" "git.hangman-lab.top/hzhang/Dialectic.Backend/internal/db" "git.hangman-lab.top/hzhang/Dialectic.Backend/internal/httpapi" + "git.hangman-lab.top/hzhang/Dialectic.Backend/internal/oidc" "git.hangman-lab.top/hzhang/Dialectic.Backend/internal/orchestrator" "git.hangman-lab.top/hzhang/Dialectic.Backend/internal/store" ) @@ -61,9 +62,38 @@ func main() { cfg.OrchestratorTickInterval) go ticker.Run(ctx) + // OIDC service — session JWT signing key MUST be stable across + // restarts (rotating invalidates every active session, which is + // the desired effect for emergency revocation only). Loaded from + // SESSION_SIGNING_KEY env; if empty in dev mode we synthesize a + // random key so dev still works (every restart logs everyone out). + signingKey := []byte(cfg.SessionSigningKey) + if len(signingKey) == 0 { + if !cfg.IsDev() { + log.Fatalf("config: SESSION_SIGNING_KEY required in prod mode") + } + signingKey = []byte("dev-only-unstable-key-restarts-invalidate-sessions") + log.Printf("oidc: using ephemeral dev session signing key (set SESSION_SIGNING_KEY for stable)") + } + oidcSvc := oidc.NewService(conn, signingKey, 24*time.Hour) + // Sweep expired state/ticket entries every minute so sync.Map + // doesn't grow unbounded. + go func() { + t := time.NewTicker(time.Minute) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + oidcSvc.SweepExpired() + } + } + }() + srv := &http.Server{ Addr: cfg.HTTPAddr, - Handler: httpapi.Mount(cfg, conn, Version), + Handler: httpapi.Mount(cfg, conn, oidcSvc, Version), ReadHeaderTimeout: 10 * time.Second, }