2023-03-30 10:54:09 +02:00
|
|
|
package jwtclaims
|
2021-08-12 12:49:10 +02:00
|
|
|
|
|
|
|
import (
|
2022-12-07 22:06:43 +01:00
|
|
|
"bytes"
|
2024-07-03 11:33:02 +02:00
|
|
|
"context"
|
2022-12-07 22:06:43 +01:00
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/x509"
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/binary"
|
2021-08-12 12:49:10 +02:00
|
|
|
"encoding/json"
|
2022-12-07 22:06:43 +01:00
|
|
|
"encoding/pem"
|
2021-08-12 12:49:10 +02:00
|
|
|
"errors"
|
2022-12-07 22:06:43 +01:00
|
|
|
"fmt"
|
|
|
|
"math/big"
|
2021-08-12 12:49:10 +02:00
|
|
|
"net/http"
|
2023-04-14 11:20:34 +02:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2023-04-19 16:11:38 +02:00
|
|
|
"sync"
|
2023-04-14 11:20:34 +02:00
|
|
|
"time"
|
2023-02-03 21:47:20 +01:00
|
|
|
|
|
|
|
"github.com/golang-jwt/jwt"
|
|
|
|
log "github.com/sirupsen/logrus"
|
2021-08-12 12:49:10 +02:00
|
|
|
)
|
|
|
|
|
2023-03-30 10:54:09 +02:00
|
|
|
// Options is a struct for specifying configuration options for the middleware.
|
|
|
|
type Options struct {
|
|
|
|
// The function that will return the Key to validate the JWT.
|
|
|
|
// It can be either a shared secret or a public key.
|
|
|
|
// Default value: nil
|
|
|
|
ValidationKeyGetter jwt.Keyfunc
|
|
|
|
// The name of the property in the request where the user information
|
|
|
|
// from the JWT will be stored.
|
|
|
|
// Default value: "user"
|
|
|
|
UserProperty string
|
|
|
|
// The function that will be called when there's an error validating the token
|
|
|
|
// Default value:
|
|
|
|
CredentialsOptional bool
|
|
|
|
// A function that extracts the token from the request
|
|
|
|
// Default: FromAuthHeader (i.e., from Authorization header as bearer token)
|
|
|
|
Debug bool
|
|
|
|
// When set, all requests with the OPTIONS method will use authentication
|
|
|
|
// Default: false
|
|
|
|
EnableAuthOnOptions bool
|
|
|
|
// When set, the middelware verifies that tokens are signed with the specific signing algorithm
|
|
|
|
// If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
|
|
|
|
// Important to avoid security issues described here: https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
|
|
|
|
// Default: nil
|
|
|
|
SigningMethod jwt.SigningMethod
|
|
|
|
}
|
|
|
|
|
2022-12-07 22:06:43 +01:00
|
|
|
// Jwks is a collection of JSONWebKey obtained from Config.HttpServerConfig.AuthKeysLocation
|
2021-08-12 12:49:10 +02:00
|
|
|
type Jwks struct {
|
2023-04-14 11:20:34 +02:00
|
|
|
Keys []JSONWebKey `json:"keys"`
|
|
|
|
expiresInTime time.Time
|
2021-08-12 12:49:10 +02:00
|
|
|
}
|
|
|
|
|
2022-12-07 22:06:43 +01:00
|
|
|
// JSONWebKey is a representation of a Jason Web Key
|
|
|
|
type JSONWebKey struct {
|
2021-08-12 12:49:10 +02:00
|
|
|
Kty string `json:"kty"`
|
|
|
|
Kid string `json:"kid"`
|
|
|
|
Use string `json:"use"`
|
|
|
|
N string `json:"n"`
|
|
|
|
E string `json:"e"`
|
|
|
|
X5c []string `json:"x5c"`
|
|
|
|
}
|
|
|
|
|
2023-03-30 17:32:44 +02:00
|
|
|
// JWTValidator struct to handle token validation and parsing
|
2023-03-30 10:54:09 +02:00
|
|
|
type JWTValidator struct {
|
|
|
|
options Options
|
|
|
|
}
|
|
|
|
|
2023-03-30 17:32:44 +02:00
|
|
|
// NewJWTValidator constructor
|
2024-07-03 11:33:02 +02:00
|
|
|
func NewJWTValidator(ctx context.Context, issuer string, audienceList []string, keysLocation string, idpSignkeyRefreshEnabled bool) (*JWTValidator, error) {
|
|
|
|
keys, err := getPemKeys(ctx, keysLocation)
|
2021-08-12 12:49:10 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-04-19 16:11:38 +02:00
|
|
|
var lock sync.Mutex
|
2023-03-30 10:54:09 +02:00
|
|
|
options := Options{
|
2021-08-12 12:49:10 +02:00
|
|
|
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
|
|
|
|
// Verify 'aud' claim
|
2023-04-04 16:40:56 +02:00
|
|
|
var checkAud bool
|
|
|
|
for _, audience := range audienceList {
|
|
|
|
checkAud = token.Claims.(jwt.MapClaims).VerifyAudience(audience, false)
|
|
|
|
if checkAud {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2021-08-12 12:49:10 +02:00
|
|
|
if !checkAud {
|
|
|
|
return token, errors.New("invalid audience")
|
|
|
|
}
|
|
|
|
// Verify 'issuer' claim
|
|
|
|
checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(issuer, false)
|
|
|
|
if !checkIss {
|
|
|
|
return token, errors.New("invalid issuer")
|
|
|
|
}
|
|
|
|
|
2023-04-14 11:20:34 +02:00
|
|
|
// If keys are rotated, verify the keys prior to token validation
|
2023-04-15 02:44:42 +02:00
|
|
|
if idpSignkeyRefreshEnabled {
|
2023-04-14 11:20:34 +02:00
|
|
|
// If the keys are invalid, retrieve new ones
|
|
|
|
if !keys.stillValid() {
|
2023-04-19 16:11:38 +02:00
|
|
|
lock.Lock()
|
|
|
|
defer lock.Unlock()
|
2023-04-21 12:34:52 +02:00
|
|
|
|
2024-07-03 11:33:02 +02:00
|
|
|
refreshedKeys, err := getPemKeys(ctx, keysLocation)
|
2023-04-14 11:20:34 +02:00
|
|
|
if err != nil {
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(ctx).Debugf("cannot get JSONWebKey: %v, falling back to old keys", err)
|
2023-04-21 12:34:52 +02:00
|
|
|
refreshedKeys = keys
|
2023-04-14 11:20:34 +02:00
|
|
|
}
|
2023-04-21 12:34:52 +02:00
|
|
|
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(ctx).Debugf("keys refreshed, new UTC expiration time: %s", refreshedKeys.expiresInTime.UTC())
|
2023-12-12 14:56:27 +01:00
|
|
|
|
2023-04-21 12:34:52 +02:00
|
|
|
keys = refreshedKeys
|
2023-04-14 11:20:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-03 11:33:02 +02:00
|
|
|
cert, err := getPemCert(ctx, token, keys)
|
2021-08-12 12:49:10 +02:00
|
|
|
if err != nil {
|
2022-12-07 22:06:43 +01:00
|
|
|
return nil, err
|
2021-08-12 12:49:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert))
|
|
|
|
return result, nil
|
|
|
|
},
|
|
|
|
SigningMethod: jwt.SigningMethodRS256,
|
2021-08-16 11:29:57 +02:00
|
|
|
EnableAuthOnOptions: false,
|
2023-03-30 10:54:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if options.UserProperty == "" {
|
|
|
|
options.UserProperty = "user"
|
|
|
|
}
|
|
|
|
|
|
|
|
return &JWTValidator{
|
|
|
|
options: options,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2023-03-30 17:32:44 +02:00
|
|
|
// ValidateAndParse validates the token and returns the parsed token
|
2024-07-03 11:33:02 +02:00
|
|
|
func (m *JWTValidator) ValidateAndParse(ctx context.Context, token string) (*jwt.Token, error) {
|
2023-03-30 10:54:09 +02:00
|
|
|
// If the token is empty...
|
|
|
|
if token == "" {
|
|
|
|
// Check if it was required
|
|
|
|
if m.options.CredentialsOptional {
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(ctx).Debugf("no credentials found (CredentialsOptional=true)")
|
2023-03-30 10:54:09 +02:00
|
|
|
// No error, just no token (and that is ok given that CredentialsOptional is true)
|
2023-09-04 17:03:44 +02:00
|
|
|
return nil, nil //nolint:nilnil
|
2023-03-30 10:54:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// If we get here, the required token is missing
|
|
|
|
errorMsg := "required authorization token not found"
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(ctx).Debugf(" Error: No credentials found (CredentialsOptional=false)")
|
2023-03-30 10:54:09 +02:00
|
|
|
return nil, fmt.Errorf(errorMsg)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now parse the token
|
|
|
|
parsedToken, err := jwt.Parse(token, m.options.ValidationKeyGetter)
|
|
|
|
|
|
|
|
// Check if there was an error in parsing...
|
|
|
|
if err != nil {
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(ctx).Errorf("error parsing token: %v", err)
|
2023-03-30 10:54:09 +02:00
|
|
|
return nil, fmt.Errorf("Error parsing token: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if m.options.SigningMethod != nil && m.options.SigningMethod.Alg() != parsedToken.Header["alg"] {
|
|
|
|
errorMsg := fmt.Sprintf("Expected %s signing method but token specified %s",
|
|
|
|
m.options.SigningMethod.Alg(),
|
|
|
|
parsedToken.Header["alg"])
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(ctx).Debugf("error validating token algorithm: %s", errorMsg)
|
2023-03-30 10:54:09 +02:00
|
|
|
return nil, fmt.Errorf("error validating token algorithm: %s", errorMsg)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if the parsed token is valid...
|
|
|
|
if !parsedToken.Valid {
|
|
|
|
errorMsg := "token is invalid"
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(ctx).Debugf(errorMsg)
|
2023-03-30 10:54:09 +02:00
|
|
|
return nil, errors.New(errorMsg)
|
|
|
|
}
|
|
|
|
|
|
|
|
return parsedToken, nil
|
2021-08-12 12:49:10 +02:00
|
|
|
}
|
|
|
|
|
2023-04-14 11:20:34 +02:00
|
|
|
// stillValid returns true if the JSONWebKey still valid and have enough time to be used
|
|
|
|
func (jwks *Jwks) stillValid() bool {
|
2023-12-12 14:56:27 +01:00
|
|
|
return !jwks.expiresInTime.IsZero() && time.Now().Add(5*time.Second).Before(jwks.expiresInTime)
|
2023-04-14 11:20:34 +02:00
|
|
|
}
|
|
|
|
|
2024-07-03 11:33:02 +02:00
|
|
|
func getPemKeys(ctx context.Context, keysLocation string) (*Jwks, error) {
|
2021-08-12 12:49:10 +02:00
|
|
|
resp, err := http.Get(keysLocation)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
2023-02-03 21:47:20 +01:00
|
|
|
jwks := &Jwks{}
|
2021-08-12 12:49:10 +02:00
|
|
|
err = json.NewDecoder(resp.Body).Decode(jwks)
|
|
|
|
if err != nil {
|
|
|
|
return jwks, err
|
|
|
|
}
|
|
|
|
|
2023-04-14 11:20:34 +02:00
|
|
|
cacheControlHeader := resp.Header.Get("Cache-Control")
|
2024-07-03 11:33:02 +02:00
|
|
|
expiresIn := getMaxAgeFromCacheHeader(ctx, cacheControlHeader)
|
2023-04-14 11:20:34 +02:00
|
|
|
jwks.expiresInTime = time.Now().Add(time.Duration(expiresIn) * time.Second)
|
|
|
|
|
2021-08-12 12:49:10 +02:00
|
|
|
return jwks, err
|
|
|
|
}
|
|
|
|
|
2024-07-03 11:33:02 +02:00
|
|
|
func getPemCert(ctx context.Context, token *jwt.Token, jwks *Jwks) (string, error) {
|
2022-12-07 22:06:43 +01:00
|
|
|
// todo as we load the jkws when the server is starting, we should build a JKS map with the pem cert at the boot time
|
2021-08-12 12:49:10 +02:00
|
|
|
cert := ""
|
|
|
|
|
|
|
|
for k := range jwks.Keys {
|
2022-12-07 22:06:43 +01:00
|
|
|
if token.Header["kid"] != jwks.Keys[k].Kid {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(jwks.Keys[k].X5c) != 0 {
|
2021-08-12 12:49:10 +02:00
|
|
|
cert = "-----BEGIN CERTIFICATE-----\n" + jwks.Keys[k].X5c[0] + "\n-----END CERTIFICATE-----"
|
2022-12-07 22:06:43 +01:00
|
|
|
return cert, nil
|
2021-08-12 12:49:10 +02:00
|
|
|
}
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(ctx).Debugf("generating validation pem from JWK")
|
2022-12-07 22:06:43 +01:00
|
|
|
return generatePemFromJWK(jwks.Keys[k])
|
|
|
|
}
|
|
|
|
|
2023-09-04 17:03:44 +02:00
|
|
|
return cert, errors.New("unable to find appropriate key")
|
2022-12-07 22:06:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func generatePemFromJWK(jwk JSONWebKey) (string, error) {
|
|
|
|
decodedModulus, err := base64.RawURLEncoding.DecodeString(jwk.N)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("unable to decode JWK modulus, error: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
intModules := big.NewInt(0)
|
|
|
|
intModules.SetBytes(decodedModulus)
|
|
|
|
|
|
|
|
exponent, err := convertExponentStringToInt(jwk.E)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("unable to decode JWK exponent, error: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
publicKey := &rsa.PublicKey{
|
|
|
|
N: intModules,
|
|
|
|
E: exponent,
|
|
|
|
}
|
|
|
|
|
|
|
|
derKey, err := x509.MarshalPKIXPublicKey(publicKey)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("unable to convert public key to DER, error: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
block := &pem.Block{
|
|
|
|
Type: "RSA PUBLIC KEY",
|
|
|
|
Bytes: derKey,
|
|
|
|
}
|
|
|
|
|
|
|
|
var out bytes.Buffer
|
|
|
|
err = pem.Encode(&out, block)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("unable to encode Pem block , error: %s", err)
|
2021-08-12 12:49:10 +02:00
|
|
|
}
|
|
|
|
|
2022-12-07 22:06:43 +01:00
|
|
|
return out.String(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func convertExponentStringToInt(stringExponent string) (int, error) {
|
|
|
|
decodedString, err := base64.StdEncoding.DecodeString(stringExponent)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
exponentBytes := decodedString
|
|
|
|
if len(decodedString) < 8 {
|
|
|
|
exponentBytes = make([]byte, 8-len(decodedString), 8)
|
|
|
|
exponentBytes = append(exponentBytes, decodedString...)
|
|
|
|
}
|
|
|
|
|
|
|
|
bytesReader := bytes.NewReader(exponentBytes)
|
|
|
|
var exponent uint64
|
|
|
|
err = binary.Read(bytesReader, binary.BigEndian, &exponent)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
2021-08-12 12:49:10 +02:00
|
|
|
}
|
|
|
|
|
2022-12-07 22:06:43 +01:00
|
|
|
return int(exponent), nil
|
2021-08-12 12:49:10 +02:00
|
|
|
}
|
2023-04-14 11:20:34 +02:00
|
|
|
|
|
|
|
// getMaxAgeFromCacheHeader extracts max-age directive from the Cache-Control header
|
2024-07-03 11:33:02 +02:00
|
|
|
func getMaxAgeFromCacheHeader(ctx context.Context, cacheControl string) int {
|
2023-04-14 11:20:34 +02:00
|
|
|
// Split into individual directives
|
|
|
|
directives := strings.Split(cacheControl, ",")
|
|
|
|
|
|
|
|
for _, directive := range directives {
|
|
|
|
directive = strings.TrimSpace(directive)
|
|
|
|
if strings.HasPrefix(directive, "max-age=") {
|
|
|
|
// Extract the max-age value
|
|
|
|
maxAgeStr := strings.TrimPrefix(directive, "max-age=")
|
|
|
|
maxAge, err := strconv.Atoi(maxAgeStr)
|
|
|
|
if err != nil {
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(ctx).Debugf("error parsing max-age: %v", err)
|
2023-04-14 11:20:34 +02:00
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
return maxAge
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0
|
|
|
|
}
|