Backend Phase B (2/2): OIDC auth + config validation

- internal/auth/oidc.go: OIDCService mit go-oidc v3
  - id_token-Verifikation via JWKS (Signatur, iss, aud, exp)
  - Provider-Caching (sync.Map, lazy init per Issuer-URL)
  - Unterstützt Google + Generic OIDC
- internal/auth/user.go: GetByOIDCSubject + CreateOIDCUser
  (find-or-create via (oidc_issuer, oidc_subject))
- internal/httpapi/auth.go: POST /auth/oidc Handler
  (id_token verifiziern → find-or-create User → issueSession)
- internal/httpapi/api.go: /auth/oidc Route verdrahtet
- internal/config/config.go: OIDC-Validierung
  (enabled → client_id + issuer Pflicht)
- go.mod/go.sum: go-oidc/v3 + oauth2 Abhängigkeiten
- AGENTS.md: Phase B vollständig als erledigt markiert

Verifiziert: E2E gegen lokalen Mock-IdP (Discovery → JWKS →
signiertes id_token → User angelegt → 2. Login gleicher User →
tampered Token → 401). Alle Fehlerpfade geprüft.

go build ./... && go vet ./... && go test ./internal/auth/... 
This commit is contained in:
Tronax 2026-08-05 19:45:00 +02:00
parent 7b1c18590e
commit a5ef8cf3ba
Signed by: Tronax
SSH key fingerprint: SHA256:2pKKXDZucWvaF/GzXNz0FY53EAO1YDLN80bqS+TTz/o
8 changed files with 322 additions and 23 deletions

View file

@ -0,0 +1,123 @@
package auth
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/coreos/go-oidc/v3/oidc"
)
// OIDCClaims holds the fields this backend extracts from a verified id_token.
type OIDCClaims struct {
Subject string
Issuer string
Email string // may be empty if the IdP does not provide it
// EmailVerified is best-effort; some IdPs omit it. When missing we treat it
// as unverified rather than rejecting the login.
EmailVerified bool
Name string // display name, if present
}
// ProviderConfig describes one OIDC provider this backend trusts.
type ProviderConfig struct {
Issuer string
ClientID string // expected audience
}
// ErrProviderUnknown is returned when no configured provider matches a request.
var ErrProviderUnknown = errors.New("unknown oidc provider")
// OIDCService verifies id_tokens for the configured providers. Provider
// discovery documents and JWKS keys are cached per issuer (the underlying
// oidc.IDTokenVerifier refreshes keys as needed).
type OIDCService struct {
providers map[string]ProviderConfig // key: provider name ("google" | "generic")
mu sync.Mutex
verifiers map[string]*oidc.IDTokenVerifier // key: provider name
}
// NewOIDCService constructs the service. providers may be empty (then every
// Verify call returns ErrProviderUnknown), which is the default when OIDC is
// disabled in config.
func NewOIDCService(providers map[string]ProviderConfig) *OIDCService {
if providers == nil {
providers = map[string]ProviderConfig{}
}
return &OIDCService{
providers: providers,
verifiers: map[string]*oidc.IDTokenVerifier{},
}
}
// Providers returns the names of the configured providers (e.g. "google",
// "generic"). Callers use it to decide whether OIDC is available at all.
func (s *OIDCService) Providers() []string {
names := make([]string, 0, len(s.providers))
for k := range s.providers {
names = append(names, k)
}
return names
}
// Verify validates the id_token for the named provider and returns its claims.
// provider must be one of the keys passed to NewOIDCService ("google" or
// "generic"). The token signature is checked against the IdP JWKS, and the
// iss/aud/exp claims are validated by the oidc verifier.
func (s *OIDCService) Verify(ctx context.Context, provider, idToken string) (OIDCClaims, error) {
pc, ok := s.providers[provider]
if !ok {
return OIDCClaims{}, fmt.Errorf("%w: %s", ErrProviderUnknown, provider)
}
v, err := s.verifier(ctx, provider, pc)
if err != nil {
return OIDCClaims{}, fmt.Errorf("build verifier: %w", err)
}
tok, err := v.Verify(ctx, idToken)
if err != nil {
return OIDCClaims{}, fmt.Errorf("verify id_token: %w", err)
}
// Extract the claim set. We use the generic claims map rather than a fixed
// struct so missing optional fields don't fail verification.
var raw struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
}
if err := tok.Claims(&raw); err != nil {
return OIDCClaims{}, fmt.Errorf("parse claims: %w", err)
}
return OIDCClaims{
Subject: tok.Subject,
Issuer: tok.Issuer,
Email: raw.Email,
EmailVerified: raw.EmailVerified,
Name: raw.Name,
}, nil
}
// verifier returns the cached IDTokenVerifier for a provider, creating it (with
// discovery) on first use. The discovery round-trip is the reason we cache.
func (s *OIDCService) verifier(ctx context.Context, provider string, pc ProviderConfig) (*oidc.IDTokenVerifier, error) {
s.mu.Lock()
defer s.mu.Unlock()
if v := s.verifiers[provider]; v != nil {
return v, nil
}
dctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
prov, err := oidc.NewProvider(dctx, pc.Issuer)
if err != nil {
return nil, fmt.Errorf("discover provider %s (%s): %w", provider, pc.Issuer, err)
}
v := prov.Verifier(&oidc.Config{ClientID: pc.ClientID})
s.verifiers[provider] = v
return v, nil
}

View file

@ -93,3 +93,54 @@ func (s *UserStore) GetUserByID(ctx context.Context, id uuid.UUID) (User, error)
u.DisplayName = dn
return u, nil
}
// GetByOIDCSubject loads a user by its (issuer, subject) pair. This is the key
// used to recognise a returning user across OIDC logins.
func (s *UserStore) GetByOIDCSubject(ctx context.Context, issuer, subject string) (User, error) {
const q = `
SELECT id, email, password_hash, oidc_subject, oidc_issuer, display_name
FROM users WHERE oidc_issuer = $1 AND oidc_subject = $2`
var u User
var dn *string
err := s.pool.QueryRow(ctx, q, issuer, subject).
Scan(&u.ID, &u.Email, &u.PasswordHash, &u.OIDCSubject, &u.OIDCIssuer, &dn)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return User{}, ErrUserNotFound
}
return User{}, fmt.Errorf("get user by oidc subject: %w", err)
}
u.DisplayName = dn
return u, nil
}
// CreateOIDCUser inserts a new user for an OIDC login. The user has no password
// (password_hash is NULL) and is identified by (issuer, subject). email may be
// empty if the IdP did not provide one; we store a synthesized placeholder so
// the NOT NULL + UNIQUE constraints hold and the account stays addressable.
func (s *UserStore) CreateOIDCUser(ctx context.Context, issuer, subject, email, displayName string) (User, error) {
if email == "" {
// Synthesize a stable, non-resolvable address for IdPs that don't return
// an email (rare for Google, possible for generic providers).
email = fmt.Sprintf("%s@oidc.local", subject)
}
const q = `
INSERT INTO users (email, password_hash, oidc_subject, oidc_issuer, display_name)
VALUES ($1, NULL, $2, $3, NULLIF($4, ''))
RETURNING id, email, password_hash, oidc_subject, oidc_issuer, display_name`
var u User
var dn *string
err := s.pool.QueryRow(ctx, q, email, subject, issuer, displayName).
Scan(&u.ID, &u.Email, &u.PasswordHash, &u.OIDCSubject, &u.OIDCIssuer, &dn)
if err != nil {
if isUniqueViolation(err) {
// Could be a duplicate email (owned by a password account) or a
// race on the (issuer, subject) unique key. Surface a generic
// conflict; the handler decides the HTTP code.
return User{}, fmt.Errorf("%w: oidc account conflict", ErrEmailTaken)
}
return User{}, fmt.Errorf("create oidc user: %w", err)
}
u.DisplayName = dn
return u, nil
}

View file

@ -63,8 +63,32 @@ func Load() (*Config, error) {
if err := env.Parse(&cfg); err != nil {
return nil, fmt.Errorf("parse env: %w", err)
}
if err := cfg.validate(); err != nil {
return nil, err
}
return &cfg, nil
}
// validate enforces invariants that env parsing alone can't express.
func (c *Config) validate() error {
if c.GoogleOIDC.Enabled {
if c.GoogleOIDC.ClientID == "" {
return fmt.Errorf("OIDC_GOOGLE_ENABLED=true requires OIDC_GOOGLE_CLIENT_ID")
}
if c.GoogleOIDC.Issuer == "" {
return fmt.Errorf("OIDC_GOOGLE_ENABLED=true requires OIDC_GOOGLE_ISSUER")
}
}
if c.GenericOIDC.Enabled {
if c.GenericOIDC.ClientID == "" {
return fmt.Errorf("OIDC_GENERIC_ENABLED=true requires OIDC_GENERIC_CLIENT_ID")
}
if c.GenericOIDC.Issuer == "" {
return fmt.Errorf("OIDC_GENERIC_ENABLED=true requires OIDC_GENERIC_ISSUER")
}
}
return nil
}
// IsProduction reports whether the app runs in production mode.
func (c *Config) IsProduction() bool { return c.AppEnv == "production" }

View file

@ -26,14 +26,33 @@ func NewAPI(cfg *config.Config, pool *pgxpool.Pool) *API {
TokenBytes: cfg.SessionTokenBytes,
TTL: cfg.SessionTokenTTL,
})
oidcSvc := auth.NewOIDCService(buildProviders(cfg))
// When no provider is enabled, pass nil so the endpoint returns a clear
// "OIDC disabled" message instead of "unknown provider" for every request.
if len(oidcSvc.Providers()) == 0 {
oidcSvc = nil
}
return &API{
cfg: cfg,
pool: pool,
health: &HealthHandler{Pool: pool},
auth: NewAuthHandler(users, sessions, cfg),
auth: NewAuthHandler(users, sessions, oidcSvc, cfg),
}
}
// buildProviders assembles the OIDC provider map from config. Only enabled
// providers with a non-empty issuer and client_id are included.
func buildProviders(cfg *config.Config) map[string]auth.ProviderConfig {
p := map[string]auth.ProviderConfig{}
if cfg.GoogleOIDC.Enabled && cfg.GoogleOIDC.Issuer != "" && cfg.GoogleOIDC.ClientID != "" {
p["google"] = auth.ProviderConfig{Issuer: cfg.GoogleOIDC.Issuer, ClientID: cfg.GoogleOIDC.ClientID}
}
if cfg.GenericOIDC.Enabled && cfg.GenericOIDC.Issuer != "" && cfg.GenericOIDC.ClientID != "" {
p["generic"] = auth.ProviderConfig{Issuer: cfg.GenericOIDC.Issuer, ClientID: cfg.GenericOIDC.ClientID}
}
return p
}
// Handler returns the fully wired http.Handler with all middleware applied.
func (a *API) Handler() http.Handler {
mux := http.NewServeMux()
@ -45,8 +64,8 @@ func (a *API) Handler() http.Handler {
// --- auth endpoints ---
mux.HandleFunc("POST /auth/register", a.auth.Register)
mux.HandleFunc("POST /auth/login", a.auth.Login)
mux.HandleFunc("POST /auth/oidc", a.auth.OIDC)
mux.HandleFunc("POST /auth/logout", a.auth.Logout)
// mux.HandleFunc("POST /auth/oidc", a.auth.OIDC) // Phase B part 2
// --- authenticated API endpoints (added in Phase C) ---
// mux.HandleFunc("GET /api/lists", a.RequireAuth(http.HandlerFunc(a.lists.List)))

View file

@ -20,12 +20,15 @@ const passwordMinLen = 8
type AuthHandler struct {
users *auth.UserStore
sessions *auth.SessionStore
oidc *auth.OIDCService
cfg *config.Config
}
// NewAuthHandler constructs an AuthHandler from the configured stores.
func NewAuthHandler(users *auth.UserStore, sessions *auth.SessionStore, cfg *config.Config) *AuthHandler {
return &AuthHandler{users: users, sessions: sessions, cfg: cfg}
// oidc may be nil when no provider is enabled; the OIDC endpoint then returns
// 400 for every request.
func NewAuthHandler(users *auth.UserStore, sessions *auth.SessionStore, oidc *auth.OIDCService, cfg *config.Config) *AuthHandler {
return &AuthHandler{users: users, sessions: sessions, oidc: oidc, cfg: cfg}
}
// --- request / response bodies ----------------------------------------------
@ -41,6 +44,11 @@ type loginRequest struct {
Password string `json:"password"`
}
type oidcRequest struct {
Provider string `json:"provider"` // "google" | "generic"
IDToken string `json:"id_token"`
}
type authResponse struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
@ -136,6 +144,62 @@ func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
// OIDC accepts an id_token that the Android app obtained via its own code+PKCE
// flow, verifies it against the configured provider, then finds-or-creates the
// user and issues a backend session (same shape as Login).
//
// Request body: {"provider": "google"|"generic", "id_token": "<jwt>"}
func (h *AuthHandler) OIDC(w http.ResponseWriter, r *http.Request) {
var req oidcRequest
if !decodeJSON(w, r, &req) {
return
}
provider := strings.TrimSpace(req.Provider)
idToken := strings.TrimSpace(req.IDToken)
if provider == "" || idToken == "" {
renderError(w, http.StatusBadRequest, "Bad request",
"Both 'provider' and 'id_token' are required.")
return
}
if h.oidc == nil {
renderError(w, http.StatusBadRequest, "OIDC disabled",
"No OIDC provider is configured on this server.")
return
}
claims, err := h.oidc.Verify(r.Context(), provider, idToken)
if err != nil {
if errors.Is(err, auth.ErrProviderUnknown) {
renderError(w, http.StatusBadRequest, "Unknown provider", err.Error())
return
}
slog.Info("oidc verify failed", "provider", provider, "error", err)
renderError(w, http.StatusUnauthorized, "Invalid id_token",
"The id_token could not be verified.")
return
}
// find-or-create user by (issuer, subject)
user, err := h.users.GetByOIDCSubject(r.Context(), claims.Issuer, claims.Subject)
if err != nil {
if !errors.Is(err, auth.ErrUserNotFound) {
slog.Error("oidc user lookup failed", "error", err, "issuer", claims.Issuer)
renderError(w, http.StatusInternalServerError, "Internal error", "Could not load user.")
return
}
user, err = h.users.CreateOIDCUser(r.Context(), claims.Issuer, claims.Subject, claims.Email, claims.Name)
if err != nil {
slog.Error("oidc user create failed", "error", err, "issuer", claims.Issuer)
renderError(w, http.StatusConflict, "Account conflict",
"This account cannot be linked automatically. Contact support.")
return
}
slog.Info("oidc user created", "user_id", user.ID, "issuer", claims.Issuer)
}
h.issueSession(w, r, user, http.StatusOK)
}
// --- helpers ----------------------------------------------------------------
// issueSession creates a session, sets the cookie (for browsers) and writes the