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
|
||||
Reference in New Issue
Block a user