IAM-13: oidc-provider-fuer-drittanwendungen (client-registrierung, authorization-code-flow, jwks ueber API-05-schluessel)
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// AuthCodeTTL folgt RFC 6749 Empfehlung: Authorization Codes sind extrem
|
||||
// kurzlebig, der Client tauscht sie sofort gegen ein Token.
|
||||
const AuthCodeTTL = 60 * time.Second
|
||||
|
||||
var ErrInvalidAuthCode = errors.New("oidc: ungueltiger, abgelaufener oder bereits verwendeter authorization code")
|
||||
|
||||
// AuthCodeData ist das Ergebnis eines eingeloesten Authorization Codes.
|
||||
type AuthCodeData struct {
|
||||
ClientID string
|
||||
UserID string
|
||||
RedirectURI string
|
||||
Scopes []string
|
||||
}
|
||||
|
||||
// AuthCodeStore verwaltet Authorization Codes innerhalb GENAU EINER Tenant-Datenbank.
|
||||
type AuthCodeStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAuthCodeStore(pool *pgxpool.Pool) *AuthCodeStore {
|
||||
return &AuthCodeStore{pool: pool}
|
||||
}
|
||||
|
||||
// Issue erzeugt einen neuen Authorization Code (Akzeptanzkriterium 2, Schritt
|
||||
// 1 des Flows) — gespeichert wird nur der Hash, das Klartext-Code wird per
|
||||
// Redirect an den Client uebertragen (Standard-OAuth2-Verhalten, der Code
|
||||
// selbst ist einmalig und kurzlebig genug, dass die Redirect-URL kein
|
||||
// nennenswertes Risiko darstellt).
|
||||
func (s *AuthCodeStore) Issue(ctx context.Context, clientID, userID, redirectURI string, scopes []string) (code string, err error) {
|
||||
code, err = randomToken(32)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("code erzeugen: %w", err)
|
||||
}
|
||||
hash := hashSecret(code)
|
||||
expiresAt := time.Now().Add(AuthCodeTTL)
|
||||
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
INSERT INTO oidc_auth_codes (code_hash, client_id, user_id, redirect_uri, scopes, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
`, hash, clientID, userID, redirectURI, scopes, expiresAt)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("code speichern: %w", err)
|
||||
}
|
||||
return code, nil
|
||||
}
|
||||
|
||||
// Consume loest einen Authorization Code genau einmal ein (Akzeptanzkriterium
|
||||
// 2, Schritt 2 des Flows) — atomar ueber die WHERE-Klausel (used_at IS NULL
|
||||
// AND expires_at > now()), gleiches Muster wie internal/authtoken (IAM-03).
|
||||
func (s *AuthCodeStore) Consume(ctx context.Context, code, clientID, redirectURI string) (AuthCodeData, error) {
|
||||
hash := hashSecret(code)
|
||||
|
||||
var data AuthCodeData
|
||||
var storedClientID, storedRedirectURI string
|
||||
row := s.pool.QueryRow(ctx, `
|
||||
UPDATE oidc_auth_codes
|
||||
SET used_at = now()
|
||||
WHERE code_hash = $1 AND used_at IS NULL AND expires_at > now()
|
||||
RETURNING client_id, user_id, redirect_uri, scopes
|
||||
`, hash)
|
||||
|
||||
if err := row.Scan(&storedClientID, &data.UserID, &storedRedirectURI, &data.Scopes); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return AuthCodeData{}, ErrInvalidAuthCode
|
||||
}
|
||||
return AuthCodeData{}, fmt.Errorf("code einloesen: %w", err)
|
||||
}
|
||||
|
||||
// client_id und redirect_uri muessen exakt zu denen des urspruenglichen
|
||||
// Authorize-Aufrufs passen (RFC 6749 4.1.3) — sonst koennte ein Code, der
|
||||
// fuer Client A ausgestellt wurde, bei Client B eingeloest werden.
|
||||
if storedClientID != clientID || storedRedirectURI != redirectURI {
|
||||
return AuthCodeData{}, ErrInvalidAuthCode
|
||||
}
|
||||
|
||||
data.ClientID = storedClientID
|
||||
data.RedirectURI = storedRedirectURI
|
||||
return data, nil
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Package oidc implementiert Core IAM-13: NEXARCH als OIDC/OAuth2-Provider,
|
||||
// damit Drittanwendungen eines Mandanten sich gegen NEXARCH-Benutzerkonten
|
||||
// authentifizieren koennen. Baut bewusst auf der bestehenden JWKS-
|
||||
// Infrastruktur (internal/moduletrust, API-05) auf statt ein zweites
|
||||
// Schluesselsystem zu bauen — siehe provider.go.
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrClientNotFound = errors.New("oidc: client nicht gefunden")
|
||||
ErrInvalidClientAuth = errors.New("oidc: ungueltige client-authentifizierung")
|
||||
ErrRedirectURINotAllowed = errors.New("oidc: redirect_uri ist fuer diesen client nicht registriert")
|
||||
)
|
||||
|
||||
// Client ist eine bei NEXARCH registrierte Drittanwendung
|
||||
// (Akzeptanzkriterium 1). AllowedScopes begrenzt, welche Scopes ein Token
|
||||
// fuer diesen Client tragen darf — unabhaengig davon, was beim Authorize-
|
||||
// Aufruf angefragt wird (Akzeptanzkriterium 3 / Pruefung 3).
|
||||
type Client struct {
|
||||
ID string
|
||||
Name string
|
||||
ClientID string
|
||||
RedirectURIs []string
|
||||
AllowedScopes []string
|
||||
}
|
||||
|
||||
// ClientStore verwaltet OAuth2-Clients innerhalb GENAU EINER Tenant-
|
||||
// Datenbank (gleiches Muster wie internal/user.TenantUserStore, IAM-03).
|
||||
type ClientStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewClientStore(pool *pgxpool.Pool) *ClientStore {
|
||||
return &ClientStore{pool: pool}
|
||||
}
|
||||
|
||||
// Register legt einen neuen OAuth2-Client an (Akzeptanzkriterium 1). Das
|
||||
// Client-Secret wird NUR hier im Klartext zurueckgegeben, gespeichert wird
|
||||
// ausschliesslich dessen SHA-256-Hash — gleiches Muster wie
|
||||
// internal/moduleregistry.Provision (API-02).
|
||||
func (s *ClientStore) Register(ctx context.Context, name string, redirectURIs, allowedScopes []string) (clientID, clientSecret string, err error) {
|
||||
if name == "" {
|
||||
return "", "", errors.New("oidc: name darf nicht leer sein")
|
||||
}
|
||||
if len(redirectURIs) == 0 {
|
||||
return "", "", errors.New("oidc: mindestens eine redirect_uri ist erforderlich")
|
||||
}
|
||||
|
||||
clientID, err = randomToken(16)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("client-id erzeugen: %w", err)
|
||||
}
|
||||
clientSecret, err = randomToken(32)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("client-secret erzeugen: %w", err)
|
||||
}
|
||||
hash := hashSecret(clientSecret)
|
||||
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
INSERT INTO oidc_clients (name, client_id, secret_hash, redirect_uris, allowed_scopes)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, name, clientID, hash, redirectURIs, allowedScopes)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("client speichern: %w", err)
|
||||
}
|
||||
return clientID, clientSecret, nil
|
||||
}
|
||||
|
||||
func (s *ClientStore) getByClientID(ctx context.Context, clientID string) (Client, []byte, error) {
|
||||
var c Client
|
||||
var storedHash []byte
|
||||
row := s.pool.QueryRow(ctx, `
|
||||
SELECT id, name, client_id, redirect_uris, allowed_scopes, secret_hash
|
||||
FROM oidc_clients WHERE client_id = $1
|
||||
`, clientID)
|
||||
if err := row.Scan(&c.ID, &c.Name, &c.ClientID, &c.RedirectURIs, &c.AllowedScopes, &storedHash); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return Client{}, nil, ErrClientNotFound
|
||||
}
|
||||
return Client{}, nil, fmt.Errorf("client laden: %w", err)
|
||||
}
|
||||
return c, storedHash, nil
|
||||
}
|
||||
|
||||
// Get laedt einen Client ohne Secret-Pruefung (fuer den Authorize-Schritt,
|
||||
// der kein Client-Secret kennt — der Browser des Endnutzers, nicht die
|
||||
// Drittanwendung selbst, ruft /oidc/authorize auf).
|
||||
func (s *ClientStore) Get(ctx context.Context, clientID string) (Client, error) {
|
||||
c, _, err := s.getByClientID(ctx, clientID)
|
||||
return c, err
|
||||
}
|
||||
|
||||
// Authenticate prueft Client-ID + Secret timing-safe (Akzeptanzkriterium 2,
|
||||
// Token-Endpunkt) — gleiches Muster wie internal/moduleregistry.Authenticate (API-02).
|
||||
func (s *ClientStore) Authenticate(ctx context.Context, clientID, clientSecret string) (Client, error) {
|
||||
c, storedHash, err := s.getByClientID(ctx, clientID)
|
||||
if err != nil {
|
||||
return Client{}, err
|
||||
}
|
||||
if !timingSafeEqual(hashSecret(clientSecret), storedHash) {
|
||||
return Client{}, ErrInvalidClientAuth
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// ValidateRedirectURI erzwingt exakten Abgleich gegen die registrierte
|
||||
// Liste (kein Praefix-/Wildcard-Match) — Standardhaertung gegen Open-Redirect
|
||||
// im Authorization-Code-Flow.
|
||||
func (c Client) ValidateRedirectURI(redirectURI string) error {
|
||||
for _, allowed := range c.RedirectURIs {
|
||||
if allowed == redirectURI {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrRedirectURINotAllowed
|
||||
}
|
||||
|
||||
// GrantedScopes schraenkt die angefragten Scopes auf das ein, was fuer den
|
||||
// Client tatsaechlich erlaubt ist (Akzeptanzkriterium 3) — nie mehr
|
||||
// gewaehren, als bei der Registrierung zugestanden wurde.
|
||||
func (c Client) GrantedScopes(requested []string) []string {
|
||||
allowed := make(map[string]bool, len(c.AllowedScopes))
|
||||
for _, s := range c.AllowedScopes {
|
||||
allowed[s] = true
|
||||
}
|
||||
var granted []string
|
||||
for _, s := range requested {
|
||||
if allowed[s] {
|
||||
granted = append(granted, s)
|
||||
}
|
||||
}
|
||||
return granted
|
||||
}
|
||||
|
||||
func randomToken(n int) (string, error) {
|
||||
buf := make([]byte, n)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func hashSecret(secret string) []byte {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
// timingSafeEqual folgt demselben Referenzmuster wie internal/moduleregistry
|
||||
// (API-02) — projektweite Konvention aus SICHERHEITSKONZEPT.md / IAM-15.
|
||||
func timingSafeEqual(a, b []byte) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare(a, b) == 1
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"gitea.perlbach24.de/scripte/nexarch/internal/auth"
|
||||
"gitea.perlbach24.de/scripte/nexarch/internal/moduletrust"
|
||||
)
|
||||
|
||||
// IDTokenTTL: kurzlebig wie ein normales Access-Token (Produkt-DNA "so
|
||||
// vertrauenswuerdig wie noetig"), ein Refresh-Flow ist ausdruecklich nicht
|
||||
// Teil dieser Kachel (kleinste Loesung, die die Akzeptanzkriterien erfuellt).
|
||||
const IDTokenTTL = 15 * time.Minute
|
||||
|
||||
// IDTokenClaims sind die vom Client verifizierbaren Angaben ueber den
|
||||
// angemeldeten Benutzer — signiert mit demselben Schluesselmaterial wie
|
||||
// Modul-zu-Modul-Tokens (internal/moduletrust, API-05), aber mit eigener,
|
||||
// OIDC-spezifischer Struktur (aud, scope), da moduletrust.Claims dafuer
|
||||
// nicht vorgesehen ist. Kein zweites Schluesselsystem — nur eine zweite
|
||||
// Claims-Form desselben Signierschluessels.
|
||||
type IDTokenClaims struct {
|
||||
Subject string `json:"sub"`
|
||||
TenantSlug string `json:"tenant"`
|
||||
Scopes []string `json:"scope"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// Handler buendelt die drei OIDC-Endpunkte. issuerURL identifiziert NEXARCH
|
||||
// als Aussteller (iss-Claim, Standard-OIDC-Feld).
|
||||
type Handler struct {
|
||||
clients *ClientStore
|
||||
authCodes *AuthCodeStore
|
||||
keys *moduletrust.KeyManager
|
||||
issuerURL string
|
||||
}
|
||||
|
||||
func NewHandler(clients *ClientStore, authCodes *AuthCodeStore, keys *moduletrust.KeyManager, issuerURL string) *Handler {
|
||||
return &Handler{clients: clients, authCodes: authCodes, keys: keys, issuerURL: issuerURL}
|
||||
}
|
||||
|
||||
type registerClientRequest struct {
|
||||
Name string `json:"name"`
|
||||
RedirectURIs []string `json:"redirect_uris"`
|
||||
AllowedScopes []string `json:"allowed_scopes"`
|
||||
}
|
||||
|
||||
type registerClientResponse struct {
|
||||
ClientID string `json:"client_id"`
|
||||
ClientSecret string `json:"client_secret"`
|
||||
}
|
||||
|
||||
// RegisterClient ist Akzeptanzkriterium 1: eine Drittanwendung wird als
|
||||
// OAuth2-Client registriert. Muss hinter auth.RequireAuth haengen — nur
|
||||
// angemeldete Benutzer des jeweiligen Mandanten duerfen Clients fuer ihren
|
||||
// eigenen Mandanten anlegen (ClientStore ist bereits auf die Tenant-DB des
|
||||
// Aufrufers gebunden, siehe NewHandler-Aufstellung im jeweiligen Modul-Server).
|
||||
func (h *Handler) RegisterClient(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := auth.ClaimsFromContext(r.Context()); !ok {
|
||||
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var req registerClientRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "ungueltiger request-body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
clientID, clientSecret, err := h.clients.Register(r.Context(), req.Name, req.RedirectURIs, req.AllowedScopes)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(registerClientResponse{ClientID: clientID, ClientSecret: clientSecret})
|
||||
}
|
||||
|
||||
// Authorize ist Schritt 1 des Authorization-Code-Flows (Akzeptanzkriterium 2).
|
||||
// Muss hinter auth.RequireAuth haengen — der aufrufende Browser ist bereits
|
||||
// als NEXARCH-Benutzer angemeldet, hier wird nur noch der Client geprueft
|
||||
// und ein Code fuer GENAU DIESEN Benutzer ausgestellt.
|
||||
func (h *Handler) Authorize(w http.ResponseWriter, r *http.Request) {
|
||||
claims, ok := auth.ClaimsFromContext(r.Context())
|
||||
if !ok {
|
||||
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
q := r.URL.Query()
|
||||
if q.Get("response_type") != "code" {
|
||||
http.Error(w, "nur response_type=code wird unterstuetzt", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
clientID := q.Get("client_id")
|
||||
redirectURI := q.Get("redirect_uri")
|
||||
state := q.Get("state")
|
||||
requestedScopes := splitScopes(q.Get("scope"))
|
||||
|
||||
client, err := h.clients.Get(r.Context(), clientID)
|
||||
if err != nil {
|
||||
http.Error(w, "unbekannter client", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := client.ValidateRedirectURI(redirectURI); err != nil {
|
||||
// Bewusst KEIN Redirect zu einer nicht registrierten redirect_uri —
|
||||
// Open-Redirect-Schutz geht vor Komfort, Fehler wird direkt angezeigt.
|
||||
http.Error(w, "redirect_uri ist fuer diesen client nicht registriert", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
granted := client.GrantedScopes(requestedScopes)
|
||||
|
||||
code, err := h.authCodes.Issue(r.Context(), client.ClientID, claims.UserID, redirectURI, granted)
|
||||
if err != nil {
|
||||
http.Error(w, "code konnte nicht ausgestellt werden", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
target, err := url.Parse(redirectURI)
|
||||
if err != nil {
|
||||
http.Error(w, "ungueltige redirect_uri", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
values := target.Query()
|
||||
values.Set("code", code)
|
||||
if state != "" {
|
||||
values.Set("state", state)
|
||||
}
|
||||
target.RawQuery = values.Encode()
|
||||
|
||||
http.Redirect(w, r, target.String(), http.StatusFound)
|
||||
}
|
||||
|
||||
// Token ist Schritt 2 des Authorization-Code-Flows (Akzeptanzkriterium 2):
|
||||
// die Drittanwendung tauscht den Code serverseitig gegen ein ID-Token.
|
||||
func (h *Handler) Token(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "ungueltiger request-body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if r.PostForm.Get("grant_type") != "authorization_code" {
|
||||
http.Error(w, "nur grant_type=authorization_code wird unterstuetzt", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
clientID := r.PostForm.Get("client_id")
|
||||
clientSecret := r.PostForm.Get("client_secret")
|
||||
code := r.PostForm.Get("code")
|
||||
redirectURI := r.PostForm.Get("redirect_uri")
|
||||
|
||||
client, err := h.clients.Authenticate(r.Context(), clientID, clientSecret)
|
||||
if err != nil {
|
||||
http.Error(w, "client-authentifizierung fehlgeschlagen", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := h.authCodes.Consume(r.Context(), code, client.ClientID, redirectURI)
|
||||
if err != nil {
|
||||
http.Error(w, "authorization code ungueltig, abgelaufen oder bereits verwendet", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
idToken, err := h.issueIDToken(data)
|
||||
if err != nil {
|
||||
http.Error(w, "token konnte nicht ausgestellt werden", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id_token": idToken,
|
||||
"access_token": idToken, // kein separates Access-Token-Format in dieser Kachel — das ID-Token traegt bereits Subject+Scopes.
|
||||
"token_type": "Bearer",
|
||||
"expires_in": int(IDTokenTTL.Seconds()),
|
||||
"scope": strings.Join(data.Scopes, " "),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) issueIDToken(data AuthCodeData) (string, error) {
|
||||
key, err := h.keys.SigningKey()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
now := time.Now()
|
||||
claims := IDTokenClaims{
|
||||
Subject: data.UserID,
|
||||
Scopes: data.Scopes,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: h.issuerURL,
|
||||
Audience: jwt.ClaimStrings{data.ClientID},
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(IDTokenTTL)),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims)
|
||||
token.Header["kid"] = key.KID
|
||||
return token.SignedString(key.Private)
|
||||
}
|
||||
|
||||
// jwk / jwkSet folgen RFC 8037 (Ed25519 als OKP-Schluesseltyp) — im
|
||||
// Unterschied zu moduletrust.ServeJWKS (internes, vereinfachtes Format fuer
|
||||
// Modul-zu-Modul-Kommunikation) muss dieser Endpunkt von generischen,
|
||||
// standardkonformen OIDC-Client-Bibliotheken Dritter lesbar sein
|
||||
// (Akzeptanzkriterium 3). Beide Endpunkte liefern dieselben Schluessel aus
|
||||
// demselben KeyManager — kein zweites Schluesselsystem, nur ein zweites,
|
||||
// spezifikationskonformes Format desselben Materials.
|
||||
type jwk struct {
|
||||
Kty string `json:"kty"`
|
||||
Crv string `json:"crv"`
|
||||
Kid string `json:"kid"`
|
||||
X string `json:"x"`
|
||||
Use string `json:"use"`
|
||||
Alg string `json:"alg"`
|
||||
}
|
||||
|
||||
type jwkSet struct {
|
||||
Keys []jwk `json:"keys"`
|
||||
}
|
||||
|
||||
func (h *Handler) JWKS(w http.ResponseWriter, r *http.Request) {
|
||||
set := h.keys.PublicKeySet()
|
||||
resp := jwkSet{Keys: make([]jwk, 0, len(set))}
|
||||
for kid, pub := range set {
|
||||
resp.Keys = append(resp.Keys, jwk{
|
||||
Kty: "OKP",
|
||||
Crv: "Ed25519",
|
||||
Kid: kid,
|
||||
X: base64.RawURLEncoding.EncodeToString(pub),
|
||||
Use: "sig",
|
||||
Alg: "EdDSA",
|
||||
})
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
func splitScopes(raw string) []string {
|
||||
if raw == "" {
|
||||
return nil
|
||||
}
|
||||
return strings.Fields(raw)
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.perlbach24.de/scripte/nexarch/internal/auth"
|
||||
"gitea.perlbach24.de/scripte/nexarch/internal/moduletrust"
|
||||
)
|
||||
|
||||
// newProviderTestSetup baut Tenant-DB-Schema (users, oidc_clients,
|
||||
// oidc_auth_codes) direkt gegen TEST_ADMIN_DSN auf, analog zum Muster in
|
||||
// internal/tenant/lifecycle_test.go — braucht kein volles Tenant-Provisioning,
|
||||
// nur eine isolierte Datenbank fuer diesen Testlauf.
|
||||
func newProviderTestSetup(t *testing.T) (*Handler, *pgxpool.Pool, func()) {
|
||||
t.Helper()
|
||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
||||
if adminDSN == "" {
|
||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
pool, err := pgxpool.New(ctx, adminDSN)
|
||||
if err != nil {
|
||||
t.Fatalf("pool: %v", err)
|
||||
}
|
||||
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'active',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS oidc_clients (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL,
|
||||
client_id TEXT NOT NULL UNIQUE,
|
||||
secret_hash BYTEA NOT NULL,
|
||||
redirect_uris TEXT[] NOT NULL,
|
||||
allowed_scopes TEXT[] NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS oidc_auth_codes (
|
||||
code_hash BYTEA PRIMARY KEY,
|
||||
client_id TEXT NOT NULL REFERENCES oidc_clients(client_id),
|
||||
user_id UUID NOT NULL REFERENCES users(id),
|
||||
redirect_uri TEXT NOT NULL,
|
||||
scopes TEXT[] NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
used_at TIMESTAMPTZ
|
||||
);
|
||||
`); err != nil {
|
||||
t.Fatalf("schema: %v", err)
|
||||
}
|
||||
|
||||
keys, err := moduletrust.NewKeyManager()
|
||||
if err != nil {
|
||||
t.Fatalf("keymanager: %v", err)
|
||||
}
|
||||
|
||||
clients := NewClientStore(pool)
|
||||
authCodes := NewAuthCodeStore(pool)
|
||||
handler := NewHandler(clients, authCodes, keys, "https://core.test.nexarch.example")
|
||||
|
||||
cleanup := func() {
|
||||
ctx := context.Background()
|
||||
_, _ = pool.Exec(ctx, `DROP TABLE IF EXISTS oidc_auth_codes, oidc_clients, users CASCADE`)
|
||||
pool.Close()
|
||||
}
|
||||
return handler, pool, cleanup
|
||||
}
|
||||
|
||||
func createTestUser(t *testing.T, pool *pgxpool.Pool, email string) string {
|
||||
t.Helper()
|
||||
var id string
|
||||
err := pool.QueryRow(context.Background(), `
|
||||
INSERT INTO users (email, name) VALUES ($1, $2) RETURNING id
|
||||
`, email, "Test Nutzer").Scan(&id)
|
||||
if err != nil {
|
||||
t.Fatalf("testnutzer anlegen: %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 1 (Client-Registrierung) + 2 (voller Flow) + 3 (JWKS-
|
||||
// Verifikation, Scope-Einschraenkung). Deckt Pruefungen 1-3 ab.
|
||||
func TestFullAuthorizationCodeFlow(t *testing.T) {
|
||||
handler, pool, cleanup := newProviderTestSetup(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
userID := createTestUser(t, pool, "nutzer@acme.example")
|
||||
|
||||
// Pruefung 1 / Akzeptanzkriterium 1: Client registriert sich.
|
||||
clientID, clientSecret, err := handler.clients.Register(ctx, "Test-Drittanwendung",
|
||||
[]string{"https://app.example.com/callback"},
|
||||
[]string{"openid", "profile"}, // erlaubte Scopes: KEIN "admin"
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
|
||||
// Session-Cookie fuer den Authorize-Aufruf ausstellen, exakt wie ein
|
||||
// echter Browser ihn haette — RequireAuth uebernimmt die Verifikation,
|
||||
// dieselbe Middleware wie in Produktion (nicht simuliert).
|
||||
issuer := auth.NewTokenIssuer("test-session-secret")
|
||||
sessionToken, err := issuer.Issue(userID, "acme")
|
||||
if err != nil {
|
||||
t.Fatalf("session-token ausstellen: %v", err)
|
||||
}
|
||||
|
||||
authorizeURL := "/oidc/authorize?" + url.Values{
|
||||
"response_type": {"code"},
|
||||
"client_id": {clientID},
|
||||
"redirect_uri": {"https://app.example.com/callback"},
|
||||
// admin wird angefragt, ist aber NICHT erlaubt -> muss herausgefiltert werden.
|
||||
"scope": {"openid profile admin"},
|
||||
"state": {"xyz123"},
|
||||
}.Encode()
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, authorizeURL, nil)
|
||||
req.AddCookie(&http.Cookie{Name: auth.CookieName, Value: sessionToken})
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
protected := auth.RequireAuth(issuer, handler.Authorize)
|
||||
protected(rec, req)
|
||||
|
||||
if rec.Code != http.StatusFound {
|
||||
t.Fatalf("authorize: status = %d, want %d, body: %s", rec.Code, http.StatusFound, rec.Body.String())
|
||||
}
|
||||
loc, err := url.Parse(rec.Header().Get("Location"))
|
||||
if err != nil {
|
||||
t.Fatalf("redirect-location parsen: %v", err)
|
||||
}
|
||||
if loc.Query().Get("state") != "xyz123" {
|
||||
t.Fatalf("state = %q, want xyz123 (muss unveraendert durchgereicht werden)", loc.Query().Get("state"))
|
||||
}
|
||||
code := loc.Query().Get("code")
|
||||
if code == "" {
|
||||
t.Fatal("erwartet gesetzten code-Parameter in der redirect-URL")
|
||||
}
|
||||
|
||||
// Pruefung 1 / Akzeptanzkriterium 2: Code gegen Token tauschen.
|
||||
tokenForm := url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"redirect_uri": {"https://app.example.com/callback"},
|
||||
"client_id": {clientID},
|
||||
"client_secret": {clientSecret},
|
||||
}
|
||||
tokenReq := httptest.NewRequest(http.MethodPost, "/oidc/token", strings.NewReader(tokenForm.Encode()))
|
||||
tokenReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
tokenRec := httptest.NewRecorder()
|
||||
handler.Token(tokenRec, tokenReq)
|
||||
|
||||
if tokenRec.Code != http.StatusOK {
|
||||
t.Fatalf("token: status = %d, want 200, body: %s", tokenRec.Code, tokenRec.Body.String())
|
||||
}
|
||||
|
||||
var tokenResp struct {
|
||||
IDToken string `json:"id_token"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
if err := decodeJSON(tokenRec.Body.Bytes(), &tokenResp); err != nil {
|
||||
t.Fatalf("token-response dekodieren: %v", err)
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 3 / Pruefung 3: "admin" wurde herausgefiltert.
|
||||
grantedScopes := strings.Fields(tokenResp.Scope)
|
||||
for _, s := range grantedScopes {
|
||||
if s == "admin" {
|
||||
t.Fatal("nicht erlaubter scope 'admin' wurde dennoch gewaehrt")
|
||||
}
|
||||
}
|
||||
if !containsAll(grantedScopes, "openid", "profile") {
|
||||
t.Fatalf("erwartete scopes openid+profile, habe %v", grantedScopes)
|
||||
}
|
||||
|
||||
// Pruefung 2 / Akzeptanzkriterium 3: ausgestelltes Token gegen JWKS verifizieren.
|
||||
jwksRec := httptest.NewRecorder()
|
||||
handler.JWKS(jwksRec, httptest.NewRequest(http.MethodGet, "/oidc/jwks.json", nil))
|
||||
|
||||
var jwks jwkSet
|
||||
if err := decodeJSON(jwksRec.Body.Bytes(), &jwks); err != nil {
|
||||
t.Fatalf("jwks dekodieren: %v", err)
|
||||
}
|
||||
if len(jwks.Keys) == 0 {
|
||||
t.Fatal("jwks enthaelt keine schluessel")
|
||||
}
|
||||
|
||||
parsedToken, err := jwt.ParseWithClaims(tokenResp.IDToken, &IDTokenClaims{}, func(tok *jwt.Token) (interface{}, error) {
|
||||
kid, _ := tok.Header["kid"].(string)
|
||||
for _, k := range jwks.Keys {
|
||||
if k.Kid == kid {
|
||||
pub, err := decodeBase64URLEd25519(k.X)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ed25519.PublicKey(pub), nil
|
||||
}
|
||||
}
|
||||
return nil, jwt.ErrTokenUnverifiable
|
||||
})
|
||||
if err != nil || !parsedToken.Valid {
|
||||
t.Fatalf("id-token gegen jwks verifizieren: %v (valid=%v)", err, parsedToken != nil && parsedToken.Valid)
|
||||
}
|
||||
|
||||
claims := parsedToken.Claims.(*IDTokenClaims)
|
||||
if claims.Subject != userID {
|
||||
t.Fatalf("sub = %q, want %q", claims.Subject, userID)
|
||||
}
|
||||
if len(claims.Audience) != 1 || claims.Audience[0] != clientID {
|
||||
t.Fatalf("aud = %v, want [%q]", claims.Audience, clientID)
|
||||
}
|
||||
}
|
||||
|
||||
// Pruefung 3 (dediziert): Client, der einen Scope anfragt, den er bei der
|
||||
// Registrierung nicht erhalten hat, bekommt ihn unter keinen Umstaenden.
|
||||
func TestGrantedScopes_NeverExceedsAllowed(t *testing.T) {
|
||||
c := Client{AllowedScopes: []string{"openid", "profile"}}
|
||||
granted := c.GrantedScopes([]string{"openid", "admin", "profile", "billing"})
|
||||
if !containsAll(granted, "openid", "profile") || len(granted) != 2 {
|
||||
t.Fatalf("granted = %v, want genau [openid profile]", granted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRedirectURI_RejectsUnregistered(t *testing.T) {
|
||||
c := Client{RedirectURIs: []string{"https://app.example.com/callback"}}
|
||||
if err := c.ValidateRedirectURI("https://boese-seite.example.com/callback"); err == nil {
|
||||
t.Fatal("erwartet fehler fuer nicht registrierte redirect_uri")
|
||||
}
|
||||
if err := c.ValidateRedirectURI("https://app.example.com/callback"); err != nil {
|
||||
t.Fatalf("registrierte redirect_uri sollte akzeptiert werden: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCodeStore_CannotBeConsumedTwice(t *testing.T) {
|
||||
handler, pool, cleanup := newProviderTestSetup(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
userID := createTestUser(t, pool, "einmalig@acme.example")
|
||||
clientID, _, err := handler.clients.Register(ctx, "Einmal-Client", []string{"https://a.example/cb"}, []string{"openid"})
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
|
||||
code, err := handler.authCodes.Issue(ctx, clientID, userID, "https://a.example/cb", []string{"openid"})
|
||||
if err != nil {
|
||||
t.Fatalf("issue: %v", err)
|
||||
}
|
||||
|
||||
if _, err := handler.authCodes.Consume(ctx, code, clientID, "https://a.example/cb"); err != nil {
|
||||
t.Fatalf("erster consume sollte funktionieren: %v", err)
|
||||
}
|
||||
if _, err := handler.authCodes.Consume(ctx, code, clientID, "https://a.example/cb"); err == nil {
|
||||
t.Fatal("zweiter consume desselben codes haette fehlschlagen muessen")
|
||||
}
|
||||
}
|
||||
|
||||
func containsAll(haystack []string, needles ...string) bool {
|
||||
set := make(map[string]bool, len(haystack))
|
||||
for _, h := range haystack {
|
||||
set[h] = true
|
||||
}
|
||||
for _, n := range needles {
|
||||
if !set[n] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func decodeJSON(data []byte, v any) error {
|
||||
return json.Unmarshal(data, v)
|
||||
}
|
||||
|
||||
func decodeBase64URLEd25519(s string) ([]byte, error) {
|
||||
return base64.RawURLEncoding.DecodeString(s)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE oidc_auth_codes;
|
||||
DROP TABLE oidc_clients;
|
||||
@@ -0,0 +1,28 @@
|
||||
-- IAM-13: NEXARCH als OIDC-Provider fuer Drittanwendungen eines Mandanten.
|
||||
-- Client-Registrierung und Authorization-Codes leben pro Mandant (nicht in
|
||||
-- der zentralen Registry), weil ein OAuth2-Client konzeptionell zu genau
|
||||
-- einem Kunden gehoert (siehe core-kanban/tickets/IAM-13.md).
|
||||
|
||||
CREATE TABLE oidc_clients (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL,
|
||||
client_id TEXT NOT NULL UNIQUE,
|
||||
secret_hash BYTEA NOT NULL,
|
||||
redirect_uris TEXT[] NOT NULL,
|
||||
allowed_scopes TEXT[] NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Auth-Codes sind bewusst kurzlebig und einmal verwendbar (RFC 6749 4.1.2):
|
||||
-- used_at IS NULL in der WHERE-Klausel beim Einloesen macht das Konsumieren
|
||||
-- atomar, gleiches Muster wie internal/authtoken (IAM-03).
|
||||
CREATE TABLE oidc_auth_codes (
|
||||
code_hash BYTEA PRIMARY KEY,
|
||||
client_id TEXT NOT NULL REFERENCES oidc_clients(client_id),
|
||||
user_id UUID NOT NULL REFERENCES users(id),
|
||||
redirect_uri TEXT NOT NULL,
|
||||
scopes TEXT[] NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
used_at TIMESTAMPTZ
|
||||
);
|
||||
Reference in New Issue
Block a user