Compare commits
4 Commits
5cf4302d50
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b2f2fae30 | |||
| b02b1706b6 | |||
| 2463129dbd | |||
| 0b16b52ee7 |
16
Dockerfile
16
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"]
|
||||
|
||||
145
cmd/dialectic-cli/main.go
Normal file
145
cmd/dialectic-cli/main.go
Normal file
@@ -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.Fprint(os.Stderr, `Usage:
|
||||
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]
|
||||
|
||||
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)
|
||||
}
|
||||
10
go.mod
10
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
|
||||
)
|
||||
|
||||
8
go.sum
8
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=
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
185
internal/auth/oidc_bearer.go
Normal file
185
internal/auth/oidc_bearer.go
Normal file
@@ -0,0 +1,185 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
)
|
||||
|
||||
var (
|
||||
errNoSub = errors.New("token missing sub")
|
||||
errBadAudience = errors.New("token audience does not match")
|
||||
)
|
||||
|
||||
// TesseraBearer middleware: accepts access tokens issued by the external
|
||||
// "Tessera" OIDC provider (Keycloak-compatible) as API bearer tokens.
|
||||
//
|
||||
// This is ADDITIVE to the existing agent-key and browser-session auth
|
||||
// paths. It only acts when the request carries `Authorization: Bearer
|
||||
// <jwt>` AND that bearer is a parseable, verifiable Tessera JWT. Agent
|
||||
// keys are opaque (not JWTs), so they fail verification here and the
|
||||
// chain falls through to the next auth step — nothing breaks.
|
||||
//
|
||||
// On success it attaches a CallerUser:
|
||||
//
|
||||
// Caller{
|
||||
// Kind: CallerUser,
|
||||
// ID: sub,
|
||||
// Email: email,
|
||||
// Name: preferred_username,
|
||||
// Roles: realm_access.roles ++ resource_access[audience].roles,
|
||||
// }
|
||||
//
|
||||
// On any failure (missing/opaque bearer, bad signature, wrong issuer,
|
||||
// wrong audience, expired) it 401s — the caller composes this into the
|
||||
// auth chain the same way as AgentAPIKey (capture 401 → fall through).
|
||||
func TesseraBearer(issuer, audience string) func(http.Handler) http.Handler {
|
||||
v := newTesseraVerifier(issuer, audience)
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw := bearerToken(r)
|
||||
if raw == "" {
|
||||
http.Error(w, "missing bearer token", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
caller, err := v.verify(r.Context(), raw)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid tessera bearer", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
ctx := WithCaller(r.Context(), caller)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// tesseraVerifier wraps a go-oidc IDTokenVerifier over the issuer's JWKS.
|
||||
// The provider (and thus its cached KeySet) is lazily fetched on first
|
||||
// use and refreshed hourly — same defensive TTL the OIDC login service
|
||||
// uses. go-oidc's RemoteKeySet handles per-kid JWKS fetching + caching
|
||||
// internally; this wrapper just adds the discovery cache + claim mapping.
|
||||
type tesseraVerifier struct {
|
||||
issuer string
|
||||
audience string
|
||||
|
||||
mu sync.Mutex
|
||||
verifier *oidc.IDTokenVerifier
|
||||
fetchedAt time.Time
|
||||
}
|
||||
|
||||
func newTesseraVerifier(issuer, audience string) *tesseraVerifier {
|
||||
return &tesseraVerifier{issuer: issuer, audience: audience}
|
||||
}
|
||||
|
||||
func (t *tesseraVerifier) getVerifier(ctx context.Context) (*oidc.IDTokenVerifier, error) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if t.verifier != nil && time.Since(t.fetchedAt) < time.Hour {
|
||||
return t.verifier, nil
|
||||
}
|
||||
p, err := oidc.NewProvider(ctx, t.issuer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// SkipClientIDCheck: Keycloak access tokens carry the app client id in
|
||||
// `aud`, but go-oidc's default aud check compares against ClientID. We
|
||||
// do the audience check ourselves in verify() so we can accept aud as
|
||||
// either a string or an array, so disable the built-in one here.
|
||||
v := p.Verifier(&oidc.Config{
|
||||
SkipClientIDCheck: true,
|
||||
SupportedSigningAlgs: []string{oidc.RS256},
|
||||
})
|
||||
t.verifier = v
|
||||
t.fetchedAt = time.Now()
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// tesseraClaims is the projection of a Tessera/Keycloak access token we
|
||||
// read. aud is decoded loosely (string or array) via audience.
|
||||
type tesseraClaims struct {
|
||||
Sub string `json:"sub"`
|
||||
Email string `json:"email"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
Aud audience `json:"aud"`
|
||||
RealmAccess struct {
|
||||
Roles []string `json:"roles"`
|
||||
} `json:"realm_access"`
|
||||
ResourceAccess map[string]struct {
|
||||
Roles []string `json:"roles"`
|
||||
} `json:"resource_access"`
|
||||
}
|
||||
|
||||
func (t *tesseraVerifier) verify(ctx context.Context, raw string) (Caller, error) {
|
||||
v, err := t.getVerifier(ctx)
|
||||
if err != nil {
|
||||
return Caller{}, err
|
||||
}
|
||||
// Verify() checks RS256 signature against JWKS, iss == issuer, and exp.
|
||||
tok, err := v.Verify(ctx, raw)
|
||||
if err != nil {
|
||||
return Caller{}, err
|
||||
}
|
||||
var c tesseraClaims
|
||||
if err := tok.Claims(&c); err != nil {
|
||||
return Caller{}, err
|
||||
}
|
||||
if c.Sub == "" {
|
||||
return Caller{}, errNoSub
|
||||
}
|
||||
if !c.Aud.contains(t.audience) {
|
||||
return Caller{}, errBadAudience
|
||||
}
|
||||
roles := append([]string{}, c.RealmAccess.Roles...)
|
||||
if ra, ok := c.ResourceAccess[t.audience]; ok {
|
||||
roles = append(roles, ra.Roles...)
|
||||
}
|
||||
name := c.PreferredUsername
|
||||
return Caller{
|
||||
Kind: CallerUser,
|
||||
ID: c.Sub,
|
||||
Email: c.Email,
|
||||
Name: name,
|
||||
Roles: roles,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// audience decodes the JWT `aud` claim, which may be a single string or
|
||||
// an array of strings.
|
||||
type audience []string
|
||||
|
||||
func (a *audience) UnmarshalJSON(b []byte) error {
|
||||
b = []byte(strings.TrimSpace(string(b)))
|
||||
if len(b) == 0 || string(b) == "null" {
|
||||
*a = nil
|
||||
return nil
|
||||
}
|
||||
if b[0] == '[' {
|
||||
var arr []string
|
||||
if err := json.Unmarshal(b, &arr); err != nil {
|
||||
return err
|
||||
}
|
||||
*a = arr
|
||||
return nil
|
||||
}
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
*a = []string{s}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a audience) contains(want string) bool {
|
||||
for _, v := range a {
|
||||
if v == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -63,9 +63,36 @@ 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
|
||||
|
||||
// OIDCBearerIssuer + OIDCBearerAudience configure acceptance of
|
||||
// access tokens issued by the external "Tessera" OIDC provider
|
||||
// (Keycloak-compatible) as API bearer tokens. ADDITIVE to the
|
||||
// existing agent-key + browser-session auth paths. A request with
|
||||
// `Authorization: Bearer <jwt>` whose JWT verifies against this
|
||||
// issuer's JWKS and carries this audience is treated as a CallerUser.
|
||||
// Env: OIDC_BEARER_ISSUER, OIDC_BEARER_AUDIENCE.
|
||||
OIDCBearerIssuer string
|
||||
OIDCBearerAudience 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 +122,10 @@ func LoadFromEnv() (*Config, error) {
|
||||
DialecticAdminAPIKey: os.Getenv("DIALECTIC_ADMIN_API_KEY"),
|
||||
OIDCIssuer: os.Getenv("OIDC_ISSUER"),
|
||||
OIDCClientID: os.Getenv("OIDC_CLIENT_ID"),
|
||||
OIDCBearerIssuer: getenv("OIDC_BEARER_ISSUER", "https://login.hangman-lab.top/realms/Hangman-Lab"),
|
||||
OIDCBearerAudience: getenv("OIDC_BEARER_AUDIENCE", "dialectic-prod"),
|
||||
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 +145,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, ", "))
|
||||
}
|
||||
|
||||
23
internal/db/migrations/004_oidc_config.sql
Normal file
23
internal/db/migrations/004_oidc_config.sql
Normal 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', '');
|
||||
@@ -3,12 +3,15 @@ package handlers
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
@@ -123,3 +126,122 @@ func randomHexKey(byteLen int) (string, error) {
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// GET /api/admin/agents/{id}
|
||||
//
|
||||
// Same x-dialectic-admin-key gate as ProvisionAgentKey. Returns a
|
||||
// rolled-up activity summary for one agent: whether a dialectic key is
|
||||
// provisioned (and when last used), per-action counts (signups /
|
||||
// arguments / verdicts), and the 20 most-recent topics the agent
|
||||
// touched in any role. Used by the frontend AgentActivity page for
|
||||
// operator diagnostics ("did sherlock get a key?", "how much is mirror
|
||||
// participating?").
|
||||
//
|
||||
// Joins are wide but capped at 20 recent topics; total query cost is
|
||||
// bounded by index scans on (agent_id, posted_at/created_at). At
|
||||
// current row counts (low thousands) returns in <50ms.
|
||||
type recentTopic struct {
|
||||
TopicID string `db:"topic_id" json:"topic_id"`
|
||||
Title string `db:"title" json:"title"`
|
||||
Status string `db:"status" json:"status"`
|
||||
Role string `db:"role" json:"role"`
|
||||
LastActionAt time.Time `db:"last_action_at" json:"last_action_at"`
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetAgentSummary(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.checkAdminAuth(r) {
|
||||
http.Error(w, "admin auth required (x-dialectic-admin-key)", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
agentID := chi.URLParam(r, "id")
|
||||
if agentID == "" {
|
||||
http.Error(w, "agent_id required in path", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
// agent_keys row (may be missing — agent never provisioned)
|
||||
var lastUsedAt sql.NullTime
|
||||
var keyProvisioned bool
|
||||
if err := h.db.QueryRowxContext(ctx,
|
||||
`SELECT last_used_at FROM agent_keys WHERE agent_id = ?`, agentID,
|
||||
).Scan(&lastUsedAt); err != nil {
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
http.Error(w, "agent_keys lookup: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
keyProvisioned = false
|
||||
} else {
|
||||
keyProvisioned = true
|
||||
}
|
||||
|
||||
// Counts (3 small queries; could be one UNION but readability wins
|
||||
// at this scale).
|
||||
count := func(q string) (int, error) {
|
||||
var n int
|
||||
err := h.db.GetContext(ctx, &n, q, agentID)
|
||||
return n, err
|
||||
}
|
||||
signups, err := count(`SELECT COUNT(*) FROM signups WHERE agent_id = ?`)
|
||||
if err != nil {
|
||||
http.Error(w, "signups count: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
args, err := count(`SELECT COUNT(*) FROM arguments WHERE agent_id = ?`)
|
||||
if err != nil {
|
||||
http.Error(w, "arguments count: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
verdicts, err := count(`SELECT COUNT(*) FROM verdicts WHERE judge_agent_id = ?`)
|
||||
if err != nil {
|
||||
http.Error(w, "verdicts count: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Recent topics: union 3 sources, dedup by topic_id keeping the
|
||||
// latest action_at + most-specific role. Allocator camps win over
|
||||
// raw signups (an allocated agent's role is meaningful; a signup
|
||||
// without allocation is just "volunteer"). Verdicts row is judge.
|
||||
var recent []recentTopic
|
||||
if err := h.db.SelectContext(ctx, &recent,
|
||||
`SELECT topic_id, title, status, role, MAX(last_action_at) AS last_action_at FROM (
|
||||
SELECT s.topic_id, t.title, t.status, 'volunteer' AS role, s.created_at AS last_action_at
|
||||
FROM signups s JOIN topics t ON t.id = s.topic_id
|
||||
WHERE s.agent_id = ?
|
||||
UNION ALL
|
||||
SELECT c.topic_id, t.title, t.status, c.camp AS role, c.allocated_at AS last_action_at
|
||||
FROM camps c JOIN topics t ON t.id = c.topic_id
|
||||
WHERE c.agent_id = ?
|
||||
UNION ALL
|
||||
SELECT a.topic_id, t.title, t.status, a.camp AS role, a.posted_at AS last_action_at
|
||||
FROM arguments a JOIN topics t ON t.id = a.topic_id
|
||||
WHERE a.agent_id = ?
|
||||
UNION ALL
|
||||
SELECT v.topic_id, t.title, t.status, 'judge' AS role, v.produced_at AS last_action_at
|
||||
FROM verdicts v JOIN topics t ON t.id = v.topic_id
|
||||
WHERE v.judge_agent_id = ?
|
||||
) AS u
|
||||
GROUP BY topic_id, title, status, role
|
||||
ORDER BY last_action_at DESC
|
||||
LIMIT 20`,
|
||||
agentID, agentID, agentID, agentID,
|
||||
); err != nil {
|
||||
http.Error(w, "recent topics: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
resp := map[string]any{
|
||||
"agent_id": agentID,
|
||||
"key_provisioned": keyProvisioned,
|
||||
"signups_count": signups,
|
||||
"arguments_count": args,
|
||||
"verdicts_count": verdicts,
|
||||
"recent_topics": recent,
|
||||
}
|
||||
if lastUsedAt.Valid {
|
||||
resp["last_used_at"] = lastUsedAt.Time
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
|
||||
189
internal/httpapi/handlers/auth.go
Normal file
189
internal/httpapi/handlers/auth.go
Normal file
@@ -0,0 +1,189 @@
|
||||
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
|
||||
allowedHosts []string // for open-redirect protection on post_login_redirect
|
||||
}
|
||||
|
||||
// NewAuthHandler wires the OIDC HTTP surface. `allowedHosts` is the
|
||||
// allow-list of hostnames the callback may 302 the browser to (sourced
|
||||
// from cfg.CORSAllowOrigins — the same origins we already trust for
|
||||
// CORS, by definition. A relative path always passes regardless.
|
||||
func NewAuthHandler(svc *oidc.Service, cookieName string, secure bool, allowedHosts []string) *AuthHandler {
|
||||
if cookieName == "" {
|
||||
cookieName = "dialectic_session"
|
||||
}
|
||||
return &AuthHandler{oidc: svc, cookieName: cookieName, secure: secure, allowedHosts: allowedHosts}
|
||||
}
|
||||
|
||||
// safeRedirectBase returns `raw` if it's a relative path OR an absolute
|
||||
// URL whose host appears in the allow-list. Otherwise it returns "/" so
|
||||
// the open-redirect attack (attacker-set PostLoginRedirect points to
|
||||
// evil.com) is neutered — the worst the SPA sees is its own root with
|
||||
// an error fragment, never an external bounce.
|
||||
//
|
||||
// Why we need this: oidc_config.post_login_redirect is set via the
|
||||
// admin cli. An admin-key compromise OR a misconfiguration that points
|
||||
// it at an external domain would otherwise let any /oidc/callback
|
||||
// error path redirect the user there with `?oidc_error=...` attached,
|
||||
// usable for phishing ("dialectic login failed: please re-enter your
|
||||
// password at evil.com/login").
|
||||
func (h *AuthHandler) safeRedirectBase(raw string) string {
|
||||
if raw == "" {
|
||||
return "/"
|
||||
}
|
||||
// Relative paths are always safe (same-origin by definition).
|
||||
if strings.HasPrefix(raw, "/") && !strings.HasPrefix(raw, "//") {
|
||||
return raw
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Host == "" {
|
||||
return "/"
|
||||
}
|
||||
// Walk the allow-list. cors.AllowedOrigins entries look like
|
||||
// "https://dialectic.hangman-lab.top" — parse host out + compare.
|
||||
for _, origin := range h.allowedHosts {
|
||||
o, err := url.Parse(origin)
|
||||
if err == nil && o.Host != "" && strings.EqualFold(o.Host, u.Host) {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return "/"
|
||||
}
|
||||
|
||||
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 {
|
||||
base = h.safeRedirectBase(c.PostLoginRedirect)
|
||||
}
|
||||
sep := "#"
|
||||
if strings.Contains(base, "#") {
|
||||
sep = "&"
|
||||
}
|
||||
http.Redirect(w, r, base+sep+"oidc_error="+url.QueryEscape(err.Error()), http.StatusFound)
|
||||
return
|
||||
}
|
||||
// Validate the success-path redirect too — HandleCallback returned
|
||||
// PostLoginRedirect from the same DB row, so the same open-redirect
|
||||
// risk applies on the happy path.
|
||||
safe := h.safeRedirectBase(redirect)
|
||||
sep := "#"
|
||||
if strings.Contains(safe, "#") {
|
||||
sep = "&"
|
||||
}
|
||||
http.Redirect(w, r, safe+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,38 @@ 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.
|
||||
// Pass the configured CORS allow-list as the open-redirect allowlist
|
||||
// for the OIDC callback — the SPA hosts we already trust for CORS
|
||||
// are by definition the same hosts a legitimate PostLoginRedirect
|
||||
// can target. Anything else (incl. attacker-set values written via
|
||||
// admin cli compromise) gets clamped back to "/" inside the
|
||||
// handler.
|
||||
authH := handlers.NewAuthHandler(oidcSvc, "dialectic_session", false, cfg.CORSAllowOrigins)
|
||||
|
||||
// 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) {
|
||||
@@ -97,10 +142,12 @@ func Mount(cfg *config.Config, db *sqlx.DB, version string) http.Handler {
|
||||
r.Get("/topics/{id}/signups", signupsH.List)
|
||||
})
|
||||
|
||||
// Admin: provision an agent api key. Auth is its own header
|
||||
// (x-dialectic-admin-key against env DIALECTIC_ADMIN_API_KEY),
|
||||
// not bearer — admin lifecycle is separate from agent identity.
|
||||
// Admin: provision an agent api key + per-agent activity summary.
|
||||
// Auth is its own header (x-dialectic-admin-key against env
|
||||
// DIALECTIC_ADMIN_API_KEY), not bearer — admin lifecycle is
|
||||
// separate from agent identity.
|
||||
r.Post("/admin/agent-keys", adminH.ProvisionAgentKey)
|
||||
r.Get("/admin/agents/{id}", adminH.GetAgentSummary)
|
||||
})
|
||||
|
||||
return r
|
||||
@@ -109,9 +156,10 @@ 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)
|
||||
tessera := auth.TesseraBearer(cfg.OIDCBearerIssuer, cfg.OIDCBearerAudience)
|
||||
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.
|
||||
@@ -125,12 +173,21 @@ 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)
|
||||
// Not an agent key (opaque) → try a Tessera (external OIDC)
|
||||
// bearer JWT. Opaque agent keys fail JWT parse here and 401,
|
||||
// which we again demote to "fall through".
|
||||
rw = &captureWriter{ResponseWriter: w}
|
||||
tessera(next).ServeHTTP(rw, r)
|
||||
if rw.status != http.StatusUnauthorized {
|
||||
return
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -142,9 +199,10 @@ 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)
|
||||
tessera := auth.TesseraBearer(cfg.OIDCBearerIssuer, cfg.OIDCBearerAudience)
|
||||
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") != "" {
|
||||
@@ -153,12 +211,23 @@ func requireAnyAuthChain(db *sqlx.DB, cfg *config.Config) func(http.Handler) htt
|
||||
if rw.status != http.StatusUnauthorized {
|
||||
return
|
||||
}
|
||||
// Not an agent key → try a Tessera (external OIDC) bearer JWT.
|
||||
rw = &captureWriter{ResponseWriter: w}
|
||||
tessera(next).ServeHTTP(rw, r)
|
||||
if rw.status != http.StatusUnauthorized {
|
||||
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
451
internal/oidc/service.go
Normal 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
|
||||
32
main.go
32
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,
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user