From 87d2dce06d0bc923151860c79c4abea2ed8c30ff Mon Sep 17 00:00:00 2001 From: jay brown Date: Fri, 11 Apr 2025 14:30:58 -0700 Subject: [PATCH] fix tests add new cognito vars --- devbox.json | 6 +- go.mod | 1 - go.sum | 2 - internal/rbac/README.md | 135 ---- internal/rbac/cognito.go | 407 ------------ internal/rbac/cognito_test.go | 590 ------------------ internal/rbac/middleware.go | 261 -------- internal/rbac/middleware_endpoint_test.go | 228 ------- internal/rbac/middleware_test.go | 128 ---- internal/rbac/private_key.pem | 28 - internal/rbac/public_key.pem | 9 - internal/serviceconfig/common_test.go | 4 + internal/serviceconfig/commonlog_test.go | 6 +- internal/test/container.go | 4 + .../github.com/golang-jwt/jwt/v5/.gitignore | 4 - vendor/github.com/golang-jwt/jwt/v5/LICENSE | 9 - .../golang-jwt/jwt/v5/MIGRATION_GUIDE.md | 195 ------ vendor/github.com/golang-jwt/jwt/v5/README.md | 167 ----- .../github.com/golang-jwt/jwt/v5/SECURITY.md | 19 - .../golang-jwt/jwt/v5/VERSION_HISTORY.md | 137 ---- vendor/github.com/golang-jwt/jwt/v5/claims.go | 16 - vendor/github.com/golang-jwt/jwt/v5/doc.go | 4 - vendor/github.com/golang-jwt/jwt/v5/ecdsa.go | 134 ---- .../golang-jwt/jwt/v5/ecdsa_utils.go | 69 -- .../github.com/golang-jwt/jwt/v5/ed25519.go | 79 --- .../golang-jwt/jwt/v5/ed25519_utils.go | 64 -- vendor/github.com/golang-jwt/jwt/v5/errors.go | 49 -- .../golang-jwt/jwt/v5/errors_go1_20.go | 47 -- .../golang-jwt/jwt/v5/errors_go_other.go | 78 --- vendor/github.com/golang-jwt/jwt/v5/hmac.go | 104 --- .../golang-jwt/jwt/v5/map_claims.go | 109 ---- vendor/github.com/golang-jwt/jwt/v5/none.go | 50 -- vendor/github.com/golang-jwt/jwt/v5/parser.go | 238 ------- .../golang-jwt/jwt/v5/parser_option.go | 128 ---- .../golang-jwt/jwt/v5/registered_claims.go | 63 -- vendor/github.com/golang-jwt/jwt/v5/rsa.go | 93 --- .../github.com/golang-jwt/jwt/v5/rsa_pss.go | 135 ---- .../github.com/golang-jwt/jwt/v5/rsa_utils.go | 107 ---- .../golang-jwt/jwt/v5/signing_method.go | 49 -- .../golang-jwt/jwt/v5/staticcheck.conf | 1 - vendor/github.com/golang-jwt/jwt/v5/token.go | 100 --- .../golang-jwt/jwt/v5/token_option.go | 5 - vendor/github.com/golang-jwt/jwt/v5/types.go | 149 ----- .../github.com/golang-jwt/jwt/v5/validator.go | 316 ---------- vendor/modules.txt | 3 - 45 files changed, 17 insertions(+), 4513 deletions(-) delete mode 100644 internal/rbac/README.md delete mode 100644 internal/rbac/cognito.go delete mode 100644 internal/rbac/cognito_test.go delete mode 100644 internal/rbac/middleware.go delete mode 100644 internal/rbac/middleware_endpoint_test.go delete mode 100644 internal/rbac/middleware_test.go delete mode 100644 internal/rbac/private_key.pem delete mode 100644 internal/rbac/public_key.pem delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/.gitignore delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/LICENSE delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/README.md delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/SECURITY.md delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/claims.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/doc.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/ecdsa.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/ed25519.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/errors.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/hmac.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/map_claims.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/none.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/parser.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/parser_option.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/registered_claims.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/rsa.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/signing_method.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/token.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/token_option.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/types.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/validator.go diff --git a/devbox.json b/devbox.json index 7da64378..d096fcf2 100644 --- a/devbox.json +++ b/devbox.json @@ -10,8 +10,10 @@ "AWS_SESSION_TOKEN": "", "BUCKET_IN": "documentin", "CLIENT_SYNC_URL": "http://localstack:4566/queue/us-east-1/000000000000/client_sync", - "COGNITO_REGION": "us-east-1", - "COGNITO_USER_POOL_ID": "NA", + "COGNITO_CLIENT_ID": "552cqkf3640t39ncehkmgpce31", + "COGNITO_CLIENT_SECRET": "aak...", + "COGNITO_DOMAIN": "https://us-east-21y6po8rr8.auth.us-east-2.amazoncognito.com", + "COGNITO_USER_POOL_ID": "us-east-2_1y6po8rR8", "DB_NOSSL": "true", "DOCUMENT_CLEAN_URL": "http://localstack:4566/queue/us-east-1/000000000000/document_clean", "DOCUMENT_INIT_URL": "http://localstack:4566/queue/us-east-1/000000000000/document_init", diff --git a/go.mod b/go.mod index 9d9d5d86..350fc5f7 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,6 @@ require ( github.com/caarlos0/env/v11 v11.3.1 github.com/getkin/kin-openapi v0.129.0 github.com/go-playground/validator/v10 v10.25.0 - github.com/golang-jwt/jwt/v5 v5.2.1 github.com/golang-migrate/migrate/v4 v4.18.2 github.com/jackc/pgx/v5 v5.7.2 github.com/joho/godotenv v1.5.1 diff --git a/go.sum b/go.sum index ccf7ad77..a3d600ec 100644 --- a/go.sum +++ b/go.sum @@ -131,8 +131,6 @@ github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PU github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= -github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-migrate/migrate/v4 v4.18.2 h1:2VSCMz7x7mjyTXx3m2zPokOY82LTRgxK1yQYKo6wWQ8= github.com/golang-migrate/migrate/v4 v4.18.2/go.mod h1:2CM6tJvn2kqPXwnXO/d3rAQYiyoIm180VsO8PRX6Rpk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= diff --git a/internal/rbac/README.md b/internal/rbac/README.md deleted file mode 100644 index 41c657aa..00000000 --- a/internal/rbac/README.md +++ /dev/null @@ -1,135 +0,0 @@ -# RBAC (Role-Based Access Control) Package - -This package provides authentication and authorization functionality for the application, with a specific focus on AWS Cognito integration and role-based access control (RBAC). - -## Overview - -The RBAC package handles all aspects of authentication and authorization, including: - -- JWT token validation and verification -- AWS Cognito integration with JWKS (JSON Web Key Set) support -- Role-based access control through Cognito groups -- Echo middleware for protecting routes based on user roles - -## Components - -### Cognito Integration (`cognito.go`) - -The package provides robust AWS Cognito integration with features including: - -- JWT token validation using Cognito's JWKS endpoint -- Automatic key rotation and caching -- Group-based authorization checks -- Token details extraction and validation - -Key components include: - -- `CognitoKeyProvider`: Manages JWT validation keys from Cognito's JWKS endpoint -- `LocalKeyProvider`: Provides local key management for testing -- `TokenDetails`: Contains extracted JWT token information -- Various helper functions for group membership verification - -## Usage - -### Setting up Cognito Key Provider - -```go -keyProvider := rbac.NewCognitoKeyProvider( - "us-east-1", // AWS Region - "your-user-pool-id" // Cognito User Pool ID / add to config -) -``` - -### Validating JWT Tokens - -```go -tokenString := "your.jwt.token" -token, claims, err := rbac.ValidateJWT(tokenString, keyProvider) -if err != nil { - // Handle validation error -} -``` - -### Checking Group Membership - -```go -// Check for a single group -if rbac.HasGroup(claims, "admin") { - // User is an admin -} - -// Check for any of multiple groups -if rbac.HasAnyGroup(claims, []string{"admin", "editor"}) { - // User has at least one of the required roles -} - -// Check for all required groups -if rbac.HasAllGroups(claims, []string{"editor", "reviewer"}) { - // User has all required roles -} -``` - -## Echo Middleware - -The package includes middleware for the Echo web framework (coming soon) that will provide: - -- Automatic JWT token validation -- Role-based route protection -- User context injection - -### Example middleware usage -This is not tested yet. -```go -import ... - -// Create the key provider once at startup -keyProvider := rbac.NewCognitoKeyProvider("us-east-1", "us-east-1_XXXXXXXX") - -// Use in middleware -func authMiddleware(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - tokenString := extractTokenFromRequest(c) - - _, claims, err := rbac.ValidateJWT(tokenString, keyProvider) - if err != nil { - return echo.NewHTTPError(http.StatusUnauthorized, "Invalid token") - } - - if !rbac.HasAnyGroup(claims, []string{"admin", "editor"}) { - return echo.NewHTTPError(http.StatusForbidden, "Insufficient permissions") - } - - return next(c) - } -} -``` - -## Security Considerations - -- All JWKS endpoints must use HTTPS -- Only trusted Cognito domains are allowed -- JWT tokens are thoroughly validated including: - - Signature verification - - Expiration checking - - Required claims validation - - Group membership verification - -## Testing - -The package includes support for generating mock JWT tokens for testing purposes using the `LocalKeyProvider`: - -```go -keyProvider := rbac.NewLocalKeyProvider( - "path/to/private.pem", - "path/to/public.pem" -) - -token, err := rbac.GenerateMockJWT( - keyProvider, - "user123", - "user@example.com", - []string{"admin", "editor"} -) -``` - - diff --git a/internal/rbac/cognito.go b/internal/rbac/cognito.go deleted file mode 100644 index 1f4a9ce2..00000000 --- a/internal/rbac/cognito.go +++ /dev/null @@ -1,407 +0,0 @@ -package rbac - -import ( - "crypto/rsa" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "math/big" - "net/http" - "net/url" - "os" - - "strings" - "time" - - "github.com/golang-jwt/jwt/v5" -) - -// KeyProvider interface for different key sources -type KeyProvider interface { - GetPublicKey(kid string) (*rsa.PublicKey, error) -} - -// LocalKeyProvider implements KeyProvider using local PEM files -type LocalKeyProvider struct { - PrivateKeyPath string - PublicKeyPath string -} - -// CognitoKeyProvider implements KeyProvider using AWS Cognito JWKS endpoint -type CognitoKeyProvider struct { - Region string - UserPoolID string - JwksCache map[string]*rsa.PublicKey // Cache for JWKS keys by Key ID -} - -// JWKS structure for Cognito public keys -type JWKS struct { - Keys []struct { - Kid string `json:"kid"` - Kty string `json:"kty"` - N string `json:"n"` - E string `json:"e"` - Use string `json:"use"` - Alg string `json:"alg"` - } `json:"keys"` -} - -// TokenDetails contains the extracted information from a JWT token -type TokenDetails struct { - Token *jwt.Token - Claims jwt.MapClaims - UserID string - Email string - Groups []string - Expiration time.Time -} - -// Load private key from file -func LoadPrivateKey(keyPath string) (*rsa.PrivateKey, error) { - keyData, err := os.ReadFile(keyPath) - if err != nil { - return nil, fmt.Errorf("error reading private key file: %w", err) - } - return jwt.ParseRSAPrivateKeyFromPEM(keyData) -} - -// Load public key from file -func LoadPublicKey(keyPath string) (*rsa.PublicKey, error) { - keyData, err := os.ReadFile(keyPath) - if err != nil { - return nil, fmt.Errorf("error reading public key file: %w", err) - } - return jwt.ParseRSAPublicKeyFromPEM(keyData) -} - -// GetPublicKey implements KeyProvider for LocalKeyProvider -func (lkp *LocalKeyProvider) GetPublicKey(kid string) (*rsa.PublicKey, error) { - // For local provider, kid is ignored since we only have one key - return LoadPublicKey(lkp.PublicKeyPath) -} - -// GetPrivateKey returns the private key for signing test tokens -func (lkp *LocalKeyProvider) GetPrivateKey() (*rsa.PrivateKey, error) { - return LoadPrivateKey(lkp.PrivateKeyPath) -} - -// jwkToPublicKey converts JSON Web Key (JWK) components to an RSA public key. -// Parameters: -// - n: base64 URL-encoded string representing the modulus of the RSA key -// - e: base64 URL-encoded string representing the exponent of the RSA key -// -// Returns: -// - *rsa.PublicKey: RSA public key constructed from the provided components -// - error: if there's an issue decoding the base64 values or creating the key -func jwkToPublicKey(n, e string) (*rsa.PublicKey, error) { - // Decode the base64 URL-encoded modulus - nBytes, err := base64.RawURLEncoding.DecodeString(n) - if err != nil { - return nil, fmt.Errorf("error decoding modulus: %w", err) - } - - // Decode the base64 URL-encoded exponent - eBytes, err := base64.RawURLEncoding.DecodeString(e) - if err != nil { - return nil, fmt.Errorf("error decoding exponent: %w", err) - } - - // Convert modulus bytes to big.Int - modulus := new(big.Int) - modulus.SetBytes(nBytes) - - // Convert exponent bytes to int - var exponent int - for i := 0; i < len(eBytes); i++ { - exponent = exponent<<8 + int(eBytes[i]) - } - - // Create RSA public key - return &rsa.PublicKey{ - N: modulus, - E: exponent, - }, nil -} - -// GetPublicKey implements KeyProvider for CognitoKeyProvider -func (ckp *CognitoKeyProvider) GetPublicKey(kid string) (*rsa.PublicKey, error) { - // Check cache first - if ckp.JwksCache == nil { - ckp.JwksCache = make(map[string]*rsa.PublicKey) - } - - if key, exists := ckp.JwksCache[kid]; exists { - return key, nil - } - - // Fetch JWKS from Cognito (old way) - // baseURL := "https://cognito-idp.amazonaws.com" - // jwksPath := fmt.Sprintf("/%s/%s/.well-known/jwks.json", ckp.AuthRegion, ckp.AuthUserPoolID) - // https://cognito-idp.us-east-2.amazonaws.com/us-east-2_1y6po8rR8/.well-known/jwks.json - jwksURL := fmt.Sprintf("https://cognito-idp.%s.amazonaws.com/%s/.well-known/jwks.json", ckp.Region, ckp.UserPoolID) - - if err := IsValidJWKSURL(jwksURL); err != nil { - return nil, fmt.Errorf("invalid JWKS URL: %w", err) - } - - client := &http.Client{ - Timeout: 10 * time.Second, - } - req, err := http.NewRequest("GET", jwksURL, nil) - if err != nil { - return nil, fmt.Errorf("error creating request for JWKS: %w", err) - } - - resp, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("error fetching JWKS from Cognito: %w", err) - } - defer resp.Body.Close() - - jwksData, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("error reading JWKS response: %w", err) - } - - var jwks JWKS - if err := json.Unmarshal(jwksData, &jwks); err != nil { - return nil, fmt.Errorf("error parsing JWKS JSON: %w", err) - } - - // Find the key with matching kid - for _, key := range jwks.Keys { - if key.Kid == kid { - // Convert JWK to RSA public key - publicKey, err := jwkToPublicKey(key.N, key.E) - if err != nil { - return nil, fmt.Errorf("error converting JWK to public key: %w", err) - } - - // Store in cache - ckp.JwksCache[kid] = publicKey - return publicKey, nil - } - } - - return nil, fmt.Errorf("no matching key found with kid: %s", kid) -} - -// NewLocalKeyProvider creates a new LocalKeyProvider -func NewLocalKeyProvider(privateKeyPath, publicKeyPath string) *LocalKeyProvider { - return &LocalKeyProvider{ - PrivateKeyPath: privateKeyPath, - PublicKeyPath: publicKeyPath, - } -} - -// NewCognitoKeyProvider creates a new CognitoKeyProvider -func NewCognitoKeyProvider(region, userPoolID string) *CognitoKeyProvider { - return &CognitoKeyProvider{ - Region: region, - UserPoolID: userPoolID, - JwksCache: make(map[string]*rsa.PublicKey), - } -} - -// GenerateTestJWT creates a test JWT with given groups -func GenerateTestJWT(keyProvider *LocalKeyProvider, userID, email string, groups []string) (string, error) { - privateKey, err := keyProvider.GetPrivateKey() - if err != nil { - return "", err - } - - // Create a header with kid value (important for verification) - headers := map[string]interface{}{ - "kid": "test-key-id", // In a real scenario this would match the key ID from Cognito - "alg": "RS256", - } - - token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ - "sub": userID, - "email": email, - "exp": time.Now().Add(time.Hour).Unix(), - "iat": time.Now().Unix(), - "iss": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXXXX", - "cognito:groups": groups, - }) - - // Set the header - for k, v := range headers { - token.Header[k] = v - } - - return token.SignedString(privateKey) -} - -// PrintTokenDetails prints the JWT token details for debugging -func PrintTokenDetails(token *jwt.Token) { - fmt.Println("\n=== JWT Token Details ===") - - // Print Header - headerJSON, _ := json.MarshalIndent(token.Header, "", " ") - fmt.Printf("\nHeader:\n%s\n", string(headerJSON)) - - // Print Claims - claimsJSON, _ := json.MarshalIndent(token.Claims, "", " ") - fmt.Printf("\nClaims:\n%s\n", string(claimsJSON)) - - // Print Signature - fmt.Printf("\nSignature: %s\n", token.Signature) - - // Print Method - fmt.Printf("\nSigning Method: %s\n", token.Method.Alg()) - - // Print Valid status - fmt.Printf("\nValid: %v\n", token.Valid) - - fmt.Println("\n=====================") -} - -// ValidateJWT validates a JWT token and returns the claims -func ValidateJWT(tokenString string, keyProvider KeyProvider) (*jwt.Token, jwt.MapClaims, error) { - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { - if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { - return nil, errors.New("unexpected signing method") - } - - // Get key ID from token header - kid, ok := token.Header["kid"].(string) - if !ok { - return nil, errors.New("no key ID (kid) in token header") - } - - // Get public key from provider - return keyProvider.GetPublicKey(kid) - }) - - if err != nil { - return nil, nil, err - } - - if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { - return token, claims, nil - } - return nil, nil, errors.New("invalid token") -} - -// ExtractTokenDetails extracts and organizes token information -func ExtractTokenDetails(token *jwt.Token, claims jwt.MapClaims) *TokenDetails { - details := &TokenDetails{ - Token: token, - Claims: claims, - } - - if sub, ok := claims["sub"].(string); ok { - details.UserID = sub - } - - if email, ok := claims["email"].(string); ok { - details.Email = email - } - - if expFloat, ok := claims["exp"].(float64); ok { - details.Expiration = time.Unix(int64(expFloat), 0) - } - - if groupsInterface, ok := claims["cognito:groups"].([]interface{}); ok { - details.Groups = make([]string, 0, len(groupsInterface)) - for _, group := range groupsInterface { - if groupStr, ok := group.(string); ok { - details.Groups = append(details.Groups, groupStr) - } - } - } - - return details -} - -// HasGroup checks if a user belongs to a specific group -func HasGroup(claims jwt.MapClaims, requiredGroup string) bool { - if groups, ok := claims["cognito:groups"].([]interface{}); ok { - for _, group := range groups { - if groupStr, ok := group.(string); ok && strings.EqualFold(groupStr, requiredGroup) { - return true - } - } - } - return false -} - -// HasAnyGroup checks if a user belongs to any of the specified groups -func HasAnyGroup(claims jwt.MapClaims, requiredGroups []string) bool { - for _, group := range requiredGroups { - if HasGroup(claims, group) { - return true - } - } - return false -} - -// HasAllGroups checks if a user belongs to all of the specified groups -func HasAllGroups(claims jwt.MapClaims, requiredGroups []string) bool { - for _, group := range requiredGroups { - if !HasGroup(claims, group) { - return false - } - } - return true -} - -// IsValidJWKSURL validates that a JWKS URL is secure and from a trusted domain -func IsValidJWKSURL(urlStr string) error { - parsed, err := url.Parse(urlStr) - if err != nil { - return fmt.Errorf("invalid URL format: %w", err) - } - - // Add your trusted domains here - trustedDomains := []string{ - "cognito-idp.us-east-1.amazonaws.com", - "cognito-idp.us-west-2.amazonaws.com", - // Add other AWS Cognito regions as needed - } - - isAllowed := false - for _, domain := range trustedDomains { - if parsed.Host == domain { - isAllowed = true - break - } - } - - if !isAllowed { - return fmt.Errorf("untrusted JWKS domain: %s", parsed.Host) - } - - // Ensure HTTPS - if parsed.Scheme != "https" { - return fmt.Errorf("JWKS URL must use HTTPS") - } - - return nil -} - -// VerifyGroupMembership verifies a user belongs to specified groups -func VerifyGroupMembership(claims jwt.MapClaims, expectedGroups []string) error { - groups, ok := claims["cognito:groups"].([]interface{}) - if !ok { - return fmt.Errorf("expected 'cognito:groups' claim, but not found") - } - - for _, eg := range expectedGroups { - found := false - for _, g := range groups { - if gStr, ok := g.(string); ok && strings.EqualFold(gStr, eg) { - found = true - break - } - } - if !found { - return fmt.Errorf("expected group %s not found in token", eg) - } - } - - return nil -} diff --git a/internal/rbac/cognito_test.go b/internal/rbac/cognito_test.go deleted file mode 100644 index 7cd786b0..00000000 --- a/internal/rbac/cognito_test.go +++ /dev/null @@ -1,590 +0,0 @@ -package rbac_test - -import ( - "crypto/rsa" - "encoding/base64" - "encoding/json" - "fmt" - "math/big" - "net/http" - "net/http/httptest" - "reflect" - "testing" - "time" - - "queryorchestration/internal/rbac" - - "github.com/golang-jwt/jwt/v5" - "github.com/stretchr/testify/assert" -) - -// TestLocalKeyProvider validates that the LocalKeyProvider can successfully -// load both private and public keys from the specified PEM files. -func TestLocalKeyProvider(t *testing.T) { - provider := rbac.NewLocalKeyProvider("private_key.pem", "public_key.pem") - - // Test loading private key - privateKey, err := provider.GetPrivateKey() - if err != nil { - t.Fatalf("Failed to load private key: %v", err) - } - if privateKey == nil { - t.Fatal("Private key is nil") - } - - // Test loading public key - publicKey, err := provider.GetPublicKey("any-kid") // kid is ignored for local provider - if err != nil { - t.Fatalf("Failed to load public key: %v", err) - } - if publicKey == nil { - t.Fatal("Public key is nil") - } -} - -// TestGenerateAndValidateJWT tests the complete JWT lifecycle: -// 1. Generating a mock JWT token with specific claims (userID, email, groups) -// 2. Validating the token with the same key provider -// 3. Verifying that all claims are correctly preserved and can be retrieved -// This test covers both tokens with and without group information. -func TestGenerateAndValidateJWT(t *testing.T) { - provider := rbac.NewLocalKeyProvider("private_key.pem", "public_key.pem") - - testCases := []struct { - name string - userID string - email string - groups []string - expected bool - }{ - { - name: "Valid token with groups", - userID: "user123", - email: "user@example.com", - groups: []string{"admins", "developers"}, - expected: true, - }, - { - name: "Valid token without groups", - userID: "user456", - email: "user2@example.com", - groups: []string{}, - expected: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - // Generate token - tokenString, err := rbac.GenerateTestJWT(provider, tc.userID, tc.email, tc.groups) - if err != nil { - t.Fatalf("Failed to generate token: %v", err) - } - - // Validate token - token, claims, err := rbac.ValidateJWT(tokenString, provider) - if err != nil { - t.Fatalf("Failed to validate token: %v", err) - } - if !token.Valid { - t.Fatal("Token should be valid") - } - - // Check claims - if sub, ok := claims["sub"].(string); !ok || sub != tc.userID { - t.Errorf("Expected sub=%s, got %v", tc.userID, claims["sub"]) - } - if email, ok := claims["email"].(string); !ok || email != tc.email { - t.Errorf("Expected email=%s, got %v", tc.email, claims["email"]) - } - - // Check groups - if len(tc.groups) > 0 { - groups, ok := claims["cognito:groups"].([]interface{}) - if !ok { - t.Fatal("Expected cognito:groups claim, but not found") - } - - if len(groups) != len(tc.groups) { - t.Fatalf("Expected %d groups, got %d", len(tc.groups), len(groups)) - } - - for i, expectedGroup := range tc.groups { - if groups[i] != expectedGroup { - t.Errorf("Expected group %s at position %d, got %v", expectedGroup, i, groups[i]) - } - } - } - }) - } -} - -// TestTokenExpiration verifies that token expiration works correctly: -// 1. A token with a future expiration time should be considered valid -// 2. A token with a past expiration time would be rejected by the JWT library -// The actual expired token test is commented out because jwt.Parse -// automatically validates expiration times. -func TestTokenExpiration(t *testing.T) { - provider := rbac.NewLocalKeyProvider("private_key.pem", "public_key.pem") - - // Helper function to generate a token with custom claims - generateCustomToken := func(expiry time.Time) (string, error) { - privateKey, err := provider.GetPrivateKey() - if err != nil { - return "", err - } - - headers := map[string]interface{}{ - "kid": "test-key-id", - "alg": "RS256", - } - - token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ - "sub": "test-user", - "email": "test@example.com", - "exp": expiry.Unix(), - "iat": time.Now().Unix(), - "iss": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXXXX", - "cognito:groups": []string{"admins"}, - }) - - for k, v := range headers { - token.Header[k] = v - } - - return token.SignedString(privateKey) - } - - // Test 1: Valid token (not expired) - t.Run("Valid token not expired", func(t *testing.T) { - tokenString, err := generateCustomToken(time.Now().Add(1 * time.Hour)) - if err != nil { - t.Fatalf("Failed to generate token: %v", err) - } - - token, _, err := rbac.ValidateJWT(tokenString, provider) - if err != nil { - t.Fatalf("Expected valid token, got error: %v", err) - } - if !token.Valid { - t.Fatal("Token should be valid") - } - }) - - // Test 2: Expired token - // This test is commented out because jwt.Parse will already validate expiration - // and return an error, so we can't directly test expired tokens with ValidateJWT - /* - t.Run("Expired token", func(t *testing.T) { - tokenString, err := generateCustomToken(time.Now().Add(-1 * time.Hour)) - if err != nil { - t.Fatalf("Failed to generate token: %v", err) - } - - _, _, err = rbac.ValidateJWT(tokenString, provider) - if err == nil { - t.Fatal("Expected error for expired token, got nil") - } - }) - */ -} - -// TestExtractTokenDetails verifies that the ExtractTokenDetails function -// correctly extracts and organizes user information from the JWT token: -// - UserID -// - Email -// - Group memberships -// - Token expiration time -// This ensures user context can be properly reconstructed from the token. -func TestExtractTokenDetails(t *testing.T) { - provider := rbac.NewLocalKeyProvider("private_key.pem", "public_key.pem") - - userID := "test-user-456" - email := "test456@example.com" - groups := []string{"admins", "developers", "testers"} - - tokenString, err := rbac.GenerateTestJWT(provider, userID, email, groups) - if err != nil { - t.Fatalf("Failed to generate token: %v", err) - } - - token, claims, err := rbac.ValidateJWT(tokenString, provider) - if err != nil { - t.Fatalf("Failed to validate token: %v", err) - } - - details := rbac.ExtractTokenDetails(token, claims) - - // Check extracted details - if details.UserID != userID { - t.Errorf("Expected UserID=%s, got %s", userID, details.UserID) - } - if details.Email != email { - t.Errorf("Expected Email=%s, got %s", email, details.Email) - } - if !reflect.DeepEqual(details.Groups, groups) { - t.Errorf("Expected Groups=%v, got %v", groups, details.Groups) - } - - // Check expiration (should be about 1 hour in the future) - expectedExp := time.Now().Add(1 * time.Hour).Unix() - actualExp := details.Expiration.Unix() - - // Allow a small time difference (5 seconds) due to test execution time - if actualExp < expectedExp-5 || actualExp > expectedExp+5 { - t.Errorf("Expected Expiration around %v, got %v", expectedExp, actualExp) - } -} - -// TestGroupMembershipFunctions validates the three group membership check functions: -// 1. HasGroup - Tests if a user belongs to a specific group -// 2. HasAnyGroup - Tests if a user belongs to at least one of several groups -// 3. HasAllGroups - Tests if a user belongs to all specified groups -// Each test includes positive and negative cases, as well as case-insensitive matching. -func TestGroupMembershipFunctions(t *testing.T) { - // Create test claims - claims := jwt.MapClaims{ - "cognito:groups": []interface{}{"admins", "developers", "viewers"}, - } - - // Test HasGroup - t.Run("HasGroup", func(t *testing.T) { - testCases := []struct { - group string - expected bool - }{ - {"admins", true}, - {"developers", true}, - {"viewers", true}, - {"editors", false}, - {"ADMINS", true}, // Case-insensitive match - } - - for _, tc := range testCases { - t.Run(tc.group, func(t *testing.T) { - result := rbac.HasGroup(claims, tc.group) - if result != tc.expected { - t.Errorf("HasGroup(%q) = %v; want %v", tc.group, result, tc.expected) - } - }) - } - }) - - // Test HasAnyGroup - t.Run("HasAnyGroup", func(t *testing.T) { - testCases := []struct { - groups []string - expected bool - }{ - {[]string{"admins", "editors"}, true}, - {[]string{"editors", "writers"}, false}, - {[]string{"ADMINS", "editors"}, true}, // Case-insensitive match - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("%v", tc.groups), func(t *testing.T) { - result := rbac.HasAnyGroup(claims, tc.groups) - if result != tc.expected { - t.Errorf("HasAnyGroup(%v) = %v; want %v", tc.groups, result, tc.expected) - } - }) - } - }) - - // Test HasAllGroups - t.Run("HasAllGroups", func(t *testing.T) { - testCases := []struct { - groups []string - expected bool - }{ - {[]string{"admins", "developers"}, true}, - {[]string{"admins", "editors"}, false}, - {[]string{"ADMINS", "DEVELOPERS"}, true}, // Case-insensitive match - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("%v", tc.groups), func(t *testing.T) { - result := rbac.HasAllGroups(claims, tc.groups) - if result != tc.expected { - t.Errorf("HasAllGroups(%v) = %v; want %v", tc.groups, result, tc.expected) - } - }) - } - }) -} - -// TestVerifyGroupMembership validates the VerifyGroupMembership function, -// which ensures that a user belongs to all required groups. -// It tests: -// 1. Successful case where all required groups are present -// 2. Error case where a required group is missing -// 3. Case-insensitive group matching -// 4. Error handling when the cognito:groups claim is missing entirely -func TestVerifyGroupMembership(t *testing.T) { - claims := jwt.MapClaims{ - "cognito:groups": []interface{}{"admins", "developers", "viewers"}, - } - - testCases := []struct { - name string - expectedGroups []string - wantErr bool - }{ - { - name: "All groups present", - expectedGroups: []string{"admins", "developers"}, - wantErr: false, - }, - { - name: "Missing group", - expectedGroups: []string{"admins", "editors"}, - wantErr: true, - }, - { - name: "Case insensitive match", - expectedGroups: []string{"ADMINS", "DEVELOPERS"}, - wantErr: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := rbac.VerifyGroupMembership(claims, tc.expectedGroups) - if tc.wantErr { - assert.Error(t, err) - } else { - assert.NoError(t, err) - } - }) - } -} - -// TestIsValidJWKSURL tests the URL validation for JWKS endpoints. -// -// JWKS (JSON Web Key Set) is a standard format used to publish public keys as a set of JWKs (JSON Web Keys). -// In the AWS Cognito context, JWKS endpoints allow services to retrieve the public keys needed to verify -// JWT tokens issued by Cognito. These endpoints must be secured (HTTPS) and trusted to prevent -// token forgery attacks. -// -// This test ensures that: -// 1. Valid Cognito JWKS URLs are accepted -// 2. Insecure URLs (HTTP instead of HTTPS) are rejected -// 3. URLs from untrusted domains are rejected -// 4. Malformed URLs are rejected -// -// This validation is critical for preventing security issues like malicious redirects, -// SSRF (Server-Side Request Forgery) attacks, or using untrusted key sources for JWT verification. -// This is important for preventing malicious redirects or SSRF attacks. -func TestIsValidJWKSURL(t *testing.T) { - testCases := []struct { - name string - url string - expectError bool - }{ - { - name: "Valid URL format and domain", - url: "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABC123/.well-known/jwks.json", - expectError: false, - }, - { - name: "Invalid scheme (HTTP)", - url: "http://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABC123/.well-known/jwks.json", - expectError: true, - }, - { - name: "Untrusted domain", - url: "https://malicious-site.com/jwks.json", - expectError: true, - }, - { - name: "Malformed URL", - url: ":not-a-url", - expectError: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := rbac.IsValidJWKSURL(tc.url) - if tc.expectError && err == nil { - t.Errorf("Expected error, got nil") - } else if !tc.expectError && err != nil { - t.Errorf("Expected no error, got %v", err) - } - }) - } -} - -// Additional tests added 3/19/25 follow. -//////////////////////////////////////////////////////////////////////////////// - -// This test uses reflection to access the unexported jwkToPublicKey function -func TestJwkToPublicKey(t *testing.T) { - // Example valid modulus (n) and exponent (e) encoded in base64 URL format - n := "ANmflPLn7S9tj88H-HiJ5mHaQ-4F9JhOZ9EHpQGC_iJ1aXm9tZso4YF9Qf1S5Pa1vX7JqJhudcAnvQIRkcwE0xj8GfJQm0bgWDulnGnQZBM-MQXs-9ZCh24z0kDGeWL3osvAew8pyzvP68y5tie2QHsucbj35Y7_5aiTn0DmvXYRpbQxLJ70xvi7Zp7wGi5rFBThjNrO-c-jIaAnZzupfG1LNz5Bpgpc" - e := "AQAB" - - // Manual implementation of jwkToPublicKey for validation - nBytes, err := base64.RawURLEncoding.DecodeString(n) - assert.NoError(t, err) - - eBytes, err := base64.RawURLEncoding.DecodeString(e) - assert.NoError(t, err) - - modulus := new(big.Int) - modulus.SetBytes(nBytes) - - var exponent int - for i := 0; i < len(eBytes); i++ { - exponent = exponent<<8 + int(eBytes[i]) - } - - // Now set up a mock server to test the GetPublicKey method - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - jwksJSON := fmt.Sprintf(`{ - "keys": [ - { - "kid": "test-key-id", - "kty": "RSA", - "n": "%s", - "e": "%s", - "use": "sig", - "alg": "RS256" - } - ] - }`, n, e) - w.Header().Set("Content-Type", "application/json") - _, err2 := w.Write([]byte(jwksJSON)) - if err2 != nil { - return - } - })) - defer server.Close() - - // Create a test JWKS result for validation - var testJWKS rbac.JWKS - testJWKSData := fmt.Sprintf(`{ - "keys": [ - { - "kid": "test-key-id", - "kty": "RSA", - "n": "%s", - "e": "%s", - "use": "sig", - "alg": "RS256" - } - ] - }`, n, e) - err = json.Unmarshal([]byte(testJWKSData), &testJWKS) - assert.NoError(t, err) - - // The test itself just verifies that we can parse the JWKS data - // This indirectly tests jwkToPublicKey since it's called inside GetPublicKey - assert.Equal(t, "test-key-id", testJWKS.Keys[0].Kid) - assert.Equal(t, n, testJWKS.Keys[0].N) - assert.Equal(t, e, testJWKS.Keys[0].E) -} - -// This test implements a mock HTTP server to test CognitoKeyProvider.GetPublicKey -func TestCognitoKeyProviderGetPublicKey(t *testing.T) { - // Set up a mock HTTP server to simulate the JWKS endpoint - n := "ANmflPLn7S9tj88H-HiJ5mHaQ-4F9JhOZ9EHpQGC_iJ1aXm9tZso4YF9Qf1S5Pa1vX7JqJhudcAnvQIRkcwE0xj8GfJQm0bgWDulnGnQZBM-MQXs-9ZCh24z0kDGeWL3osvAew8pyzvP68y5tie2QHsucbj35Y7_5aiTn0DmvXYRpbQxLJ70xvi7Zp7wGi5rFBThjNrO-c-jIaAnZzupfG1LNz5Bpgpc" - e := "AQAB" - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Make sure the request path matches what we expect - assert.Contains(t, r.URL.Path, "/.well-known/jwks.json") - - jwksJSON := fmt.Sprintf(`{ - "keys": [ - { - "kid": "test-key-id", - "kty": "RSA", - "n": "%s", - "e": "%s", - "use": "sig", - "alg": "RS256" - } - ] - }`, n, e) - w.Header().Set("Content-Type", "application/json") - _, err := w.Write([]byte(jwksJSON)) - if err != nil { - return - } - })) - defer server.Close() - - // Override the host and protocol in the CognitoKeyProvider - // We'll create a standard CognitoKeyProvider and then use reflection to modify its fields - provider := rbac.NewCognitoKeyProvider("us-east-1", "test-pool-id") - - // Use reflection to modify the actual URL used by GetPublicKey - // This isn't the cleanest approach, but it allows us to test without modifying the original code - providerValue := reflect.ValueOf(provider) - - // Get the cache field to check caching - jwksCacheField := reflect.Indirect(providerValue).FieldByName("JwksCache") - //jwksCache := jwksCacheField.Interface().(map[string]*rsa.PublicKey) - //assert.NotNil(t, jwksCache) - jwksCacheInterface := jwksCacheField.Interface() - jwksCache, ok := jwksCacheInterface.(map[string]*rsa.PublicKey) - assert.True(t, ok, "JwksCache field is not of expected type") - assert.NotNil(t, jwksCache) - - // Instead of trying to patch the URL (which is difficult with reflection), - // we'll verify that the provider was created correctly - regionField := reflect.Indirect(providerValue).FieldByName("AuthRegion") - userPoolIDField := reflect.Indirect(providerValue).FieldByName("AuthUserPoolID") - - assert.Equal(t, "us-east-1", regionField.String()) - assert.Equal(t, "test-pool-id", userPoolIDField.String()) -} - -// TestNewCognitoKeyProvider tests the NewCognitoKeyProvider function -func TestNewCognitoKeyProvider(t *testing.T) { - // Create a provider with test values - region := "us-west-2" - userPoolID := "us-west-2_testpool" - - provider := rbac.NewCognitoKeyProvider(region, userPoolID) - assert.NotNil(t, provider) - - // Use reflection to check the internal fields - providerValue := reflect.ValueOf(provider).Elem() - - regionField := providerValue.FieldByName("AuthRegion") - assert.Equal(t, region, regionField.String()) - - userPoolIDField := providerValue.FieldByName("AuthUserPoolID") - assert.Equal(t, userPoolID, userPoolIDField.String()) - - jwksCacheField := providerValue.FieldByName("JwksCache") - jwksCacheInterface := jwksCacheField.Interface() - jwksCache, ok := jwksCacheInterface.(map[string]*rsa.PublicKey) - assert.True(t, ok, "JwksCache field is not of expected type") - assert.NotNil(t, jwksCache) - assert.Len(t, jwksCache, 0) // Should be empty initially -} - -// TestPrintTokenDetails tests the PrintTokenDetails function -func TestPrintTokenDetails(t *testing.T) { - // Create a simple JWT token - token := &jwt.Token{ - Header: map[string]interface{}{ - "alg": "RS256", - "kid": "test-key-id", - }, - Claims: jwt.MapClaims{ - "sub": "user123", - "email": "user@example.com", - "exp": float64(time.Now().Add(time.Hour).Unix()), - }, - Method: jwt.SigningMethodRS256, - Signature: []byte("sample-signature"), - Valid: true, - } - - // Since PrintTokenDetails just prints to stdout and doesn't return anything, - // we'll just call it and make sure it doesn't panic for coverage. - rbac.PrintTokenDetails(token) -} diff --git a/internal/rbac/middleware.go b/internal/rbac/middleware.go deleted file mode 100644 index 39dea317..00000000 --- a/internal/rbac/middleware.go +++ /dev/null @@ -1,261 +0,0 @@ -package rbac - -import ( - "errors" - "fmt" - "log/slog" - "net/http" - "strings" - - "github.com/golang-jwt/jwt/v5" - "github.com/labstack/echo/v4" -) - -// JWTConfig contains configuration for the JWT middleware -type JWTConfig struct { - KeyProvider KeyProvider - TokenLookup string // Format: "header:" or "query:" or "cookie:" - AuthScheme string // Usually "Bearer" - RequiredGroups []string // Groups that are required for access (any one of these) - ContextKey string // Key to store the claims in the context - ErrorHandler func(echo.Context, error) error - Logger *slog.Logger // Logger instance for middleware -} - -// DefaultJWTConfig is the default JWT auth middleware config -var DefaultJWTConfig = JWTConfig{ - TokenLookup: "header:Authorization", - AuthScheme: "Bearer", - ContextKey: "user", - ErrorHandler: defaultErrorHandler, -} - -// defaultErrorHandler returns a 401 Unauthorized error for JWT validation failures -func defaultErrorHandler(c echo.Context, err error) error { - return echo.NewHTTPError(http.StatusUnauthorized, "invalid or expired jwt") -} - -// extractToken determines which token extractor to use based on config -func extractToken(config JWTConfig) func(echo.Context) (string, error) { - parts := strings.Split(config.TokenLookup, ":") - extractor := tokenFromHeader(parts[1], config.AuthScheme) - if parts[0] == "query" { - extractor = tokenFromQuery(parts[1]) - } else if parts[0] == "cookie" { - extractor = tokenFromCookie(parts[1]) - } - return extractor -} - -// validateGroups checks if the user belongs to any of the required groups -func validateGroups(claims jwt.MapClaims, requiredGroups []string, logger *slog.Logger) bool { - if len(requiredGroups) == 0 { - logger.Debug("no required groups specified, access granted") - return true - } - - groups, ok := claims["cognito:groups"].([]interface{}) - if !ok { - logger.Warn("no groups found in claims", "user", claims["sub"]) - return false - } - - userGroups := make([]string, 0) - for _, group := range groups { - if groupStr, ok := group.(string); ok { - userGroups = append(userGroups, groupStr) - } - } - - for _, reqGroup := range requiredGroups { - for _, group := range groups { - if groupStr, ok := group.(string); ok && strings.EqualFold(groupStr, reqGroup) { - logger.Debug("group validation successful", - "user", claims["sub"], - "required_group", reqGroup, - "user_groups", userGroups) - return true - } - } - } - - logger.Warn("group validation failed", - "user", claims["sub"], - "required_groups", requiredGroups, - "user_groups", userGroups) - return false -} - -// parseJWT parses and validates the JWT token -func parseJWT(tokenString string, keyProvider KeyProvider, logger *slog.Logger) (*jwt.Token, jwt.MapClaims, error) { - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { - if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { - logger.Error("unexpected signing method", "method", token.Method.Alg()) - return nil, errors.New("unexpected signing method") - } - - // Get key ID from token header - kid, ok := token.Header["kid"].(string) - if !ok { - logger.Error("no key ID in token header") - return nil, errors.New("no key ID (kid) in token header") - } - - // Get public key from provider - return keyProvider.GetPublicKey(kid) - }) - - if err != nil { - logger.Error("failed to parse JWT", "error", err) - return nil, nil, err - } - - claims, ok := token.Claims.(jwt.MapClaims) - if !ok || !token.Valid { - logger.Error("invalid token claims") - return nil, nil, errors.New("invalid token") - } - - logger.Debug("JWT parsed successfully", - "user", claims["sub"], - "email", claims["email"]) - return token, claims, nil -} - -// JWTWithConfig returns a JWT auth middleware with config -func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc { - // Set defaults - if config.TokenLookup == "" { - config.TokenLookup = DefaultJWTConfig.TokenLookup - } - if config.AuthScheme == "" { - config.AuthScheme = DefaultJWTConfig.AuthScheme - } - if config.ContextKey == "" { - config.ContextKey = DefaultJWTConfig.ContextKey - } - if config.ErrorHandler == nil { - config.ErrorHandler = DefaultJWTConfig.ErrorHandler - } - if config.KeyProvider == nil { - panic("JWT middleware requires a KeyProvider") - } - if config.Logger == nil { - config.Logger = slog.Default() - } - - extractor := extractToken(config) - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - tokenString, err := extractor(c) - if err != nil { - config.Logger.Error("failed to extract token", - "error", err, - "path", c.Request().URL.Path, - "method", c.Request().Method) - return config.ErrorHandler(c, err) - } - - _, claims, err := parseJWT(tokenString, config.KeyProvider, config.Logger) - if err != nil { - config.Logger.Error("failed to validate JWT", - "error", err, - "path", c.Request().URL.Path, - "method", c.Request().Method) - return config.ErrorHandler(c, err) - } - - // Check required groups if specified - if !validateGroups(claims, config.RequiredGroups, config.Logger) { - config.Logger.Warn("insufficient permissions", - "user", claims["sub"], - "path", c.Request().URL.Path, - "method", c.Request().Method) - return echo.NewHTTPError(http.StatusForbidden, "insufficient permissions") - } - - // Store user information in context - c.Set(config.ContextKey, claims) - - config.Logger.Info("authenticated request", - "user", claims["sub"], - "path", c.Request().URL.Path, - "method", c.Request().Method) - - return next(c) - } - } -} - -// JWT returns a JWT auth middleware with default configuration -func JWT(keyProvider KeyProvider) echo.MiddlewareFunc { - config := DefaultJWTConfig - config.KeyProvider = keyProvider - return JWTWithConfig(config) -} - -// tokenFromHeader extracts token from Authorization header -func tokenFromHeader(header string, authScheme string) func(echo.Context) (string, error) { - return func(c echo.Context) (string, error) { - auth := c.Request().Header.Get(header) - if auth == "" { - return "", fmt.Errorf("missing auth header: %s", header) - } - - l := len(authScheme) - if len(auth) > l+1 && auth[:l] == authScheme { - return auth[l+1:], nil - } - return "", fmt.Errorf("invalid auth header format for scheme: %s", authScheme) - } -} - -// tokenFromQuery extracts token from query parameter -func tokenFromQuery(param string) func(echo.Context) (string, error) { - return func(c echo.Context) (string, error) { - token := c.QueryParam(param) - if token == "" { - return "", errors.New("missing auth query parameter") - } - return token, nil - } -} - -// tokenFromCookie extracts token from cookie -func tokenFromCookie(name string) func(echo.Context) (string, error) { - return func(c echo.Context) (string, error) { - cookie, err := c.Cookie(name) - if err != nil { - return "", err - } - return cookie.Value, nil - } -} - -//// GroupGuard middleware ensures a user has at least one of the required groups -//func GroupGuard(requiredGroups ...string) echo.MiddlewareFunc { -// return func(next echo.HandlerFunc) echo.HandlerFunc { -// return func(c echo.Context) error { -// userClaims, ok := c.Get("user").(jwt.MapClaims) -// if !ok { -// return echo.NewHTTPError(http.StatusUnauthorized, "user not authenticated") -// } -// -// groups, ok := userClaims["cognito:groups"].([]interface{}) -// if !ok { -// return echo.NewHTTPError(http.StatusForbidden, "no groups found for user") -// } -// -// for _, requiredGroup := range requiredGroups { -// for _, group := range groups { -// if groupStr, ok := group.(string); ok && strings.EqualFold(groupStr, requiredGroup) { -// return next(c) -// } -// } -// } -// -// return echo.NewHTTPError(http.StatusForbidden, "insufficient permissions") -// } -// } -//} diff --git a/internal/rbac/middleware_endpoint_test.go b/internal/rbac/middleware_endpoint_test.go deleted file mode 100644 index 9e377b26..00000000 --- a/internal/rbac/middleware_endpoint_test.go +++ /dev/null @@ -1,228 +0,0 @@ -package rbac_test - -import ( - "net/http" - "net/http/httptest" - "testing" - - "queryorchestration/internal/rbac" - - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/assert" -) - -// testSetup creates a new Echo instance and key provider for testing -func testSetup(t *testing.T) (*echo.Echo, *rbac.LocalKeyProvider) { - // Use local key files - privateKeyPath := "./private_key.pem" - publicKeyPath := "./public_key.pem" - - // Create and initialize key provider - keyProvider := rbac.NewLocalKeyProvider(privateKeyPath, publicKeyPath) - //TestKeyProvider(t, privateKeyPath, publicKeyPath) - - // Initialize Echo instance - e := echo.New() - - return e, keyProvider -} - -// createTestEndpoint creates a test endpoint with the given JWT config -func createTestEndpoint(e *echo.Echo, config rbac.JWTConfig) { - e.GET("/test", func(c echo.Context) error { - return c.String(http.StatusOK, "authorized") - }, rbac.JWTWithConfig(config)) -} - -// makeTestRequest creates and executes a test request with the given token -func makeTestRequest(t *testing.T, e *echo.Echo, token string, setupReq func(*http.Request)) *httptest.ResponseRecorder { - req := httptest.NewRequest(http.MethodGet, "/test", nil) - if setupReq != nil { - setupReq(req) - } else { - req.Header.Set("Authorization", "Bearer "+token) - } - rec := httptest.NewRecorder() - e.ServeHTTP(rec, req) - return rec -} - -// TestJWTMiddleware tests the core JWT middleware functionality with group-based authorization. -// It validates: -// 1. A user with the required 'foo' group can access a protected endpoint -// 2. A user with only 'bar' group (and not 'foo') is properly denied access -// 3. A user with multiple groups including the required 'foo' group is granted access -// This test demonstrates the basic setup for protecting routes with the JWT middleware -// and ensuring only users with appropriate group membership can access restricted resources. -func TestJWTMiddleware(t *testing.T) { - e, keyProvider := testSetup(t) - - // Set up a restricted endpoint that requires the 'foo' group - createTestEndpoint(e, rbac.JWTConfig{ - KeyProvider: keyProvider, - RequiredGroups: []string{"foo"}, - }) - - // Test cases - tests := []struct { - name string - groups []string - wantStatus int - }{ - { - name: "Authorized user with 'foo' group", - groups: []string{"foo"}, - wantStatus: http.StatusOK, - }, - { - name: "Unauthorized user with 'bar' group", - groups: []string{"bar"}, - wantStatus: http.StatusForbidden, - }, - { - name: "User with multiple groups including required", - groups: []string{"bar", "foo", "baz"}, - wantStatus: http.StatusOK, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Generate JWT token with test groups - token, err := rbac.GenerateTestJWT(keyProvider, "test-user-id", "test@example.com", tt.groups) - if err != nil { - t.Fatalf("Failed to generate JWT: %v", err) - } - - // Make test request and verify response - rec := makeTestRequest(t, e, token, nil) - assert.Equal(t, tt.wantStatus, rec.Code) - if tt.wantStatus == http.StatusOK { - assert.Equal(t, "authorized", rec.Body.String()) - } - }) - } -} - -// TestTokenExtraction validates different methods for extracting JWT tokens: -// 1. From Authorization header (standard Bearer token) -// 2. From URL query parameters -// 3. From cookies -// Each method is configured through the TokenLookup field in JWTConfig. -// The test confirms that the middleware can successfully authenticate a user -// regardless of where the token is provided, as long as it's valid and -// contains the required group membership. -func TestTokenExtraction(t *testing.T) { - _, keyProvider := testSetup(t) - - // Generate JWT token with 'foo' group - token, err := rbac.GenerateTestJWT(keyProvider, "test-user-id", "test@example.com", []string{"foo"}) - if err != nil { - t.Fatalf("Failed to generate JWT: %v", err) - } - - // Test different token extraction methods - tests := []struct { - name string - config rbac.JWTConfig - setupReq func(req *http.Request) - wantStatus int - }{ - { - name: "Extract from header", - config: rbac.JWTConfig{ - KeyProvider: keyProvider, - TokenLookup: "header:Authorization", - AuthScheme: "Bearer", - RequiredGroups: []string{"foo"}, - }, - setupReq: func(req *http.Request) { - req.Header.Set("Authorization", "Bearer "+token) - }, - wantStatus: http.StatusOK, - }, - { - name: "Extract from query parameter", - config: rbac.JWTConfig{ - KeyProvider: keyProvider, - TokenLookup: "query:token", - RequiredGroups: []string{"foo"}, - }, - setupReq: func(req *http.Request) { - q := req.URL.Query() - q.Add("token", token) - req.URL.RawQuery = q.Encode() - }, - wantStatus: http.StatusOK, - }, - { - name: "Extract from cookie", - config: rbac.JWTConfig{ - KeyProvider: keyProvider, - TokenLookup: "cookie:jwt", - RequiredGroups: []string{"foo"}, - }, - setupReq: func(req *http.Request) { - req.AddCookie(&http.Cookie{ - Name: "jwt", - Value: token, - }) - }, - wantStatus: http.StatusOK, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Create new Echo instance for each test to avoid config conflicts - e := echo.New() - createTestEndpoint(e, tt.config) - - // Make test request and verify response - rec := makeTestRequest(t, e, token, tt.setupReq) - assert.Equal(t, tt.wantStatus, rec.Code) - if tt.wantStatus == http.StatusOK { - assert.Equal(t, "authorized", rec.Body.String()) - } - }) - } -} - -// TestCustomErrorHandler verifies that custom error handling works correctly. -// It tests: -// 1. Setting up a custom error handler function in the JWTConfig -// 2. Sending an invalid JWT token in the request -// 3. Confirming that the custom error handler is invoked and provides -// the expected response format and status code -// -// This allows for customized error responses when authentication fails, -// which is useful for providing more context or formatting errors -// according to API standards. -func TestCustomErrorHandler(t *testing.T) { - e, keyProvider := testSetup(t) - - // Custom error handler - customErrorHandler := func(c echo.Context, err error) error { - return c.JSON(http.StatusUnauthorized, map[string]string{ - "error": "Custom auth error: " + err.Error(), - }) - } - - // Set up a restricted endpoint with custom error handler - createTestEndpoint(e, rbac.JWTConfig{ - KeyProvider: keyProvider, - RequiredGroups: []string{"foo"}, - ErrorHandler: customErrorHandler, - }) - - // Create test request with invalid token and verify response - rec := makeTestRequest(t, e, "invalidtoken", nil) - assert.Equal(t, http.StatusUnauthorized, rec.Code) - assert.Contains(t, rec.Body.String(), "Custom auth error") -} - -// These tests require valid RSA key files (private_key.pem and public_key.pem) -// in the current directory. These keys are used to sign and verify JWT tokens -// during the tests. In a production environment, the public key would typically -// be retrieved from AWS Cognito's JWKS endpoint, but for testing, we use local files. -// Make sure to generate these key files before running the tests. diff --git a/internal/rbac/middleware_test.go b/internal/rbac/middleware_test.go deleted file mode 100644 index f2b0ef6f..00000000 --- a/internal/rbac/middleware_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package rbac_test - -import ( - "crypto/rsa" - "math/big" - "net/http" - "net/http/httptest" - "testing" - - "queryorchestration/internal/rbac" - - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/assert" -) - -// mockKeyProvider is a mock implementation of the KeyProvider interface -type mockKeyProvider struct{} - -// GetPublicKey returns a mock public key -func (m *mockKeyProvider) GetPublicKey(kid string) (*rsa.PublicKey, error) { - // Create a mock RSA public key with minimal valid structure - return &rsa.PublicKey{ - N: big.NewInt(123), // Just a dummy value - E: 65537, // Common RSA exponent - }, nil -} - -// createMockKeyProvider creates a mock KeyProvider for testing -func createMockKeyProvider() rbac.KeyProvider { - return &mockKeyProvider{} -} - -// TestDefaultErrorHandler tests the defaultErrorHandler function -func TestDefaultErrorHandler(t *testing.T) { - // Create a new Echo instance - e := echo.New() - req := httptest.NewRequest(http.MethodGet, "/", nil) - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - // Create a test error - //testErr := errors.New("test error") - - // Access the defaultErrorHandler function directly - // In a real implementation, you might use an exported test helper function like: - // err := rbac.DefaultErrorHandlerTest(c, testErr) - - // In this case, we'll test the error handler through the Echo middleware - // by creating a config with our own error handler that logs what was called - var capturedError error - customErrorHandler := func(c echo.Context, err error) error { - capturedError = err - return echo.NewHTTPError(http.StatusUnauthorized, "captured: "+err.Error()) - } - - config := rbac.JWTConfig{ - KeyProvider: createMockKeyProvider(), - ErrorHandler: customErrorHandler, - } - - // Create middleware with our config - middleware := rbac.JWTWithConfig(config) - - // Create a handler that should never be called - handler := func(c echo.Context) error { - return c.String(http.StatusOK, "success") - } - - // Call the middleware with a bad request (no Authorization header) - middlewareHandler := middleware(handler) - err := middlewareHandler(c) - - // Verify that our error handler was called - assert.NotNil(t, capturedError) - assert.NotNil(t, err) - - // The error should be an HTTP error - httpErr, ok := err.(*echo.HTTPError) - assert.True(t, ok) - assert.Equal(t, http.StatusUnauthorized, httpErr.Code) -} - -// TestJWT tests the JWT function which creates middleware with default config -func TestJWT(t *testing.T) { - // Create a new Echo instance - e := echo.New() - - // Create a simple test endpoint with the JWT middleware - e.GET("/protected", func(c echo.Context) error { - return c.String(http.StatusOK, "success") - }, rbac.JWT(createMockKeyProvider())) - - // Create a test request with an invalid token (format doesn't matter for this test) - // The mock key provider will accept any token - req := httptest.NewRequest(http.MethodGet, "/protected", nil) - req.Header.Set("Authorization", "Bearer valid-token") - rec := httptest.NewRecorder() - - // Process the request (this will fail because our mock doesn't properly validate) - e.ServeHTTP(rec, req) - - // The response status should reflect whether validation succeeded - // In a real test, this would depend on token validity - // Here, we expect an error because our mock key provider doesn't correctly - // validate the token structure - assert.Equal(t, http.StatusUnauthorized, rec.Code) -} - -// TestJWTWithMissingHeader tests JWT middleware with a missing Authorization header -func TestJWTWithMissingHeader(t *testing.T) { - // Create a new Echo instance - e := echo.New() - - // Create a simple test endpoint with the JWT middleware - e.GET("/protected", func(c echo.Context) error { - return c.String(http.StatusOK, "success") - }, rbac.JWT(createMockKeyProvider())) - - // Create a test request with no Authorization header - req := httptest.NewRequest(http.MethodGet, "/protected", nil) - rec := httptest.NewRecorder() - - // Process the request - e.ServeHTTP(rec, req) - - // This should fail with a 401 Unauthorized - assert.Equal(t, http.StatusUnauthorized, rec.Code) -} diff --git a/internal/rbac/private_key.pem b/internal/rbac/private_key.pem deleted file mode 100644 index c6ad7f8f..00000000 --- a/internal/rbac/private_key.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDX5vunPVZ3fVNY -dwJzOvTsgoHWEQlkXs/FSjHz90HzLCloZ8/g7yqIEPwmxmHHkHVjMJryyhzoOhnU -6OYuDDFiTlWL6UFX74+EC/bVDVFWOU016R6WZX+paeIn7JV7pvovoG+WCRgaypUy -rJ4FGAMNel8uuq1KCrhV5UsQ6e6IGJ3bry+mRp9+Pqk91viWj1JVc1t+t2IfyJMY -/Hka0FiobnIAVSQPrI6ULoZul80ndB26mK2WRsr6A+S/DVHZLJ2qvtxrtdqXsK+m -tr+MKrBWFhcnMrNkYCCTEFWC4TiyYIXWGWhHSNj87CIaboggQ2ybLvAiulFvrgf8 -ES6LyRj3AgMBAAECggEAZ7MkMGG/xEjH3XfcD2jD901/+0fXkQQRG5vVfm7GmHwf -r2wdZta5QP2XfzBOCsKR/4B7DB6T3974RVFQLdHhbmxdnoP8xLXl4vC0MATjilyf -f0NnU6mQtdiLrc1uxyOei32t2wynLUccfmh2xc+Qt8qNKS60yRl5DJjDg245CdiW -ZhN40svLKfeVPallv2zrIZRbySEWXsCZRzBE+CYNrdRTWXSp45xCrRn+lseUxQXH -n+VoaP2KzHGgE4Lv5476EtVAq9G1yVN6Z0+8xWOiG9s+X3BNKPXWP4BGvg9tjBi0 -77U/hYrytMEPu8RV0ZR0zvlFVItqjujdKOJ9zJWTIQKBgQD/shNiXwCG/Ywrvs/g -lWNkvM+8iYyALtCuOR7rsuR0QP0OnC9HsZbttOwMwiC8yJiMZ7DuBWp7iqfjmPs7 -90dTxn4iQNkdoUE1DrobViPp+7pWIHqDH82r/Gy3nwMXLt/UFxi85lYd1Oo3us9C -ICvhFmzGAzIfiTKTXIJqJF9EqQKBgQDYKMe2ACP4rGVmJTSTkMn9c22gDTeCMEgI -dvlZOS7PJXAsznlnpTH+KLEyJhRenj08VxO6LcXI1urTe5G5aPStutBzods2X/iM -i1CmtOzeRGOkDVmqdYGgk0SXvTQg/z9MnwYCv+a904LQdMQ7TGgaoCYMJc3qWLO7 -p+/qGSZUnwKBgBvZZ2cVddc+EmBJXhbV7odwUSf1y0nCz5PKQOXnDB7lXSqUNEoY -u5mUVQlms24cYxEX0ht6l4hxJ6wQY3y6iBhFzEMq0Pr7L0D6I6cKkMrRUhBDZVSW -yC3tRmIRfaKuxk4xXc5lQAfrwr7jJ+PJ4T2Y1awTeQgaR1npf4LUB1RRAoGBAL+t -GbrX0Q33wUqcf0zDPXoT2wfr8GbvbVCkP2PRAyMIrbnttVYk9HnNl6NChRmJ8/8H -sCSN5i679StnDcd9vEo5uBJxWjOTUpE+EFxjXw+RUVHtzK8M18+OB2sOiaUg8f59 -nRTfGjsFzaAPitqSXFYP4O0wsLG3ylkDCAlsF8M9AoGALYTvOBdGJn/31XazCSeS -v2/iYnn41aw2DzxEYIn+QfkKH7Ctc39dfYV1jrhoI7m2T90GJKYfiZidd27fzmib -aPGQhCRFS7NPj2wI4kAFftRRtowIzHwEvVi1VvKWbyZII04FLU6aNVWrZE/E+2f5 -/4AmcI3dqS5PhGQEystcvhY= ------END PRIVATE KEY----- diff --git a/internal/rbac/public_key.pem b/internal/rbac/public_key.pem deleted file mode 100644 index 66fcd0ac..00000000 --- a/internal/rbac/public_key.pem +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1+b7pz1Wd31TWHcCczr0 -7IKB1hEJZF7PxUox8/dB8ywpaGfP4O8qiBD8JsZhx5B1YzCa8soc6DoZ1OjmLgwx -Yk5Vi+lBV++PhAv21Q1RVjlNNekelmV/qWniJ+yVe6b6L6BvlgkYGsqVMqyeBRgD -DXpfLrqtSgq4VeVLEOnuiBid268vpkaffj6pPdb4lo9SVXNbfrdiH8iTGPx5GtBY -qG5yAFUkD6yOlC6GbpfNJ3QdupitlkbK+gPkvw1R2Sydqr7ca7Xal7Cvpra/jCqw -VhYXJzKzZGAgkxBVguE4smCF1hloR0jY/OwiGm6IIENsmy7wIrpRb64H/BEui8kY -9wIDAQAB ------END PUBLIC KEY----- diff --git a/internal/serviceconfig/common_test.go b/internal/serviceconfig/common_test.go index be3f7c8d..5951dccb 100644 --- a/internal/serviceconfig/common_test.go +++ b/internal/serviceconfig/common_test.go @@ -41,6 +41,10 @@ func TestInitializeConfig(t *testing.T) { "SUB_FIELD1:": "value1", "SUB_FIELD2": "42", "PWD": "/foo", + "COGNITO_USER_POOL_ID": "poolid", + "COGNITO_CLIENT_SECRET": "secret", + "COGNITO_DOMAIN": "domain", + "COGNITO_CLIENT_ID": "clientid", }, wantErr: false, }, diff --git a/internal/serviceconfig/commonlog_test.go b/internal/serviceconfig/commonlog_test.go index 84a0733e..5cb62329 100644 --- a/internal/serviceconfig/commonlog_test.go +++ b/internal/serviceconfig/commonlog_test.go @@ -26,6 +26,10 @@ func TestPrintConfigRecursive(t *testing.T) { "AWS_ACCESS_KEY_ID": "key", "AWS_SECRET_ACCESS_KEY": "password", "AWS_REGION": "region", + "COGNITO_USER_POOL_ID": "poolid", + "COGNITO_CLIENT_SECRET": "secret", + "COGNITO_DOMAIN": "domain", + "COGNITO_CLIENT_ID": "clientid", "PWD": "/foo", // Only include vars needed by BaseConfig } @@ -59,7 +63,7 @@ func TestPrintConfigRecursive(t *testing.T) { // Check that each environment variable value appears in the logs // except for sensitive values which should be masked for envKey, envValue := range envVars { - if envKey == "PGPASSWORD" || envKey == "AWS_SECRET_ACCESS_KEY" { + if envKey == "PGPASSWORD" || envKey == "AWS_SECRET_ACCESS_KEY" || envKey == "COGNITO_CLIENT_SECRET" { // Password should be masked if strings.Contains(logOutput, envValue) { t.Errorf("Full password should not appear in logs: %s", logOutput) diff --git a/internal/test/container.go b/internal/test/container.go index 6e5fa196..973d6b55 100644 --- a/internal/test/container.go +++ b/internal/test/container.go @@ -50,6 +50,10 @@ func createContainer(t testing.TB, ctx context.Context, cfg *containerConfig) (t "AWS_ENDPOINT_URL_TEXTRACT": cfg.MockHTTP, "AWS_S3_USE_PATH_STYLE": strconv.FormatBool(true), "LOG_LEVEL": "DEBUG", + "COGNITO_USER_POOL_ID": "coguserpoolid", + "COGNITO_CLIENT_SECRET": "cogsecret", + "COGNITO_DOMAIN": "cogdomain", + "COGNITO_CLIENT_ID": "clientid", } if cfg.Env != nil { for k, v := range cfg.Env { diff --git a/vendor/github.com/golang-jwt/jwt/v5/.gitignore b/vendor/github.com/golang-jwt/jwt/v5/.gitignore deleted file mode 100644 index 09573e01..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.DS_Store -bin -.idea/ - diff --git a/vendor/github.com/golang-jwt/jwt/v5/LICENSE b/vendor/github.com/golang-jwt/jwt/v5/LICENSE deleted file mode 100644 index 35dbc252..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -Copyright (c) 2012 Dave Grijalva -Copyright (c) 2021 golang-jwt maintainers - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md b/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md deleted file mode 100644 index ff9c57e1..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md +++ /dev/null @@ -1,195 +0,0 @@ -# Migration Guide (v5.0.0) - -Version `v5` contains a major rework of core functionalities in the `jwt-go` -library. This includes support for several validation options as well as a -re-design of the `Claims` interface. Lastly, we reworked how errors work under -the hood, which should provide a better overall developer experience. - -Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0), -the import path will be: - - "github.com/golang-jwt/jwt/v5" - -For most users, changing the import path *should* suffice. However, since we -intentionally changed and cleaned some of the public API, existing programs -might need to be updated. The following sections describe significant changes -and corresponding updates for existing programs. - -## Parsing and Validation Options - -Under the hood, a new `Validator` struct takes care of validating the claims. A -long awaited feature has been the option to fine-tune the validation of tokens. -This is now possible with several `ParserOption` functions that can be appended -to most `Parse` functions, such as `ParseWithClaims`. The most important options -and changes are: - * Added `WithLeeway` to support specifying the leeway that is allowed when - validating time-based claims, such as `exp` or `nbf`. - * Changed default behavior to not check the `iat` claim. Usage of this claim - is OPTIONAL according to the JWT RFC. The claim itself is also purely - informational according to the RFC, so a strict validation failure is not - recommended. If you want to check for sensible values in these claims, - please use the `WithIssuedAt` parser option. - * Added `WithAudience`, `WithSubject` and `WithIssuer` to support checking for - expected `aud`, `sub` and `iss`. - * Added `WithStrictDecoding` and `WithPaddingAllowed` options to allow - previously global settings to enable base64 strict encoding and the parsing - of base64 strings with padding. The latter is strictly speaking against the - standard, but unfortunately some of the major identity providers issue some - of these incorrect tokens. Both options are disabled by default. - -## Changes to the `Claims` interface - -### Complete Restructuring - -Previously, the claims interface was satisfied with an implementation of a -`Valid() error` function. This had several issues: - * The different claim types (struct claims, map claims, etc.) then contained - similar (but not 100 % identical) code of how this validation was done. This - lead to a lot of (almost) duplicate code and was hard to maintain - * It was not really semantically close to what a "claim" (or a set of claims) - really is; which is a list of defined key/value pairs with a certain - semantic meaning. - -Since all the validation functionality is now extracted into the validator, all -`VerifyXXX` and `Valid` functions have been removed from the `Claims` interface. -Instead, the interface now represents a list of getters to retrieve values with -a specific meaning. This allows us to completely decouple the validation logic -with the underlying storage representation of the claim, which could be a -struct, a map or even something stored in a database. - -```go -type Claims interface { - GetExpirationTime() (*NumericDate, error) - GetIssuedAt() (*NumericDate, error) - GetNotBefore() (*NumericDate, error) - GetIssuer() (string, error) - GetSubject() (string, error) - GetAudience() (ClaimStrings, error) -} -``` - -Users that previously directly called the `Valid` function on their claims, -e.g., to perform validation independently of parsing/verifying a token, can now -use the `jwt.NewValidator` function to create a `Validator` independently of the -`Parser`. - -```go -var v = jwt.NewValidator(jwt.WithLeeway(5*time.Second)) -v.Validate(myClaims) -``` - -### Supported Claim Types and Removal of `StandardClaims` - -The two standard claim types supported by this library, `MapClaims` and -`RegisteredClaims` both implement the necessary functions of this interface. The -old `StandardClaims` struct, which has already been deprecated in `v4` is now -removed. - -Users using custom claims, in most cases, will not experience any changes in the -behavior as long as they embedded `RegisteredClaims`. If they created a new -claim type from scratch, they now need to implemented the proper getter -functions. - -### Migrating Application Specific Logic of the old `Valid` - -Previously, users could override the `Valid` method in a custom claim, for -example to extend the validation with application-specific claims. However, this -was always very dangerous, since once could easily disable the standard -validation and signature checking. - -In order to avoid that, while still supporting the use-case, a new -`ClaimsValidator` interface has been introduced. This interface consists of the -`Validate() error` function. If the validator sees, that a `Claims` struct -implements this interface, the errors returned to the `Validate` function will -be *appended* to the regular standard validation. It is not possible to disable -the standard validation anymore (even only by accident). - -Usage examples can be found in [example_test.go](./example_test.go), to build -claims structs like the following. - -```go -// MyCustomClaims includes all registered claims, plus Foo. -type MyCustomClaims struct { - Foo string `json:"foo"` - jwt.RegisteredClaims -} - -// Validate can be used to execute additional application-specific claims -// validation. -func (m MyCustomClaims) Validate() error { - if m.Foo != "bar" { - return errors.New("must be foobar") - } - - return nil -} -``` - -## Changes to the `Token` and `Parser` struct - -The previously global functions `DecodeSegment` and `EncodeSegment` were moved -to the `Parser` and `Token` struct respectively. This will allow us in the -future to configure the behavior of these two based on options supplied on the -parser or the token (creation). This also removes two previously global -variables and moves them to parser options `WithStrictDecoding` and -`WithPaddingAllowed`. - -In order to do that, we had to adjust the way signing methods work. Previously -they were given a base64 encoded signature in `Verify` and were expected to -return a base64 encoded version of the signature in `Sign`, both as a `string`. -However, this made it necessary to have `DecodeSegment` and `EncodeSegment` -global and was a less than perfect design because we were repeating -encoding/decoding steps for all signing methods. Now, `Sign` and `Verify` -operate on a decoded signature as a `[]byte`, which feels more natural for a -cryptographic operation anyway. Lastly, `Parse` and `SignedString` take care of -the final encoding/decoding part. - -In addition to that, we also changed the `Signature` field on `Token` from a -`string` to `[]byte` and this is also now populated with the decoded form. This -is also more consistent, because the other parts of the JWT, mainly `Header` and -`Claims` were already stored in decoded form in `Token`. Only the signature was -stored in base64 encoded form, which was redundant with the information in the -`Raw` field, which contains the complete token as base64. - -```go -type Token struct { - Raw string // Raw contains the raw token - Method SigningMethod // Method is the signing method used or to be used - Header map[string]interface{} // Header is the first segment of the token in decoded form - Claims Claims // Claims is the second segment of the token in decoded form - Signature []byte // Signature is the third segment of the token in decoded form - Valid bool // Valid specifies if the token is valid -} -``` - -Most (if not all) of these changes should not impact the normal usage of this -library. Only users directly accessing the `Signature` field as well as -developers of custom signing methods should be affected. - -# Migration Guide (v4.0.0) - -Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), -the import path will be: - - "github.com/golang-jwt/jwt/v4" - -The `/v4` version will be backwards compatible with existing `v3.x.y` tags in -this repo, as well as `github.com/dgrijalva/jwt-go`. For most users this should -be a drop-in replacement, if you're having troubles migrating, please open an -issue. - -You can replace all occurrences of `github.com/dgrijalva/jwt-go` or -`github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually -or by using tools such as `sed` or `gofmt`. - -And then you'd typically run: - -``` -go get github.com/golang-jwt/jwt/v4 -go mod tidy -``` - -# Older releases (before v3.2.0) - -The original migration guide for older releases can be found at -https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. diff --git a/vendor/github.com/golang-jwt/jwt/v5/README.md b/vendor/github.com/golang-jwt/jwt/v5/README.md deleted file mode 100644 index 964598a3..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/README.md +++ /dev/null @@ -1,167 +0,0 @@ -# jwt-go - -[![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) -[![Go -Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v5.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) -[![Coverage Status](https://coveralls.io/repos/github/golang-jwt/jwt/badge.svg?branch=main)](https://coveralls.io/github/golang-jwt/jwt?branch=main) - -A [go](http://www.golang.org) (or 'golang' for search engine friendliness) -implementation of [JSON Web -Tokens](https://datatracker.ietf.org/doc/html/rfc7519). - -Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0) -this project adds Go module support, but maintains backwards compatibility with -older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. See the -[`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. Version -v5.0.0 introduces major improvements to the validation of tokens, but is not -entirely backwards compatible. - -> After the original author of the library suggested migrating the maintenance -> of `jwt-go`, a dedicated team of open source maintainers decided to clone the -> existing library into this repository. See -> [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a -> detailed discussion on this topic. - - -**SECURITY NOTICE:** Some older versions of Go have a security issue in the -crypto/elliptic. Recommendation is to upgrade to at least 1.15 See issue -[dgrijalva/jwt-go#216](https://github.com/dgrijalva/jwt-go/issues/216) for more -detail. - -**SECURITY NOTICE:** It's important that you [validate the `alg` presented is -what you -expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). -This library attempts to make it easy to do the right thing by requiring key -types match the expected alg, but you should take the extra step to verify it in -your usage. See the examples provided. - -### Supported Go versions - -Our support of Go versions is aligned with Go's [version release -policy](https://golang.org/doc/devel/release#policy). So we will support a major -version of Go until there are two newer major releases. We no longer support -building jwt-go with unsupported Go versions, as these contain security -vulnerabilities which will not be fixed. - -## What the heck is a JWT? - -JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web -Tokens. - -In short, it's a signed JSON object that does something useful (for example, -authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is -made of three parts, separated by `.`'s. The first two parts are JSON objects, -that have been [base64url](https://datatracker.ietf.org/doc/html/rfc4648) -encoded. The last part is the signature, encoded the same way. - -The first part is called the header. It contains the necessary information for -verifying the last part, the signature. For example, which encryption method -was used for signing and what key was used. - -The part in the middle is the interesting bit. It's called the Claims and -contains the actual stuff you care about. Refer to [RFC -7519](https://datatracker.ietf.org/doc/html/rfc7519) for information about -reserved keys and the proper way to add your own. - -## What's in the box? - -This library supports the parsing and verification as well as the generation and -signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, -RSA-PSS, and ECDSA, though hooks are present for adding your own. - -## Installation Guidelines - -1. To install the jwt package, you first need to have - [Go](https://go.dev/doc/install) installed, then you can use the command - below to add `jwt-go` as a dependency in your Go program. - -```sh -go get -u github.com/golang-jwt/jwt/v5 -``` - -2. Import it in your code: - -```go -import "github.com/golang-jwt/jwt/v5" -``` - -## Usage - -A detailed usage guide, including how to sign and verify tokens can be found on -our [documentation website](https://golang-jwt.github.io/jwt/usage/create/). - -## Examples - -See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) -for examples of usage: - -* [Simple example of parsing and validating a - token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac) -* [Simple example of building and signing a - token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-New-Hmac) -* [Directory of - Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#pkg-examples) - -## Compliance - -This library was last reviewed to comply with [RFC -7519](https://datatracker.ietf.org/doc/html/rfc7519) dated May 2015 with a few -notable differences: - -* In order to protect against accidental use of [Unsecured - JWTs](https://datatracker.ietf.org/doc/html/rfc7519#section-6), tokens using - `alg=none` will only be accepted if the constant - `jwt.UnsafeAllowNoneSignatureType` is provided as the key. - -## Project Status & Versioning - -This library is considered production ready. Feedback and feature requests are -appreciated. The API should be considered stable. There should be very few -backwards-incompatible changes outside of major version updates (and only with -good reason). - -This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull -requests will land on `main`. Periodically, versions will be tagged from -`main`. You can find all the releases on [the project releases -page](https://github.com/golang-jwt/jwt/releases). - -**BREAKING CHANGES:*** A full list of breaking changes is available in -`VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating -your code. - -## Extensions - -This library publishes all the necessary components for adding your own signing -methods or key functions. Simply implement the `SigningMethod` interface and -register a factory method using `RegisterSigningMethod` or provide a -`jwt.Keyfunc`. - -A common use case would be integrating with different 3rd party signature -providers, like key management services from various cloud providers or Hardware -Security Modules (HSMs) or to implement additional standards. - -| Extension | Purpose | Repo | -| --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | -| GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go | -| AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms | -| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | - -*Disclaimer*: Unless otherwise specified, these integrations are maintained by -third parties and should not be considered as a primary offer by any of the -mentioned cloud providers - -## More - -Go package documentation can be found [on -pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). Additional -documentation can be found on [our project -page](https://golang-jwt.github.io/jwt/). - -The command line utility included in this project (cmd/jwt) provides a -straightforward example of token creation and parsing as well as a useful tool -for debugging your own integration. You'll also find several implementation -examples in the documentation. - -[golang-jwt](https://github.com/orgs/golang-jwt) incorporates a modified version -of the JWT logo, which is distributed under the terms of the [MIT -License](https://github.com/jsonwebtoken/jsonwebtoken.github.io/blob/master/LICENSE.txt). diff --git a/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md b/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md deleted file mode 100644 index b08402c3..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md +++ /dev/null @@ -1,19 +0,0 @@ -# Security Policy - -## Supported Versions - -As of February 2022 (and until this document is updated), the latest version `v4` is supported. - -## Reporting a Vulnerability - -If you think you found a vulnerability, and even if you are not sure, please report it to jwt-go-security@googlegroups.com or one of the other [golang-jwt maintainers](https://github.com/orgs/golang-jwt/people). Please try be explicit, describe steps to reproduce the security issue with code example(s). - -You will receive a response within a timely manner. If the issue is confirmed, we will do our best to release a patch as soon as possible given the complexity of the problem. - -## Public Discussions - -Please avoid publicly discussing a potential security vulnerability. - -Let's take this offline and find a solution first, this limits the potential impact as much as possible. - -We appreciate your help! diff --git a/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md b/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md deleted file mode 100644 index b5039e49..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md +++ /dev/null @@ -1,137 +0,0 @@ -# `jwt-go` Version History - -The following version history is kept for historic purposes. To retrieve the current changes of each version, please refer to the change-log of the specific release versions on https://github.com/golang-jwt/jwt/releases. - -## 4.0.0 - -* Introduces support for Go modules. The `v4` version will be backwards compatible with `v3.x.y`. - -## 3.2.2 - -* Starting from this release, we are adopting the policy to support the most 2 recent versions of Go currently available. By the time of this release, this is Go 1.15 and 1.16 ([#28](https://github.com/golang-jwt/jwt/pull/28)). -* Fixed a potential issue that could occur when the verification of `exp`, `iat` or `nbf` was not required and contained invalid contents, i.e. non-numeric/date. Thanks for @thaJeztah for making us aware of that and @giorgos-f3 for originally reporting it to the formtech fork ([#40](https://github.com/golang-jwt/jwt/pull/40)). -* Added support for EdDSA / ED25519 ([#36](https://github.com/golang-jwt/jwt/pull/36)). -* Optimized allocations ([#33](https://github.com/golang-jwt/jwt/pull/33)). - -## 3.2.1 - -* **Import Path Change**: See MIGRATION_GUIDE.md for tips on updating your code - * Changed the import path from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt` -* Fixed type confusing issue between `string` and `[]string` in `VerifyAudience` ([#12](https://github.com/golang-jwt/jwt/pull/12)). This fixes CVE-2020-26160 - -#### 3.2.0 - -* Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation -* HMAC signing method returns `ErrInvalidKeyType` instead of `ErrInvalidKey` where appropriate -* Added options to `request.ParseFromRequest`, which allows for an arbitrary list of modifiers to parsing behavior. Initial set include `WithClaims` and `WithParser`. Existing usage of this function will continue to work as before. -* Deprecated `ParseFromRequestWithClaims` to simplify API in the future. - -#### 3.1.0 - -* Improvements to `jwt` command line tool -* Added `SkipClaimsValidation` option to `Parser` -* Documentation updates - -#### 3.0.0 - -* **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code - * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods. - * `ParseFromRequest` has been moved to `request` subpackage and usage has changed - * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims. -* Other Additions and Changes - * Added `Claims` interface type to allow users to decode the claims into a custom type - * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into. - * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage - * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims` - * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`. - * Added several new, more specific, validation errors to error type bitmask - * Moved examples from README to executable example files - * Signing method registry is now thread safe - * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser) - -#### 2.7.0 - -This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes. - -* Added new option `-show` to the `jwt` command that will just output the decoded token without verifying -* Error text for expired tokens includes how long it's been expired -* Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM` -* Documentation updates - -#### 2.6.0 - -* Exposed inner error within ValidationError -* Fixed validation errors when using UseJSONNumber flag -* Added several unit tests - -#### 2.5.0 - -* Added support for signing method none. You shouldn't use this. The API tries to make this clear. -* Updated/fixed some documentation -* Added more helpful error message when trying to parse tokens that begin with `BEARER ` - -#### 2.4.0 - -* Added new type, Parser, to allow for configuration of various parsing parameters - * You can now specify a list of valid signing methods. Anything outside this set will be rejected. - * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON -* Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go) -* Fixed some bugs with ECDSA parsing - -#### 2.3.0 - -* Added support for ECDSA signing methods -* Added support for RSA PSS signing methods (requires go v1.4) - -#### 2.2.0 - -* Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic. - -#### 2.1.0 - -Backwards compatible API change that was missed in 2.0.0. - -* The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte` - -#### 2.0.0 - -There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change. - -The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`. - -It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`. - -* **Compatibility Breaking Changes** - * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct` - * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct` - * `KeyFunc` now returns `interface{}` instead of `[]byte` - * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key - * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key -* Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type. - * Added public package global `SigningMethodHS256` - * Added public package global `SigningMethodHS384` - * Added public package global `SigningMethodHS512` -* Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type. - * Added public package global `SigningMethodRS256` - * Added public package global `SigningMethodRS384` - * Added public package global `SigningMethodRS512` -* Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged. -* Refactored the RSA implementation to be easier to read -* Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` - -## 1.0.2 - -* Fixed bug in parsing public keys from certificates -* Added more tests around the parsing of keys for RS256 -* Code refactoring in RS256 implementation. No functional changes - -## 1.0.1 - -* Fixed panic if RS256 signing method was passed an invalid key - -## 1.0.0 - -* First versioned release -* API stabilized -* Supports creating, signing, parsing, and validating JWT tokens -* Supports RS256 and HS256 signing methods diff --git a/vendor/github.com/golang-jwt/jwt/v5/claims.go b/vendor/github.com/golang-jwt/jwt/v5/claims.go deleted file mode 100644 index d50ff3da..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/claims.go +++ /dev/null @@ -1,16 +0,0 @@ -package jwt - -// Claims represent any form of a JWT Claims Set according to -// https://datatracker.ietf.org/doc/html/rfc7519#section-4. In order to have a -// common basis for validation, it is required that an implementation is able to -// supply at least the claim names provided in -// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 namely `exp`, -// `iat`, `nbf`, `iss`, `sub` and `aud`. -type Claims interface { - GetExpirationTime() (*NumericDate, error) - GetIssuedAt() (*NumericDate, error) - GetNotBefore() (*NumericDate, error) - GetIssuer() (string, error) - GetSubject() (string, error) - GetAudience() (ClaimStrings, error) -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/doc.go b/vendor/github.com/golang-jwt/jwt/v5/doc.go deleted file mode 100644 index a86dc1a3..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html -// -// See README.md for more info. -package jwt diff --git a/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go b/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go deleted file mode 100644 index c929e4a0..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go +++ /dev/null @@ -1,134 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rand" - "errors" - "math/big" -) - -var ( - // Sadly this is missing from crypto/ecdsa compared to crypto/rsa - ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") -) - -// SigningMethodECDSA implements the ECDSA family of signing methods. -// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification -type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - KeySize int - CurveBits int -} - -// Specific instances for EC256 and company -var ( - SigningMethodES256 *SigningMethodECDSA - SigningMethodES384 *SigningMethodECDSA - SigningMethodES512 *SigningMethodECDSA -) - -func init() { - // ES256 - SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} - RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { - return SigningMethodES256 - }) - - // ES384 - SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} - RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { - return SigningMethodES384 - }) - - // ES512 - SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} - RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { - return SigningMethodES512 - }) -} - -func (m *SigningMethodECDSA) Alg() string { - return m.Name -} - -// Verify implements token verification for the SigningMethod. -// For this verify method, key must be an ecdsa.PublicKey struct -func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key interface{}) error { - // Get the key - var ecdsaKey *ecdsa.PublicKey - switch k := key.(type) { - case *ecdsa.PublicKey: - ecdsaKey = k - default: - return newError("ECDSA verify expects *ecdsa.PublicKey", ErrInvalidKeyType) - } - - if len(sig) != 2*m.KeySize { - return ErrECDSAVerification - } - - r := big.NewInt(0).SetBytes(sig[:m.KeySize]) - s := big.NewInt(0).SetBytes(sig[m.KeySize:]) - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus { - return nil - } - - return ErrECDSAVerification -} - -// Sign implements token signing for the SigningMethod. -// For this signing method, key must be an ecdsa.PrivateKey struct -func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) ([]byte, error) { - // Get the key - var ecdsaKey *ecdsa.PrivateKey - switch k := key.(type) { - case *ecdsa.PrivateKey: - ecdsaKey = k - default: - return nil, newError("ECDSA sign expects *ecdsa.PrivateKey", ErrInvalidKeyType) - } - - // Create the hasher - if !m.Hash.Available() { - return nil, ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return r, s - if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { - curveBits := ecdsaKey.Curve.Params().BitSize - - if m.CurveBits != curveBits { - return nil, ErrInvalidKey - } - - keyBytes := curveBits / 8 - if curveBits%8 > 0 { - keyBytes += 1 - } - - // We serialize the outputs (r and s) into big-endian byte arrays - // padded with zeros on the left to make sure the sizes work out. - // Output must be 2*keyBytes long. - out := make([]byte, 2*keyBytes) - r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output. - s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. - - return out, nil - } else { - return nil, err - } -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go b/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go deleted file mode 100644 index 5700636d..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go +++ /dev/null @@ -1,69 +0,0 @@ -package jwt - -import ( - "crypto/ecdsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrNotECPublicKey = errors.New("key is not a valid ECDSA public key") - ErrNotECPrivateKey = errors.New("key is not a valid ECDSA private key") -) - -// ParseECPrivateKeyFromPEM parses a PEM encoded Elliptic Curve Private Key Structure -func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - } - - var pkey *ecdsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { - return nil, ErrNotECPrivateKey - } - - return pkey, nil -} - -// ParseECPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key -func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *ecdsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { - return nil, ErrNotECPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/ed25519.go b/vendor/github.com/golang-jwt/jwt/v5/ed25519.go deleted file mode 100644 index c2138119..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/ed25519.go +++ /dev/null @@ -1,79 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/ed25519" - "crypto/rand" - "errors" -) - -var ( - ErrEd25519Verification = errors.New("ed25519: verification error") -) - -// SigningMethodEd25519 implements the EdDSA family. -// Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification -type SigningMethodEd25519 struct{} - -// Specific instance for EdDSA -var ( - SigningMethodEdDSA *SigningMethodEd25519 -) - -func init() { - SigningMethodEdDSA = &SigningMethodEd25519{} - RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod { - return SigningMethodEdDSA - }) -} - -func (m *SigningMethodEd25519) Alg() string { - return "EdDSA" -} - -// Verify implements token verification for the SigningMethod. -// For this verify method, key must be an ed25519.PublicKey -func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key interface{}) error { - var ed25519Key ed25519.PublicKey - var ok bool - - if ed25519Key, ok = key.(ed25519.PublicKey); !ok { - return newError("Ed25519 verify expects ed25519.PublicKey", ErrInvalidKeyType) - } - - if len(ed25519Key) != ed25519.PublicKeySize { - return ErrInvalidKey - } - - // Verify the signature - if !ed25519.Verify(ed25519Key, []byte(signingString), sig) { - return ErrEd25519Verification - } - - return nil -} - -// Sign implements token signing for the SigningMethod. -// For this signing method, key must be an ed25519.PrivateKey -func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]byte, error) { - var ed25519Key crypto.Signer - var ok bool - - if ed25519Key, ok = key.(crypto.Signer); !ok { - return nil, newError("Ed25519 sign expects crypto.Signer", ErrInvalidKeyType) - } - - if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok { - return nil, ErrInvalidKey - } - - // Sign the string and return the result. ed25519 performs a two-pass hash - // as part of its algorithm. Therefore, we need to pass a non-prehashed - // message into the Sign function, as indicated by crypto.Hash(0) - sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0)) - if err != nil { - return nil, err - } - - return sig, nil -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go b/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go deleted file mode 100644 index cdb5e68e..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go +++ /dev/null @@ -1,64 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/ed25519" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrNotEdPrivateKey = errors.New("key is not a valid Ed25519 private key") - ErrNotEdPublicKey = errors.New("key is not a valid Ed25519 public key") -) - -// ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key -func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - - var pkey ed25519.PrivateKey - var ok bool - if pkey, ok = parsedKey.(ed25519.PrivateKey); !ok { - return nil, ErrNotEdPrivateKey - } - - return pkey, nil -} - -// ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key -func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - return nil, err - } - - var pkey ed25519.PublicKey - var ok bool - if pkey, ok = parsedKey.(ed25519.PublicKey); !ok { - return nil, ErrNotEdPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors.go b/vendor/github.com/golang-jwt/jwt/v5/errors.go deleted file mode 100644 index 23bb616d..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/errors.go +++ /dev/null @@ -1,49 +0,0 @@ -package jwt - -import ( - "errors" - "strings" -) - -var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") - ErrTokenMalformed = errors.New("token is malformed") - ErrTokenUnverifiable = errors.New("token is unverifiable") - ErrTokenSignatureInvalid = errors.New("token signature is invalid") - ErrTokenRequiredClaimMissing = errors.New("token is missing required claim") - ErrTokenInvalidAudience = errors.New("token has invalid audience") - ErrTokenExpired = errors.New("token is expired") - ErrTokenUsedBeforeIssued = errors.New("token used before issued") - ErrTokenInvalidIssuer = errors.New("token has invalid issuer") - ErrTokenInvalidSubject = errors.New("token has invalid subject") - ErrTokenNotValidYet = errors.New("token is not valid yet") - ErrTokenInvalidId = errors.New("token has invalid id") - ErrTokenInvalidClaims = errors.New("token has invalid claims") - ErrInvalidType = errors.New("invalid type for claim") -) - -// joinedError is an error type that works similar to what [errors.Join] -// produces, with the exception that it has a nice error string; mainly its -// error messages are concatenated using a comma, rather than a newline. -type joinedError struct { - errs []error -} - -func (je joinedError) Error() string { - msg := []string{} - for _, err := range je.errs { - msg = append(msg, err.Error()) - } - - return strings.Join(msg, ", ") -} - -// joinErrors joins together multiple errors. Useful for scenarios where -// multiple errors next to each other occur, e.g., in claims validation. -func joinErrors(errs ...error) error { - return &joinedError{ - errs: errs, - } -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go b/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go deleted file mode 100644 index a893d355..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go +++ /dev/null @@ -1,47 +0,0 @@ -//go:build go1.20 -// +build go1.20 - -package jwt - -import ( - "fmt" -) - -// Unwrap implements the multiple error unwrapping for this error type, which is -// possible in Go 1.20. -func (je joinedError) Unwrap() []error { - return je.errs -} - -// newError creates a new error message with a detailed error message. The -// message will be prefixed with the contents of the supplied error type. -// Additionally, more errors, that provide more context can be supplied which -// will be appended to the message. This makes use of Go 1.20's possibility to -// include more than one %w formatting directive in [fmt.Errorf]. -// -// For example, -// -// newError("no keyfunc was provided", ErrTokenUnverifiable) -// -// will produce the error string -// -// "token is unverifiable: no keyfunc was provided" -func newError(message string, err error, more ...error) error { - var format string - var args []any - if message != "" { - format = "%w: %s" - args = []any{err, message} - } else { - format = "%w" - args = []any{err} - } - - for _, e := range more { - format += ": %w" - args = append(args, e) - } - - err = fmt.Errorf(format, args...) - return err -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go b/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go deleted file mode 100644 index 2ad542f0..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go +++ /dev/null @@ -1,78 +0,0 @@ -//go:build !go1.20 -// +build !go1.20 - -package jwt - -import ( - "errors" - "fmt" -) - -// Is implements checking for multiple errors using [errors.Is], since multiple -// error unwrapping is not possible in versions less than Go 1.20. -func (je joinedError) Is(err error) bool { - for _, e := range je.errs { - if errors.Is(e, err) { - return true - } - } - - return false -} - -// wrappedErrors is a workaround for wrapping multiple errors in environments -// where Go 1.20 is not available. It basically uses the already implemented -// functionality of joinedError to handle multiple errors with supplies a -// custom error message that is identical to the one we produce in Go 1.20 using -// multiple %w directives. -type wrappedErrors struct { - msg string - joinedError -} - -// Error returns the stored error string -func (we wrappedErrors) Error() string { - return we.msg -} - -// newError creates a new error message with a detailed error message. The -// message will be prefixed with the contents of the supplied error type. -// Additionally, more errors, that provide more context can be supplied which -// will be appended to the message. Since we cannot use of Go 1.20's possibility -// to include more than one %w formatting directive in [fmt.Errorf], we have to -// emulate that. -// -// For example, -// -// newError("no keyfunc was provided", ErrTokenUnverifiable) -// -// will produce the error string -// -// "token is unverifiable: no keyfunc was provided" -func newError(message string, err error, more ...error) error { - // We cannot wrap multiple errors here with %w, so we have to be a little - // bit creative. Basically, we are using %s instead of %w to produce the - // same error message and then throw the result into a custom error struct. - var format string - var args []any - if message != "" { - format = "%s: %s" - args = []any{err, message} - } else { - format = "%s" - args = []any{err} - } - errs := []error{err} - - for _, e := range more { - format += ": %s" - args = append(args, e) - errs = append(errs, e) - } - - err = &wrappedErrors{ - msg: fmt.Sprintf(format, args...), - joinedError: joinedError{errs: errs}, - } - return err -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/hmac.go b/vendor/github.com/golang-jwt/jwt/v5/hmac.go deleted file mode 100644 index aca600ce..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/hmac.go +++ /dev/null @@ -1,104 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/hmac" - "errors" -) - -// SigningMethodHMAC implements the HMAC-SHA family of signing methods. -// Expects key type of []byte for both signing and validation -type SigningMethodHMAC struct { - Name string - Hash crypto.Hash -} - -// Specific instances for HS256 and company -var ( - SigningMethodHS256 *SigningMethodHMAC - SigningMethodHS384 *SigningMethodHMAC - SigningMethodHS512 *SigningMethodHMAC - ErrSignatureInvalid = errors.New("signature is invalid") -) - -func init() { - // HS256 - SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { - return SigningMethodHS256 - }) - - // HS384 - SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { - return SigningMethodHS384 - }) - - // HS512 - SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { - return SigningMethodHS512 - }) -} - -func (m *SigningMethodHMAC) Alg() string { - return m.Name -} - -// Verify implements token verification for the SigningMethod. Returns nil if -// the signature is valid. Key must be []byte. -// -// Note it is not advised to provide a []byte which was converted from a 'human -// readable' string using a subset of ASCII characters. To maximize entropy, you -// should ideally be providing a []byte key which was produced from a -// cryptographically random source, e.g. crypto/rand. Additional information -// about this, and why we intentionally are not supporting string as a key can -// be found on our usage guide -// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types. -func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interface{}) error { - // Verify the key is the right type - keyBytes, ok := key.([]byte) - if !ok { - return newError("HMAC verify expects []byte", ErrInvalidKeyType) - } - - // Can we use the specified hashing method? - if !m.Hash.Available() { - return ErrHashUnavailable - } - - // This signing method is symmetric, so we validate the signature - // by reproducing the signature from the signing string and key, then - // comparing that against the provided signature. - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - if !hmac.Equal(sig, hasher.Sum(nil)) { - return ErrSignatureInvalid - } - - // No validation errors. Signature is good. - return nil -} - -// Sign implements token signing for the SigningMethod. Key must be []byte. -// -// Note it is not advised to provide a []byte which was converted from a 'human -// readable' string using a subset of ASCII characters. To maximize entropy, you -// should ideally be providing a []byte key which was produced from a -// cryptographically random source, e.g. crypto/rand. Additional information -// about this, and why we intentionally are not supporting string as a key can -// be found on our usage guide https://golang-jwt.github.io/jwt/usage/signing_methods/. -func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) { - if keyBytes, ok := key.([]byte); ok { - if !m.Hash.Available() { - return nil, ErrHashUnavailable - } - - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - - return hasher.Sum(nil), nil - } - - return nil, newError("HMAC sign expects []byte", ErrInvalidKeyType) -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/map_claims.go b/vendor/github.com/golang-jwt/jwt/v5/map_claims.go deleted file mode 100644 index b2b51a1f..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/map_claims.go +++ /dev/null @@ -1,109 +0,0 @@ -package jwt - -import ( - "encoding/json" - "fmt" -) - -// MapClaims is a claims type that uses the map[string]interface{} for JSON -// decoding. This is the default claims type if you don't supply one -type MapClaims map[string]interface{} - -// GetExpirationTime implements the Claims interface. -func (m MapClaims) GetExpirationTime() (*NumericDate, error) { - return m.parseNumericDate("exp") -} - -// GetNotBefore implements the Claims interface. -func (m MapClaims) GetNotBefore() (*NumericDate, error) { - return m.parseNumericDate("nbf") -} - -// GetIssuedAt implements the Claims interface. -func (m MapClaims) GetIssuedAt() (*NumericDate, error) { - return m.parseNumericDate("iat") -} - -// GetAudience implements the Claims interface. -func (m MapClaims) GetAudience() (ClaimStrings, error) { - return m.parseClaimsString("aud") -} - -// GetIssuer implements the Claims interface. -func (m MapClaims) GetIssuer() (string, error) { - return m.parseString("iss") -} - -// GetSubject implements the Claims interface. -func (m MapClaims) GetSubject() (string, error) { - return m.parseString("sub") -} - -// parseNumericDate tries to parse a key in the map claims type as a number -// date. This will succeed, if the underlying type is either a [float64] or a -// [json.Number]. Otherwise, nil will be returned. -func (m MapClaims) parseNumericDate(key string) (*NumericDate, error) { - v, ok := m[key] - if !ok { - return nil, nil - } - - switch exp := v.(type) { - case float64: - if exp == 0 { - return nil, nil - } - - return newNumericDateFromSeconds(exp), nil - case json.Number: - v, _ := exp.Float64() - - return newNumericDateFromSeconds(v), nil - } - - return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) -} - -// parseClaimsString tries to parse a key in the map claims type as a -// [ClaimsStrings] type, which can either be a string or an array of string. -func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) { - var cs []string - switch v := m[key].(type) { - case string: - cs = append(cs, v) - case []string: - cs = v - case []interface{}: - for _, a := range v { - vs, ok := a.(string) - if !ok { - return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) - } - cs = append(cs, vs) - } - } - - return cs, nil -} - -// parseString tries to parse a key in the map claims type as a [string] type. -// If the key does not exist, an empty string is returned. If the key has the -// wrong type, an error is returned. -func (m MapClaims) parseString(key string) (string, error) { - var ( - ok bool - raw interface{} - iss string - ) - raw, ok = m[key] - if !ok { - return "", nil - } - - iss, ok = raw.(string) - if !ok { - return "", newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) - } - - return iss, nil -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/none.go b/vendor/github.com/golang-jwt/jwt/v5/none.go deleted file mode 100644 index 685c2ea3..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/none.go +++ /dev/null @@ -1,50 +0,0 @@ -package jwt - -// SigningMethodNone implements the none signing method. This is required by the spec -// but you probably should never use it. -var SigningMethodNone *signingMethodNone - -const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" - -var NoneSignatureTypeDisallowedError error - -type signingMethodNone struct{} -type unsafeNoneMagicConstant string - -func init() { - SigningMethodNone = &signingMethodNone{} - NoneSignatureTypeDisallowedError = newError("'none' signature type is not allowed", ErrTokenUnverifiable) - - RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { - return SigningMethodNone - }) -} - -func (m *signingMethodNone) Alg() string { - return "none" -} - -// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Verify(signingString string, sig []byte, key interface{}) (err error) { - // Key must be UnsafeAllowNoneSignatureType to prevent accidentally - // accepting 'none' signing method - if _, ok := key.(unsafeNoneMagicConstant); !ok { - return NoneSignatureTypeDisallowedError - } - // If signing method is none, signature must be an empty string - if len(sig) != 0 { - return newError("'none' signing method with non-empty signature", ErrTokenUnverifiable) - } - - // Accept 'none' signing method. - return nil -} - -// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Sign(signingString string, key interface{}) ([]byte, error) { - if _, ok := key.(unsafeNoneMagicConstant); ok { - return []byte{}, nil - } - - return nil, NoneSignatureTypeDisallowedError -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/parser.go b/vendor/github.com/golang-jwt/jwt/v5/parser.go deleted file mode 100644 index ecf99af7..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/parser.go +++ /dev/null @@ -1,238 +0,0 @@ -package jwt - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "strings" -) - -type Parser struct { - // If populated, only these methods will be considered valid. - validMethods []string - - // Use JSON Number format in JSON decoder. - useJSONNumber bool - - // Skip claims validation during token parsing. - skipClaimsValidation bool - - validator *Validator - - decodeStrict bool - - decodePaddingAllowed bool -} - -// NewParser creates a new Parser with the specified options -func NewParser(options ...ParserOption) *Parser { - p := &Parser{ - validator: &Validator{}, - } - - // Loop through our parsing options and apply them - for _, option := range options { - option(p) - } - - return p -} - -// Parse parses, validates, verifies the signature and returns the parsed token. -// keyFunc will receive the parsed token and should return the key for validating. -func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) -} - -// ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims -// interface. This provides default values which can be overridden and allows a caller to use their own type, rather -// than the default MapClaims implementation of Claims. -// -// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), -// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the -// proper memory for it before passing in the overall claims, otherwise you might run into a panic. -func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - token, parts, err := p.ParseUnverified(tokenString, claims) - if err != nil { - return token, err - } - - // Verify signing method is in the required set - if p.validMethods != nil { - var signingMethodValid = false - var alg = token.Method.Alg() - for _, m := range p.validMethods { - if m == alg { - signingMethodValid = true - break - } - } - if !signingMethodValid { - // signing method is not in the listed set - return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid) - } - } - - // Decode signature - token.Signature, err = p.DecodeSegment(parts[2]) - if err != nil { - return token, newError("could not base64 decode signature", ErrTokenMalformed, err) - } - text := strings.Join(parts[0:2], ".") - - // Lookup key(s) - if keyFunc == nil { - // keyFunc was not provided. short circuiting validation - return token, newError("no keyfunc was provided", ErrTokenUnverifiable) - } - - got, err := keyFunc(token) - if err != nil { - return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) - } - - switch have := got.(type) { - case VerificationKeySet: - if len(have.Keys) == 0 { - return token, newError("keyfunc returned empty verification key set", ErrTokenUnverifiable) - } - // Iterate through keys and verify signature, skipping the rest when a match is found. - // Return the last error if no match is found. - for _, key := range have.Keys { - if err = token.Method.Verify(text, token.Signature, key); err == nil { - break - } - } - default: - err = token.Method.Verify(text, token.Signature, have) - } - if err != nil { - return token, newError("", ErrTokenSignatureInvalid, err) - } - - // Validate Claims - if !p.skipClaimsValidation { - // Make sure we have at least a default validator - if p.validator == nil { - p.validator = NewValidator() - } - - if err := p.validator.Validate(claims); err != nil { - return token, newError("", ErrTokenInvalidClaims, err) - } - } - - // No errors so far, token is valid. - token.Valid = true - - return token, nil -} - -// ParseUnverified parses the token but doesn't validate the signature. -// -// WARNING: Don't use this method unless you know what you're doing. -// -// It's only ever useful in cases where you know the signature is valid (since it has already -// been or will be checked elsewhere in the stack) and you want to extract values from it. -func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { - parts = strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, parts, newError("token contains an invalid number of segments", ErrTokenMalformed) - } - - token = &Token{Raw: tokenString} - - // parse Header - var headerBytes []byte - if headerBytes, err = p.DecodeSegment(parts[0]); err != nil { - return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err) - } - if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err) - } - - // parse Claims - token.Claims = claims - - claimBytes, err := p.DecodeSegment(parts[1]) - if err != nil { - return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) - } - - // If `useJSONNumber` is enabled then we must use *json.Decoder to decode - // the claims. However, this comes with a performance penalty so only use - // it if we must and, otherwise, simple use json.Unmarshal. - if !p.useJSONNumber { - // JSON Unmarshal. Special case for map type to avoid weird pointer behavior. - if c, ok := token.Claims.(MapClaims); ok { - err = json.Unmarshal(claimBytes, &c) - } else { - err = json.Unmarshal(claimBytes, &claims) - } - } else { - dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - dec.UseNumber() - // JSON Decode. Special case for map type to avoid weird pointer behavior. - if c, ok := token.Claims.(MapClaims); ok { - err = dec.Decode(&c) - } else { - err = dec.Decode(&claims) - } - } - if err != nil { - return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err) - } - - // Lookup signature method - if method, ok := token.Header["alg"].(string); ok { - if token.Method = GetSigningMethod(method); token.Method == nil { - return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable) - } - } else { - return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable) - } - - return token, parts, nil -} - -// DecodeSegment decodes a JWT specific base64url encoding. This function will -// take into account whether the [Parser] is configured with additional options, -// such as [WithStrictDecoding] or [WithPaddingAllowed]. -func (p *Parser) DecodeSegment(seg string) ([]byte, error) { - encoding := base64.RawURLEncoding - - if p.decodePaddingAllowed { - if l := len(seg) % 4; l > 0 { - seg += strings.Repeat("=", 4-l) - } - encoding = base64.URLEncoding - } - - if p.decodeStrict { - encoding = encoding.Strict() - } - return encoding.DecodeString(seg) -} - -// Parse parses, validates, verifies the signature and returns the parsed token. -// keyFunc will receive the parsed token and should return the cryptographic key -// for verifying the signature. The caller is strongly encouraged to set the -// WithValidMethods option to validate the 'alg' claim in the token matches the -// expected algorithm. For more details about the importance of validating the -// 'alg' claim, see -// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ -func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { - return NewParser(options...).Parse(tokenString, keyFunc) -} - -// ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). -// -// Note: If you provide a custom claim implementation that embeds one of the -// standard claims (such as RegisteredClaims), make sure that a) you either -// embed a non-pointer version of the claims or b) if you are using a pointer, -// allocate the proper memory for it before passing in the overall claims, -// otherwise you might run into a panic. -func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { - return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/parser_option.go b/vendor/github.com/golang-jwt/jwt/v5/parser_option.go deleted file mode 100644 index 88a780fb..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/parser_option.go +++ /dev/null @@ -1,128 +0,0 @@ -package jwt - -import "time" - -// ParserOption is used to implement functional-style options that modify the -// behavior of the parser. To add new options, just create a function (ideally -// beginning with With or Without) that returns an anonymous function that takes -// a *Parser type as input and manipulates its configuration accordingly. -type ParserOption func(*Parser) - -// WithValidMethods is an option to supply algorithm methods that the parser -// will check. Only those methods will be considered valid. It is heavily -// encouraged to use this option in order to prevent attacks such as -// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. -func WithValidMethods(methods []string) ParserOption { - return func(p *Parser) { - p.validMethods = methods - } -} - -// WithJSONNumber is an option to configure the underlying JSON parser with -// UseNumber. -func WithJSONNumber() ParserOption { - return func(p *Parser) { - p.useJSONNumber = true - } -} - -// WithoutClaimsValidation is an option to disable claims validation. This -// option should only be used if you exactly know what you are doing. -func WithoutClaimsValidation() ParserOption { - return func(p *Parser) { - p.skipClaimsValidation = true - } -} - -// WithLeeway returns the ParserOption for specifying the leeway window. -func WithLeeway(leeway time.Duration) ParserOption { - return func(p *Parser) { - p.validator.leeway = leeway - } -} - -// WithTimeFunc returns the ParserOption for specifying the time func. The -// primary use-case for this is testing. If you are looking for a way to account -// for clock-skew, WithLeeway should be used instead. -func WithTimeFunc(f func() time.Time) ParserOption { - return func(p *Parser) { - p.validator.timeFunc = f - } -} - -// WithIssuedAt returns the ParserOption to enable verification -// of issued-at. -func WithIssuedAt() ParserOption { - return func(p *Parser) { - p.validator.verifyIat = true - } -} - -// WithExpirationRequired returns the ParserOption to make exp claim required. -// By default exp claim is optional. -func WithExpirationRequired() ParserOption { - return func(p *Parser) { - p.validator.requireExp = true - } -} - -// WithAudience configures the validator to require the specified audience in -// the `aud` claim. Validation will fail if the audience is not listed in the -// token or the `aud` claim is missing. -// -// NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is -// application-specific. Since this validation API is helping developers in -// writing secure application, we decided to REQUIRE the existence of the claim, -// if an audience is expected. -func WithAudience(aud string) ParserOption { - return func(p *Parser) { - p.validator.expectedAud = aud - } -} - -// WithIssuer configures the validator to require the specified issuer in the -// `iss` claim. Validation will fail if a different issuer is specified in the -// token or the `iss` claim is missing. -// -// NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is -// application-specific. Since this validation API is helping developers in -// writing secure application, we decided to REQUIRE the existence of the claim, -// if an issuer is expected. -func WithIssuer(iss string) ParserOption { - return func(p *Parser) { - p.validator.expectedIss = iss - } -} - -// WithSubject configures the validator to require the specified subject in the -// `sub` claim. Validation will fail if a different subject is specified in the -// token or the `sub` claim is missing. -// -// NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is -// application-specific. Since this validation API is helping developers in -// writing secure application, we decided to REQUIRE the existence of the claim, -// if a subject is expected. -func WithSubject(sub string) ParserOption { - return func(p *Parser) { - p.validator.expectedSub = sub - } -} - -// WithPaddingAllowed will enable the codec used for decoding JWTs to allow -// padding. Note that the JWS RFC7515 states that the tokens will utilize a -// Base64url encoding with no padding. Unfortunately, some implementations of -// JWT are producing non-standard tokens, and thus require support for decoding. -func WithPaddingAllowed() ParserOption { - return func(p *Parser) { - p.decodePaddingAllowed = true - } -} - -// WithStrictDecoding will switch the codec used for decoding JWTs into strict -// mode. In this mode, the decoder requires that trailing padding bits are zero, -// as described in RFC 4648 section 3.5. -func WithStrictDecoding() ParserOption { - return func(p *Parser) { - p.decodeStrict = true - } -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go b/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go deleted file mode 100644 index 77951a53..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go +++ /dev/null @@ -1,63 +0,0 @@ -package jwt - -// RegisteredClaims are a structured version of the JWT Claims Set, -// restricted to Registered Claim Names, as referenced at -// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 -// -// This type can be used on its own, but then additional private and -// public claims embedded in the JWT will not be parsed. The typical use-case -// therefore is to embedded this in a user-defined claim type. -// -// See examples for how to use this with your own claim types. -type RegisteredClaims struct { - // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 - Issuer string `json:"iss,omitempty"` - - // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 - Subject string `json:"sub,omitempty"` - - // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 - Audience ClaimStrings `json:"aud,omitempty"` - - // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 - ExpiresAt *NumericDate `json:"exp,omitempty"` - - // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 - NotBefore *NumericDate `json:"nbf,omitempty"` - - // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 - IssuedAt *NumericDate `json:"iat,omitempty"` - - // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 - ID string `json:"jti,omitempty"` -} - -// GetExpirationTime implements the Claims interface. -func (c RegisteredClaims) GetExpirationTime() (*NumericDate, error) { - return c.ExpiresAt, nil -} - -// GetNotBefore implements the Claims interface. -func (c RegisteredClaims) GetNotBefore() (*NumericDate, error) { - return c.NotBefore, nil -} - -// GetIssuedAt implements the Claims interface. -func (c RegisteredClaims) GetIssuedAt() (*NumericDate, error) { - return c.IssuedAt, nil -} - -// GetAudience implements the Claims interface. -func (c RegisteredClaims) GetAudience() (ClaimStrings, error) { - return c.Audience, nil -} - -// GetIssuer implements the Claims interface. -func (c RegisteredClaims) GetIssuer() (string, error) { - return c.Issuer, nil -} - -// GetSubject implements the Claims interface. -func (c RegisteredClaims) GetSubject() (string, error) { - return c.Subject, nil -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa.go b/vendor/github.com/golang-jwt/jwt/v5/rsa.go deleted file mode 100644 index 83cbee6a..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/rsa.go +++ /dev/null @@ -1,93 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" -) - -// SigningMethodRSA implements the RSA family of signing methods. -// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation -type SigningMethodRSA struct { - Name string - Hash crypto.Hash -} - -// Specific instances for RS256 and company -var ( - SigningMethodRS256 *SigningMethodRSA - SigningMethodRS384 *SigningMethodRSA - SigningMethodRS512 *SigningMethodRSA -) - -func init() { - // RS256 - SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { - return SigningMethodRS256 - }) - - // RS384 - SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { - return SigningMethodRS384 - }) - - // RS512 - SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { - return SigningMethodRS512 - }) -} - -func (m *SigningMethodRSA) Alg() string { - return m.Name -} - -// Verify implements token verification for the SigningMethod -// For this signing method, must be an *rsa.PublicKey structure. -func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key interface{}) error { - var rsaKey *rsa.PublicKey - var ok bool - - if rsaKey, ok = key.(*rsa.PublicKey); !ok { - return newError("RSA verify expects *rsa.PublicKey", ErrInvalidKeyType) - } - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) -} - -// Sign implements token signing for the SigningMethod -// For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(signingString string, key interface{}) ([]byte, error) { - var rsaKey *rsa.PrivateKey - var ok bool - - // Validate type of key - if rsaKey, ok = key.(*rsa.PrivateKey); !ok { - return nil, newError("RSA sign expects *rsa.PrivateKey", ErrInvalidKeyType) - } - - // Create the hasher - if !m.Hash.Available() { - return nil, ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return the encoded bytes - if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { - return sigBytes, nil - } else { - return nil, err - } -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go b/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go deleted file mode 100644 index 28c386ec..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go +++ /dev/null @@ -1,135 +0,0 @@ -//go:build go1.4 -// +build go1.4 - -package jwt - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" -) - -// SigningMethodRSAPSS implements the RSAPSS family of signing methods signing methods -type SigningMethodRSAPSS struct { - *SigningMethodRSA - Options *rsa.PSSOptions - // VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS. - // Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow - // https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously. - // See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details. - VerifyOptions *rsa.PSSOptions -} - -// Specific instances for RS/PS and company. -var ( - SigningMethodPS256 *SigningMethodRSAPSS - SigningMethodPS384 *SigningMethodRSAPSS - SigningMethodPS512 *SigningMethodRSAPSS -) - -func init() { - // PS256 - SigningMethodPS256 = &SigningMethodRSAPSS{ - SigningMethodRSA: &SigningMethodRSA{ - Name: "PS256", - Hash: crypto.SHA256, - }, - Options: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthEqualsHash, - }, - VerifyOptions: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - }, - } - RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { - return SigningMethodPS256 - }) - - // PS384 - SigningMethodPS384 = &SigningMethodRSAPSS{ - SigningMethodRSA: &SigningMethodRSA{ - Name: "PS384", - Hash: crypto.SHA384, - }, - Options: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthEqualsHash, - }, - VerifyOptions: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - }, - } - RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { - return SigningMethodPS384 - }) - - // PS512 - SigningMethodPS512 = &SigningMethodRSAPSS{ - SigningMethodRSA: &SigningMethodRSA{ - Name: "PS512", - Hash: crypto.SHA512, - }, - Options: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthEqualsHash, - }, - VerifyOptions: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - }, - } - RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { - return SigningMethodPS512 - }) -} - -// Verify implements token verification for the SigningMethod. -// For this verify method, key must be an rsa.PublicKey struct -func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key interface{}) error { - var rsaKey *rsa.PublicKey - switch k := key.(type) { - case *rsa.PublicKey: - rsaKey = k - default: - return newError("RSA-PSS verify expects *rsa.PublicKey", ErrInvalidKeyType) - } - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - opts := m.Options - if m.VerifyOptions != nil { - opts = m.VerifyOptions - } - - return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts) -} - -// Sign implements token signing for the SigningMethod. -// For this signing method, key must be an rsa.PrivateKey struct -func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) ([]byte, error) { - var rsaKey *rsa.PrivateKey - - switch k := key.(type) { - case *rsa.PrivateKey: - rsaKey = k - default: - return nil, newError("RSA-PSS sign expects *rsa.PrivateKey", ErrInvalidKeyType) - } - - // Create the hasher - if !m.Hash.Available() { - return nil, ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return the encoded bytes - if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { - return sigBytes, nil - } else { - return nil, err - } -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go b/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go deleted file mode 100644 index b3aeebbe..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go +++ /dev/null @@ -1,107 +0,0 @@ -package jwt - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key") - ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key") -) - -// ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key -func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// ParseRSAPrivateKeyFromPEMWithPassword parses a PEM encoded PKCS1 or PKCS8 private key protected with password -// -// Deprecated: This function is deprecated and should not be used anymore. It uses the deprecated x509.DecryptPEMBlock -// function, which was deprecated since RFC 1423 is regarded insecure by design. Unfortunately, there is no alternative -// in the Go standard library for now. See https://github.com/golang/go/issues/8860. -func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - - var blockDecrypted []byte - if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { - return nil, err - } - - if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// ParseRSAPublicKeyFromPEM parses a certificate or a PEM encoded PKCS1 or PKIX public key -func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - if parsedKey, err = x509.ParsePKCS1PublicKey(block.Bytes); err != nil { - return nil, err - } - } - } - - var pkey *rsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { - return nil, ErrNotRSAPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/signing_method.go b/vendor/github.com/golang-jwt/jwt/v5/signing_method.go deleted file mode 100644 index 0d73631c..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/signing_method.go +++ /dev/null @@ -1,49 +0,0 @@ -package jwt - -import ( - "sync" -) - -var signingMethods = map[string]func() SigningMethod{} -var signingMethodLock = new(sync.RWMutex) - -// SigningMethod can be used add new methods for signing or verifying tokens. It -// takes a decoded signature as an input in the Verify function and produces a -// signature in Sign. The signature is then usually base64 encoded as part of a -// JWT. -type SigningMethod interface { - Verify(signingString string, sig []byte, key interface{}) error // Returns nil if signature is valid - Sign(signingString string, key interface{}) ([]byte, error) // Returns signature or error - Alg() string // returns the alg identifier for this method (example: 'HS256') -} - -// RegisterSigningMethod registers the "alg" name and a factory function for signing method. -// This is typically done during init() in the method's implementation -func RegisterSigningMethod(alg string, f func() SigningMethod) { - signingMethodLock.Lock() - defer signingMethodLock.Unlock() - - signingMethods[alg] = f -} - -// GetSigningMethod retrieves a signing method from an "alg" string -func GetSigningMethod(alg string) (method SigningMethod) { - signingMethodLock.RLock() - defer signingMethodLock.RUnlock() - - if methodF, ok := signingMethods[alg]; ok { - method = methodF() - } - return -} - -// GetAlgorithms returns a list of registered "alg" names -func GetAlgorithms() (algs []string) { - signingMethodLock.RLock() - defer signingMethodLock.RUnlock() - - for alg := range signingMethods { - algs = append(algs, alg) - } - return -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf b/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf deleted file mode 100644 index 53745d51..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf +++ /dev/null @@ -1 +0,0 @@ -checks = ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1023"] diff --git a/vendor/github.com/golang-jwt/jwt/v5/token.go b/vendor/github.com/golang-jwt/jwt/v5/token.go deleted file mode 100644 index 352873a2..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/token.go +++ /dev/null @@ -1,100 +0,0 @@ -package jwt - -import ( - "crypto" - "encoding/base64" - "encoding/json" -) - -// Keyfunc will be used by the Parse methods as a callback function to supply -// the key for verification. The function receives the parsed, but unverified -// Token. This allows you to use properties in the Header of the token (such as -// `kid`) to identify which key to use. -// -// The returned interface{} may be a single key or a VerificationKeySet containing -// multiple keys. -type Keyfunc func(*Token) (interface{}, error) - -// VerificationKey represents a public or secret key for verifying a token's signature. -type VerificationKey interface { - crypto.PublicKey | []uint8 -} - -// VerificationKeySet is a set of public or secret keys. It is used by the parser to verify a token. -type VerificationKeySet struct { - Keys []VerificationKey -} - -// Token represents a JWT Token. Different fields will be used depending on -// whether you're creating or parsing/verifying a token. -type Token struct { - Raw string // Raw contains the raw token. Populated when you [Parse] a token - Method SigningMethod // Method is the signing method used or to be used - Header map[string]interface{} // Header is the first segment of the token in decoded form - Claims Claims // Claims is the second segment of the token in decoded form - Signature []byte // Signature is the third segment of the token in decoded form. Populated when you Parse a token - Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token -} - -// New creates a new [Token] with the specified signing method and an empty map -// of claims. Additional options can be specified, but are currently unused. -func New(method SigningMethod, opts ...TokenOption) *Token { - return NewWithClaims(method, MapClaims{}, opts...) -} - -// NewWithClaims creates a new [Token] with the specified signing method and -// claims. Additional options can be specified, but are currently unused. -func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token { - return &Token{ - Header: map[string]interface{}{ - "typ": "JWT", - "alg": method.Alg(), - }, - Claims: claims, - Method: method, - } -} - -// SignedString creates and returns a complete, signed JWT. The token is signed -// using the SigningMethod specified in the token. Please refer to -// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types -// for an overview of the different signing methods and their respective key -// types. -func (t *Token) SignedString(key interface{}) (string, error) { - sstr, err := t.SigningString() - if err != nil { - return "", err - } - - sig, err := t.Method.Sign(sstr, key) - if err != nil { - return "", err - } - - return sstr + "." + t.EncodeSegment(sig), nil -} - -// SigningString generates the signing string. This is the most expensive part -// of the whole deal. Unless you need this for something special, just go -// straight for the SignedString. -func (t *Token) SigningString() (string, error) { - h, err := json.Marshal(t.Header) - if err != nil { - return "", err - } - - c, err := json.Marshal(t.Claims) - if err != nil { - return "", err - } - - return t.EncodeSegment(h) + "." + t.EncodeSegment(c), nil -} - -// EncodeSegment encodes a JWT specific base64url encoding with padding -// stripped. In the future, this function might take into account a -// [TokenOption]. Therefore, this function exists as a method of [Token], rather -// than a global function. -func (*Token) EncodeSegment(seg []byte) string { - return base64.RawURLEncoding.EncodeToString(seg) -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/token_option.go b/vendor/github.com/golang-jwt/jwt/v5/token_option.go deleted file mode 100644 index b4ae3bad..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/token_option.go +++ /dev/null @@ -1,5 +0,0 @@ -package jwt - -// TokenOption is a reserved type, which provides some forward compatibility, -// if we ever want to introduce token creation-related options. -type TokenOption func(*Token) diff --git a/vendor/github.com/golang-jwt/jwt/v5/types.go b/vendor/github.com/golang-jwt/jwt/v5/types.go deleted file mode 100644 index b2655a9e..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/types.go +++ /dev/null @@ -1,149 +0,0 @@ -package jwt - -import ( - "encoding/json" - "fmt" - "math" - "strconv" - "time" -) - -// TimePrecision sets the precision of times and dates within this library. This -// has an influence on the precision of times when comparing expiry or other -// related time fields. Furthermore, it is also the precision of times when -// serializing. -// -// For backwards compatibility the default precision is set to seconds, so that -// no fractional timestamps are generated. -var TimePrecision = time.Second - -// MarshalSingleStringAsArray modifies the behavior of the ClaimStrings type, -// especially its MarshalJSON function. -// -// If it is set to true (the default), it will always serialize the type as an -// array of strings, even if it just contains one element, defaulting to the -// behavior of the underlying []string. If it is set to false, it will serialize -// to a single string, if it contains one element. Otherwise, it will serialize -// to an array of strings. -var MarshalSingleStringAsArray = true - -// NumericDate represents a JSON numeric date value, as referenced at -// https://datatracker.ietf.org/doc/html/rfc7519#section-2. -type NumericDate struct { - time.Time -} - -// NewNumericDate constructs a new *NumericDate from a standard library time.Time struct. -// It will truncate the timestamp according to the precision specified in TimePrecision. -func NewNumericDate(t time.Time) *NumericDate { - return &NumericDate{t.Truncate(TimePrecision)} -} - -// newNumericDateFromSeconds creates a new *NumericDate out of a float64 representing a -// UNIX epoch with the float fraction representing non-integer seconds. -func newNumericDateFromSeconds(f float64) *NumericDate { - round, frac := math.Modf(f) - return NewNumericDate(time.Unix(int64(round), int64(frac*1e9))) -} - -// MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epoch -// represented in NumericDate to a byte array, using the precision specified in TimePrecision. -func (date NumericDate) MarshalJSON() (b []byte, err error) { - var prec int - if TimePrecision < time.Second { - prec = int(math.Log10(float64(time.Second) / float64(TimePrecision))) - } - truncatedDate := date.Truncate(TimePrecision) - - // For very large timestamps, UnixNano would overflow an int64, but this - // function requires nanosecond level precision, so we have to use the - // following technique to get round the issue: - // - // 1. Take the normal unix timestamp to form the whole number part of the - // output, - // 2. Take the result of the Nanosecond function, which returns the offset - // within the second of the particular unix time instance, to form the - // decimal part of the output - // 3. Concatenate them to produce the final result - seconds := strconv.FormatInt(truncatedDate.Unix(), 10) - nanosecondsOffset := strconv.FormatFloat(float64(truncatedDate.Nanosecond())/float64(time.Second), 'f', prec, 64) - - output := append([]byte(seconds), []byte(nanosecondsOffset)[1:]...) - - return output, nil -} - -// UnmarshalJSON is an implementation of the json.RawMessage interface and -// deserializes a [NumericDate] from a JSON representation, i.e. a -// [json.Number]. This number represents an UNIX epoch with either integer or -// non-integer seconds. -func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { - var ( - number json.Number - f float64 - ) - - if err = json.Unmarshal(b, &number); err != nil { - return fmt.Errorf("could not parse NumericData: %w", err) - } - - if f, err = number.Float64(); err != nil { - return fmt.Errorf("could not convert json number value to float: %w", err) - } - - n := newNumericDateFromSeconds(f) - *date = *n - - return nil -} - -// ClaimStrings is basically just a slice of strings, but it can be either -// serialized from a string array or just a string. This type is necessary, -// since the "aud" claim can either be a single string or an array. -type ClaimStrings []string - -func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { - var value interface{} - - if err = json.Unmarshal(data, &value); err != nil { - return err - } - - var aud []string - - switch v := value.(type) { - case string: - aud = append(aud, v) - case []string: - aud = ClaimStrings(v) - case []interface{}: - for _, vv := range v { - vs, ok := vv.(string) - if !ok { - return ErrInvalidType - } - aud = append(aud, vs) - } - case nil: - return nil - default: - return ErrInvalidType - } - - *s = aud - - return -} - -func (s ClaimStrings) MarshalJSON() (b []byte, err error) { - // This handles a special case in the JWT RFC. If the string array, e.g. - // used by the "aud" field, only contains one element, it MAY be serialized - // as a single string. This may or may not be desired based on the ecosystem - // of other JWT library used, so we make it configurable by the variable - // MarshalSingleStringAsArray. - if len(s) == 1 && !MarshalSingleStringAsArray { - return json.Marshal(s[0]) - } - - return json.Marshal([]string(s)) -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/validator.go b/vendor/github.com/golang-jwt/jwt/v5/validator.go deleted file mode 100644 index 008ecd87..00000000 --- a/vendor/github.com/golang-jwt/jwt/v5/validator.go +++ /dev/null @@ -1,316 +0,0 @@ -package jwt - -import ( - "crypto/subtle" - "fmt" - "time" -) - -// ClaimsValidator is an interface that can be implemented by custom claims who -// wish to execute any additional claims validation based on -// application-specific logic. The Validate function is then executed in -// addition to the regular claims validation and any error returned is appended -// to the final validation result. -// -// type MyCustomClaims struct { -// Foo string `json:"foo"` -// jwt.RegisteredClaims -// } -// -// func (m MyCustomClaims) Validate() error { -// if m.Foo != "bar" { -// return errors.New("must be foobar") -// } -// return nil -// } -type ClaimsValidator interface { - Claims - Validate() error -} - -// Validator is the core of the new Validation API. It is automatically used by -// a [Parser] during parsing and can be modified with various parser options. -// -// The [NewValidator] function should be used to create an instance of this -// struct. -type Validator struct { - // leeway is an optional leeway that can be provided to account for clock skew. - leeway time.Duration - - // timeFunc is used to supply the current time that is needed for - // validation. If unspecified, this defaults to time.Now. - timeFunc func() time.Time - - // requireExp specifies whether the exp claim is required - requireExp bool - - // verifyIat specifies whether the iat (Issued At) claim will be verified. - // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this - // only specifies the age of the token, but no validation check is - // necessary. However, if wanted, it can be checked if the iat is - // unrealistic, i.e., in the future. - verifyIat bool - - // expectedAud contains the audience this token expects. Supplying an empty - // string will disable aud checking. - expectedAud string - - // expectedIss contains the issuer this token expects. Supplying an empty - // string will disable iss checking. - expectedIss string - - // expectedSub contains the subject this token expects. Supplying an empty - // string will disable sub checking. - expectedSub string -} - -// NewValidator can be used to create a stand-alone validator with the supplied -// options. This validator can then be used to validate already parsed claims. -// -// Note: Under normal circumstances, explicitly creating a validator is not -// needed and can potentially be dangerous; instead functions of the [Parser] -// class should be used. -// -// The [Validator] is only checking the *validity* of the claims, such as its -// expiration time, but it does NOT perform *signature verification* of the -// token. -func NewValidator(opts ...ParserOption) *Validator { - p := NewParser(opts...) - return p.validator -} - -// Validate validates the given claims. It will also perform any custom -// validation if claims implements the [ClaimsValidator] interface. -// -// Note: It will NOT perform any *signature verification* on the token that -// contains the claims and expects that the [Claim] was already successfully -// verified. -func (v *Validator) Validate(claims Claims) error { - var ( - now time.Time - errs []error = make([]error, 0, 6) - err error - ) - - // Check, if we have a time func - if v.timeFunc != nil { - now = v.timeFunc() - } else { - now = time.Now() - } - - // We always need to check the expiration time, but usage of the claim - // itself is OPTIONAL by default. requireExp overrides this behavior - // and makes the exp claim mandatory. - if err = v.verifyExpiresAt(claims, now, v.requireExp); err != nil { - errs = append(errs, err) - } - - // We always need to check not-before, but usage of the claim itself is - // OPTIONAL. - if err = v.verifyNotBefore(claims, now, false); err != nil { - errs = append(errs, err) - } - - // Check issued-at if the option is enabled - if v.verifyIat { - if err = v.verifyIssuedAt(claims, now, false); err != nil { - errs = append(errs, err) - } - } - - // If we have an expected audience, we also require the audience claim - if v.expectedAud != "" { - if err = v.verifyAudience(claims, v.expectedAud, true); err != nil { - errs = append(errs, err) - } - } - - // If we have an expected issuer, we also require the issuer claim - if v.expectedIss != "" { - if err = v.verifyIssuer(claims, v.expectedIss, true); err != nil { - errs = append(errs, err) - } - } - - // If we have an expected subject, we also require the subject claim - if v.expectedSub != "" { - if err = v.verifySubject(claims, v.expectedSub, true); err != nil { - errs = append(errs, err) - } - } - - // Finally, we want to give the claim itself some possibility to do some - // additional custom validation based on a custom Validate function. - cvt, ok := claims.(ClaimsValidator) - if ok { - if err := cvt.Validate(); err != nil { - errs = append(errs, err) - } - } - - if len(errs) == 0 { - return nil - } - - return joinErrors(errs...) -} - -// verifyExpiresAt compares the exp claim in claims against cmp. This function -// will succeed if cmp < exp. Additional leeway is taken into account. -// -// If exp is not set, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *Validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { - exp, err := claims.GetExpirationTime() - if err != nil { - return err - } - - if exp == nil { - return errorIfRequired(required, "exp") - } - - return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired) -} - -// verifyIssuedAt compares the iat claim in claims against cmp. This function -// will succeed if cmp >= iat. Additional leeway is taken into account. -// -// If iat is not set, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *Validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { - iat, err := claims.GetIssuedAt() - if err != nil { - return err - } - - if iat == nil { - return errorIfRequired(required, "iat") - } - - return errorIfFalse(!cmp.Before(iat.Add(-v.leeway)), ErrTokenUsedBeforeIssued) -} - -// verifyNotBefore compares the nbf claim in claims against cmp. This function -// will return true if cmp >= nbf. Additional leeway is taken into account. -// -// If nbf is not set, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *Validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { - nbf, err := claims.GetNotBefore() - if err != nil { - return err - } - - if nbf == nil { - return errorIfRequired(required, "nbf") - } - - return errorIfFalse(!cmp.Before(nbf.Add(-v.leeway)), ErrTokenNotValidYet) -} - -// verifyAudience compares the aud claim against cmp. -// -// If aud is not set or an empty list, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *Validator) verifyAudience(claims Claims, cmp string, required bool) error { - aud, err := claims.GetAudience() - if err != nil { - return err - } - - if len(aud) == 0 { - return errorIfRequired(required, "aud") - } - - // use a var here to keep constant time compare when looping over a number of claims - result := false - - var stringClaims string - for _, a := range aud { - if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { - result = true - } - stringClaims = stringClaims + a - } - - // case where "" is sent in one or many aud claims - if stringClaims == "" { - return errorIfRequired(required, "aud") - } - - return errorIfFalse(result, ErrTokenInvalidAudience) -} - -// verifyIssuer compares the iss claim in claims against cmp. -// -// If iss is not set, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *Validator) verifyIssuer(claims Claims, cmp string, required bool) error { - iss, err := claims.GetIssuer() - if err != nil { - return err - } - - if iss == "" { - return errorIfRequired(required, "iss") - } - - return errorIfFalse(iss == cmp, ErrTokenInvalidIssuer) -} - -// verifySubject compares the sub claim against cmp. -// -// If sub is not set, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *Validator) verifySubject(claims Claims, cmp string, required bool) error { - sub, err := claims.GetSubject() - if err != nil { - return err - } - - if sub == "" { - return errorIfRequired(required, "sub") - } - - return errorIfFalse(sub == cmp, ErrTokenInvalidSubject) -} - -// errorIfFalse returns the error specified in err, if the value is true. -// Otherwise, nil is returned. -func errorIfFalse(value bool, err error) error { - if value { - return nil - } else { - return err - } -} - -// errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is -// true. Otherwise, nil is returned. -func errorIfRequired(required bool, claim string) error { - if required { - return newError(fmt.Sprintf("%s claim is required", claim), ErrTokenRequiredClaimMissing) - } else { - return nil - } -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 9f878387..450e55ba 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -299,9 +299,6 @@ github.com/goccy/go-json/internal/runtime # github.com/gogo/protobuf v1.3.2 ## explicit; go 1.15 github.com/gogo/protobuf/proto -# github.com/golang-jwt/jwt/v5 v5.2.1 -## explicit; go 1.18 -github.com/golang-jwt/jwt/v5 # github.com/golang-migrate/migrate/v4 v4.18.2 ## explicit; go 1.22.0 github.com/golang-migrate/migrate/v4