mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
The gateway accepted an ID token when its aud named one of the configured audiences. Keycloak ID tokens carry no other marker. The gateway now refuses a token whose payload typ is ID, or whose header typ is id+jwt, in any letter case. The log reason is id_token. The header check runs before any key fetch. The payload check runs after the signature check. Access tokens still pass.
402 lines
11 KiB
Go
402 lines
11 KiB
Go
package traefikllmgateway
|
|
|
|
import (
|
|
"crypto"
|
|
"crypto/ecdh"
|
|
"crypto/ecdsa"
|
|
"crypto/elliptic"
|
|
"crypto/rsa"
|
|
"crypto/sha256"
|
|
"crypto/sha512"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"math/big"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
errTokenMalformed = errors.New("oidc: malformed token")
|
|
errTokenExpired = errors.New("oidc: token expired")
|
|
errTokenNotYetValid = errors.New("oidc: token not yet valid")
|
|
errTokenBadSignature = errors.New("oidc: bad token signature")
|
|
errTokenBadAlg = errors.New("oidc: token algorithm not allowed for this key")
|
|
errTokenIssuer = errors.New("oidc: token issuer mismatch")
|
|
errTokenAudience = errors.New("oidc: token audience not accepted")
|
|
errTokenUnknownKid = errors.New("oidc: token signed by an unknown key")
|
|
errEmailNotVerified = errors.New("oidc: email not verified")
|
|
errTokenIsIDToken = errors.New("oidc: an ID token is not an access token")
|
|
)
|
|
|
|
// oidcClockSkew tolerates small clock drift between the IdP and the gateway.
|
|
const oidcClockSkew = 60 * time.Second
|
|
|
|
const (
|
|
// oidcPayloadTypID is the payload typ Keycloak sets on ID tokens.
|
|
oidcPayloadTypID = "id"
|
|
// oidcHeaderTypID is the header typ of an ID token JWT (RFC 9068 names
|
|
// "at+jwt" for access tokens).
|
|
oidcHeaderTypID = "id+jwt"
|
|
)
|
|
|
|
// jwk is one JSON Web Key (RFC 7517) as published in a JWKS document.
|
|
type jwk struct {
|
|
Kty string `json:"kty"`
|
|
Kid string `json:"kid"`
|
|
Use string `json:"use"`
|
|
N string `json:"n"`
|
|
E string `json:"e"`
|
|
Crv string `json:"crv"`
|
|
X string `json:"x"`
|
|
Y string `json:"y"`
|
|
}
|
|
|
|
// jwkSet holds the usable signature keys of a JWKS, by kid.
|
|
type jwkSet struct {
|
|
keys map[string]crypto.PublicKey
|
|
}
|
|
|
|
// jwsAlg describes one allowed JWS algorithm.
|
|
type jwsAlg struct {
|
|
curve elliptic.Curve // nil for RSA algorithms
|
|
hash crypto.Hash
|
|
pss bool
|
|
}
|
|
|
|
// allowedJWSAlgs is the closed set of accepted algorithms. Symmetric and
|
|
// "none" algorithms are absent on purpose: a public key must never act as an
|
|
// HMAC secret.
|
|
var allowedJWSAlgs = map[string]jwsAlg{
|
|
"RS256": {hash: crypto.SHA256},
|
|
"RS384": {hash: crypto.SHA384},
|
|
"RS512": {hash: crypto.SHA512},
|
|
"PS256": {hash: crypto.SHA256, pss: true},
|
|
"ES256": {hash: crypto.SHA256, curve: elliptic.P256()},
|
|
"ES384": {hash: crypto.SHA384, curve: elliptic.P384()},
|
|
}
|
|
|
|
// parseJWKS reads the signature keys from a JWKS document. Keys for
|
|
// encryption, key types this gateway does not verify and malformed or weak
|
|
// keys are skipped, so one bad key cannot block the others. It fails only
|
|
// when a supported key was malformed and no usable key remains.
|
|
func parseJWKS(body []byte) (*jwkSet, error) {
|
|
var doc struct {
|
|
Keys []jwk `json:"keys"`
|
|
}
|
|
if err := json.Unmarshal(body, &doc); err != nil {
|
|
return nil, fmt.Errorf("oidc: jwks: %w", err)
|
|
}
|
|
set := &jwkSet{keys: make(map[string]crypto.PublicKey, len(doc.Keys))}
|
|
var firstErr error
|
|
for _, k := range doc.Keys {
|
|
if k.Use != "" && k.Use != "sig" {
|
|
continue
|
|
}
|
|
var (
|
|
pub crypto.PublicKey
|
|
err error
|
|
)
|
|
switch k.Kty {
|
|
case "RSA":
|
|
pub, err = rsaKey(k)
|
|
case "EC":
|
|
curve := curveByName(k.Crv)
|
|
if curve == nil {
|
|
continue
|
|
}
|
|
pub, err = ecKey(k, curve)
|
|
default:
|
|
continue
|
|
}
|
|
if err != nil {
|
|
if firstErr == nil {
|
|
firstErr = fmt.Errorf("oidc: jwks key %q: %w", k.Kid, err)
|
|
}
|
|
continue
|
|
}
|
|
set.keys[k.Kid] = pub
|
|
}
|
|
if len(set.keys) == 0 && firstErr != nil {
|
|
return nil, firstErr
|
|
}
|
|
return set, nil
|
|
}
|
|
|
|
func ecdhCurve(c elliptic.Curve) ecdh.Curve {
|
|
if c == elliptic.P384() {
|
|
return ecdh.P384()
|
|
}
|
|
return ecdh.P256()
|
|
}
|
|
|
|
func curveByName(name string) elliptic.Curve {
|
|
switch name {
|
|
case "P-256":
|
|
return elliptic.P256()
|
|
case "P-384":
|
|
return elliptic.P384()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func rsaKey(k jwk) (*rsa.PublicKey, error) {
|
|
n, err := base64.RawURLEncoding.DecodeString(k.N)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("modulus: %w", err)
|
|
}
|
|
e, err := base64.RawURLEncoding.DecodeString(k.E)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("exponent: %w", err)
|
|
}
|
|
exp := new(big.Int).SetBytes(e)
|
|
if len(n) == 0 || !exp.IsInt64() || exp.Int64() < 3 || exp.Int64() > 1<<31-1 {
|
|
return nil, errors.New("invalid RSA parameters")
|
|
}
|
|
mod := new(big.Int).SetBytes(n)
|
|
if mod.BitLen() < oidcMinRSABits {
|
|
return nil, fmt.Errorf("RSA key of %d bits is under %d", mod.BitLen(), oidcMinRSABits)
|
|
}
|
|
return &rsa.PublicKey{N: mod, E: int(exp.Int64())}, nil
|
|
}
|
|
|
|
func ecKey(k jwk, curve elliptic.Curve) (*ecdsa.PublicKey, error) {
|
|
x, err := base64.RawURLEncoding.DecodeString(k.X)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("x: %w", err)
|
|
}
|
|
y, err := base64.RawURLEncoding.DecodeString(k.Y)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("y: %w", err)
|
|
}
|
|
size := (curve.Params().BitSize + 7) / 8
|
|
if len(x) != size || len(y) != size {
|
|
return nil, errors.New("coordinate length does not match the curve")
|
|
}
|
|
// crypto/ecdh's NewPublicKey rejects a point that is not on the curve.
|
|
point := append(append([]byte{4}, x...), y...)
|
|
if _, err := ecdhCurve(curve).NewPublicKey(point); err != nil {
|
|
return nil, fmt.Errorf("point: %w", err)
|
|
}
|
|
return &ecdsa.PublicKey{Curve: curve, X: new(big.Int).SetBytes(x), Y: new(big.Int).SetBytes(y)}, nil
|
|
}
|
|
|
|
// oidcMinRSABits is the smallest RSA modulus accepted for token signatures.
|
|
const oidcMinRSABits = 2048
|
|
|
|
// jwtHeader is the protected header of a compact JWS.
|
|
type jwtHeader struct {
|
|
Alg string `json:"alg"`
|
|
Kid string `json:"kid"`
|
|
Typ string `json:"typ"`
|
|
}
|
|
|
|
func splitJWT(token string) ([]string, *jwtHeader, error) {
|
|
parts := strings.Split(token, ".")
|
|
if len(parts) != 3 {
|
|
return nil, nil, errTokenMalformed
|
|
}
|
|
raw, err := base64.RawURLEncoding.DecodeString(parts[0])
|
|
if err != nil {
|
|
return nil, nil, errTokenMalformed
|
|
}
|
|
var hdr jwtHeader
|
|
if err := json.Unmarshal(raw, &hdr); err != nil || hdr.Alg == "" {
|
|
return nil, nil, errTokenMalformed
|
|
}
|
|
return parts, &hdr, nil
|
|
}
|
|
|
|
// looksLikeJWT reports whether token has the compact JWS shape, so an opaque
|
|
// token is never sent through signature checks.
|
|
func looksLikeJWT(token string) bool {
|
|
_, _, err := splitJWT(token)
|
|
return err == nil
|
|
}
|
|
|
|
// jwtKid returns the kid of token's protected header. A disallowed alg is
|
|
// refused here, before any key fetch.
|
|
func jwtKid(token string) (string, error) {
|
|
_, hdr, err := splitJWT(token)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if _, ok := allowedJWSAlgs[hdr.Alg]; !ok {
|
|
return "", errTokenBadAlg
|
|
}
|
|
if strings.EqualFold(hdr.Typ, oidcHeaderTypID) {
|
|
return "", errTokenIsIDToken
|
|
}
|
|
return hdr.Kid, nil
|
|
}
|
|
|
|
// verifyJWT checks token's signature against keys and its claims against s,
|
|
// and returns the claims.
|
|
func verifyJWT(token string, keys *jwkSet, s *oidcSettings, now time.Time) (map[string]any, error) {
|
|
parts, hdr, err := splitJWT(token)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
alg, ok := allowedJWSAlgs[hdr.Alg]
|
|
if !ok {
|
|
return nil, errTokenBadAlg
|
|
}
|
|
if strings.EqualFold(hdr.Typ, oidcHeaderTypID) {
|
|
return nil, errTokenIsIDToken
|
|
}
|
|
pub, err := keys.lookup(hdr.Kid)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sig, err := base64.RawURLEncoding.DecodeString(parts[2])
|
|
if err != nil {
|
|
return nil, errTokenBadSignature
|
|
}
|
|
if err = verifySignature(alg, pub, []byte(parts[0]+"."+parts[1]), sig); err != nil {
|
|
return nil, err
|
|
}
|
|
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
|
|
if err != nil {
|
|
return nil, errTokenMalformed
|
|
}
|
|
var claims map[string]any
|
|
if err := json.Unmarshal(raw, &claims); err != nil {
|
|
return nil, errTokenMalformed
|
|
}
|
|
if err := checkClaims(claims, s, now); err != nil {
|
|
return nil, err
|
|
}
|
|
return claims, nil
|
|
}
|
|
|
|
// lookup returns the key for kid. A token without a kid matches only when
|
|
// the set holds exactly one key.
|
|
func (k *jwkSet) lookup(kid string) (crypto.PublicKey, error) {
|
|
if pub, ok := k.keys[kid]; ok {
|
|
return pub, nil
|
|
}
|
|
if kid == "" && len(k.keys) == 1 {
|
|
for _, pub := range k.keys {
|
|
return pub, nil
|
|
}
|
|
}
|
|
return nil, errTokenUnknownKid
|
|
}
|
|
|
|
func verifySignature(alg jwsAlg, pub crypto.PublicKey, input, sig []byte) error {
|
|
digest := hashInput(alg.hash, input)
|
|
switch key := pub.(type) {
|
|
case *rsa.PublicKey:
|
|
if alg.curve != nil {
|
|
return errTokenBadAlg
|
|
}
|
|
var err error
|
|
if alg.pss {
|
|
err = rsa.VerifyPSS(key, alg.hash, digest, sig, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
|
|
} else {
|
|
err = rsa.VerifyPKCS1v15(key, alg.hash, digest, sig)
|
|
}
|
|
if err != nil {
|
|
return errTokenBadSignature
|
|
}
|
|
return nil
|
|
case *ecdsa.PublicKey:
|
|
if alg.curve == nil || key.Curve != alg.curve {
|
|
return errTokenBadAlg
|
|
}
|
|
size := (key.Curve.Params().BitSize + 7) / 8
|
|
if len(sig) != 2*size {
|
|
return errTokenBadSignature
|
|
}
|
|
r := new(big.Int).SetBytes(sig[:size])
|
|
sv := new(big.Int).SetBytes(sig[size:])
|
|
if !ecdsa.Verify(key, digest, r, sv) {
|
|
return errTokenBadSignature
|
|
}
|
|
return nil
|
|
}
|
|
return errTokenBadAlg
|
|
}
|
|
|
|
func hashInput(h crypto.Hash, input []byte) []byte {
|
|
switch h {
|
|
case crypto.SHA384:
|
|
d := sha512.Sum384(input)
|
|
return d[:]
|
|
case crypto.SHA512:
|
|
d := sha512.Sum512(input)
|
|
return d[:]
|
|
default:
|
|
d := sha256.Sum256(input)
|
|
return d[:]
|
|
}
|
|
}
|
|
|
|
func checkClaims(claims map[string]any, s *oidcSettings, now time.Time) error {
|
|
if typ, _ := claims["typ"].(string); strings.EqualFold(typ, oidcPayloadTypID) {
|
|
return errTokenIsIDToken
|
|
}
|
|
if iss, _ := claims["iss"].(string); iss != s.issuer {
|
|
return errTokenIssuer
|
|
}
|
|
exp, ok := numericClaim(claims, "exp")
|
|
if !ok || now.After(time.Unix(exp, 0).Add(oidcClockSkew)) {
|
|
return errTokenExpired
|
|
}
|
|
if nbf, ok := numericClaim(claims, "nbf"); ok && now.Add(oidcClockSkew).Before(time.Unix(nbf, 0)) {
|
|
return errTokenNotYetValid
|
|
}
|
|
if !audienceAccepted(claims, s.audiences, s.acceptAzp) {
|
|
return errTokenAudience
|
|
}
|
|
if s.requireEmailVerified && !emailVerified(claims) {
|
|
return errEmailNotVerified
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func numericClaim(claims map[string]any, name string) (int64, bool) {
|
|
v, ok := claims[name].(float64)
|
|
if !ok {
|
|
return 0, false
|
|
}
|
|
return int64(v), true
|
|
}
|
|
|
|
// audienceAccepted matches aud (a string or an array). With acceptAzp it
|
|
// also matches azp: Keycloak and similar IdPs put the requesting client in
|
|
// azp, not aud, of access tokens. azp alone also passes a token the client
|
|
// obtained for another service, so it is opt-in.
|
|
func audienceAccepted(claims map[string]any, accepted map[string]bool, acceptAzp bool) bool {
|
|
switch aud := claims["aud"].(type) {
|
|
case string:
|
|
if accepted[aud] {
|
|
return true
|
|
}
|
|
case []any:
|
|
for _, a := range aud {
|
|
if s, ok := a.(string); ok && accepted[s] {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
if !acceptAzp {
|
|
return false
|
|
}
|
|
azp, _ := claims["azp"].(string)
|
|
return azp != "" && accepted[azp]
|
|
}
|
|
|
|
// emailVerified accepts a boolean true or the string "true", which some IdPs
|
|
// emit.
|
|
func emailVerified(claims map[string]any) bool {
|
|
switch v := claims["email_verified"].(type) {
|
|
case bool:
|
|
return v
|
|
case string:
|
|
return v == "true"
|
|
}
|
|
return false
|
|
}
|