Add OIDC login via Authentik: PKCE, JIT provisioning, email linking (#5)
OIDC is pansy's primary login path (Authentik the target IdP); local auth (#4) remains the fallback and both issue the same session cookie. - deps: github.com/coreos/go-oidc/v3 + golang.org/x/oauth2 (both pure Go; CGO stays off). - api/oidc.go: lazy issuer discovery (retried per-request, never crashes a server that also serves local auth), GET /auth/oidc/login builds an authorization-code URL with PKCE S256 + random state + nonce stashed in a short-lived HttpOnly cookie, GET /auth/oidc/callback verifies state (constant-time), exchanges the code with the PKCE verifier, verifies the ID token + nonce, and starts a pansy session. Failures redirect to /login?error=... ; success to /gardens. - service.LoginOIDC: (issuer,subject) match -> login; else *verified* email match -> link onto the existing account; else JIT-create (the IdP gates access, so PANSY_REGISTRATION doesn't apply). Unverified email colliding with an existing account is refused (takeover guard); no email is refused (email is the account key). Reuses the atomic CreateUser. - store: GetUserByOIDC + LinkOIDC (unique-pair backstop). - config: OIDCReady() (needs issuer+client+BaseURL for the redirect URI); /auth/providers now reports oidc from it and defaults the button label to "Sign in with Authentik". OIDC routes are only registered when ready, so an unconfigured instance 404s them. - PANSY_LOCAL_AUTH=false rejects/hides local auth but not OIDC. Tests: service provisioning (JIT, repeat login, link, unverified-collision refusal, no-email, name fallback, works with local auth off); api (routes-absent-when-unconfigured, providers reporting, login redirect with PKCE params + tx cookie via a fake discovery server, callback state/error paths). Smoke-tested: unreachable issuer degrades to error=oidc_unavailable with the server still up and local auth working. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
+16
-2
@@ -19,8 +19,9 @@ import (
|
||||
// handlers carries the dependencies shared by every HTTP handler. Handlers stay
|
||||
// thin: decode the request, call a service method, encode the result.
|
||||
type handlers struct {
|
||||
cfg *config.Config
|
||||
svc *service.Service
|
||||
cfg *config.Config
|
||||
svc *service.Service
|
||||
oidc *oidcClient // nil unless OIDC is configured (see config.OIDCReady)
|
||||
}
|
||||
|
||||
// New builds the gin engine with the standard middleware stack and registers the
|
||||
@@ -59,6 +60,19 @@ func New(cfg *config.Config, svc *service.Service) *gin.Engine {
|
||||
auth.GET("/providers", h.providers)
|
||||
auth.GET("/me", h.requireAuth(), h.me)
|
||||
|
||||
// OIDC routes exist only when OIDC can actually be offered, so an unconfigured
|
||||
// instance 404s them (matching what /auth/providers advertises). Provider
|
||||
// discovery is lazy (first request), so a briefly-unreachable IdP doesn't stop
|
||||
// the server — or local auth — from starting.
|
||||
switch {
|
||||
case cfg.OIDCReady():
|
||||
h.oidc = newOIDCClient(cfg)
|
||||
auth.GET("/oidc/login", h.oidcLogin)
|
||||
auth.GET("/oidc/callback", h.oidcCallback)
|
||||
case cfg.OIDC.Enabled():
|
||||
slog.Warn("api: OIDC is configured but PANSY_BASE_URL is unset; OIDC disabled (an absolute redirect URI is required)")
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
|
||||
+11
-3
@@ -160,18 +160,26 @@ func (h *handlers) csrfGuard() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// startSession issues a session for the user and writes the session cookie.
|
||||
func (h *handlers) startSession(c *gin.Context, userID int64) error {
|
||||
token, expiresAt, err := h.svc.CreateSession(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.setSessionCookie(c, token, expiresAt)
|
||||
return nil
|
||||
}
|
||||
|
||||
// startSessionAndRespond issues a session, sets the cookie, and returns the user
|
||||
// as JSON — the shared tail of register and login.
|
||||
func (h *handlers) startSessionAndRespond(c *gin.Context, user *domain.User) {
|
||||
token, expiresAt, err := h.svc.CreateSession(c.Request.Context(), user.ID)
|
||||
if err != nil {
|
||||
if err := h.startSession(c, user.ID); err != nil {
|
||||
// The account exists and is usable via login; only the auto-login cookie
|
||||
// failed. Log it so the operator can see the underlying DB problem.
|
||||
slog.Error("api: could not start session", "user_id", user.ID, "error", err)
|
||||
writeAPIError(c, http.StatusInternalServerError, "INTERNAL", "could not start session")
|
||||
return
|
||||
}
|
||||
h.setSessionCookie(c, token, expiresAt)
|
||||
c.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/config"
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/service"
|
||||
)
|
||||
|
||||
const (
|
||||
// oidcCallbackPath is appended to PANSY_BASE_URL to form the redirect URI
|
||||
// registered with the IdP.
|
||||
oidcCallbackPath = "/api/v1/auth/oidc/callback"
|
||||
// oidcTxCookie holds the short-lived per-login transaction state (CSRF state,
|
||||
// PKCE verifier, nonce) between /oidc/login and /oidc/callback.
|
||||
oidcTxCookie = "pansy_oidc_tx"
|
||||
oidcTxMaxAge = 10 * time.Minute
|
||||
// oidcDiscoveryTimeout bounds a single lazy discovery attempt so a hung IdP
|
||||
// can't wedge a request goroutine.
|
||||
oidcDiscoveryTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
// oidcClient lazily performs OIDC discovery and holds the derived verifier and
|
||||
// oauth2 config. Discovery is deferred to the first login/callback (and retried
|
||||
// on the next request if it fails) so an IdP that's momentarily unreachable at
|
||||
// boot doesn't stop the server — or local auth — from starting.
|
||||
type oidcClient struct {
|
||||
issuer string
|
||||
clientID string
|
||||
clientSecret string
|
||||
redirectURL string
|
||||
|
||||
mu sync.Mutex
|
||||
provider *oidc.Provider
|
||||
verifier *oidc.IDTokenVerifier
|
||||
oauth *oauth2.Config
|
||||
}
|
||||
|
||||
func newOIDCClient(cfg *config.Config) *oidcClient {
|
||||
return &oidcClient{
|
||||
issuer: cfg.OIDC.Issuer,
|
||||
clientID: cfg.OIDC.ClientID,
|
||||
clientSecret: cfg.OIDC.ClientSecret,
|
||||
redirectURL: cfg.BaseURL + oidcCallbackPath,
|
||||
}
|
||||
}
|
||||
|
||||
// ensure performs discovery once (idempotent) and builds the verifier + oauth2
|
||||
// config. Safe for concurrent callers; a failure leaves the client uninitialized
|
||||
// so the next request retries.
|
||||
func (o *oidcClient) ensure(ctx context.Context) error {
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
if o.provider != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
dctx, cancel := context.WithTimeout(ctx, oidcDiscoveryTimeout)
|
||||
defer cancel()
|
||||
|
||||
provider, err := oidc.NewProvider(dctx, o.issuer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
o.provider = provider
|
||||
o.verifier = provider.Verifier(&oidc.Config{ClientID: o.clientID})
|
||||
o.oauth = &oauth2.Config{
|
||||
ClientID: o.clientID,
|
||||
ClientSecret: o.clientSecret,
|
||||
Endpoint: provider.Endpoint(),
|
||||
RedirectURL: o.redirectURL,
|
||||
Scopes: []string{oidc.ScopeOpenID, "email", "profile"},
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// oidcTx is the per-login transaction stashed in the tx cookie. It never leaves
|
||||
// the browser as anything an attacker can forge (HttpOnly, our domain), and the
|
||||
// callback checks the returned state against it (CSRF), uses the PKCE verifier
|
||||
// for the code exchange, and checks the ID-token nonce.
|
||||
type oidcTx struct {
|
||||
State string `json:"s"`
|
||||
Verifier string `json:"v"`
|
||||
Nonce string `json:"n"`
|
||||
}
|
||||
|
||||
// oidcLogin starts the authorization-code + PKCE flow: it stashes fresh state,
|
||||
// PKCE verifier, and nonce in a short-lived cookie, then redirects to the IdP.
|
||||
func (h *handlers) oidcLogin(c *gin.Context) {
|
||||
if err := h.oidc.ensure(c.Request.Context()); err != nil {
|
||||
slog.Error("api: oidc discovery failed", "error", err)
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc_unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
state, err1 := randToken()
|
||||
nonce, err2 := randToken()
|
||||
if err1 != nil || err2 != nil {
|
||||
slog.Error("api: oidc token generation failed", "state_err", err1, "nonce_err", err2)
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc")
|
||||
return
|
||||
}
|
||||
verifier := oauth2.GenerateVerifier()
|
||||
|
||||
h.setOIDCTxCookie(c, oidcTx{State: state, Verifier: verifier, Nonce: nonce})
|
||||
|
||||
authURL := h.oidc.oauth.AuthCodeURL(state,
|
||||
oauth2.S256ChallengeOption(verifier),
|
||||
oidc.Nonce(nonce),
|
||||
)
|
||||
c.Redirect(http.StatusFound, authURL)
|
||||
}
|
||||
|
||||
// oidcCallback completes the flow: verify state, exchange the code (with the PKCE
|
||||
// verifier), verify the ID token and nonce, provision/link the user, and start a
|
||||
// pansy session. Every failure clears the tx cookie and redirects to the login
|
||||
// page with an error code rather than leaking details to the browser.
|
||||
func (h *handlers) oidcCallback(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
tx, haveTx := h.readOIDCTxCookie(c)
|
||||
h.clearOIDCTxCookie(c)
|
||||
|
||||
// A provider-side error (e.g. user denied consent) comes back as ?error=.
|
||||
if e := c.Query("error"); e != "" {
|
||||
slog.Warn("api: oidc provider returned error", "error", e)
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc")
|
||||
return
|
||||
}
|
||||
|
||||
// State must be present and match the cookie (CSRF protection). Constant-time
|
||||
// compare avoids leaking via timing.
|
||||
state := c.Query("state")
|
||||
if !haveTx || state == "" || subtle.ConstantTimeCompare([]byte(state), []byte(tx.State)) != 1 {
|
||||
slog.Warn("api: oidc state mismatch or missing transaction")
|
||||
c.Redirect(http.StatusFound, "/login?error=state")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.oidc.ensure(ctx); err != nil {
|
||||
slog.Error("api: oidc discovery failed on callback", "error", err)
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc_unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
code := c.Query("code")
|
||||
if code == "" {
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc")
|
||||
return
|
||||
}
|
||||
|
||||
token, err := h.oidc.oauth.Exchange(ctx, code, oauth2.VerifierOption(tx.Verifier))
|
||||
if err != nil {
|
||||
slog.Error("api: oidc code exchange failed", "error", err)
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc")
|
||||
return
|
||||
}
|
||||
|
||||
rawIDToken, ok := token.Extra("id_token").(string)
|
||||
if !ok || rawIDToken == "" {
|
||||
slog.Error("api: oidc token response missing id_token")
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc")
|
||||
return
|
||||
}
|
||||
|
||||
idToken, err := h.oidc.verifier.Verify(ctx, rawIDToken)
|
||||
if err != nil {
|
||||
slog.Error("api: oidc id_token verification failed", "error", err)
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc")
|
||||
return
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(idToken.Nonce), []byte(tx.Nonce)) != 1 {
|
||||
slog.Warn("api: oidc nonce mismatch")
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc")
|
||||
return
|
||||
}
|
||||
|
||||
var claims struct {
|
||||
Email string `json:"email"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
Name string `json:"name"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
}
|
||||
if err := idToken.Claims(&claims); err != nil {
|
||||
slog.Error("api: oidc claims decode failed", "error", err)
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc")
|
||||
return
|
||||
}
|
||||
name := claims.Name
|
||||
if name == "" {
|
||||
name = claims.PreferredUsername
|
||||
}
|
||||
|
||||
// Issuer/Subject come from the *verified* token, not raw claims.
|
||||
user, err := h.svc.LoginOIDC(ctx, service.OIDCIdentity{
|
||||
Issuer: idToken.Issuer,
|
||||
Subject: idToken.Subject,
|
||||
Email: claims.Email,
|
||||
EmailVerified: claims.EmailVerified,
|
||||
Name: name,
|
||||
})
|
||||
if err != nil {
|
||||
slog.Warn("api: oidc provisioning failed", "error", err)
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.startSession(c, user.ID); err != nil {
|
||||
slog.Error("api: oidc session start failed", "user_id", user.ID, "error", err)
|
||||
c.Redirect(http.StatusFound, "/login?error=oidc")
|
||||
return
|
||||
}
|
||||
c.Redirect(http.StatusFound, "/gardens")
|
||||
}
|
||||
|
||||
// setOIDCTxCookie writes the login transaction as a compact base64 JSON cookie.
|
||||
func (h *handlers) setOIDCTxCookie(c *gin.Context, tx oidcTx) {
|
||||
b, err := json.Marshal(tx)
|
||||
if err != nil {
|
||||
// tx holds only our own generated strings, so this cannot fail in practice.
|
||||
slog.Error("api: marshal oidc tx", "error", err)
|
||||
return
|
||||
}
|
||||
value := base64.RawURLEncoding.EncodeToString(b)
|
||||
// SameSite=Lax so the cookie survives the IdP's top-level redirect back to the
|
||||
// callback (Strict would drop it on that cross-site navigation).
|
||||
c.SetSameSite(http.SameSiteLaxMode)
|
||||
c.SetCookie(oidcTxCookie, value, int(oidcTxMaxAge.Seconds()), "/", "", h.cookieSecure(), true)
|
||||
}
|
||||
|
||||
func (h *handlers) readOIDCTxCookie(c *gin.Context) (oidcTx, bool) {
|
||||
value, err := c.Cookie(oidcTxCookie)
|
||||
if err != nil || value == "" {
|
||||
return oidcTx{}, false
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(value)
|
||||
if err != nil {
|
||||
return oidcTx{}, false
|
||||
}
|
||||
var tx oidcTx
|
||||
if err := json.Unmarshal(raw, &tx); err != nil || tx.State == "" || tx.Verifier == "" {
|
||||
return oidcTx{}, false
|
||||
}
|
||||
return tx, true
|
||||
}
|
||||
|
||||
func (h *handlers) clearOIDCTxCookie(c *gin.Context) {
|
||||
c.SetSameSite(http.SameSiteLaxMode)
|
||||
c.SetCookie(oidcTxCookie, "", -1, "/", "", h.cookieSecure(), true)
|
||||
}
|
||||
|
||||
// randToken returns 32 bytes of URL-safe randomness for state/nonce values.
|
||||
func randToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/config"
|
||||
)
|
||||
|
||||
// fakeIssuer stands up a minimal OIDC discovery endpoint so oidcClient.ensure
|
||||
// succeeds without a real IdP. It only needs to serve the discovery document for
|
||||
// the login-initiation and route tests; token exchange is covered by the
|
||||
// service-layer provisioning tests and manual Authentik verification.
|
||||
func fakeIssuer(t *testing.T) string {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
var issuer string
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"issuer": issuer,
|
||||
"authorization_endpoint": issuer + "/authorize",
|
||||
"token_endpoint": issuer + "/token",
|
||||
"jwks_uri": issuer + "/jwks",
|
||||
})
|
||||
})
|
||||
ts := httptest.NewServer(mux)
|
||||
t.Cleanup(ts.Close)
|
||||
issuer = ts.URL
|
||||
return issuer
|
||||
}
|
||||
|
||||
func oidcCfg(t *testing.T) *config.Config {
|
||||
cfg := localCfg()
|
||||
cfg.BaseURL = "https://pansy.example.com"
|
||||
cfg.OIDC = config.OIDCConfig{Issuer: fakeIssuer(t), ClientID: "pansy-client", ButtonLabel: "Sign in with Authentik"}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func TestOIDCRoutesAbsentWhenUnconfigured(t *testing.T) {
|
||||
r := authEngine(t, localCfg()) // no OIDC
|
||||
for _, path := range []string{"/api/v1/auth/oidc/login", "/api/v1/auth/oidc/callback"} {
|
||||
w := doJSON(t, r, http.MethodGet, path, nil, nil)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("GET %s status = %d, want 404 when OIDC unconfigured", path, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvidersReportsOIDCWhenConfigured(t *testing.T) {
|
||||
r := authEngine(t, oidcCfg(t))
|
||||
w := doJSON(t, r, http.MethodGet, "/api/v1/auth/providers", nil, nil)
|
||||
var got struct {
|
||||
Local bool `json:"local"`
|
||||
OIDC bool `json:"oidc"`
|
||||
OIDCLabel string `json:"oidcLabel"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode providers: %v", err)
|
||||
}
|
||||
if !got.OIDC || got.OIDCLabel != "Sign in with Authentik" {
|
||||
t.Errorf("providers = %+v, want oidc=true with Authentik label", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCLoginRedirectsToProviderWithPKCE(t *testing.T) {
|
||||
r := authEngine(t, oidcCfg(t))
|
||||
w := doJSON(t, r, http.MethodGet, "/api/v1/auth/oidc/login", nil, nil)
|
||||
if w.Code != http.StatusFound {
|
||||
t.Fatalf("oidc login status = %d, want 302 (body %s)", w.Code, w.Body.String())
|
||||
}
|
||||
loc := w.Header().Get("Location")
|
||||
for _, want := range []string{"/authorize?", "code_challenge=", "code_challenge_method=S256", "state=", "nonce="} {
|
||||
if !strings.Contains(loc, want) {
|
||||
t.Errorf("auth redirect %q missing %q", loc, want)
|
||||
}
|
||||
}
|
||||
// The transaction cookie must be set so the callback can validate state.
|
||||
var haveTx bool
|
||||
for _, ck := range w.Result().Cookies() {
|
||||
if ck.Name == oidcTxCookie {
|
||||
haveTx = ck.HttpOnly && ck.Value != ""
|
||||
}
|
||||
}
|
||||
if !haveTx {
|
||||
t.Error("expected an HttpOnly pansy_oidc_tx cookie to be set")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCCallbackWithoutTransactionRejected(t *testing.T) {
|
||||
r := authEngine(t, oidcCfg(t))
|
||||
// No tx cookie → state can't be validated → redirect to login with error=state.
|
||||
w := doJSON(t, r, http.MethodGet, "/api/v1/auth/oidc/callback?state=abc&code=xyz", nil, nil)
|
||||
if w.Code != http.StatusFound {
|
||||
t.Fatalf("callback status = %d, want 302", w.Code)
|
||||
}
|
||||
if loc := w.Header().Get("Location"); !strings.Contains(loc, "error=state") {
|
||||
t.Errorf("callback redirect = %q, want error=state", loc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCCallbackProviderErrorRedirects(t *testing.T) {
|
||||
r := authEngine(t, oidcCfg(t))
|
||||
w := doJSON(t, r, http.MethodGet, "/api/v1/auth/oidc/callback?error=access_denied", nil, nil)
|
||||
if w.Code != http.StatusFound {
|
||||
t.Fatalf("callback status = %d, want 302", w.Code)
|
||||
}
|
||||
if loc := w.Header().Get("Location"); !strings.Contains(loc, "error=oidc") {
|
||||
t.Errorf("callback redirect = %q, want error=oidc", loc)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user