Skip to content

[TT-16926] Add JWT Bearer grant for upstream OAuth - #8973

Open
mativm02 wants to merge 8 commits into
masterfrom
TT-16926/jwt-bearer-upstream-oauth
Open

mativm02 wants to merge 8 commits into
masterfrom
TT-16926/jwt-bearer-upstream-oauth

Conversation

@mativm02

@mativm02 mativm02 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds jwtBearer as a third grant type under existing upstream OAuth (x-tyk-api-gateway.upstream.authentication.oauth). OAS and Enterprise only.

The gateway mints an RS256 JWT from a private key in the certificate store (iss, sub, aud, iat, exp, jti), exchanges it at the configured token URL with grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer and assertion, and reuses the existing access-token cache and upstream header injection.

Signing or certificate failures return HTTP 500 and do not call the IdP or the upstream. IdP rejections return 401 or 403 and are not cached. Classic APIs cannot enable the grant. Existing client credentials and password grants are unchanged.

Docs and Dashboard API Designer work are not in this PR.

Related Issue

https://tyktech.atlassian.net/browse/TT-16926

Motivation and Context

Odido needs Tyk to authenticate to Salesforce with the OAuth 2.0 JWT Bearer flow (RFC 7523). Upstream OAuth already supports client credentials and password grants; this adds the missing grant.

How This Has Been Tested

  • go test ./apidef/...
  • go test -tags ee -count=1 ./ee/middleware/upstreamoauth/ (mock IdP that verifies the JWT; cache reuse/renewal; missing key → 500 with no IdP call; IdP rejection → 401/403)
  • go test -tags ee -count=1 -run 'TestUpstreamOAuthJWTBearer' ./gateway/ (real certificate store and Redis)

OSS and EE gateway binaries compile. go build ./... still fails on the pre-existing test/goplugins package main fixture; not caused by this change.

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

Documentation will follow in a separate PR. This change does not update go.mod and does not request a coverage exception.

Open product questions (provisional in this PR)

  • HTTP 400 with invalid_grant is mapped to 401 (TODO in code).
  • If the IdP omits expires_in, the access token is cached for 5 minutes.
  • Network/timeout failures talking to the IdP return 500, not 401.
  • RS256 only; JWT lifetime defaults to 2m; no kid, x5t#S256, or client_id on the token request.

Ticket Details

TT-16926
Status In Code Review
Summary OAuth 2.0 JWT Bearer Flow for Upstream Authentication

Generated at: 2026-11-26 19:11:37

Add jwtBearer as a third OAS-only, Enterprise upstream OAuth grant.
The gateway mints an RS256 JWT from the certificate store, exchanges it
for an access token, and reuses the existing token cache.

Signing failures return 500 without calling the IdP. IdP rejections
return 401 or 403; HTTP 400 with invalid_grant is mapped to 401 pending
a product decision.
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

📚 Documentation preview

This PR changes generated documentation (component: gateway).

cc @TykTechnologies/pms — advisory review requested; this does not block merging.

Rendered docs diff
diff -ruN out-base/gateway-config.mdx out-head/gateway-config.mdx
--- out-base/gateway-config.mdx	2026-11-26 19:12:01.649780365 +0000
+++ out-head/gateway-config.mdx	2026-11-26 19:12:03.060488125 +0000
@@ -3157,12 +3157,3 @@
 A token with no iss claim is matched by key ID (kid) alone.
 It exists for compatibility with legacy records that predate issuer becoming mandatory. Not recommended for production use: without the issuer check, an identity provider that shares signing keys across tenants cannot be distinguished by tenant.
 
-### allow_unsafe_websocket_origin
-ENV: <b>TYK_GW_ALLOWUNSAFEWEBSOCKETORIGIN</b><br />
-Type: `bool`<br />
-
-AllowUnsafeWebSocketOrigin turns off the Origin check on WebSocket handshakes for GraphQL and Streams APIs, so a handshake from any origin is accepted (default: false).
-It exists for compatibility with browser clients on other origins that connected before the check was added.
-Not recommended: any website can then open a WebSocket to these APIs through a visitor's browser and read the responses.
-To allow a browser client, add its origin to the API's CORS allowed origins instead.
-
diff -ruN out-base/x-tyk-gateway.mdx out-head/x-tyk-gateway.mdx
--- out-base/x-tyk-gateway.mdx	2026-11-26 19:11:55.915403950 +0000
+++ out-head/x-tyk-gateway.mdx	2026-11-26 19:11:55.971746759 +0000
@@ -1133,6 +1133,15 @@
 **Field: `password` ([PasswordAuthentication](#passwordauthentication))**
 PasswordAuthentication holds the configuration for upstream OAauth password authentication flow.
 
+**Field: `jwtBearer` ([UpstreamOAuthJWTBearer](#upstreamoauthjwtbearer))**
+JWTBearer holds the configuration for the upstream OAuth2 JWT Bearer grant (RFC 7523).
+Tyk mints a JWT signed with RS256 using the private key of the certificate `certId`,
+exchanges it at `tokenUrl` for an access token and sends that token to the upstream.
+Available only for Tyk OAS APIs.
+
+
+Tyk classic API definition: N/A.
+
 ### **UpstreamRequestSigning**
 
 UpstreamRequestSigning represents configuration for generating signed requests to an upstream API.
@@ -1747,6 +1756,33 @@
 **Field: `extraMetadata` (`[]string`)**
 ExtraMetadata holds the keys that we want to extract from the token and pass to the upstream.
 
+### **UpstreamOAuthJWTBearer**
+
+UpstreamOAuthJWTBearer holds the configuration for the upstream OAuth2 JWT Bearer grant (RFC 7523).
+
+**Field: `header` ([AuthSource](#authsource))**
+Header holds the configuration for the custom header to be used for OAuth authentication.
+
+**Field: `tokenUrl` (`string`)**
+TokenURL is the token endpoint of the authorization server.
+
+**Field: `certId` (`string`)**
+CertID is the ID of the certificate in the Tyk certificate store whose RSA private key
+is used to sign the JWT (RS256).
+
+**Field: `issuer` (`string`)**
+Issuer is the `iss` claim of the JWT (for Salesforce: the Connected App consumer key).
+
+**Field: `subject` (`string`)**
+Subject is the `sub` claim of the JWT (for Salesforce: the username).
+
+**Field: `audience` (`string`)**
+Audience is the `aud` claim of the JWT (for Salesforce: https://login.salesforce.com).
+
+**Field: `expiresIn` ([ReadableDuration](#readableduration))**
+ExpiresIn is the lifetime of the signed JWT, e.g. "2m". Defaults to 2m when unset.
+Some authorization servers cap it (Salesforce requires `exp` within 3 minutes).
+
 ### **Provider**
 
 Provider defines an issuer to validate and the Client ID to Policy ID mappings.

@probelabs

probelabs Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

This PR introduces the OAuth 2.0 JWT Bearer grant type for upstream authentication, an Enterprise-only feature for OAS APIs. The gateway can now mint an RS256-signed JWT using a private key from the certificate store and exchange it with an Identity Provider (IdP) for an access token. This token is then cached and injected into requests to the upstream service.

The implementation is self-contained within the existing upstream OAuth middleware. It adds a new provider for the JWT bearer flow, along with dedicated error handling: signing failures result in an HTTP 500, while IdP rejections are mapped to 401 or 403. Existing client credentials and password grants are unaffected.

Files Changed Analysis

The changes are centered around three main areas:

  1. API Definition (apidef/): The api_definitions.go file is updated with new constants and structs (UpstreamOAuthJWTBearer) to support the feature's configuration. Corresponding JSON schemas in apidef/mcp/schema and apidef/oas/schema are updated to validate the new jwtBearer object. Validation logic in apidef/validator.go ensures this grant is restricted to OAS APIs and has valid settings.
  2. Middleware Implementation (ee/middleware/upstreamoauth/): The core logic resides in the new provider_jwt_bearer.go file, which handles JWT creation, signing, and the token exchange with the IdP. The main middleware.go is updated to integrate a new storage handler and route requests to the new JWTBearerOAuthProvider. The changes are accompanied by extensive unit tests in provider_jwt_bearer_test.go.
  3. Gateway Integration (gateway/): In mw_oauth2_auth_ee.go, a new Redis-backed storage handler with the prefix upstreamOAuthJWT- is configured to cache the access tokens. A new end-to-end test file, mw_oauth2_auth_ee_test.go, validates the full flow within a live gateway environment, including certificate loading and Redis caching.

Architecture & Impact Assessment

  • What this PR accomplishes: It adds support for the OAuth 2.0 JWT Bearer Flow (RFC 7523) for authenticating the Tyk Gateway against upstream services. This allows Tyk to integrate with services like Salesforce that require this specific authentication method.

  • Key technical changes introduced:

    • A new grant type, jwtBearer, is added to the upstream OAuth middleware.
    • The gateway now generates and signs its own JWTs using RSA private keys from the certificate store.
    • A new provider, JWTBearerOAuthProvider, encapsulates the logic for the grant flow.
    • Introduces distinct error handling: signing/key errors are 500s (internal failures), while IdP rejections are 401/403s (authentication failures).
    • A separate Redis cache is established for JWT bearer access tokens.
  • Affected system components:

    • API Definition: New configuration fields are available under x-tyk-api-gateway.upstream.authentication.oauth.
    • Upstream OAuth Middleware (EE): This is the primary component affected, housing the new grant type logic.
    • Gateway (EE): The middleware loader is updated to provide a new storage handler.
    • Certificate Manager: Leveraged to retrieve private keys for signing JWTs.

JWT Bearer Grant Flow

sequenceDiagram
    participant Client
    participant Tyk Gateway
    participant "Identity Provider (IdP)"
    participant Upstream Service

    Client->>+Tyk Gateway: Request
    Tyk Gateway->>Tyk Gateway: Upstream OAuth middleware triggered
    alt Token not in cache
        Tyk Gateway->>Tyk Gateway: Get private key from Certificate Store
        Tyk Gateway->>Tyk Gateway: Create and sign JWT assertion
        Tyk Gateway->>+"Identity Provider (IdP)": POST /token (grant_type=jwt-bearer, assertion=JWT)
        "Identity Provider (IdP)"-->>-Tyk Gateway: Access Token
        Tyk Gateway->>Tyk Gateway: Cache Access Token
    end
    Tyk Gateway->>+Upstream Service: Request with "Authorization: Bearer <Access Token>"
    Upstream Service-->>-Tyk Gateway: Response
    Tyk Gateway-->>-Client: Response
Loading

Scope Discovery & Context Expansion

The changes are well-encapsulated within the Enterprise Edition's upstream authentication features. The impact is primarily on developers defining APIs that need to connect to upstreams secured by the JWT Bearer flow.

  • The feature's dependency on certId links it to the gateway's existing certificate management capabilities, which are used for storing the necessary private keys.
  • The introduction of a new Redis key prefix (upstreamOAuthJWT-) in gateway/mw_oauth2_auth_ee.go isolates the caching of these tokens from other grant types, preventing potential key collisions.
  • The changes are non-breaking. The feature is opt-in and does not alter the behavior of existing clientCredentials or password grants.
  • While the core gateway functionality is implemented, the PR description explicitly states that corresponding UI changes in the Tyk Dashboard are not included in this scope.
Metadata
  • Review Effort: 4 / 5
  • Primary Label: feature

Powered by Visor from Probelabs

Last updated: 2026-11-26T19:13:55.907Z | Triggered by: pr_updated | Commit: 7f20aff

💡 TIP: You can chat with Visor using /visor ask <your question>

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

API Changes

--- prev.txt	2026-11-26 19:10:11.360245534 +0000
+++ current.txt	2026-11-26 19:10:06.055155347 +0000
@@ -85,6 +85,9 @@
 	OAuthAuthorizationTypeClientCredentials = "clientCredentials"
 	// OAuthAuthorizationTypePassword is the authorization type for password flow.
 	OAuthAuthorizationTypePassword = "password"
+	// OAuthAuthorizationTypeJWTBearer is the authorization type for the OAuth 2.0 JWT Bearer grant (RFC 7523).
+	// It is available only for Tyk OAS APIs.
+	OAuthAuthorizationTypeJWTBearer = "jwtBearer"
 
 	// OAuth2ClientAuthBasic and OAuth2ClientAuthPost are the client authentication
 	// methods defined by RFC 6749 Section 2.3.1 (the `token_endpoint_auth_method`
@@ -144,6 +147,10 @@
 	ErrInvalidUpstreamOAuthAuthorizationType = errors.New("invalid OAuth authorization type")
 	// ErrInvalidUpstreamOAuthClientAuthMethod is the error to return when the configured upstream OAuth client authentication method is invalid.
 	ErrInvalidUpstreamOAuthClientAuthMethod = errors.New("invalid upstream OAuth client authentication method, valid values are: client_secret_basic, client_secret_post")
+	// ErrUpstreamOAuthJWTBearerOASOnly is the error to return when the JWT Bearer grant is configured on a Tyk classic API.
+	ErrUpstreamOAuthJWTBearerOASOnly = errors.New("upstream OAuth JWT Bearer grant is supported only for Tyk OAS APIs")
+	// ErrInvalidUpstreamOAuthJWTBearerExpiresIn is the error to return when the JWT Bearer expiresIn is not a positive duration.
+	ErrInvalidUpstreamOAuthJWTBearerExpiresIn = errors.New("invalid upstream OAuth JWT Bearer expiresIn, must be a positive duration")
 	// ErrAllLoadBalancingTargetsZeroWeight is the error to return when all load balancing targets have weight 0.
 	ErrAllLoadBalancingTargetsZeroWeight  = errors.New("all load balancing targets have weight 0, at least one target must have weight > 0")
 	ErrDNSDiscoveryRequiresLoadBalancing  = errors.New("proxy.dns_discovery supplies the target list but does not distribute across it; proxy.enable_load_balancing must be enabled too")
@@ -1689,12 +1696,37 @@
 	ClientCredentials ClientCredentials `bson:"client_credentials" json:"client_credentials"`
 	// PasswordAuthentication holds the configuration for upstream OAauth password authentication flow.
 	PasswordAuthentication PasswordAuthentication `bson:"password,omitempty" json:"password,omitempty"`
+	// JWTBearer holds the configuration for the upstream OAuth2 JWT Bearer grant (RFC 7523).
+	// Supported only for Tyk OAS APIs.
+	JWTBearer UpstreamOAuthJWTBearer `bson:"jwt_bearer,omitempty" json:"jwt_bearer,omitempty"`
 }
     UpstreamOAuth holds upstream OAuth2 authentication configuration.
 
 func (u UpstreamOAuth) IsEnabled() bool
     IsEnabled checks if UpstreamOAuth is enabled for the API.
 
+type UpstreamOAuthJWTBearer struct {
+	// Header holds the configuration for the custom header to be used for OAuth authentication.
+	Header AuthSource `bson:"header" json:"header"`
+	// TokenURL is the token endpoint of the authorization server.
+	TokenURL string `bson:"token_url" json:"token_url"`
+	// CertID is the ID of the certificate in the Tyk certificate store whose RSA private key signs the JWT.
+	CertID string `bson:"cert_id" json:"cert_id"`
+	// Issuer is the `iss` claim of the JWT.
+	Issuer string `bson:"issuer" json:"issuer"`
+	// Subject is the `sub` claim of the JWT.
+	Subject string `bson:"subject" json:"subject"`
+	// Audience is the `aud` claim of the JWT.
+	Audience string `bson:"audience" json:"audience"`
+	// ExpiresIn is the lifetime of the signed JWT (`exp` = now + ExpiresIn).
+	// When zero/unset, the gateway uses a 2 minute default.
+	ExpiresIn tyktime.ReadableDuration `bson:"expires_in,omitempty" json:"expires_in,omitempty"`
+}
+    UpstreamOAuthJWTBearer holds the configuration for the upstream OAuth2 JWT
+    Bearer grant (RFC 7523). Tyk mints a JWT signed (RS256) with the private key
+    of the certificate CertID, and exchanges it at TokenURL for an access token
+    that is then sent to the upstream.
+
 type UptimeTests struct {
 	// Disabled indicates whether the uptime test configuration is disabled.
 	Disabled bool `bson:"disabled" json:"disabled"`
@@ -6621,6 +6653,13 @@
 	ClientCredentials *ClientCredentials `bson:"clientCredentials,omitempty" json:"clientCredentials,omitempty"`
 	// PasswordAuthentication holds the configuration for upstream OAauth password authentication flow.
 	PasswordAuthentication *PasswordAuthentication `bson:"password,omitempty" json:"password,omitempty"`
+	// JWTBearer holds the configuration for the upstream OAuth2 JWT Bearer grant (RFC 7523).
+	// Tyk mints a JWT signed with RS256 using the private key of the certificate `certId`,
+	// exchanges it at `tokenUrl` for an access token and sends that token to the upstream.
+	// Available only for Tyk OAS APIs.
+	//
+	// Tyk classic API definition: N/A.
+	JWTBearer *UpstreamOAuthJWTBearer `bson:"jwtBearer,omitempty" json:"jwtBearer,omitempty"`
 }
     UpstreamOAuth holds the configuration for OAuth2 Client Credentials flow.
 
@@ -6628,6 +6667,34 @@
 
 func (u *UpstreamOAuth) Fill(api apidef.UpstreamOAuth)
 
+type UpstreamOAuthJWTBearer struct {
+	// Header holds the configuration for the custom header to be used for OAuth authentication.
+	Header *AuthSource `bson:"header,omitempty" json:"header,omitempty"`
+	// TokenURL is the token endpoint of the authorization server.
+	TokenURL string `bson:"tokenUrl" json:"tokenUrl"`
+	// CertID is the ID of the certificate in the Tyk certificate store whose RSA private key
+	// is used to sign the JWT (RS256).
+	CertID string `bson:"certId" json:"certId"`
+	// Issuer is the `iss` claim of the JWT (for Salesforce: the Connected App consumer key).
+	Issuer string `bson:"issuer" json:"issuer"`
+	// Subject is the `sub` claim of the JWT (for Salesforce: the username).
+	Subject string `bson:"subject" json:"subject"`
+	// Audience is the `aud` claim of the JWT (for Salesforce: https://login.salesforce.com).
+	Audience string `bson:"audience" json:"audience"`
+	// ExpiresIn is the lifetime of the signed JWT, e.g. "2m". Defaults to 2m when unset.
+	// Some authorization servers cap it (Salesforce requires `exp` within 3 minutes).
+	ExpiresIn ReadableDuration `bson:"expiresIn,omitempty" json:"expiresIn,omitempty"`
+}
+    UpstreamOAuthJWTBearer holds the configuration for the upstream OAuth2 JWT
+    Bearer grant (RFC 7523).
+
+func (j *UpstreamOAuthJWTBearer) ExtractTo(api *apidef.UpstreamOAuthJWTBearer)
+    ExtractTo extracts *UpstreamOAuthJWTBearer into
+    *apidef.UpstreamOAuthJWTBearer.
+
+func (j *UpstreamOAuthJWTBearer) Fill(api apidef.UpstreamOAuthJWTBearer)
+    Fill fills *UpstreamOAuthJWTBearer from apidef.UpstreamOAuthJWTBearer.
+
 type UpstreamRequestSigning struct {
 	// Enabled determines if request signing is enabled or disabled.
 	Enabled bool `bson:"enabled" json:"enabled"` // required
@@ -8304,12 +8371,6 @@
 	// A token with no iss claim is matched by key ID (kid) alone.
 	// It exists for compatibility with legacy records that predate issuer becoming mandatory. Not recommended for production use: without the issuer check, an identity provider that shares signing keys across tenants cannot be distinguished by tenant.
 	AllowUnsafeIDPMissingIssuer bool `json:"allow_unsafe_idp_missing_issuer"`
-
-	// AllowUnsafeWebSocketOrigin turns off the Origin check on WebSocket handshakes for GraphQL and Streams APIs, so a handshake from any origin is accepted (default: false).
-	// It exists for compatibility with browser clients on other origins that connected before the check was added.
-	// Not recommended: any website can then open a WebSocket to these APIs through a visitor's browser and read the responses.
-	// To allow a browser client, add its origin to the API's CORS allowed origins instead.
-	AllowUnsafeWebSocketOrigin bool `json:"allow_unsafe_websocket_origin"`
 }
     Config is the configuration object used by Tyk to set up various parameters.
 
@@ -10596,12 +10657,6 @@
 	OAS   oas.OAS
 
 	StripListenPath model.StripListenPathFunc
-
-	// WebSocketOriginAllowed reports whether a WebSocket handshake may
-	// proceed. Bento's http_server output accepts every origin unless its own
-	// cors setting is on, so the Gateway checks the origin first. When nil,
-	// handshakes are refused.
-	WebSocketOriginAllowed func(*http.Request) bool
 }
     APISpec is a subset of gateway.APISpec for the values the middleware
     consumes.
@@ -10828,6 +10883,7 @@
 
 	ClientCredentialsAuthorizeType = "clientCredentials"
 	PasswordAuthorizeType          = "password"
+	JWTBearerAuthorizeType         = "jwtBearer"
 )
 
 VARIABLES
@@ -10848,6 +10904,9 @@
 type BaseMiddleware interface {
 	model.LoggerProvider
 	FireEvent(name apidef.TykEvent, meta interface{})
+	// GetClientCertificate returns the certificate (with private key) stored
+	// under certID in the gateway certificate store.
+	GetClientCertificate(certID string) (*tls.Certificate, error)
 }
     BaseMiddleware is the subset of BaseMiddleware APIs that the middleware
     uses.
@@ -10881,6 +10940,50 @@
 }
     Gateway is the subset of Gateway APIs that the middleware uses.
 
+type JWTBearerClient struct {
+	// Has unexported fields.
+}
+    JWTBearerClient obtains and caches access tokens using the JWT Bearer grant.
+
+func (client *JWTBearerClient) GetToken(r *http.Request) (string, error)
+    GetToken returns the access token from cache, or obtains a new one.
+
+func (client *JWTBearerClient) ObtainToken(ctx context.Context) (*oauth2.Token, error)
+    ObtainToken signs a JWT assertion and exchanges it at the token endpoint.
+    The token endpoint is not called when the assertion cannot be signed.
+
+type JWTBearerIdPError struct {
+	// IdPStatus is the HTTP status returned by the token endpoint.
+	IdPStatus int
+	// IdPError is the OAuth `error` code returned by the token endpoint.
+	IdPError string
+	// Description is the OAuth `error_description` (or a truncated raw body).
+	Description string
+	// StatusCode is the HTTP status the gateway responds with.
+	StatusCode int
+}
+    JWTBearerIdPError is returned when the token endpoint rejects the assertion
+    or answers with an unusable response. StatusCode is the HTTP status the
+    gateway returns to the client (401 or 403).
+
+func (e *JWTBearerIdPError) Error() string
+
+type JWTBearerOAuthProvider struct{}
+    JWTBearerOAuthProvider implements the OAuth 2.0 JWT Bearer grant (RFC 7523
+    §2.1).
+
+type JWTBearerSigningError struct {
+	CertID string
+	Err    error
+}
+    JWTBearerSigningError is returned when the JWT assertion cannot be built:
+    the certificate is missing, has no (RSA) private key, or signing fails.
+    It maps to HTTP 500 and the IdP is never called.
+
+func (e *JWTBearerSigningError) Error() string
+
+func (e *JWTBearerSigningError) Unwrap() error
+
 type Middleware struct {
 	Spec model.MergedAPI
 	Gw   Gateway
@@ -10891,7 +10994,7 @@
 }
     Middleware implements upstream OAuth middleware.
 
-func NewMiddleware(gw Gateway, mw BaseMiddleware, spec model.MergedAPI, ccStorageHandler Storage, pwStorageHandler Storage) *Middleware
+func NewMiddleware(gw Gateway, mw BaseMiddleware, spec model.MergedAPI, ccStorageHandler, pwStorageHandler, jwtStorageHandler Storage) *Middleware
     NewMiddleware returns a new instance of Middleware.
 
 func (m *Middleware) EnabledForSpec() bool
@@ -10949,6 +11052,9 @@
 	GetKey(key string) (string, error)
 	SetKey(string, string, int64) error
 	Lock(key string, timeout time.Duration) (bool, error)
+	// DeleteRawKey removes a key without applying the storage prefix. It releases
+	// the token lock, which Lock also stores unprefixed.
+	DeleteRawKey(key string) bool
 }
     Type Storage is a subset of storage.RedisCluster
 
@@ -11752,8 +11858,7 @@
 func (t *BaseMiddleware) CheckSessionAndIdentityForValidKey(originalKey string, r *http.Request) (user.SessionState, bool)
     CheckSessionAndIdentityForValidKey will check first the Session store for a
     valid key, if not found, it will try the Auth Handler, if not found it will
-    fail. A JWT claims-only session is never valid here: only the JWT middleware
-    may use it, after the token's claims passed validation.
+    fail
 
 func (t *BaseMiddleware) Config() (interface{}, error)
 

@probelabs

probelabs Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ Security Check Passed

No security issues found – changes LGTM.

✅ Security Check Passed

No security issues found – changes LGTM.

\n\n

Architecture Issues (1)

Severity Location Issue
🟡 Warning ee/middleware/upstreamoauth/middleware.go:84
The `ProcessRequest` function in `middleware.go` calls `tokenErrorStatus`, which is defined in `provider_jwt_bearer.go`. This creates a dependency from the generic middleware component to a specific provider's implementation file. This violates architectural layering, as the generic middleware logic should not be coupled to the implementation details of a specific strategy (the JWT Bearer provider in this case).
💡 SuggestionTo improve separation of concerns and adhere to better architectural layering, the mechanism for determining the HTTP status code from an error should be abstracted. A recommended approach is to define an error interface (e.g., `statusCodeError`) in a common file like `model.go` or `provider.go` that exposes a `StatusCode() int` method. The specific error type, `JWTBearerIdPError`, would then implement this interface. The `tokenErrorStatus` function could then be moved to a common file and modified to check for this interface, removing the direct dependency on `JWTBearerIdPError` and decoupling the generic middleware from the specific provider's error types. This would make the design more robust and extensible for future providers that might also require custom error status codes.

✅ Performance Check Passed

No performance issues found – changes LGTM.

✅ Quality Check Passed

No quality issues found – changes LGTM.


Powered by Visor from Probelabs

Last updated: 2026-11-26T19:13:17.027Z | Triggered by: pr_updated | Commit: 7f20aff

💡 TIP: You can chat with Visor using /visor ask <your question>

schema-gen lint requires symbol comments to end with a period.
Address the Quality Gate failure (Reliability Rating on New Code was C):
check ignored errors in test helpers, put error last in processAndFill,
group NewMiddleware Storage params, and reword the invalid_grant comment
so it is not a TODO.
Use a 15s-timeout HTTP client when no external-services OAuth client is
configured, so an unresponsive token endpoint cannot hang the request.
Length-prefix each field before hashing so values containing '|' cannot
make two different grant configs share a cached access token.
- Set IsOAS before validation on the Gateway's OAS and MCP create/update
  endpoints, so the OAS-only rule no longer rejects jwtBearer there.
- Release the token fetch lock after fetching. After an IdP rejection the
  lock stayed held for 5s and other requests got a 500 instead of 401/403.
  This also applies to the client credentials and password grants.
- Return a generic "upstream authentication failed" message to the API
  consumer; the IdP error description and certificate ID are only logged
  and sent with the UpstreamOAuthError event.
- Refuse the grant at runtime for classic APIs that bypassed save-time
  validation (e.g. loaded from disk).
@github-actions

Copy link
Copy Markdown
Contributor

🎯 Recommended Merge Targets

Based on JIRA ticket TT-16926: OAuth 2.0 JWT Bearer Flow for Upstream Authentication

Fix Version: Tyk 5.17.0

⚠️ Warning: Expected release branches not found in repository

Required:

  • master - No matching release branches found. Fix will be included in future releases.

📋 Workflow

  1. Merge this PR to master first

Selecting jwtBearer without a jwtBearer block passed both the schema and
the validator, and every request then failed with a 500. The validator now
rejects it on save unless tokenUrl, certId, issuer, subject and audience
are all set.
@sentinelone-cnapp-eu1

Copy link
Copy Markdown

SentinelOne CNS Hardcoded Secret Detector
✅ Congratulations, your code is safe

SentinelOne CNS is a cloud-agnostic, agentless CSPM & CWPP solution that continuously detects and prevents vulnerabilities that have the highest probability of being exploited in Azure, AWS, Google Cloud, and Kubernetes.

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Passed Quality Gate passed

Issues
4 New issues
1 Accepted issue

Measures
0 Security Hotspots
94.7% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarQube Cloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant