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:
145
internal/httpapi/handlers/auth.go
Normal file
145
internal/httpapi/handlers/auth.go
Normal 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
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user