Skip to content

[TT-15359]: Added extra jwt validation #7269

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Aug 8, 2025
Merged

Conversation

kofoworola
Copy link
Contributor

@kofoworola kofoworola commented Aug 4, 2025

TT-15359
Summary Core Registered Claims Validation
Type Story Story
Status In Dev
Points N/A
Labels jira_escalated

Description

TT-15359

Related Issue

Motivation and Context

How This Has Been Tested

Screenshots (if appropriate)

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring or add test (improvements in base code or adds test coverage to functionality)

Checklist

  • I ensured that the documentation is up to date
  • I explained why this PR updates go.mod in detail with reasoning why it's required
  • I would like a code coverage CI quality gate exception and have explained why

Copy link
Contributor

github-actions bot commented Aug 4, 2025

🚀 Performance Snapshot

Effort Perf Risk Hot Paths Benchmarks TL;DR
Low 🟡 ⚠️ Added JWT claim validations (issuer, audience, JTI, subject) may impact request processing time in high-volume scenarios
## Performance Impact Analysis

This PR adds additional JWT validation capabilities to the Tyk Gateway for OAS APIs. The changes introduce validation for issuer, audience, JWT ID, and subject claims against configured values. These validations are performed during the JWT middleware's request processing flow, which is a critical path for authenticated API requests.

The validation is conditionally executed only for OAS APIs and only when the corresponding validation options are configured, which limits the performance impact to specific use cases.

## Critical Areas

The JWT middleware's ProcessRequest function is a hot path for all JWT-authenticated requests. The PR modifies this function to call a new validateClaims method which performs additional validations beyond the existing time-based validations.

Each validation involves map lookups, string comparisons, and potentially array iterations when checking against lists of allowed values. The subject validation is particularly noteworthy as it calls getIdentityFromToken, which may involve additional processing depending on the token structure.

## Optimization Recommendations
  1. Consider caching validation results for tokens that are frequently reused to avoid repeated validation overhead.

  2. For audience validation, the nested loops (iterating through token audiences and allowed audiences) could be optimized by using a map lookup instead of linear search when the allowed audience list is large.

  3. Error logging in validation functions could be made conditional based on log level to reduce overhead in production environments.

  4. Consider adding benchmarks to measure the performance impact of these validations, especially for high-volume scenarios.

## Summary
  • The PR adds valuable security features with minimal performance overhead for most use cases.
  • The impact is limited to OAS APIs with specific JWT validation configurations.
  • In high-volume scenarios with many JWT validations, the additional checks could add noticeable overhead.
  • The nested loops in audience validation could be optimized for better performance with large lists.

Tip: Mention me again using /performance <request>.
Powered by Probe AI
Performance Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 4, 2025

🛡️ Security Snapshot

Effort Risk Level Tests Compliance TL;DR
Medium 🟢 ✔️ Added JWT claim validation enhances security by allowing strict issuer, audience, JWT ID, and subject validation
## Security Impact Analysis

This PR adds enhanced JWT validation capabilities to the Tyk API Gateway, specifically for APIs defined using the OpenAPI Specification (OAS). The changes introduce validation for four critical JWT claims: issuer (iss), audience (aud), JWT ID (jti), and subject. These validations help prevent token misuse by ensuring tokens contain expected values and required fields, significantly improving the security posture of JWT-protected APIs.

## Identified Vulnerabilities

No vulnerabilities introduced. On the contrary, this PR addresses potential security weaknesses:

High Severity (Mitigated):

  • Token forgery/replay attacks mitigated by allowing strict issuer validation
  • Cross-tenant token misuse prevented by audience validation
  • Improper token usage prevented by subject validation

Medium Severity (Mitigated):

  • Replay attacks further mitigated by optional JWT ID (jti) validation
## Security Recommendations

The implementation is solid with comprehensive validation and error handling. Recommendations:

  1. Consider adding documentation or examples showing how to configure these new JWT validations
  2. Ensure error messages don't leak sensitive information about validation configuration
  3. Consider adding metrics/logging for rejected tokens to help detect potential attacks
## OWASP Compliance

This PR strengthens compliance with several OWASP Top 10 categories:

  • A2:2021 - Cryptographic Failures: Enhances JWT security beyond signature verification
  • A5:2021 - Security Misconfiguration: Provides more granular control over JWT acceptance criteria
  • A7:2021 - Identification and Authentication Failures: Improves token validation with additional claim checks

The implementation follows security best practices for JWT validation as recommended by OWASP JWT Cheat Sheet.

## Summary
  • This PR adds valuable security controls for JWT validation, allowing API administrators to enforce stricter token acceptance criteria
  • The implementation is well-tested with unit tests for each validation function
  • The changes only affect OAS-defined APIs and won't break existing configurations
  • No security issues identified – change LGTM

Tip: Mention me again using /security <request>.
Powered by Probe AI
Security Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 4, 2025

📦 Impact Review Snapshot

Effort Downstream Updates Compatibility Docs TL;DR
Low ⚠️ 🟢 ⚠️ Added JWT validation for issuer, audience, JWT ID, and subject claims in OAS APIs
## Impact Assessment

This PR adds enhanced JWT validation capabilities to the Tyk Gateway for OAS-based APIs. The changes introduce four new validation options:

  1. Issuer Validation - Validates the iss claim against a list of allowed issuers
  2. Audience Validation - Validates the aud claim against a list of allowed audiences
  3. JWT ID Validation - Requires the presence of a jti claim when enabled
  4. Subject Validation - Validates the subject (from kid/identityBaseField/sub) against a list of allowed subjects

These features are added to the OAS JWT security schema in the JWT struct and implemented in the JWT middleware. The changes are backward compatible as they're only activated when explicitly configured.

## Required Updates
  1. tyk-operator:

    • CRD updates needed to expose the new JWT validation fields
    • Controller logic to handle these new fields when processing API definitions
  2. portal:

    • UI updates to expose these new JWT validation options in the API designer
    • Form validation for the new fields
  3. Documentation:

    • Updates needed to document these new JWT validation features
    • Examples of how to configure and use these validations
## Compatibility Concerns

The changes are backward compatible since:

  • The new validation features are only active when explicitly configured
  • They only apply to OAS-based APIs (checked with if !k.Spec.IsOAS condition)
  • Default behavior remains unchanged when the new fields are not set

No breaking changes are introduced to existing APIs or authentication flows.

## Summary & Recommendations
  • This PR enhances JWT security by adding standard claim validations that are important for proper OAuth/OIDC implementations
  • Updates to tyk-operator and portal should be prioritized to expose these new features to users
  • Documentation should be updated to explain these new validation options and their security benefits
  • Consider adding integration tests that verify these validations work with common identity providers

Tip: Mention me again using /dependency <request>.
Powered by Probe AI
Tyk Gateway Dependency Impact Reviewer

Copy link
Contributor

github-actions bot commented Aug 4, 2025

🚦 Connectivity Review Snapshot

Effort Tests Security Perf TL;DR
Low 🔒 none 🟢 Added enhanced JWT validation for issuer, audience, JWT ID, and subject claims
## Connectivity Assessment
  • Redis Connections: No changes to Redis connectivity - the JWT validation is performed in-memory without requiring additional Redis operations.
  • RPC Connections: No impact on RPC connections - the JWT validation is performed locally within the gateway.
  • Synchronization Mechanisms: No changes to synchronization mechanisms - the validation is stateless and doesn't require coordination between gateway instances.
## Test Coverage Validation
  • Redis Tests: Not applicable as the changes don't affect Redis connectivity.
  • RPC Tests: Not applicable as the changes don't affect RPC connectivity.
  • Failure Scenario Tests: The PR includes commented-out test cases for the new JWT validation functionality, which should be uncommented and enabled to ensure proper test coverage.
## Security & Performance Impact
  • Authentication Changes: The PR adds enhanced JWT validation for issuer, audience, JWT ID, and subject claims, improving security by allowing more fine-grained control over accepted tokens.
  • Performance Considerations: The additional validation is performed in-memory and should have minimal performance impact as it's only adding simple claim checks.
  • Error Handling: Proper error handling is implemented with detailed error messages for each validation failure, which helps with troubleshooting.
## Summary & Recommendations
  • The PR enhances JWT validation with additional claim checks that improve security without impacting connectivity.
  • Recommend uncommenting and enabling the test cases to ensure proper test coverage.
  • Consider adding documentation for these new JWT validation features to help users understand how to configure them.

Tip: Mention me again using /connectivity <request>.
Powered by Probe AI
Connectivity Issues Reviewer Prompt for Tyk Gateway

@kofoworola kofoworola marked this pull request as ready for review August 4, 2025 09:47
@kofoworola kofoworola force-pushed the feat/update-jwt-validation branch from 2c94688 to e59d030 Compare August 4, 2025 09:48
@buger
Copy link
Member

buger commented Aug 4, 2025

Let's make that PR title a 💯 shall we? 💪

Your PR title and story title look slightly different. Just checking in to know if it was intentional!

Story Title Core Registered Claims Validation
PR Title [TT-15359]: Added extra jwt validation

Check out this guide to learn more about PR best-practices.

@buger
Copy link
Member

buger commented Aug 4, 2025

This PR is too huge for one to review 💔

Additions 1408 🙅‍♀️
Expected ⬇️ 800

Consider breaking it down into multiple small PRs.

Check out this guide to learn more about PR best-practices.

Copy link
Contributor

github-actions bot commented Aug 4, 2025

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Claims Type Assertion

The new claim validation functions (e.g., validateIssuer, validateAudience, validateJTI) assume that claims are always of type jwt.MapClaims and perform type assertions accordingly. If the claims type changes or is not as expected, this could cause runtime errors. The reviewer should validate that all code paths guarantee the claims type, or add safer handling.

func validateIssuer(claims jwt.Claims, allowedIssuers []string) error {
	if claims, ok := claims.(jwt.MapClaims); ok {
		iss, exists := claims[ISS]
		if !exists {
			return errors.New("issuer claim is required but not present in token")
		}

		issuer, ok := iss.(string)
		if !ok {
			return errors.New("issuer claim must be a string")
		}

		for _, allowed := range allowedIssuers {
			if issuer == allowed {
				return nil
			}
		}

		return fmt.Errorf("invalid issuer claim: %s", issuer)
	}
	return errors.New("invalid claims type")
}

func validateAudience(claims jwt.Claims, allowedAudiences []string) error {
	if claims, ok := claims.(jwt.MapClaims); ok {
		aud, exists := claims[AUD]
		if !exists {
			return errors.New("audience claim is required but not present in token")
		}

		var audiences []string
		switch v := aud.(type) {
		case string:
			audiences = []string{v}
		case []interface{}:
			for _, a := range v {
				if s, ok := a.(string); ok {
					audiences = append(audiences, s)
				}
			}
		default:
			return errors.New("invalid audience claim format")
		}

		for _, tokenAud := range audiences {
			for _, allowedAud := range allowedAudiences {
				if tokenAud == allowedAud {
					return nil
				}
			}
		}

		return fmt.Errorf("no matching audience found in token: %v", audiences)
	}
	return errors.New("invalid claims type")
}
Logging Sensitive Data

Error logs in validateExtraClaims may include sensitive JWT claim values (such as issuer, audience, subject) in error messages. The reviewer should ensure that logging these values does not inadvertently expose sensitive information in production logs.

	if !k.Spec.IsOAS {
		return nil // Skip extra validations for non-OAS APIs
	}

	jwtConfig := k.Spec.OAS.GetJWTConfiguration()

	// Issuer validation
	if len(jwtConfig.AllowedIssuers) > 0 {
		if err := validateIssuer(claims, jwtConfig.AllowedIssuers); err != nil {
			k.Logger().WithError(err).Error("JWT issuer validation failed")
			return err
		}
	}

	// Audience validation
	if len(jwtConfig.AllowedAudiences) > 0 {
		if err := validateAudience(claims, jwtConfig.AllowedAudiences); err != nil {
			k.Logger().WithError(err).Error("JWT audience validation failed")
			return err
		}
	}

	// JWT ID validation
	if jwtConfig.RequireJTI {
		if err := validateJTI(claims); err != nil {
			k.Logger().WithError(err).Error("JWT ID validation failed")
			return err
		}
	}

	// Subject validation
	if len(jwtConfig.AllowedSubjects) > 0 {
		subject, err := k.getIdentityFromToken(token)
		if err != nil {
			k.Logger().WithError(err).Error("Failed to get identity from token")
			return err
		}

		if err := validateSubjectValue(subject, jwtConfig.AllowedSubjects); err != nil {
			k.Logger().WithError(err).Error("JWT subject validation failed")
			return err
		}
	}

	return nil
}

Copy link
Contributor

github-actions bot commented Aug 4, 2025

PR Code Suggestions ✨

No code suggestions found for the PR.

Copy link
Contributor

github-actions bot commented Aug 4, 2025

API Changes

--- prev.txt	2025-08-08 09:38:11.409043474 +0000
+++ current.txt	2025-08-08 09:38:01.769977316 +0000
@@ -3286,6 +3286,13 @@
 }
     JSVMEvent represents a JavaScript VM event configuration for event handlers.
 
+type JTIValidation struct {
+	// Enabled indicates whether JWT ID claim is required.
+	// When true, tokens must include a 'jti' claim.
+	Enabled bool `bson:"enabled" json:"enabled"`
+}
+    JTIValidation contains the configuration for the validation of the JWT ID.
+
 type JWT struct {
 	// Enabled activates the basic authentication mode.
 	//
@@ -3314,6 +3321,10 @@
 	// Tyk classic API definition: `jwt_identity_base_field`
 	IdentityBaseField string `bson:"identityBaseField,omitempty" json:"identityBaseField,omitempty"`
 
+	// SubjectClaims specifies a list of claims that can be used to identity the subject of the JWT.
+	// The field is an OAS only field and is only used in OAS APIs.
+	SubjectClaims []string `bson:"subjectClaims,omitempty" json:"subjectClaims,omitempty"`
+
 	// SkipKid controls skipping using the `kid` claim from a JWT (default behaviour).
 	// When this is true, the field configured in IdentityBaseField is checked first.
 	//
@@ -3326,6 +3337,11 @@
 	// Tyk classic API definition: `jwt_policy_field_name`
 	PolicyFieldName string `bson:"policyFieldName,omitempty" json:"policyFieldName,omitempty"`
 
+	// BasePolicyClaims specifies a list of claims from which the base PolicyID is extracted.
+	// The policy is applied to the session as a base policy.
+	// The field is an OAS only field and is only used in OAS APIs.
+	BasePolicyClaims []string `bson:"basePolicyClaims,omitempty" json:"basePolicyClaims,omitempty"`
+
 	// ClientBaseField is used when PolicyFieldName is not provided. It will get
 	// a session key and use the policies from that. The field ensures that requests
 	// use the same session.
@@ -3356,6 +3372,21 @@
 	// Tyk classic API definition: `jwt_expires_at_validation_skew`.
 	ExpiresAtValidationSkew uint64 `bson:"expiresAtValidationSkew,omitempty" json:"expiresAtValidationSkew,omitempty"`
 
+	// AllowedIssuers contains a list of accepted issuers for JWT validation.
+	// When configured, the JWT's issuer claim must match one of these values.
+	AllowedIssuers []string `bson:"allowedIssuers,omitempty" json:"allowedIssuers,omitempty"`
+
+	// AllowedAudiences contains a list of accepted audiences for JWT validation.
+	// When configured, the JWT's audience claim must match one of these values.
+	AllowedAudiences []string `bson:"allowedAudiences,omitempty" json:"allowedAudiences,omitempty"`
+
+	// JTIValidation contains the configuration for the validation of the JWT ID.
+	JTIValidation JTIValidation `bson:"jtiValidation,omitempty" json:"jtiValidation,omitempty"`
+
+	// AllowedSubjects contains a list of accepted subjects for JWT validation.
+	// When configured, the subject from kid/identityBaseField/sub must match one of these values.
+	AllowedSubjects []string `bson:"allowedSubjects,omitempty" json:"allowedSubjects,omitempty"`
+
 	// IDPClientIDMappingDisabled prevents Tyk from automatically detecting the use of certain IDPs based on standard claims
 	// that they include in the JWT: `client_id`, `cid`, `clientId`. Setting this flag to `true` disables the mapping and avoids
 	// accidentally misidentifying the use of one of these IDPs if one of their standard values is configured in your JWT.
@@ -3580,6 +3611,8 @@
 func (s *OAS) Fill(api apidef.APIDefinition)
     Fill fills *OAS definition from apidef.APIDefinition.
 
+func (s *OAS) GetJWTConfiguration() *JWT
+
 func (s *OAS) GetTykExtension() *XTykAPIGateway
     GetTykExtension returns our OAS schema extension from inside *OAS.
 
@@ -4167,6 +4200,11 @@
 	// - For JWT: `scopes.jwt.scope_claim_name`
 	ClaimName string `bson:"claimName,omitempty" json:"claimName,omitempty"`
 
+	// Claims contains a list of claims that contains the claim name.
+	// The first match from the list of claims in the token is used.
+	// OAS only field applied to OAS apis.
+	Claims []string `bson:"claims,omitempty" json:"claims,omitempty"`
+
 	// ScopeToPolicyMapping contains the mappings of scopes to policy IDs.
 	//
 	// Tyk classic API definition:
@@ -8507,6 +8545,9 @@
 	HMACSign  = "hmac"
 	RSASign   = "rsa"
 	ECDSASign = "ecdsa"
+	ISS       = "iss"
+	AUD       = "aud"
+	JTI       = "jti"
 )
 const (
 	ErrOAuthAuthorizationFieldMissing   = "oauth.auth_field_missing"
@@ -8593,6 +8634,7 @@
 var (
 	ErrNoSuitableUserIDClaimFound = errors.New("no suitable claims for user ID were found")
 	ErrEmptyUserIDInSubClaim      = errors.New("found an empty user ID in sub claim")
+	ErrEmptyUserIDInClaim         = errors.New("found an empty user ID in predefined base claim")
 )
 var (
 	ErrSyncResourceNotKnown = errors.New("unknown resource to sync")

Copy link
Contributor

github-actions bot commented Aug 4, 2025

Performance Impact Review for PR #7269: Added extra JWT validation

Overview

This PR adds enhanced JWT validation capabilities to the Tyk Gateway for OAS APIs, specifically adding validation for issuer (iss), audience (aud), JWT ID (jti), and subject claims. These validations are implemented in the JWT middleware's validateExtraClaims function, which is called during token validation in the ProcessRequest method.

Performance Analysis

The performance impact of these changes is likely to be minimal for most deployments, but could become noticeable in high-volume scenarios with many JWT validations. Key observations:

  1. Conditional Execution: The validations are only performed for OAS APIs and only when the corresponding configuration is set, limiting the performance impact to specific use cases.

  2. Issuer Validation: Simple string comparison against a list of allowed issuers. O(n) complexity where n is the number of allowed issuers.

  3. Audience Validation: More complex as it handles both string and array audience claims. Contains nested loops (iterating through token audiences and allowed audiences), which could be inefficient for large lists. This is the most performance-sensitive part of the changes.

  4. JWT ID Validation: Simple check for the presence of the jti claim. Negligible performance impact.

  5. Subject Validation: Requires calling getIdentityFromToken() which may involve additional processing to extract the subject from the token.

Optimization Recommendations

  1. Audience Validation: Consider optimizing the nested loops in audience validation by using a map lookup instead of linear search when the allowed audience list is large.

  2. Caching: For frequently reused tokens, consider caching validation results to avoid repeated validation overhead.

  3. Benchmarking: Add benchmarks to measure the performance impact of these validations, especially for high-volume scenarios.

Conclusion

The PR adds valuable security features with minimal performance overhead for most use cases. The impact is limited to OAS APIs with specific JWT validation configurations. In high-volume scenarios with many JWT validations, the additional checks could add noticeable overhead, particularly the audience validation with its nested loops.


Tip: Mention me again using /performance <request>.
Powered by Probe AI
Performance Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 4, 2025

📦 Impact Review Snapshot

Effort Downstream Updates Compatibility Docs TL;DR
Low ⚠️ 🟢 ⚠️ Added JWT validation for issuer, audience, JWT ID, and subject claims in OAS APIs
## Impact Assessment

This PR adds enhanced JWT validation capabilities to the Tyk Gateway for OAS-based APIs. The changes introduce four new validation options:

  1. Issuer Validation - Validates the iss claim against a list of allowed issuers
  2. Audience Validation - Validates the aud claim against a list of allowed audiences
  3. JWT ID Validation - Requires the presence of a jti claim when enabled
  4. Subject Validation - Validates the subject (from kid/identityBaseField/sub) against a list of allowed subjects

These validations are implemented in the JWT middleware and only apply to OAS APIs when the corresponding validation options are configured. The changes are backward compatible as they're only activated when explicitly configured.

## Required Updates
  1. tyk-operator:

    • CRD updates needed in api_definitions.go to expose the new JWT validation fields
    • Controller logic to handle these new fields when processing API definitions
  2. tyk-charts:

    • No immediate updates required as the changes don't affect configuration or deployment
  3. portal:

    • UI updates needed to expose these new JWT validation options in the API designer
    • Form validation for the new fields
  4. Documentation:

    • Updates needed to document these new JWT validation features
    • Examples of how to configure and use these validations
## Compatibility Concerns

The changes are backward compatible since:

  • The new validation features are only active when explicitly configured
  • They only apply to OAS-based APIs (checked with if !k.Spec.IsOAS condition)
  • Default behavior remains unchanged when the new fields are not set

No breaking changes are introduced to existing APIs or authentication flows.

## Summary & Recommendations
  • This PR enhances JWT security by adding standard claim validations that are important for proper OAuth/OIDC implementations
  • Updates to tyk-operator and portal should be prioritized to expose these new features to users
  • Documentation should be updated to explain these new validation options and their security benefits
  • Consider adding integration tests that verify these validations work with common identity providers

Tip: Mention me again using /dependency <request>.
Powered by Probe AI
Tyk Gateway Dependency Impact Reviewer

Copy link
Contributor

github-actions bot commented Aug 4, 2025

🛡️ Security Snapshot

Effort Risk Level Tests Compliance TL;DR
Low 🟢 ✔️ Added JWT validation for issuer, audience, JWT ID, and subject claims enhances security posture
## Security Impact Analysis

This PR adds enhanced JWT validation capabilities for OAS-defined APIs in Tyk Gateway. The implementation adds validation for standard JWT registered claims: issuer (iss), audience (aud), JWT ID (jti), and subject validation. These validations are conditionally applied based on configuration and only for OAS APIs, making this a non-breaking change that improves security without disrupting existing setups.

## Identified Vulnerabilities

No vulnerabilities introduced. On the contrary, this PR addresses potential security weaknesses:

High Severity (Mitigated):

  • Token forgery/replay attacks mitigated by allowing strict issuer validation
  • Cross-tenant token misuse prevented by audience validation
  • Token misuse across different subjects prevented by subject validation

Medium Severity (Mitigated):

  • Replay attacks further mitigated by optional JWT ID (jti) validation
## Security Recommendations

The implementation is solid with proper validation and error handling. Some minor recommendations:

  1. Consider adding documentation explaining these new JWT validation features and their security benefits
  2. Consider adding metrics or observability for rejected tokens to help detect potential attacks
  3. The error messages include the invalid values which could potentially leak information in logs - consider sanitizing these in production environments
## OWASP Compliance

This PR strengthens compliance with several OWASP Top 10 categories:

  • A2:2021 - Cryptographic Failures: Enhances JWT security beyond signature verification
  • A7:2021 - Identification and Authentication Failures: Improves token validation with additional claim checks

The implementation follows security best practices for JWT validation as recommended by OWASP JWT Cheat Sheet, particularly the validation of registered claims.

## Summary
  • The PR adds valuable security controls for JWT validation, allowing API administrators to enforce stricter token acceptance criteria
  • The implementation is well-tested with comprehensive unit tests for each validation function
  • The changes only affect OAS-defined APIs and won't break existing configurations
  • No security issues identified – change LGTM

Tip: Mention me again using /security <request>.
Powered by Probe AI
Security Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 4, 2025

📦 Impact Review Snapshot

Effort Downstream Updates Compatibility Docs TL;DR
Low ⚠️ 🟢 ⚠️ Added JWT validation for issuer, audience, JWT ID, and subject claims in OAS APIs
## Impact Assessment

This PR adds enhanced JWT validation capabilities to the Tyk Gateway for OAS-based APIs. The changes introduce four new validation options:

  1. Issuer Validation - Validates the iss claim against a list of allowed issuers
  2. Audience Validation - Validates the aud claim against a list of allowed audiences
  3. JWT ID Validation - Requires the presence of a jti claim when enabled
  4. Subject Validation - Validates the subject (from kid/identityBaseField/sub) against a list of allowed subjects

These features are added to the OAS JWT security schema in the JWT struct and implemented in the JWT middleware. The changes are backward compatible as they're only activated when explicitly configured.

## Required Updates
  1. tyk-operator:

    • CRD updates needed to expose the new JWT validation fields
    • Controller logic to handle these new fields when processing API definitions
  2. portal:

    • UI updates to expose these new JWT validation options in the API designer
    • Form validation for the new fields
  3. Documentation:

    • Updates needed to document these new JWT validation features
    • Examples of how to configure and use these validations
## Compatibility Concerns

The changes are backward compatible since:

  • The new validation features are only active when explicitly configured
  • They only apply to OAS-based APIs (checked with if !k.Spec.IsOAS condition)
  • Default behavior remains unchanged when the new fields are not set

No breaking changes are introduced to existing APIs or authentication flows.

## Summary & Recommendations
  • This PR enhances JWT security by adding standard claim validations that are important for proper OAuth/OIDC implementations
  • Updates to tyk-operator and portal should be prioritized to expose these new features to users
  • Documentation should be updated to explain these new validation options and their security benefits
  • Consider adding integration tests that verify these validations work with common identity providers

Tip: Mention me again using /dependency <request>.
Powered by Probe AI
Tyk Gateway Dependency Impact Reviewer

Copy link
Contributor

github-actions bot commented Aug 4, 2025

🛡️ Security Snapshot

Effort Risk Level Tests Compliance TL;DR
Medium 🟢 ⚠️ ✔️ Added JWT validation for issuer, audience, JWT ID, and subject claims enhances security but lacks dedicated tests
## Security Impact Analysis

This PR adds enhanced JWT validation capabilities to the Tyk API Gateway for OAS-defined APIs. The implementation introduces validation for four standard JWT claims: issuer (iss), audience (aud), JWT ID (jti), and subject. These validations are conditionally executed based on configuration and only apply to OAS APIs. The code properly handles different claim formats and provides clear error messages. This enhancement significantly improves security by allowing API administrators to enforce stricter token acceptance criteria, which helps prevent token misuse and unauthorized access.

## Identified Vulnerabilities

No new vulnerabilities introduced. Instead, this PR mitigates several potential security issues:

High Severity (Mitigated):

  • Token forgery/replay attacks mitigated by allowing strict issuer validation
  • Cross-tenant token misuse prevented by audience validation
  • Unauthorized access prevented by subject validation

Medium Severity (Mitigated):

  • Replay attacks further mitigated by optional JWT ID (jti) validation

Low Severity (Potential):

  • Error logging in validation functions includes claim values, which could potentially expose sensitive information in logs
  • Type assertions without sufficient error handling could lead to panics with malformed tokens
## Security Recommendations
  1. Add unit tests: Create dedicated tests for each validation function to ensure proper handling of edge cases and malformed claims.

  2. Consider sensitive data exposure: Review error logging to ensure it doesn't expose sensitive claim information in production environments.

  3. Optimize audience validation: The nested loops for audience validation could be replaced with a map lookup for better performance with large lists.

  4. Add documentation: Provide clear documentation on how to configure these new JWT validation options and their security benefits.

  5. Consider caching validation results: For frequently reused tokens, caching validation results could improve performance without compromising security.

## OWASP Compliance

This PR strengthens compliance with several OWASP Top 10 categories:

  • A2:2021 - Cryptographic Failures: Enhances JWT security beyond basic signature verification
  • A5:2021 - Security Misconfiguration: Provides more granular control over JWT acceptance criteria
  • A7:2021 - Identification and Authentication Failures: Improves token validation with additional claim checks

The implementation follows security best practices for JWT validation as recommended by OWASP JWT Cheat Sheet, including proper claim validation and type checking.

## Summary
  • This PR adds valuable security controls for JWT validation, allowing API administrators to enforce stricter token acceptance criteria
  • The implementation is well-structured and follows best practices for JWT validation
  • The changes only affect OAS-defined APIs and won't break existing configurations
  • The main concern is the lack of dedicated unit tests for the new validation functions
  • No security issues identified – change LGTM

Tip: Mention me again using /security <request>.
Powered by Probe AI
Security Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 4, 2025

JWT Core Registered Claims Validation PR Analysis

This PR adds enhanced JWT validation capabilities to the Tyk Gateway for OpenAPI Specification (OAS) APIs. The implementation adds validation for standard JWT registered claims as defined in RFC 7519:

  1. Issuer (iss) Validation: Validates the token's issuer claim against a configurable list of allowed issuers
  2. Audience (aud) Validation: Validates the token's audience claim against a configurable list of allowed audiences
  3. JWT ID (jti) Validation: Can require the presence of a JWT ID claim
  4. Subject Validation: Validates the subject (extracted from kid/identityBaseField/sub) against a list of allowed subjects

The implementation includes:

  • New validation functions for each claim type
  • Integration with the existing JWT middleware validation flow
  • Comprehensive unit tests for each validation scenario
  • Proper error handling and logging

These validations are only applied to OAS APIs and only when the corresponding validation options are configured, making this a non-breaking change. The PR also improves how JWT configuration is retrieved, using GetJWTConfiguration() instead of directly accessing the configuration properties.

This enhancement follows JWT best practices and allows API administrators to implement stricter token acceptance criteria, improving security for JWT-authenticated APIs.


Tip: Mention me again using /connectivity <request>.
Powered by Probe AI
Connectivity Issues Reviewer Prompt for Tyk Gateway

Copy link
Contributor

github-actions bot commented Aug 4, 2025

🚦 Connectivity Review Snapshot

Effort Tests Security Perf TL;DR
Low ⚠️ 🔒 none 🟢 Added JWT claim validation for issuer, audience, JWT ID, and subject claims in OAS APIs
## Connectivity Assessment
  • Redis Connections: No changes to Redis connectivity - the JWT validation is performed in-memory without requiring additional Redis operations.
  • RPC Connections: No impact on RPC connections - the JWT validation is performed locally within the gateway.
  • Synchronization Mechanisms: No changes to synchronization mechanisms - the validation is stateless and doesn't require coordination between gateway instances.
## Test Coverage Validation
  • Redis Tests: Not applicable as the changes don't affect Redis connectivity.
  • RPC Tests: Not applicable as the changes don't affect RPC connectivity.
  • Failure Scenario Tests: The PR appears to include test functions for the new JWT validation features, but they may be commented out or not yet committed, as they weren't found in the current codebase search.
## Security & Performance Impact
  • Authentication Changes: The PR adds enhanced JWT validation for issuer, audience, JWT ID, and subject claims, improving security by allowing more fine-grained control over accepted tokens.
  • Performance Considerations: The additional validation is performed in-memory and should have minimal performance impact as it's only adding simple claim checks.
  • Error Handling: Proper error handling is implemented with detailed error messages for each validation failure, which helps with troubleshooting.
## Summary & Recommendations
  • The PR enhances JWT validation with additional claim checks that improve security without impacting connectivity.
  • Recommend ensuring that the test cases for the new validation functions are uncommented and enabled to ensure proper test coverage.
  • The changes only affect OAS APIs and are only activated when explicitly configured.
  • No suggestions to provide – change LGTM.

Tip: Mention me again using /connectivity <request>.
Powered by Probe AI
Connectivity Issues Reviewer Prompt for Tyk Gateway

Copy link
Contributor

github-actions bot commented Aug 4, 2025

JWT Claim Validation Enhancement Analysis

This PR adds enhanced JWT validation capabilities to the Tyk Gateway for APIs defined using the OpenAPI Specification (OAS). The implementation adds support for validating four standard JWT claims:

  1. Issuer Validation - Validates the iss claim against a configurable list of allowed issuers
  2. Audience Validation - Validates the aud claim against a configurable list of allowed audiences
  3. JWT ID Validation - Can require the presence of a jti claim when enabled
  4. Subject Validation - Validates the subject (from kid/identityBaseField/sub) against a list of allowed subjects

The implementation includes:

  • New fields in the JWT struct in the OAS definition to configure these validations
  • Validation functions for each claim type with appropriate error handling
  • Comprehensive test coverage for each validation scenario
  • A refactoring to use GetJWTConfiguration() instead of directly accessing the JWT configuration

This is a valuable security enhancement that follows JWT best practices by allowing API administrators to enforce stricter token acceptance criteria. The validation is only applied to OAS-defined APIs and only when the corresponding validation options are configured, ensuring backward compatibility with existing setups.

The code is well-structured with proper error handling and logging, making it easy to diagnose validation failures. The test suite covers both positive and negative test cases for each validation type.


Tip: Mention me again using /performance <request>.
Powered by Probe AI
Performance Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 4, 2025

🛡️ Security Snapshot

Effort Risk Level Tests Compliance TL;DR
Low 🟢 ✔️ Added JWT validation for issuer, audience, JWT ID, and subject claims enhances security posture
## Security Impact Analysis

This PR adds enhanced JWT validation capabilities to the Tyk API Gateway for OAS-defined APIs. The implementation adds validation for four standard JWT registered claims: issuer (iss), audience (aud), JWT ID (jti), and subject validation. These validations are conditionally executed based on configuration and only apply to OAS APIs. The code properly handles different claim formats and provides clear error messages. This enhancement significantly improves security by allowing API administrators to enforce stricter token acceptance criteria.

## Identified Vulnerabilities

No new vulnerabilities introduced. On the contrary, this PR mitigates several potential security issues:

High Severity (Mitigated):

  • Token forgery/replay attacks mitigated by allowing strict issuer validation
  • Cross-tenant token misuse prevented by audience validation
  • Unauthorized access prevented by subject validation

Medium Severity (Mitigated):

  • Replay attacks further mitigated by optional JWT ID (jti) validation

Low Severity (Potential):

  • Error logging in validation functions includes claim values, which could potentially expose sensitive information in logs
## Security Recommendations

The implementation is solid with proper validation and error handling. Some minor recommendations:

  1. Consider sanitizing error messages to avoid potentially leaking sensitive claim values in logs
  2. The nested loops for audience validation could be optimized with a map lookup for better performance with large lists
  3. Add documentation explaining these new JWT validation features and their security benefits
  4. Consider adding metrics or observability for rejected tokens to help detect potential attacks
## OWASP Compliance

This PR strengthens compliance with several OWASP Top 10 categories:

  • A2:2021 - Cryptographic Failures: Enhances JWT security beyond basic signature verification
  • A5:2021 - Security Misconfiguration: Provides more granular control over JWT acceptance criteria
  • A7:2021 - Identification and Authentication Failures: Improves token validation with additional claim checks

The implementation follows security best practices for JWT validation as recommended by OWASP JWT Cheat Sheet, including proper claim validation and type checking.

## Summary
  • This PR adds valuable security controls for JWT validation, allowing API administrators to enforce stricter token acceptance criteria
  • The implementation is well-structured and follows best practices for JWT validation
  • The changes only affect OAS-defined APIs and won't break existing configurations
  • No security issues identified – change LGTM

Tip: Mention me again using /security <request>.
Powered by Probe AI
Security Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 4, 2025

🚀 Performance Snapshot

Effort Perf Risk Hot Paths Benchmarks TL;DR
Low 🟡 ⚠️ Added JWT claim validations (issuer, audience, JWT ID, subject) may impact request processing time in high-volume scenarios
## Performance Impact Analysis

This PR adds enhanced JWT validation capabilities to the Tyk Gateway for OAS APIs. The implementation adds validation for four standard JWT claims: issuer (iss), audience (aud), JWT ID (jti), and subject. These validations are performed during the JWT middleware's request processing flow, which is a critical path for authenticated API requests.

The validations are conditionally executed only for OAS APIs and only when the corresponding validation options are configured, which limits the performance impact to specific use cases. However, in high-volume scenarios with many JWT validations, the additional checks could add noticeable overhead.

## Critical Areas

The JWT middleware's ProcessRequest function is a hot path for all JWT-authenticated requests. The PR modifies this function to call a new validateExtraClaims method which performs additional validations beyond the existing time-based validations.

The audience validation is particularly performance-sensitive as it contains nested loops (iterating through token audiences and allowed audiences), which could be inefficient for large lists of allowed audiences. The subject validation also requires an additional call to getIdentityFromToken(), which may involve extra processing depending on the token structure.

## Optimization Recommendations
  1. Consider optimizing the audience validation by using a map lookup instead of nested loops when the allowed audience list is large.

  2. For frequently reused tokens, consider implementing a validation result cache to avoid repeated validation overhead.

  3. The error logging in validation functions includes claim values, which could potentially impact performance in high-volume scenarios with many validation failures. Consider making this logging conditional based on log level.

  4. Add benchmarks to measure the performance impact of these validations, especially for high-volume scenarios with large lists of allowed values.

## Summary
  • The PR adds valuable security features with minimal performance overhead for most use cases.
  • The impact is limited to OAS APIs with specific JWT validation configurations.
  • In high-volume scenarios with many JWT validations, the additional checks could add noticeable overhead.
  • The nested loops in audience validation could be optimized for better performance with large lists.

Tip: Mention me again using /performance <request>.
Powered by Probe AI
Performance Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 4, 2025

📦 Impact Review Snapshot

Effort Downstream Updates Compatibility Docs TL;DR
Low ⚠️ 🟢 ⚠️ Added JWT validation for issuer, audience, JWT ID, and subject claims in OAS APIs
## Impact Assessment

This PR adds enhanced JWT validation capabilities to the Tyk Gateway for OAS-based APIs. The changes introduce four new validation options:

  1. Issuer Validation - Validates the iss claim against a list of allowed issuers
  2. Audience Validation - Validates the aud claim against a list of allowed audiences
  3. JWT ID Validation - Requires the presence of a jti claim when enabled
  4. Subject Validation - Validates the subject (from kid/identityBaseField/sub) against a list of allowed subjects

These features are added to the OAS JWT security schema in the JWT struct and implemented in the JWT middleware. The changes are backward compatible as they're only activated when explicitly configured.

## Required Updates
  1. tyk-operator:

    • CRD updates needed to expose the new JWT validation fields
    • Controller logic to handle these new fields when processing API definitions
  2. portal:

    • UI updates to expose these new JWT validation options in the API designer
    • Form validation for the new fields
  3. Documentation:

    • Updates needed to document these new JWT validation features
    • Examples of how to configure and use these validations
## Compatibility Concerns

The changes are backward compatible since:

  • The new validation features are only active when explicitly configured
  • They only apply to OAS-based APIs (checked with if !k.Spec.IsOAS condition)
  • Default behavior remains unchanged when the new fields are not set

No breaking changes are introduced to existing APIs or authentication flows.

## Summary & Recommendations
  • This PR enhances JWT security by adding standard claim validations that are important for proper OAuth/OIDC implementations
  • Updates to tyk-operator and portal should be prioritized to expose these new features to users
  • Documentation should be updated to explain these new validation options and their security benefits
  • Consider adding integration tests that verify these validations work with common identity providers

Tip: Mention me again using /dependency <request>.
Powered by Probe AI
Tyk Gateway Dependency Impact Reviewer

Copy link
Contributor

github-actions bot commented Aug 4, 2025

🚦 Connectivity Review Snapshot

Effort Tests Security Perf TL;DR
Low 🔒 none 🟢 Added JWT validation for issuer, audience, JWT ID, and subject claims in OAS APIs
## Connectivity Assessment
  • Redis Connections: No changes to Redis connectivity - the JWT validation is performed in-memory without requiring additional Redis operations.
  • RPC Connections: No impact on RPC connections - the JWT validation is performed locally within the gateway.
  • Synchronization Mechanisms: No changes to synchronization mechanisms - the validation is stateless and doesn't require coordination between gateway instances.
## Test Coverage Validation
  • Redis Tests: Not applicable as the changes don't affect Redis connectivity.
  • RPC Tests: Not applicable as the changes don't affect RPC connectivity.
  • Failure Scenario Tests: The PR includes comprehensive test cases for the new JWT validation functionality in TestJWTExtraClaimsValidation, covering both positive and negative scenarios for each validation type.
## Security & Performance Impact
  • Authentication Changes: The PR adds enhanced JWT validation for issuer, audience, JWT ID, and subject claims, improving security by allowing more fine-grained control over accepted tokens.
  • Performance Considerations: The additional validation is performed in-memory and should have minimal performance impact as it's only adding simple claim checks.
  • Error Handling: Proper error handling is implemented with detailed error messages for each validation failure, which helps with troubleshooting.
## Summary & Recommendations
  • The PR enhances JWT validation with additional claim checks that improve security without impacting connectivity.
  • The changes only affect OAS APIs and are only activated when explicitly configured.
  • The implementation includes proper tests for all validation functions.
  • No suggestions to provide – change LGTM.

Tip: Mention me again using /connectivity <request>.
Powered by Probe AI
Connectivity Issues Reviewer Prompt for Tyk Gateway

@kofoworola kofoworola force-pushed the feat/update-jwt-validation branch from 17d0bb7 to ef3fb87 Compare August 5, 2025 08:01
Copy link
Contributor

github-actions bot commented Aug 5, 2025

🚦 Connectivity Review Snapshot

Effort Tests Security Perf TL;DR
Low 🔒 none 🟢 Added JWT validation for issuer, audience, JWT ID, and subject claims in OAS APIs
## Connectivity Assessment
  • Redis Connections: No changes to Redis connectivity - the JWT validation is performed in-memory without requiring additional Redis operations.
  • RPC Connections: No impact on RPC connections - the JWT validation is performed locally within the gateway.
  • Synchronization Mechanisms: No changes to synchronization mechanisms - the validation is stateless and doesn't require coordination between gateway instances.
## Test Coverage Validation
  • Redis Tests: Not applicable as the changes don't affect Redis connectivity.
  • RPC Tests: Not applicable as the changes don't affect RPC connectivity.
  • Failure Scenario Tests: The PR includes comprehensive test cases in TestJWTExtraClaimsValidation that verify both positive and negative scenarios for each validation type, including invalid issuer, audience, JWT ID, and subject claims.
## Security & Performance Impact
  • Authentication Changes: The PR adds enhanced JWT validation for issuer, audience, JWT ID, and subject claims, improving security by allowing more fine-grained control over accepted tokens.
  • Performance Considerations: The additional validation is performed in-memory and should have minimal performance impact as it's only adding simple claim checks that are conditionally executed only for OAS APIs.
  • Error Handling: Proper error handling is implemented with detailed error messages for each validation failure, which helps with troubleshooting.
## Summary & Recommendations
  • The PR enhances JWT validation with additional claim checks that improve security without impacting connectivity.
  • The changes only affect OAS APIs and are only activated when explicitly configured.
  • The implementation includes proper tests for all validation functions.
  • No suggestions to provide – change LGTM.

Tip: Mention me again using /connectivity <request>.
Powered by Probe AI
Connectivity Issues Reviewer Prompt for Tyk Gateway

Copy link
Contributor

github-actions bot commented Aug 5, 2025

🚦 Connectivity Review Snapshot

Effort Tests Security Perf TL;DR
Low 🔒 none 🟢 Added JWT validation for issuer, audience, JWT ID, and subject claims in OAS APIs
## Connectivity Assessment
  • Redis Connections: No changes to Redis connectivity - the JWT validation is performed in-memory without requiring additional Redis operations.
  • RPC Connections: No impact on RPC connections - the JWT validation is performed locally within the gateway.
  • Synchronization Mechanisms: No changes to synchronization mechanisms - the validation is stateless and doesn't require coordination between gateway instances.
## Test Coverage Validation
  • Redis Tests: Not applicable as the changes don't affect Redis connectivity.
  • RPC Tests: Not applicable as the changes don't affect RPC connectivity.
  • Failure Scenario Tests: The PR includes comprehensive test cases in TestJWTExtraClaimsValidation that cover both positive and negative scenarios for each validation type, ensuring proper error handling.
## Security & Performance Impact
  • Authentication Changes: The PR adds enhanced JWT validation for issuer, audience, JWT ID, and subject claims, improving security by allowing more fine-grained control over accepted tokens.
  • Performance Considerations: The additional validation is performed in-memory and should have minimal performance impact as it's only adding simple claim checks.
  • Error Handling: Proper error handling is implemented with detailed error messages for each validation failure, which helps with troubleshooting.
## Summary & Recommendations
  • The PR enhances JWT validation with additional claim checks that improve security without impacting connectivity.
  • The changes only affect OAS APIs and are only activated when explicitly configured.
  • The implementation includes proper tests for all validation functions.
  • No suggestions to provide – change LGTM.

Tip: Mention me again using /connectivity <request>.
Powered by Probe AI
Connectivity Issues Reviewer Prompt for Tyk Gateway

Copy link
Contributor

github-actions bot commented Aug 5, 2025

Analysis of PR #7269: Added extra JWT validation

This PR enhances the JWT validation capabilities in Tyk Gateway by adding support for validating four standard JWT registered claims as defined in RFC 7519:

  1. Issuer (iss) Validation: Validates the token's issuer claim against a configurable list of allowed issuers
  2. Audience (aud) Validation: Validates the token's audience claim against a configurable list of allowed audiences
  3. JWT ID (jti) Validation: Can require the presence of a JWT ID claim
  4. Subject Validation: Validates the subject (extracted from kid/identityBaseField/sub) against a list of allowed subjects

Implementation Details

The implementation adds:

  • New fields to the JWT struct in the OAS package:

    AllowedIssuers []string
    AllowedAudiences []string
    RequireJTI bool
    AllowedSubjects []string
  • New constants for JWT claims:

    ISS = "iss"
    AUD = "aud"
    JTI = "jti"
  • Validation functions in the JWT middleware:

    validateIssuer(claims jwt.Claims, allowedIssuers []string) error
    validateAudience(claims jwt.Claims, allowedAudiences []string) error
    validateJTI(claims jwt.Claims) error
    validateSubjectValue(subject string, allowedSubjects []string) error
  • A validateExtraClaims method that conditionally applies these validations based on configuration

Key Aspects

  1. Conditional Application: The validations are only applied to OAS APIs and only when the corresponding validation options are configured, making this a non-breaking change.

  2. Security Enhancement: This PR improves security by allowing API administrators to implement stricter token acceptance criteria, which helps prevent token misuse and unauthorized access.

  3. Comprehensive Validation: The implementation handles different claim formats (e.g., audience can be a string or array) and provides clear error messages for validation failures.

  4. Performance Considerations: The audience validation contains nested loops which could be optimized for large lists of allowed audiences by using a map lookup instead.

This PR is a valuable addition that follows JWT best practices by allowing validation of standard registered claims, enhancing the security posture of JWT-authenticated APIs in Tyk Gateway.


Tip: Mention me again using /performance <request>.
Powered by Probe AI
Performance Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 6, 2025

🛡️ Security Snapshot

Effort Risk Level Tests Compliance TL;DR
Low 🟢 ✔️ Added JWT validation for issuer, audience, JWT ID, and subject claims enhances security posture
## Security Impact Analysis

This PR adds enhanced JWT validation capabilities to the Tyk API Gateway for OAS-defined APIs. The implementation adds validation for four standard JWT registered claims: issuer (iss), audience (aud), JWT ID (jti), and subject. These validations are conditionally executed based on configuration and only apply to OAS APIs. The code properly handles different claim formats and provides clear error messages. This enhancement significantly improves security by allowing API administrators to enforce stricter token acceptance criteria.

## Identified Vulnerabilities

No new vulnerabilities introduced. On the contrary, this PR mitigates several potential security issues:

High Severity (Mitigated):

  • Token forgery/replay attacks mitigated by allowing strict issuer validation
  • Cross-tenant token misuse prevented by audience validation
  • Unauthorized access prevented by subject validation

Medium Severity (Mitigated):

  • Replay attacks further mitigated by optional JWT ID (jti) validation

Low Severity (Potential):

  • Error logging in validation functions includes claim values, which could potentially expose sensitive information in logs
## Security Recommendations

The implementation is solid with proper validation and error handling. Some minor recommendations:

  1. Consider sanitizing error messages to avoid potentially leaking sensitive claim values in logs
  2. The nested loops for audience validation could be optimized with a map lookup for better performance with large lists
  3. Consider adding metrics or observability for rejected tokens to help detect potential attacks
## OWASP Compliance

This PR strengthens compliance with several OWASP Top 10 categories:

  • A2:2021 - Cryptographic Failures: Enhances JWT security beyond basic signature verification
  • A5:2021 - Security Misconfiguration: Provides more granular control over JWT acceptance criteria
  • A7:2021 - Identification and Authentication Failures: Improves token validation with additional claim checks

The implementation follows security best practices for JWT validation as recommended by OWASP JWT Cheat Sheet, including proper claim validation and type checking.

## Summary
  • This PR adds valuable security controls for JWT validation, allowing API administrators to enforce stricter token acceptance criteria
  • The implementation is well-structured and follows best practices for JWT validation
  • The changes only affect OAS-defined APIs and won't break existing configurations
  • No security issues identified – change LGTM

Tip: Mention me again using /security <request>.
Powered by Probe AI
Security Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 7, 2025

JWT Core Registered Claims Validation PR Review

This PR enhances Tyk Gateway's JWT authentication by adding validation for standard JWT registered claims as defined in RFC 7519. The implementation adds support for validating four key JWT claims:

  1. Issuer (iss) Validation: Validates the token's issuer claim against a configurable list of allowed issuers
  2. Audience (aud) Validation: Validates the token's audience claim against a configurable list of allowed audiences
  3. JWT ID (jti) Validation: Can require the presence of a JWT ID claim
  4. Subject Validation: Validates the subject (extracted from kid/identityBaseField/sub) against a list of allowed subjects

Implementation Details

The PR adds:

  • New fields to the JWT struct in the OAS package:

    AllowedIssuers []string
    AllowedAudiences []string
    JTIValidation JTIValidation
    AllowedSubjects []string
  • New validation functions in the JWT middleware:

    validateIssuer(claims jwt.Claims, allowedIssuers []string) error
    validateAudience(claims jwt.Claims, allowedAudiences []string) error
    validateJTI(claims jwt.Claims) error
    validateSubjectValue(subject string, allowedSubjects []string) error
  • A validateExtraClaims method that conditionally applies these validations based on configuration

  • Comprehensive test coverage in TestJWTExtraClaimsValidation

Key Strengths

  1. Enhanced Security: Allows API administrators to enforce stricter token acceptance criteria, preventing token misuse and unauthorized access
  2. Standards Compliance: Follows JWT best practices by validating standard registered claims
  3. Backward Compatibility: Only applies to OAS APIs and only when explicitly configured
  4. Comprehensive Testing: Includes tests for both positive and negative scenarios for each validation type
  5. Flexible Configuration: Each validation can be independently enabled/configured

Technical Considerations

  1. Performance: The audience validation contains nested loops which could be optimized for large lists of allowed audiences by using a map lookup instead
  2. Error Logging: Error messages include claim values which could potentially expose sensitive information in logs
  3. Type Assertions: The validation functions assume claims are of type jwt.MapClaims and perform type assertions accordingly

Impact on Downstream Projects

This PR will require updates to:

  1. tyk-operator: CRD updates needed to expose the new JWT validation fields
  2. portal: UI updates to expose these new JWT validation options in the API designer
  3. Documentation: Updates needed to explain these new validation options

Conclusion

This PR is a valuable security enhancement that follows JWT best practices by allowing validation of standard registered claims. The implementation is well-structured with proper error handling and comprehensive test coverage. The changes only affect OAS APIs and are only activated when explicitly configured, ensuring backward compatibility with existing setups.


Tip: Mention me again using /connectivity <request>.
Powered by Probe AI
Connectivity Issues Reviewer Prompt for Tyk Gateway

Copy link
Contributor

github-actions bot commented Aug 7, 2025

Analysis of PR #7269: Added JWT Core Registered Claims Validation

This PR enhances JWT authentication in Tyk Gateway by adding validation for standard JWT registered claims as defined in RFC 7519. The implementation adds four new validation capabilities for OAS-defined APIs:

Key Changes

  1. Issuer (iss) Validation: Validates the token's issuer claim against a configurable list of allowed issuers
  2. Audience (aud) Validation: Validates the token's audience claim against a configurable list of allowed audiences
  3. JWT ID (jti) Validation: Can require the presence of a JWT ID claim
  4. Subject Validation: Validates the subject (extracted from kid/identityBaseField/sub) against a list of allowed subjects

Implementation Details

The PR adds:

  • New fields to the JWT struct in the OAS package:

    AllowedIssuers []string
    AllowedAudiences []string
    JTIValidation JTIValidation // with Enabled field
    AllowedSubjects []string
  • New validation functions in the JWT middleware:

    validateIssuer(claims jwt.MapClaims, allowedIssuers []string) error
    validateAudience(claims jwt.MapClaims, allowedAudiences []string) error
    validateJTI(claims jwt.MapClaims) error
    validateSubjectValue(subject string, allowedSubjects []string) error
  • A validateExtraClaims method that conditionally applies these validations based on configuration

Notable Structural Changes

  1. The ClaimName field in the Scopes struct was changed from a string to a string array ([]string), which could potentially be a breaking change as noted in a comment.

  2. The PolicyFieldName field in the JWT struct was also changed from a string to a string array ([]string), allowing multiple policy field names to be specified.

Security and Performance Considerations

  • These validations are only applied to OAS APIs (checked with if !k.Spec.IsOAS condition) and only when the corresponding validation options are configured.
  • The audience validation contains nested loops which could be optimized for large lists of allowed audiences by using a map lookup instead.
  • The validations follow standard JWT practices as defined in RFC 7519, enhancing security by allowing API administrators to enforce stricter token acceptance criteria.

This PR significantly improves security by preventing token misuse and unauthorized access through more comprehensive JWT validation.


Tip: Mention me again using /performance <request>.
Powered by Probe AI
Performance Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 7, 2025

🛡️ Security Snapshot

Effort Risk Level Tests Compliance TL;DR
Low 🟢 ✔️ Added JWT validation for issuer, audience, JWT ID, and subject claims enhances security posture
## Security Impact Analysis

This PR adds enhanced JWT validation capabilities to the Tyk API Gateway for OAS-defined APIs. The implementation adds validation for four standard JWT registered claims: issuer (iss), audience (aud), JWT ID (jti), and subject validation. These validations are conditionally executed based on configuration and only apply to OAS APIs. The code properly handles different claim formats and provides clear error messages, significantly improving security by allowing API administrators to enforce stricter token acceptance criteria.

## Identified Vulnerabilities

No new vulnerabilities introduced. On the contrary, this PR mitigates several potential security issues:

High Severity (Mitigated):

  • Token forgery/replay attacks mitigated by allowing strict issuer validation
  • Cross-tenant token misuse prevented by audience validation
  • Unauthorized access prevented by subject validation

Medium Severity (Mitigated):

  • Replay attacks further mitigated by optional JWT ID (jti) validation

Low Severity (Potential):

  • Error logging in validation functions includes claim values, which could potentially expose sensitive information in logs
## Security Recommendations

The implementation is solid with proper validation and error handling. Some minor recommendations:

  1. Consider sanitizing error messages to avoid potentially leaking sensitive claim values in logs
  2. The nested loops for audience validation could be optimized with a map lookup for better performance with large lists
  3. Consider adding metrics or observability for rejected tokens to help detect potential attacks
## OWASP Compliance

This PR strengthens compliance with several OWASP Top 10 categories:

  • A2:2021 - Cryptographic Failures: Enhances JWT security beyond basic signature verification
  • A5:2021 - Security Misconfiguration: Provides more granular control over JWT acceptance criteria
  • A7:2021 - Identification and Authentication Failures: Improves token validation with additional claim checks

The implementation follows security best practices for JWT validation as recommended by OWASP JWT Cheat Sheet, including proper claim validation and type checking.

## Summary
  • This PR adds valuable security controls for JWT validation, allowing API administrators to enforce stricter token acceptance criteria
  • The implementation is well-structured and follows best practices for JWT validation
  • The changes only affect OAS-defined APIs and won't break existing configurations
  • No security issues identified – change LGTM

Tip: Mention me again using /security <request>.
Powered by Probe AI
Security Impact Reviewer Prompt

Copy link
Contributor

github-actions bot commented Aug 7, 2025

📦 Impact Review Snapshot

Effort Downstream Updates Compatibility Docs TL;DR
Low ⚠️ 🟡 ⚠️ Added JWT validation for issuer, audience, JWT ID, and subject claims in OAS APIs with potential compatibility concern for ClaimName type change
## Impact Assessment

This PR adds enhanced JWT validation capabilities to the Tyk Gateway for OAS-based APIs. The implementation adds validation for four standard JWT registered claims:

  1. Issuer Validation - Validates the iss claim against a list of allowed issuers
  2. Audience Validation - Validates the aud claim against a list of allowed audiences
  3. JWT ID Validation - Requires the presence of a jti claim when enabled
  4. Subject Validation - Validates the subject (from kid/identityBaseField/sub) against a list of allowed subjects

The PR also changes the ClaimName field in the Scopes struct from a string to a string array, allowing multiple scope claim names to be specified. This change is potentially breaking for existing configurations that rely on the specific type.

## Required Updates
  1. tyk-operator:

    • CRD updates needed to expose the new JWT validation fields
    • Controller logic to handle these new fields when processing API definitions
    • Update handling of ClaimName to support both string and array types
  2. portal:

    • UI updates to expose these new JWT validation options in the API designer
    • Form validation for the new fields
    • Update handling of ClaimName to support both string and array types
  3. Documentation:

    • Updates needed to document these new JWT validation features
    • Examples of how to configure and use these validations
    • Documentation of the ClaimName type change and how to handle it
## Compatibility Concerns

The JWT validation features are backward compatible since:

  • They only apply to OAS-based APIs (checked with if !k.Spec.IsOAS condition)
  • They're only active when explicitly configured
  • Default behavior remains unchanged when the new fields are not set

However, the change of ClaimName from a string to a string array is potentially breaking:

  • Existing configurations that rely on the specific type might be affected
  • Code that directly accesses this field expecting a string may break
  • A custom unmarshaler or backward compatibility layer might be needed to handle both types
## Summary & Recommendations
  • This PR enhances JWT security by adding standard claim validations that are important for proper OAuth/OIDC implementations
  • The implementation is well-tested with comprehensive test coverage for both positive and negative scenarios
  • The ClaimName type change should be carefully reviewed to ensure backward compatibility
  • Consider implementing a custom unmarshaler for ClaimName that can handle both string and array types
  • Updates to tyk-operator and portal should be prioritized to expose these new features to users
  • Documentation should be updated to explain these new validation options and their security benefits

Tip: Mention me again using /dependency <request>.
Powered by Probe AI
Tyk Gateway Dependency Impact Reviewer

Copy link
Contributor

@edsonmichaque edsonmichaque left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@kofoworola kofoworola force-pushed the feat/update-jwt-validation branch from 740db61 to d0e5ed1 Compare August 8, 2025 09:37
@kofoworola kofoworola enabled auto-merge (squash) August 8, 2025 11:11
Copy link

sonarqubecloud bot commented Aug 8, 2025

@kofoworola kofoworola merged commit d6a9aa5 into master Aug 8, 2025
42 of 47 checks passed
@kofoworola kofoworola deleted the feat/update-jwt-validation branch August 8, 2025 11:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants