Files
Dialectic.Backend/main.go
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

119 lines
3.7 KiB
Go

// Dialectic.Backend.Go — entrypoint.
//
// Greenfield Go rewrite of the Python v1 backend; agent-only debate
// platform per /home/hzhang/arch/DIALECTIC-V2-DESIGN.md.
//
// This file: load config → open db → run migrations → mount routes →
// serve until SIGINT/SIGTERM. Everything else lives in internal/.
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"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/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"
)
// Version is overridden at build time via -ldflags="-X main.Version=...".
var Version = "dev"
func main() {
log.SetFlags(log.LstdFlags | log.Lmicroseconds | log.Lshortfile)
cfg, err := config.LoadFromEnv()
if err != nil {
log.Fatalf("config: %v", err)
}
log.Printf("starting dialectic-backend %s mode=%s addr=%s", Version, cfg.Mode, cfg.HTTPAddr)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
conn, err := db.Open(ctx, cfg.DSN())
if err != nil {
log.Fatalf("db open: %v", err)
}
defer conn.Close()
if err := db.RunMigrations(ctx, conn); err != nil {
log.Fatalf("migrations: %v", err)
}
log.Printf("migrations: ok")
// Wire orchestrator + start the ticker. Backend no longer broadcasts
// to Fabric — proposers post a single recruitment fabric-send-message,
// downstream agents book HF on_call slots to be woken at debate time.
topicStore := store.NewTopicStore(conn)
signupStore := store.NewSignupStore(conn)
campStore := store.NewCampStore(conn)
roundStore := store.NewRoundStore(conn)
ticker := orchestrator.NewTicker(conn, topicStore, signupStore, campStore, roundStore,
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, oidcSvc, Version),
ReadHeaderTimeout: 10 * time.Second,
}
// Graceful shutdown on SIGINT/SIGTERM.
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
go func() {
<-shutdown
log.Printf("shutdown signal received")
ctx2, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx2); err != nil {
log.Printf("http shutdown error: %v", err)
}
}()
log.Printf("http server listening on %s", cfg.HTTPAddr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("http serve: %v", err)
}
log.Printf("bye")
}