Skip to content

[TT-14451] Authorise Tyk OAS JWT APIs by claim rules alone - #8937

Merged
pvormste merged 5 commits into
masterfrom
TT-14451-claims-only-jwt
Nov 26, 2026
Merged

pvormste merged 5 commits into
masterfrom
TT-14451-claims-only-jwt

Conversation

@pvormste

@pvormste pvormste commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Adds claims-only mode for Tyk OAS JWT APIs. When every policy field is empty (basePolicyClaims, defaultPolicies, scopes.claims/claimName, the effective scope-to-policy mapping incl. a Client IdP Registry binding, and clientBaseField) and at least one custom claim rule is blocking, of type exact_match or contains, with a non-empty allowed value, the claim rules alone decide access. Tyk Classic APIs and every policy-based configuration behave as before.

  • Detection: JWTMiddleware.claimsOnlyMode runs per request. A required-only or nonBlocking rule does not count.
  • Session: claims-only sessions are stored under a per-API session ID, generateToken(org, sha256(apiID + "\x00" + identity)). They never share or overwrite the org + md5(identity) session that policy-based JWT APIs use, and their AccessRights hold this API only. Both the new-session and the existing-session paths accept them.
  • Not a credential: claims-only sessions carry tyk_jwt_claims_only: true in their metadata, and CheckSessionAndIdentityForValidKey treats such a session as not found. So the derivable key does not work as an auth token, basic auth, OAuth or HMAC credential, or through a plugin ID extractor, also on multi-auth APIs. The marker travels with the session to other Gateways and MDCB Data Planes.
  • Lifetime: a claims-only session is deleted at the JWT's exp. Without exp it lives for the API's session_lifetime, or 3600 s by default.
  • contains fix: for numeric and boolean claims, customClaimsContainsMatch compared only against the last allowed value (tier: 1 against [1, 2] was rejected). It now returns on the first match.

Related Issue

https://tyktech.atlassian.net/browse/TT-14451 (API Designer: TT-18820; Dashboard API tests: TykTechnologies/tyk-analytics, branch TT-14451-claims-only-jwt)

Motivation and Context

Customers using claim-based authorisation had to attach a dummy shared policy to every JWT API. A session with empty AccessRights grants every API, and the shared session key is computable from the org ID and the identity. Making the policy fields optional therefore needed per-API sessions scoped to the API, which must not be usable as credentials.

How This Has Been Tested

  • Unit and integration tests: gateway/mw_jwt_claims_only_test.go covers AC2–AC8, the scope-claim-name case, the session key refused by other auth methods, the bounded session lifetime and the contains fix. They fail on master and pass here. The existing JWT, claim, scope, session, auth, OAuth, HMAC, basic, multi-auth and OpenID suites pass.
  • QA script, end to end: the script creates its own APIs, Policies and JWTs through the Dashboard API.
    • Control Plane Gateway (PostgreSQL Dashboard): 44 of 44 checks pass.
    • Worker Gateway through MDCB (Data Plane): 42 pass and 0 fail. The 2 per-API key checks report INCOMPLETE because the Dashboard cannot see the worker's Redis. Checking that Redis by hand, the stored session ID matches the derivation, each session holds only its own API, carries the marker and has a TTL bounded by exp.
  • Dashboard API pytest (oas_api_jwt_claims_only_test.py, MongoDB): 8 of 8 pass.
  • Code review: two rounds of review with validation tests. The first round's three findings (one major, two medium) are fixed. The second round found one low finding: a real key or policy with the marker in its metadata is refused.

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. A docs draft exists; the docs PR is still to do (AC10).
  • I explained why this PR updates go.mod in detail with reasoning why it's required (no go.mod change)
  • I would like a code coverage CI quality gate exception and have explained why

Upgrade note: Tyk OAS JWT APIs that match the claims-only rule return 403 on older Gateways. After the upgrade they authorise by their claim rules, without being re-saved.

🤖 Generated with Claude Code

Ticket Details

TT-14451
Status Merge
Summary JWT Auth with claims based or custom authorisation

Generated at: 2026-11-26 15:43:08

pvormste and others added 2 commits November 16, 2026 13:28
A Tyk OAS JWT API without any policy source (base policy claim, client
ID base field, default policies, effective scope-to-policy mapping) now
runs in claims-only mode when at least one custom claim rule restricts
access: blocking, of type exact_match or contains, with a non-empty
allowed value. Such APIs returned 403 before.

A claims-only session is stored under a per-API key and limited to that
API. It never replaces the session the identity shares across the org's
other JWT APIs, and its derivable key opens no other API. Both the
new-session and the existing-session path accept it.

Also fix the contains rule for numeric and boolean claims, which only
compared against the last allowed value.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
- Keep an API policy-based when a scope claim is configured, even without
  a scope-to-policy mapping.
- Refuse claims-only JWT sessions in every key lookup except the JWT
  middleware's own, so their derivable key is no credential.
- Bound claims-only sessions: the Redis record is deleted at the JWT's
  exp, or after the API's session lifetime (default one hour) when the
  JWT has none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pvormste
pvormste marked this pull request as ready for review November 17, 2026 16:30
@probelabs

probelabs Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

This PR introduces a claims-only mode for Tyk OAS JWT APIs, enabling authorization based solely on custom claim rules without needing an associated policy. This simplifies configurations for users who rely on claim-based authorization.

This mode is activated when no other policy sources (like basePolicyClaims, defaultPolicies, or scopes) are defined, and at least one blocking custom claim rule (exact_match or contains) is present. Key changes include:

  • New Authorization Logic: A claimsOnlyMode is detected per request in the JWT middleware, triggering a new policy-less authorization path.
  • Isolated Session Management: Claims-only sessions are stored under a per-API, SHA256-based session ID (sha256(apiID + "\x00" + identity)). This prevents collisions with standard organization-level JWT sessions and restricts access rights to only the API that created the session.
  • Enhanced Security: These sessions are marked with tyk_jwt_claims_only: true metadata. The core CheckSessionAndIdentityForValidKey function is updated to reject these sessions when presented as credentials, preventing the derivable session key from being used as a standard auth token.
  • Session Lifetime: The session's lifetime is tied to the JWT's exp claim. If exp is not present, it defaults to the API's session_lifetime or 3600 seconds.
  • Bug Fix: A fix is included for customClaimsContainsMatch to correctly evaluate numeric and boolean claims against all allowed values, not just the last one.

Files Changed Analysis

The changes are focused on the gateway's JWT middleware and core authentication logic:

  • gateway/mw_jwt.go: Contains the bulk of the new feature logic. This includes the detection of claims-only mode (claimsOnlyMode), generation of the new per-API session key (claimsOnlySessionKeyID), marking session metadata, and managing the session lifecycle (boundClaimsOnlySession, restrictSessionToAPI). It also includes the bug fix for customClaimsContainsMatch.
  • gateway/middleware.go: A critical security change is made to CheckSessionAndIdentityForValidKey. It now wraps the original logic to explicitly check for and reject sessions marked as tyk_jwt_claims_only, preventing them from being used as general-purpose credentials.
  • gateway/mw_jwt_claims_only_test.go: A comprehensive new test file (720 lines) has been added. It provides extensive coverage for the new functionality, including success/failure paths, session isolation, security hardening, and edge cases.

Architecture & Impact Assessment

  • What this PR accomplishes: It removes the need for users to create and attach a dummy policy to JWT-secured APIs when authorization is purely claim-based, providing a more secure and self-contained mechanism within the API definition.

  • Key technical changes introduced:

    • A new conditional authorization path within the JWT middleware based on the claimsOnlyMode check.
    • A new API-specific session key derivation function (claimsOnlySessionKeyID) using SHA256 to ensure session isolation.
    • Extension of the session state metadata with a tyk_jwt_claims_only flag to differentiate these sessions.
    • Hardening of the core session validation logic in CheckSessionAndIdentityForValidKey to reject these new session types when used as authentication tokens.
  • Affected system components: The changes primarily affect the API Gateway's authentication and session management layers, specifically for Tyk OAS APIs using JWT. The session metadata change also impacts distributed environments like MDCB, as the marker will be propagated with the session state, ensuring consistent security behavior.

Flow: Claims-Only JWT Authentication

sequenceDiagram
    participant Client
    participant Gateway
    participant Redis

    Client->>Gateway: Request with JWT
    Gateway->>Gateway: JWTMiddleware: Validate JWT signature & claims
    Gateway->>Gateway: Detect claimsOnlyMode() = true
    Gateway->>Gateway: Generate per-API session ID (SHA256)
    Gateway->>Redis: Check for existing session
    alt Session Not Found
        Redis-->>Gateway: Not found
        Gateway->>Gateway: Create new SessionState
        Gateway->>Gateway: Add `tyk_jwt_claims_only: true` metadata
        Gateway->>Gateway: Restrict AccessRights to current API
        Gateway->>Gateway: Set session lifetime based on JWT `exp`
        Gateway->>Redis: Store new session
    else Session Found
        Redis-->>Gateway: Return existing session
        Gateway->>Gateway: Verify it's a claims-only session
    end
    Gateway->>Gateway: Process request
    Gateway-->>Client: 200 OK
Loading

Scope Discovery & Context Expansion

The changes are well-contained within the gateway's JWT handling, but the modification to CheckSessionAndIdentityForValidKey in gateway/middleware.go has a broad, positive security impact. This function is a central part of the gateway's security model, used by various authentication methods (e.g., standard auth tokens, basic auth) to validate credentials against the session store. By adding a check to reject claims-only sessions, this PR correctly prevents the new, derivable session keys from being abused to impersonate a user on other APIs or through different authentication mechanisms.

The introduction of the tyk_jwt_claims_only metadata field in user.SessionState is a critical detail that affects any system component that reads or replicates session data, such as MDCB, ensuring consistent behavior across a distributed Tyk deployment.

References

  • Core Feature Logic: gateway/mw_jwt.go
  • Security Hardening: gateway/middleware.go#CheckSessionAndIdentityForValidKey
  • Testing: gateway/mw_jwt_claims_only_test.go
Metadata
  • Review Effort: 4 / 5
  • Primary Label: feature

Powered by Visor from Probelabs

Last updated: 2026-11-26T15:45:54.471Z | Triggered by: pr_updated | Commit: 2ef37e7

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

@github-actions

Copy link
Copy Markdown
Contributor

🎯 Recommended Merge Targets

Based on JIRA ticket TT-14451: JWT Auth with claims based or custom authorisation

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

@probelabs

probelabs Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

✅ Security Check Passed

No security issues found – changes LGTM.

✅ Performance Check Passed

No performance issues found – changes LGTM.

✅ Security Check Passed

No security issues found – changes LGTM.

\n\n \n\n

✅ Performance Check Passed

No performance issues found – changes LGTM.

\n\n

✅ Quality Check Passed

No quality issues found – changes LGTM.


Powered by Visor from Probelabs

Last updated: 2026-11-26T15:44:58.754Z | Triggered by: pr_updated | Commit: 2ef37e7

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

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

imogenkraak
imogenkraak previously approved these changes Nov 18, 2026
@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

API Changes

--- prev.txt	2026-11-26 15:44:23.703810037 +0000
+++ current.txt	2026-11-26 15:44:18.510714151 +0000
@@ -11752,7 +11752,8 @@
 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
+    fail. A JWT claims-only session is never valid here: only the JWT middleware
+    may use it, after the token's claims passed validation.
 
 func (t *BaseMiddleware) Config() (interface{}, error)
 

- errcheck: check the type assertion of the claims-only session marker.
- revive: the private session lookup does not use the request.
- staticcheck QF1008: drop the embedded openapi3.T from the test selectors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@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
1 New issue
0 Accepted issues

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

See analysis details on SonarQube Cloud

@pvormste
pvormste merged commit 8e5f6f1 into master Nov 26, 2026
64 of 65 checks passed
@pvormste
pvormste deleted the TT-14451-claims-only-jwt branch November 26, 2026 16:35
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.

4 participants