Files
Sebastian UnterschützandClaude Opus 5.5 9ad5f29f1b feat(sso): add openid connect client with pkce and guarded discovery
Issuer URLs come from customers, so requests to their IdPs refuse
non-public addresses unless private networks are explicitly allowed.

Refs #4

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 00:30:43 +01:00

167 lines
5.0 KiB
Go

// Package ssotest provides a minimal OpenID Connect provider for tests.
package ssotest
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
)
// User is the identity the IDP asserts for the next login.
type User struct {
Subject string
Email string
EmailVerified bool
Name string
}
// IDP is an in-memory authorization server. It signs ID tokens with a fresh
// RSA key and enforces PKCE.
type IDP struct {
Server *httptest.Server
ClientID string
Secret string
key *rsa.PrivateKey
signer jose.Signer
mu sync.Mutex
user User
codes map[string]grant
// NonceOverride, when set, replaces the nonce in issued tokens.
NonceOverride string
// AudienceOverride, when set, replaces the audience in issued tokens.
AudienceOverride string
}
type grant struct {
nonce, challenge, redirect string
user User
}
// New starts an IDP that is shut down when t ends.
func New(t *testing.T) *IDP {
t.Helper()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: jose.JSONWebKey{Key: key, KeyID: "k1"}}, nil)
if err != nil {
t.Fatal(err)
}
idp := &IDP{ClientID: "client-1", Secret: "secret-1", key: key, signer: signer, codes: map[string]grant{}}
mux := http.NewServeMux()
mux.HandleFunc("GET /.well-known/openid-configuration", idp.discovery)
mux.HandleFunc("GET /keys", idp.keys)
mux.HandleFunc("GET /authorize", idp.authorize)
mux.HandleFunc("POST /token", idp.token)
idp.Server = httptest.NewServer(mux)
t.Cleanup(idp.Server.Close)
return idp
}
// Issuer is the issuer URL to configure.
func (i *IDP) Issuer() string { return i.Server.URL }
// SetUser selects who the next authorization asserts.
func (i *IDP) SetUser(u User) {
i.mu.Lock()
defer i.mu.Unlock()
i.user = u
}
func (i *IDP) discovery(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, map[string]any{
"issuer": i.Issuer(),
"authorization_endpoint": i.Issuer() + "/authorize",
"token_endpoint": i.Issuer() + "/token",
"jwks_uri": i.Issuer() + "/keys",
"response_types_supported": []string{"code"},
"subject_types_supported": []string{"public"},
"id_token_signing_alg_values_supported": []string{"RS256"},
})
}
func (i *IDP) keys(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &i.key.PublicKey, KeyID: "k1", Algorithm: "RS256", Use: "sig"}}})
}
// authorize skips the login screen and immediately redirects back with a code.
func (i *IDP) authorize(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if q.Get("client_id") != i.ClientID || q.Get("code_challenge_method") != "S256" {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
code := rand.Text()
i.mu.Lock()
i.codes[code] = grant{nonce: q.Get("nonce"), challenge: q.Get("code_challenge"), redirect: q.Get("redirect_uri"), user: i.user}
i.mu.Unlock()
back, _ := url.Parse(q.Get("redirect_uri"))
v := back.Query()
v.Set("code", code)
v.Set("state", q.Get("state"))
back.RawQuery = v.Encode()
http.Redirect(w, r, back.String(), http.StatusFound)
}
func (i *IDP) token(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "bad form", http.StatusBadRequest)
return
}
id, secret, ok := r.BasicAuth()
if !ok {
id, secret = r.PostForm.Get("client_id"), r.PostForm.Get("client_secret")
}
if id != i.ClientID || secret != i.Secret {
http.Error(w, `{"error":"invalid_client"}`, http.StatusUnauthorized)
return
}
i.mu.Lock()
g, ok := i.codes[r.PostForm.Get("code")]
delete(i.codes, r.PostForm.Get("code"))
i.mu.Unlock()
sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier")))
if !ok || base64.RawURLEncoding.EncodeToString(sum[:]) != g.challenge || r.PostForm.Get("redirect_uri") != g.redirect {
http.Error(w, `{"error":"invalid_grant"}`, http.StatusBadRequest)
return
}
nonce, aud := g.nonce, i.ClientID
if i.NonceOverride != "" {
nonce = i.NonceOverride
}
if i.AudienceOverride != "" {
aud = i.AudienceOverride
}
now := time.Now()
claims := map[string]any{
"iss": i.Issuer(), "sub": g.user.Subject, "aud": aud, "nonce": nonce,
"iat": now.Unix(), "exp": now.Add(5 * time.Minute).Unix(),
"email": g.user.Email, "email_verified": g.user.EmailVerified, "name": g.user.Name,
}
raw, err := jwt.Signed(i.signer).Claims(claims).Serialize()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, map[string]any{"access_token": "at", "token_type": "Bearer", "expires_in": 300, "id_token": raw})
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}