Files
2026-08-06 18:26:45 +12:00

154 lines
4.2 KiB
Go

// Package auth implements the OIDC authorization-code login flow and the
// app's own JWT session cookie that replaces the OIDC tokens after login.
package auth
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net/http"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
const (
stateCookieName = "oidc_state"
verifierCookieName = "oidc_verifier"
oidcCookieTTL = 5 * time.Minute
)
// OIDCClaims is the subset of ID token claims we care about.
type OIDCClaims struct {
Sub string `json:"sub"`
Email string `json:"email"`
Name string `json:"name"`
}
// Authenticator wraps the discovered OIDC provider + oauth2 config for the
// authorization-code flow.
type Authenticator struct {
provider *oidc.Provider
verifier *oidc.IDTokenVerifier
oauthConfig oauth2.Config
// secureCookies controls the Secure flag on the short-lived login
// cookies; false only makes sense for local http:// development.
secureCookies bool
}
func NewAuthenticator(ctx context.Context, issuerURL, clientID, clientSecret, redirectURL string, secureCookies bool) (*Authenticator, error) {
provider, err := oidc.NewProvider(ctx, issuerURL)
if err != nil {
return nil, fmt.Errorf("discover oidc provider: %w", err)
}
return &Authenticator{
provider: provider,
verifier: provider.Verifier(&oidc.Config{ClientID: clientID}),
oauthConfig: oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
},
secureCookies: secureCookies,
}, nil
}
// BeginLogin generates state + a PKCE verifier, stashes both in short-lived
// cookies, and redirects the browser to the provider's authorize endpoint.
func (a *Authenticator) BeginLogin(w http.ResponseWriter, r *http.Request) {
state := randomToken()
verifier := oauth2.GenerateVerifier()
setShortLivedCookie(w, stateCookieName, state, a.secureCookies)
setShortLivedCookie(w, verifierCookieName, verifier, a.secureCookies)
authURL := a.oauthConfig.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier))
http.Redirect(w, r, authURL, http.StatusFound)
}
// HandleCallback validates state, exchanges the code for tokens, and returns
// the verified ID token claims. It also clears the short-lived cookies.
func (a *Authenticator) HandleCallback(ctx context.Context, w http.ResponseWriter, r *http.Request) (*OIDCClaims, error) {
defer clearCookie(w, stateCookieName)
defer clearCookie(w, verifierCookieName)
stateCookie, err := r.Cookie(stateCookieName)
if err != nil {
return nil, errors.New("missing state cookie")
}
verifierCookie, err := r.Cookie(verifierCookieName)
if err != nil {
return nil, errors.New("missing verifier cookie")
}
if r.URL.Query().Get("state") != stateCookie.Value {
return nil, errors.New("state mismatch")
}
code := r.URL.Query().Get("code")
if code == "" {
return nil, errors.New("missing code")
}
token, err := a.oauthConfig.Exchange(ctx, code, oauth2.VerifierOption(verifierCookie.Value))
if err != nil {
return nil, fmt.Errorf("exchange code: %w", err)
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
return nil, errors.New("no id_token in token response")
}
idToken, err := a.verifier.Verify(ctx, rawIDToken)
if err != nil {
return nil, fmt.Errorf("verify id_token: %w", err)
}
var claims OIDCClaims
if err := idToken.Claims(&claims); err != nil {
return nil, fmt.Errorf("parse id_token claims: %w", err)
}
if claims.Sub == "" {
return nil, errors.New("id_token missing sub")
}
return &claims, nil
}
func randomToken() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
panic(err) // crypto/rand failing is unrecoverable
}
return base64.RawURLEncoding.EncodeToString(b)
}
func setShortLivedCookie(w http.ResponseWriter, name, value string, secure bool) {
http.SetCookie(w, &http.Cookie{
Name: name,
Value: value,
Path: "/",
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteLaxMode,
MaxAge: int(oidcCookieTTL.Seconds()),
})
}
func clearCookie(w http.ResponseWriter, name string) {
http.SetCookie(w, &http.Cookie{
Name: name,
Value: "",
Path: "/",
HttpOnly: true,
MaxAge: -1,
})
}