Skip to content

feat(auth): verify OAuth access tokens via JWKS for virtual server MCP - #3715

Merged
jonpspri merged 4 commits into
IBM:mainfrom
kimsehwan96:fix/oauth-jwks-token-verification
Apr 12, 2026
Merged

jonpspri merged 4 commits into
IBM:mainfrom
kimsehwan96:fix/oauth-jwks-token-verification

Conversation

@kimsehwan96

@kimsehwan96 kimsehwan96 commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

🔗 Related Issue

Partially addresses #2659


📝 Summary

Virtual servers with oauth_enabled=True advertise RFC 9728 Protected Resource Metadata, directing MCP clients to authenticate via an IdP (e.g., Keycloak, Authentik). However, when the client presents the IdP-issued access token, ContextForge rejects it with "Invalid token" because verify_credentials() only validates ContextForge-issued JWTs (iss: "mcpgateway").

This PR adds IdP-issued OAuth access token verification via OIDC discovery + JWKS:

  • Issuer-based routing: Peeks at the token's iss claim before verification. ContextForge-issued tokens (iss == settings.jwt_issuer) go through the existing path; IdP-issued tokens are routed to JWKS-based verification.
  • OIDC discovery + JWKS: Fetches /.well-known/openid-configuration from the token's issuer, resolves jwks_uri, and verifies the signature using the IdP's public keys. Metadata is cached (300s TTL).
  • Per-server issuer allowlist: Each virtual server's oauth_config.authorization_servers determines which issuers are trusted. Server A (Authentik) and Server B (Keycloak) are fully independent.
  • Audience validation: When oauth_config.client_id is configured, the token's aud claim is validated. When not configured, audience check is skipped (opt-in).
  • User resolution: Verified tokens are resolved against the ContextForge user database. Users must already exist (no auto-creation) — the expected flow is SSO login first, then MCP client access.

🏷️ Type of Change

  • Bug fix
  • Feature / Enhancement
  • Documentation
  • Refactor
  • Chore (deps, CI, tooling)
  • Other (describe below)

🧪 Verification

Check Command Status
Lint suite make lint
Unit tests make test
Coverage ≥ 80% make coverage

✅ Checklist

  • Code formatted (make black isort pre-commit)
  • Tests added/updated for changes
  • Documentation updated (if applicable)
  • No secrets or credentials committed

📓 Notes (optional)

  • OIDC discovery cache duplication: sso_service.py has a similar OIDC discovery + JWKS cache for SSO id_token verification. The two caches serve different request paths (SSO callback vs MCP transport) with different lifecycles. A shared utility extraction is possible as a follow-up.

Auth flow

MCP Client → POST /servers/{id}/mcp (Bearer <IdP token>)
  → peek token iss claim
  → iss != "mcpgateway" → _try_oauth_access_token()
    → DB lookup: server.oauth_enabled? oauth_config?
    → issuer in authorization_servers allowlist?
    → OIDC discovery → JWKS → signature verification
    → (optional) audience validation against client_id
    → DB user lookup (must exist, must be active)
    → teams resolved from DB → user_context populated

@crivetimihai crivetimihai added enhancement New feature or request MUST P1: Non-negotiable, critical requirements without which the product is non-functional or unsafe labels Mar 20, 2026
@crivetimihai crivetimihai added this to the Release 1.0.0 milestone Mar 20, 2026
@crivetimihai crivetimihai added security Improves security mcp-protocol Alignment with MCP protocol or specification labels Mar 20, 2026
@crivetimihai

Copy link
Copy Markdown
Member

Thanks @kimsehwan96. Well-designed feature — the issuer-based routing with per-server allowlist and OIDC discovery caching is the right architecture. Addresses #2659. The note about shared OIDC discovery cache extraction as a follow-up is reasonable. Will review the implementation in detail.

@junlin3012

Copy link
Copy Markdown
Contributor

Tested and confirmed working ✅

I applied this PR as a patch on top of ghcr.io/ibm/mcp-context-forge:1.0.0-RC-2 and deployed it to Cloud Run (asia-southeast1).

Test setup

  • IdP: Keycloak 26.1.4 (separate Cloud Run service)
  • Virtual server: oauth_enabled=True, authorization_servers: ["https://keycloak-.../realms/fluid"]
  • Client: mcp-remote (npm) connecting via Claude Code CLI

Results

  1. JWKS verification — verify_oauth_access_token() correctly fetches Keycloak's OIDC discovery metadata, resolves the JWKS URI, and verifies RS256 token signatures. Tested both locally (docker-compose) and on Cloud Run.

  2. Issuer routing — _auth_jwt() correctly peeks at the iss claim and routes IdP-issued tokens to the new OAuth verification path while leaving ContextForge-issued tokens (iss: "mcpgateway") on the existing path.

  3. End-to-end OAuth flow — mcp-remote discovers the RFC 9728 protected resource metadata, finds the Keycloak authorization server, opens a browser for login, exchanges the auth code for a token, and presents it to ContextForge. With this PR, ContextForge accepts the Keycloak-issued token and establishes a StreamableHTTP MCP connection successfully.

  4. Invalid tokens rejected — Tokens with wrong signatures are correctly rejected with "Invalid OAuth access token" (401).

Patch method

FROM ghcr.io/ibm/mcp-context-forge:1.0.0-RC-2
COPY patches/streamablehttp_transport.py /app/mcpgateway/transports/streamablehttp_transport.py
COPY patches/verify_credentials.py /app/mcpgateway/utils/verify_credentials.py

This is a critical feature for anyone using ContextForge with an external IdP (Keycloak, Authentik, Auth0, etc.) for MCP client authentication. Without it, only ContextForge-issued tokens are accepted, which blocks the RFC 9728 OAuth flow entirely.

Would love to see this merged before 1.0.0-GA. Great work @kimsehwan96! 🚀

@hanniesnng

hanniesnng commented Mar 27, 2026 •

Copy link
Copy Markdown

Works for my case with Okta. Apart from the above mentioned changes, the only patches/updates I need to make is:

  • adding a client_id in the virtual server's auth config
  • adding a redirect_url in the virtual server's auth config
  • Dockerfile to patch changes
FROM ghcr.io/ibm/mcp-context-forge:1.0.0-RC-2
COPY patches/streamablehttp_transport.py /app/mcpgateway/transports/streamablehttp_transport.py
COPY patches/verify_credentials.py /app/mcpgateway/utils/verify_credentials.py
COPY patches/metrics.py /app/mcpgateway/services/metrics.py

This works for grant_types authorization_code & refresh_token. Not sure if it works for client credential flow but good work @kimsehwan96

@kelf

kelf commented Mar 31, 2026

Copy link
Copy Markdown

Had to merge this into a custom build, but works great (small tweak for latest codebase). Looking forward to seeing it merged.

@kimsehwan96
kimsehwan96 force-pushed the fix/oauth-jwks-token-verification branch 2 times, most recently from e7bcc0c to 131eb72 Compare April 1, 2026 23:31
@kimsehwan96

kimsehwan96 commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main and applied the following updates:

  1. Fix: _resolve_teams_from_db_sync ImportError
    During rebase, _resolve_teams_from_db_sync (referenced in _try_oauth_access_token) was removed from auth.py in upstream — it was replaced by the async_resolve_teams_from_db(email, user_info). Updated the import and call site accordingly:

Before (ImportError at runtime):

from mcpgateway.auth import _get_user_by_email_sync, _resolve_teams_from_db_sync
final_teams = None if is_admin else await asyncio.to_thread(_resolve_teams_from_db_sync, user_email, is_admin=False)

After:

from mcpgateway.auth import _get_user_by_email_sync, _resolve_teams_from_db
final_teams = None if is_admin else await _resolve_teams_from_db(user_email, user_record)

Confirmed the ImportError via python3 -c "from mcpgateway.auth import _resolve_teams_from_db_sync" — fails on current codebase.

  1. Unit tests
    All 155 tests in test_auth.py pass (including the existing TestVerifyOauthAccessToken class).

  2. E2E tests added (tests/e2e/test_oauth_jwks_e2e.py)
    5 tests running against a real ContextForge + Keycloak docker-compose stack (docker compose --profile sso up -d). All 5 pass.

  ┌────────────────────────────────────────────┬──────────────────────────────┐
  │                    Test                    │             Type             │
  ├────────────────────────────────────────────┼──────────────────────────────┤
  │ test_valid_keycloak_jwt_accepted           │ Positive                     │
  ├────────────────────────────────────────────┼──────────────────────────────┤
  │ test_non_oauth_server_rejects_keycloak_jwt │ Deny-path (feature disabled) │
  ├────────────────────────────────────────────┼──────────────────────────────┤
  │ test_wrong_issuer_rejected                 │ Deny-path (issuer allowlist) │
  ├────────────────────────────────────────────┼──────────────────────────────┤
  │ test_invalid_token_rejected                │ Deny-path (unauthenticated)  │
  ├────────────────────────────────────────────┼──────────────────────────────┤
  │ test_user_not_in_cf_rejected               │ Deny-path (user not in DB)   │
  └────────────────────────────────────────────┴──────────────────────────────┘

Notable issues encountered during e2e setup:

  • Keycloak issuer mismatch: The default KC_HOSTNAME=localhost causes the JWT iss claim to use localhost, which is unreachable from inside the gateway container for OIDC discovery. Solved by overriding the Keycloak hostname when starting the stack:

    KC_HOSTNAME=keycloak KC_HOSTNAME_PORT=8080 docker compose -f docker-compose.yml -f docker-compose.sso.yml --profile sso up -d keycloak

    This ensures the token issuer is http://keycloak:8080/realms/mcp-gateway, which the gateway can reach for JWKS verification.

  • JWT secret: The .env file overrides JWT_SECRET_KEY with a shorter value than the docker-compose default. The test reads JWT_SECRET_KEY from the environment with the correct fallback.

@kimsehwan96
kimsehwan96 force-pushed the fix/oauth-jwks-token-verification branch 2 times, most recently from aef0e41 to 9a30860 Compare April 2, 2026 22:20
@calculus-ask

calculus-ask commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

@kimsehwan96 @crivetimihai

I have tested MCP CF in both local and in EKS deployment with ADFS (SSO login) using Keycloak its working fine. ✅

Able to list both the both the tools in time server. ✅

Observed one issue in EKS deployment (https://mcpgateway-dev.mcp-sf.cld.*****.net) is, i need to give http:// in both Cursor and Keycloak redirect uri since the "/.well-known/oauth-protected-resource/servers/75c1f9d6f49f421086e2ee2c54027ae4/mcp" returning only http not https. ❌

Keycloak redirects:
Valid redirect URIs 
http://mcpgateway-dev.mcp-sf.cld.*****.net/oauth/callback
cursor://anysphere.cursor-mcp/oauth/callback

Cursor Settings:
    "test-vs-ask": {
      "url": "http://mcpgateway-dev.mcp-sf.cld.*****.net/servers/75c1f9d6f49f421086e2ee2c54027ae4/mcp"
    }

Ref: #3535

@crivetimihai crivetimihai self-assigned this Apr 8, 2026
crivetimihai added a commit that referenced this pull request Apr 8, 2026
…C, tests

Review fixes for the OAuth access token verification feature (#3715):

Security:
- Validate issuer URL and discovered jwks_uri against SSRF protections
  before outbound fetches (validate_core_url on both paths)
- Validate discovered metadata issuer matches queried issuer (RFC 8414 §3.3)
- Persist oauth_client_id from admin UI into oauth_config for audience
  validation; log warning when audience check is skipped

Correctness:
- Fall through to verify_credentials on jwt.DecodeError instead of
  early-rejecting (fixes 7 broken existing tests)
- Wrap _get_user_by_email_sync and _resolve_teams_from_db in try/except
  returning 503 on DB failures (parity with _auth_jwt path)
- Distinguish infra failures (503) from auth failures (401) via
  OAUTH_VERIFY_UNAVAILABLE sentinel in verify_oauth_access_token
- Fix internal MCP RPC RBAC to enable check_any_team for
  oauth_access_token (non-admin team-scoped users were denied)
- Add auth_method and set_trace_context_from_teams for observability
- Add TOOLS_MANAGE_PLUGINS to Permissions class (fixes team_admin
  bootstrap failure from #4068, see #4085)
- Fix DAR101 flake8 docstring issue in observability.py

Tests:
- 30+ new unit tests covering _auth_jwt OAuth routing,
  _try_oauth_access_token branches, verify_oauth_access_token edge
  cases, SSRF rejection, issuer mismatch, 503 vs 401 classification,
  DB error handling, and trace context

Signed-off-by: Mihai Criveti <[email protected]>
@crivetimihai

Copy link
Copy Markdown
Member

Maintainer review — changes applied

Rebased onto main and applied the following fixes during review:

Security hardening

  • SSRF protection: Validate issuer URL via validate_core_url before OIDC discovery fetch, and validate discovered jwks_uri before passing to PyJWKClient (which uses urllib directly, bypassing the shared HTTP client)
  • Discovery issuer mismatch: Verify that the OIDC discovery document's issuer field matches the queried issuer before trusting jwks_uri (RFC 8414 §3.3)
  • Audience validation: Admin server form now persists oauth_client_id into oauth_config.client_id; added a warning log when audience validation is disabled due to missing client_id

Correctness

  • Issuer peek fallthrough: Changed jwt.decode at the top of _auth_jwt to fall through to verify_credentials on DecodeError instead of early-rejecting — the original code broke 7 existing tests that use mock tokens
  • DB error handling: Wrapped _get_user_by_email_sync and _resolve_teams_from_db in try/except returning 503, matching the existing _auth_jwt error handling pattern
  • 401 vs 503 classification: Introduced OAUTH_VERIFY_UNAVAILABLE sentinel so _try_oauth_access_token returns 503 for infrastructure failures (OIDC/JWKS unreachable) vs 401 for invalid tokens
  • Internal MCP RPC RBAC: Fixed _ensure_rpc_permission to enable check_any_team for oauth_access_token — non-admin team-scoped users were incorrectly denied on the internal Rust→Python MCP dispatch path

Observability

  • Added auth_method: "oauth" to user_context_var and set_trace_context_from_teams() call for parity with other auth paths

Other fixes (pre-existing, not from this PR)

Tests

  • 30+ new unit tests covering all branches: _auth_jwt OAuth routing, _try_oauth_access_token (happy path, admin bypass, server not found, OAuth disabled, DB errors, token verification failure, missing email, inactive user, preferred_username fallback, single authorization_server config, trace context), verify_oauth_access_token edge cases (issuer mismatch, SSRF rejection, cache expiry, 5xx vs 4xx discovery, JWKS cache miss), and the 503 transport path
  • All 628 unit tests pass, 40/40 E2E RBAC tests pass
  • Ruff, black, flake8 clean

crivetimihai
crivetimihai previously approved these changes Apr 8, 2026

@crivetimihai crivetimihai left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving with maintainer review fixes applied. The feature design is sound — issuer-based token routing, per-server allowlists, JWKS caching, and user pre-existence requirement are all correct.

Security hardening (SSRF validation on both issuer and jwks_uri, discovery issuer mismatch check, audience validation persistence, 401 vs 503 classification) and error handling gaps (uncaught DB errors, missing trace context) have been addressed in the review commit. Full unit test coverage for all new code paths.

Nice work on the overall design, @kimsehwan96 — the auth flow is clean and well-structured.

crivetimihai added a commit that referenced this pull request Apr 8, 2026
…C, tests

Review fixes for the OAuth access token verification feature (#3715):

Security:
- Validate issuer URL and discovered jwks_uri against SSRF protections
  before outbound fetches (validate_core_url on both paths)
- Validate discovered metadata issuer matches queried issuer (RFC 8414 §3.3)
- Persist oauth_client_id from admin UI into oauth_config for audience
  validation; log warning when audience check is skipped

Correctness:
- Fall through to verify_credentials on jwt.DecodeError instead of
  early-rejecting (fixes 7 broken existing tests)
- Wrap _get_user_by_email_sync and _resolve_teams_from_db in try/except
  returning 503 on DB failures (parity with _auth_jwt path)
- Distinguish infra failures (503) from auth failures (401) via
  OAUTH_VERIFY_UNAVAILABLE sentinel in verify_oauth_access_token
- Fix internal MCP RPC RBAC to enable check_any_team for
  oauth_access_token (non-admin team-scoped users were denied)
- Add auth_method and set_trace_context_from_teams for observability
- Add TOOLS_MANAGE_PLUGINS to Permissions class (fixes team_admin
  bootstrap failure from #4068, see #4085)
- Fix DAR101 flake8 docstring issue in observability.py

Tests:
- 30+ new unit tests covering _auth_jwt OAuth routing,
  _try_oauth_access_token branches, verify_oauth_access_token edge
  cases, SSRF rejection, issuer mismatch, 503 vs 401 classification,
  DB error handling, and trace context

Signed-off-by: Mihai Criveti <[email protected]>
@calculus-ask

Copy link
Copy Markdown
Contributor

@crivetimihai

ADFS is not connecting, pls find the logs below

Scenario 1:
Authorization Server URL: https://adfs.ds.*****.net/adfs
Scopes (space-separated): openid profile email
Token Endpoint URL (optional): Blank

Cursor Log:
2026-04-09 21:57:17.168 [info] [V2] Handling CreateClient action
2026-04-09 21:57:17.168 [info] [V2 FSM] connection:connect_start: conn=idle,auth=unknown -> conn=connecting,auth=unknown
2026-04-09 21:57:22.489 [warning] Transient error connecting to streamableHttp server: HTTP 503 trying to load OAuth metadata from https://adfs.ds.*****.net/.well-known/oauth-authorization-server/adfs
2026-04-09 21:57:22.492 [warning] Connection failed: HTTP 503 trying to load OAuth metadata from https://adfs.ds.*****.net/.well-known/oauth-authorization-server/adfs
2026-04-09 21:57:22.492 [warning] [V2 FSM] connection:connect_failure: conn=connecting,auth=unknown -> conn=failed,auth=unknown

Correct OAuth discovery endpoints : https://adfs.ds.*****.net/adfs/.well-known/openid-configuration
MCP CF returns: https://adfs.ds.*****.net/.well-known/oauth-authorization-server/adfs

Scenario 2:

Authorization Server URL: https://adfs.ds.*****.net/adfs/oauth2/authorize
Scopes (space-separated): openid profile email
Token Endpoint URL (optional): https://adfs.ds.*****.net/adfs/oauth2/token

2026-04-09 22:02:13.843 [info] [V2] Handling CreateClient action
2026-04-09 22:02:13.843 [info] [V2 FSM] connection:connect_start: conn=idle,auth=unknown -> conn=connecting,auth=unknown
2026-04-09 22:02:19.227 [warning] Transient error connecting to streamableHttp server: HTTP 503 trying to load OAuth metadata from https://adfs.ds.*****.net/.well-known/oauth-authorization-server/adfs/oauth2/authorize
2026-04-09 22:02:19.231 [warning] Connection failed: HTTP 503 trying to load OAuth metadata from https://adfs.ds.*****.net/.well-known/oauth-authorization-server/adfs/oauth2/authorize
2026-04-09 22:02:19.231 [warning] [V2 FSM] connection:connect_failure: conn=connecting,auth=unknown -> conn=failed,auth=unknown
2026-04-09 22:02:19.232 [info] CreateClient completed, connected: false, statusType: error

=====

curl -i https://adfs.ds.*****.net/adfs/.well-known/openid-configuration
HTTP/1.1 200 OK
Content-Length: 1943
Content-Type: application/json;charset=UTF-8
Server: Microsoft-HTTPAPI/2.0
Strict-Transport-Security: max-age = 31536000
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Content-Security-Policy: default-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data:;
Date: Thu, 09 Apr 2026 16:25:26 GMT

{"issuer":"https://adfs.ds.*****.net/adfs","authorization_endpoint":"https://adfs.ds.*****.net/adfs/oauth2/authorize/","token_endpoint":"https://adfs.ds.*****.net/adfs/oauth2/token/", ...

@ja8zyjits

Copy link
Copy Markdown
Collaborator

User Stories Coverage Analysis: PR #3715 vs Issue #2659

Analysis Date: 2026-04-09
PR: #3715 - OAuth Access Token Verification via JWKS
Issue: #2659 - OIDC Token Verification - Enterprise Claims Extraction


Executive Summary

PR #3715 does NOT implement any of the user stories from Issue #2659.

The PR implements a different but complementary feature:


User Story Coverage Analysis

❌ US-1: Platform Admin - Extract Entra ID Groups for Role Mapping

Status: NOT IMPLEMENTED

What Issue #2659 Requires:

Given an Entra ID SSO provider is configured
And the id_token contains claims:
  groups: ["group-id-1", "group-id-2"]
  roles: ["Platform.Admin", "Tools.Read"]
When a user completes SSO login
Then the gateway should:
  - Verify the id_token signature using JWKS
  - Extract groups and roles from verified claims
  - Apply team_mapping rules to assign teams
  - Apply role_mapping rules to assign permissions

What PR #3715 Implements:

  • OAuth access token verification for MCP endpoints
  • Only extracts email, preferred_username, sub for user identification
  • Does NOT extract groups or roles
  • Does NOT apply team_mapping or role_mapping
  • Does NOT modify SSO login flow

Coverage: 0% - Different token type, different use case


❌ US-2: Platform Admin - Extract Keycloak Realm Roles

Status: NOT IMPLEMENTED

What Issue #2659 Requires:

Given a Keycloak SSO provider is configured
And the id_token contains claims:
  realm_access:
    roles: ["admin", "developer"]
  resource_access:
    mcp-gateway:
      roles: ["tools.write", "servers.admin"]
  groups: ["/engineering", "/security"]
When a user completes SSO login
Then the gateway should:
  - Extract realm_access.roles for platform-wide permissions
  - Extract resource_access.{client}.roles for app-specific permissions
  - Extract groups for team membership

What PR #3715 Implements:

  • OAuth access token verification for MCP endpoints
  • Only extracts basic identity claims (email, sub)
  • Does NOT extract realm_access or resource_access
  • Does NOT extract groups
  • Does NOT modify SSO login flow

Coverage: 0% - Different token type, no claims extraction


⚠️ US-3: Security Engineer - Verify Token Signatures

Status: PARTIALLY IMPLEMENTED (Different Context)

What Issue #2659 Requires:

Given token verification is enabled (default)
When an id_token is received during SSO callback
Then the gateway should:
  - Fetch JWKS from provider (cached with 1-hour TTL)
  - Verify JWT signature against public key (kid matching)
  - Validate iss claim matches configured issuer
  - Validate aud claim matches client_id
  - Validate exp claim (with 60-second clock skew tolerance)
  - Validate nonce if one was sent in auth request

What PR #3715 Implements:

# In verify_oauth_access_token()
- Fetch JWKS from provider (cached with 5-min TTL, not 1-hour)
- Verify JWT signature against public key (kid matching) ✅
- Validate iss claim matches configured issuer ✅
- Validate aud claim matches client_id (optional) ✅
- Validate exp claim ✅
- Does NOT validate nonce (not applicable to access tokens)

Key Differences:

  • Token Type: access_token (PR) vs id_token (Issue)
  • Use Case: MCP endpoint auth (PR) vs SSO callback (Issue)
  • Cache TTL: 300s (PR) vs 3600s (Issue requirement)
  • Nonce: Not validated (PR) vs Required (Issue)

Coverage: ~40% - Core verification logic similar but different context


❌ US-4: Platform Admin - Configure Custom JWKS Endpoint

Status: NOT IMPLEMENTED

What Issue #2659 Requires:

Given an SSO provider is configured with:
  jwks_uri: "https://custom-idp.example.com/keys.json"
When token verification occurs
Then the gateway should:
  - Use the configured jwks_uri instead of OIDC discovery

What PR #3715 Implements:

  • OIDC discovery to find jwks_uri automatically
  • Does NOT add jwks_uri field to SSOProvider model
  • Does NOT support custom JWKS endpoint configuration
  • Always uses OIDC discovery (no fallback to configured URI)

Coverage: 0% - No database schema changes, no custom JWKS support


❌ US-5: Operations Team - Monitor Verification Failures

Status: NOT IMPLEMENTED

What Issue #2659 Requires:

When verification fails due to:
  - Expired token
  - Invalid signature
  - Issuer mismatch
  - Audience mismatch
  - JWKS fetch failure
Then the gateway should:
  - Log at WARNING level with failure reason
  - Include provider_id, failure_type (no sensitive claims)
And metrics should track:
  - sso_token_verification_total{status="success|failure", provider="..."}
  - sso_token_verification_failures{reason="...", provider="..."}

What PR #3715 Implements:

# In verify_oauth_access_token()
logger.warning("OAuth token issuer %s not in allowlist %s", normalized_issuer, normalized_allowed)
logger.warning("No jwks_uri in OIDC metadata for issuer %s", normalized_issuer)
logger.warning("OAuth access token verification failed (issuer=%s): %s", normalized_issuer, exc)
logger.info("OAuth access token verified (issuer=%s, sub=%s)", normalized_issuer, verified.get("sub", "unknown"))

What's Missing:

  • No metrics tracking (sso_token_verification_total, sso_token_verification_failures)
  • No structured failure types
  • No provider_id in logs (uses issuer instead)
  • Logs are for access token verification, not SSO callback

Coverage: ~20% - Basic logging present but no metrics


❌ US-6: Developer - Disable Verification for Development

Status: NOT IMPLEMENTED

What Issue #2659 Requires:

Given SSO_REQUIRE_TOKEN_VERIFICATION=false in environment
When an id_token is received during SSO callback
Then the gateway should:
  - Log a WARNING: "Token verification disabled - development only"
  - Skip signature verification entirely
  - Return None from verification (userinfo-only mode)

What PR #3715 Implements:

  • No SSO_REQUIRE_TOKEN_VERIFICATION setting
  • No ability to disable OAuth access token verification
  • Verification is always enabled for oauth_enabled servers

Coverage: 0% - No configuration option


Implementation Tasks Coverage

Phase 1: Database & API ❌ NOT IMPLEMENTED

Task Status Notes
Add jwks_uri column to SSOProvider model ❌ No database changes
Add jwks_uri to SSOProviderCreateRequest ❌ No API changes
Add jwks_uri to SSOProviderUpdateRequest ❌ No API changes
Update get_sso_provider response ❌ No API changes
Create Alembic migration ❌ No migrations

Coverage: 0/5 tasks (0%)


Phase 2: JWKS Infrastructure ⚠️ PARTIALLY IMPLEMENTED

Task Status Notes
Create mcpgateway/services/jwks_service.py ❌ Code in verify_credentials.py instead
Implement async JWKS fetching with httpx ✅ Uses PyJWKClient
Implement JWKS caching with configurable TTL ⚠️ Hardcoded 5-min TTL, not configurable
Implement OIDC discovery with caching ✅ Implemented in _discover_oidc_metadata()
Implement key rotation handling ✅ PyJWKClient handles kid miss
Implement HTTPS enforcement ❌ No HTTPS validation
Implement origin validation ❌ No origin validation
Implement discovery issuer validation ❌ No issuer mismatch check

Coverage: 3/8 tasks (38%)


Phase 3: Token Verification ⚠️ PARTIALLY IMPLEMENTED (Wrong Token Type)

Task Status Notes
Add _verify_id_token() method to SSOService ❌ Implemented verify_oauth_access_token() instead
Implement algorithm allowlist ✅ RS*, ES*, PS*, EdDSA supported
Add _get_issuer_validation_params() ❌ Not implemented
Add _validate_multitenant_issuer() ❌ Not implemented
Add _validate_authorized_party() ❌ Not implemented
Implement nonce validation ❌ Not applicable to access tokens
Implement clock skew tolerance ⚠️ PyJWT default (no explicit 60s)
Update _get_user_info() to use verified tokens ❌ Not modified
Deprecate _decode_jwt_claims() ❌ Not modified

Coverage: 1.5/9 tasks (17%) - Wrong token type


Phase 4: Claims Extraction ❌ NOT IMPLEMENTED

Task Status Notes
Implement _extract_entra_claims() ❌ Not implemented
Implement _extract_keycloak_claims() ❌ Not implemented
Implement _extract_generic_oidc_claims() ❌ Not implemented
Handle group overage (_claim_names) ❌ Not implemented

Coverage: 0/4 tasks (0%)


Phase 5: Configuration ❌ NOT IMPLEMENTED

Task Status Notes
Add SSO_REQUIRE_TOKEN_VERIFICATION setting ❌ Not implemented
Add SSO_JWKS_CACHE_TTL setting ❌ Hardcoded to 300s
Add SSO_OIDC_DISCOVERY_CACHE_TTL setting ❌ Hardcoded to 300s
Update .env.example ❌ Not updated
Update docs/docs/manage/configuration.md ❌ Not updated

Coverage: 0/5 tasks (0%)


Phase 6: Testing ⚠️ PARTIALLY IMPLEMENTED (Different Scope)

Task Status Notes
Unit tests for signature verification ✅ 13 tests in test_auth.py
Unit tests for claim validation ✅ Tests iss, aud, exp
Unit tests for JWKS caching and refresh ✅ Cache reuse test
Unit tests for multi-tenant Entra ID ❌ Not implemented
Unit tests for HTTPS enforcement ❌ Not implemented
Unit tests for origin validation ❌ Not implemented
Unit tests for alg=none rejection ⚠️ Implicit via algorithm allowlist
Integration tests with mock JWKS endpoint ✅ 5 E2E tests with Keycloak

Coverage: 4/8 tasks (50%) - Tests for access tokens, not id_tokens


Overall Coverage Summary

Category Tasks Completed Total Tasks Coverage
User Stories 0 6 0%
Phase 1: Database & API 0 5 0%
Phase 2: JWKS Infrastructure 3 8 38%
Phase 3: Token Verification 1.5 9 17%
Phase 4: Claims Extraction 0 4 0%
Phase 5: Configuration 0 5 0%
Phase 6: Testing 4 8 50%
TOTAL 8.5 45 19%

Conclusion

PR #3715 implements a DIFFERENT feature than Issue #2659 requires:

What Issue #2659 Needs (NOT in PR)

  • ✅ Token Type: id_token verification during SSO callback
  • ✅ Claims Extraction: Groups, roles, custom claims from Entra ID/Keycloak
  • ✅ Role Mapping: Automatic RBAC assignment from IdP groups
  • ✅ Database Schema: jwks_uri column on SSOProvider
  • ✅ Configuration: SSO_REQUIRE_TOKEN_VERIFICATION, cache TTL settings

What PR #3715 Implements (NOT in Issue)

  • ✅ Token Type: access_token verification for MCP virtual server endpoints
  • ✅ Use Case: RFC 9728 compliance for OAuth-enabled virtual servers
  • ✅ Issuer Routing: Distinguish ContextForge-issued vs IdP-issued tokens
  • ✅ Per-Server Config: oauth_enabled and authorization_servers on virtual servers

Overlap (19% of Issue Requirements)

  • ✅ OIDC discovery + JWKS fetching (but different cache TTL)
  • ✅ JWT signature verification (but for access tokens, not id_tokens)
  • ✅ Algorithm allowlist (RS*, ES*, PS*, EdDSA)
  • ✅ Issuer validation (but per-server allowlist, not SSO provider config)

Recommendation: PR #3715 should be treated as a separate feature that enables OAuth access token verification for MCP endpoints. Issue #2659 remains open and requires a separate implementation for id_token verification during SSO callback with enterprise claims extraction.

@kimsehwan96

Copy link
Copy Markdown
Contributor Author

Thank you for the thorough analysis, @ja8zyjits. You're absolutely right.

When I created this PR, I was addressing a specific problem: OAuth-enabled Virtual Servers had no way to verify incoming access tokens. After implementing it, I searched for an existing issue that seemed closest to this requirement and linked #2659 — but as your analysis clearly shows, it doesn't implement any of the user stories from that issue.

To summarize:

These are complementary but separate features with ~19% overlap (JWKS infrastructure).

Proposed next steps:

  1. I'll create a separate, dedicated issue for what this PR actually implements (OAuth access token verification for virtual servers)
  2. Update this PR to reference the new issue instead of [EPIC][SSO][SECURITY]: OIDC Token Verification - Enterprise Claims Extraction #2659
  3. Leave [EPIC][SSO][SECURITY]: OIDC Token Verification - Enterprise Claims Extraction #2659 open — it requires its own implementation for id_token verification and claims extraction

Would that work for you?

@ja8zyjits

Copy link
Copy Markdown
Collaborator

Hi @kimsehwan96 ,

I appreciate your clarification. It was my mistake to consider this as fix for #2659 since you only referred it and not marked it as closing.

Regards,
Jitesh

@jonpspri
jonpspri force-pushed the fix/oauth-jwks-token-verification branch from abcb0e0 to 10945a7 Compare April 12, 2026 07:14
kimsehwan96 and others added 4 commits April 12, 2026 08:50
…P endpoints

Add OAuth access token verification for virtual servers with
oauth_enabled=True (RFC 9728). Routes to ContextForge-issued or
IdP-issued verification based on token issuer claim. IdP-issued
tokens are verified via OIDC discovery + JWKS. Validates audience
when oauth_config.client_id is configured. Requires pre-existing
ContextForge user (no auto-creation).

Signed-off-by: kimsehwan96 <[email protected]>
Add end-to-end tests for the OAuth access token verification via JWKS
feature on virtual server MCP endpoints. Tests run against a real
ContextForge + Keycloak docker-compose stack and cover:

- Valid Keycloak JWT accepted on oauth_enabled server
- Non-OAuth server rejects IdP JWT (feature disabled deny-path)
- Wrong issuer rejected (issuer allowlist deny-path)
- Invalid/garbage token rejected (unauthenticated deny-path)
- Unregistered user rejected (user not in CF DB deny-path)

Requires: docker compose --profile sso up -d

Signed-off-by: kimsehwan96 <[email protected]>
…bypass

Follow-up security hardening on top of the OAuth/JWKS verification feature
for virtual server MCP endpoints. Closes multiple replay and bypass paths
surfaced across several review rounds, and extends test coverage to lock
the resulting invariants.

Audience binding (RFC 8707/9728):
- Always enforce a non-empty expected_audience containing the canonical MCP
  resource URL; callers no longer pass None when oauth_config.client_id is
  absent.
- Derive the resource URL from settings.app_domain, not the caller-controlled
  Host / X-Forwarded-Host headers. Operators must set app_domain to the
  gateway's public URL; the helper fails closed (401) when it is empty.
- oauth_config.resource (scalar or list) and legacy client_id extend the
  expected-audience list rather than replacing the resource URL.

OIDC ID token rejection:
- verify_oauth_access_token now rejects tokens carrying nonce or at_hash
  claims before the JWKS signing-key lookup, so a front-channel OIDC ID
  token obtained via SSO cannot be replayed as an MCP bearer token on a
  server configured with a matching client_id in aud.

Routing and fall-through:
- OAuth dispatch in _route_idp_issued_token is independent of the
  JWT_ISSUER_VERIFICATION toggle; that setting only governs how internal
  ContextForge JWTs are checked.
- _try_oauth_access_token decodes the token once (threaded from the
  router) and returns NOT_APPLICABLE when the issuer is missing or outside
  the server's allowlist, so legacy gateway JWTs whose iss predates
  settings.jwt_issuer still flow to verify_credentials when issuer
  verification is disabled.
- oauth_enabled=True with empty oauth_config or empty authorization_servers
  fails closed with 503 instead of falling through to internal
  verification — no internal JWT can reach an advertised-OAuth resource.

Discovery:
- _discover_oidc_metadata probes both the RFC 8414 OAuth authorization
  server metadata URL and the OIDC discovery URL. Non-OIDC OAuth servers
  are no longer blackholed by a single OIDC probe failure.
- Negative caching distinguishes transient failures (network errors,
  5xx, 408, 429; cached 5s) from permanent failures (404, malformed
  JSON; cached 30s) so a brief IdP restart does not blackhole every
  virtual server sharing that issuer.

Observability:
- New oauth_verify_events_counter with success / failed / not_applicable /
  error outcomes. _route_idp_issued_token emits the error label on
  unhandled exceptions before re-raising.
- Allowlist-deferral, successful verification, and undecodable-token
  paths log at DEBUG/INFO with sanitized server_id and issuer so auth
  floods do not pollute WARN-level observability.
- _build_public_base_url narrows its exception catch and logs malformed
  ASGI scopes at WARNING with request path and client tuple.

Tests:
- 14 new regression tests across TestOAuthAudienceEnforcement,
  TestLegacyJwtOnOauthEnabledServer, TestOAuthServerMisconfigurationRejected,
  TestRouteIdpIssuedToken, and TestVerifyOauthAccessToken.
- Invariants locked: audience binding to app_domain, forwarded-host
  header rejection (parametrized over Host / X-Forwarded-Host / Forwarded
  / X-Original-Host), ID-token rejection ordering (asserting the JWKS
  client is never consulted), RFC 8414 + OIDC dual-probe outcomes,
  OAuth routing decoupled from JWT_ISSUER_VERIFICATION, metrics counter
  labels, non-string iss handling, list-audience any-of semantics.

730 unit tests passing.

Signed-off-by: Jonathan Springer <[email protected]>
… coverage

Final security hardening pass plus coverage for all new OAuth/JWKS
error branches. Addresses three findings from an independent pre-merge
audit and raises test coverage to 99%/97% on the two changed files.

SSRF defense-in-depth:
- _resolve_authorization_servers rejects non-HTTPS issuer URLs with a
  logged warning.
- verify_oauth_access_token validates that jwks_uri shares the issuer's
  scheme (https) and origin (netloc).
- _discover_oidc_metadata validates the metadata issuer field against
  the expected issuer per RFC 8414 section 3.3.

Post-decode issuer re-verification:
- After signature verification, the verified payload's iss claim is
  re-checked against the normalized issuer used for JWKS resolution,
  with trailing-slash normalization.

Log-injection hardening:
- All logger calls in verify_oauth_access_token that interpolate the
  issuer URL or jwks_uri now pass through sanitize_for_log().

Coverage (18 new tests):
- TestTryOauthAccessTokenErrorBranches: missing server_id, DB error,
  disabled server, empty oauth_config, missing email, unregistered user,
  inactive user, team-resolution exception, full SUCCESS path.
- TestBuildServerResourceUrlAppDomainError: app_domain __str__ raises.
- TestAuthJwtRoutingReturn: _auth_jwt returns routed True/False.
- TestVerifyOauthAccessToken extensions: cache-expiry pop, transient
  probe failure, invalid JSON, non-dict metadata, missing jwks_uri,
  PyJWKClient lazy construction.

748 unit tests passing.

Signed-off-by: Jonathan Springer <[email protected]>
@jonpspri
jonpspri force-pushed the fix/oauth-jwks-token-verification branch from 10945a7 to 8c314ad Compare April 12, 2026 07:52
@jonpspri
jonpspri merged commit 9bd1a18 into IBM:main Apr 12, 2026
25 checks passed
claudia-gray pushed a commit that referenced this pull request Apr 13, 2026
#3715)

* feat(auth): verify OAuth access tokens via JWKS for virtual server MCP endpoints

Add OAuth access token verification for virtual servers with
oauth_enabled=True (RFC 9728). Routes to ContextForge-issued or
IdP-issued verification based on token issuer claim. IdP-issued
tokens are verified via OIDC discovery + JWKS. Validates audience
when oauth_config.client_id is configured. Requires pre-existing
ContextForge user (no auto-creation).

Signed-off-by: kimsehwan96 <[email protected]>

* test(e2e): add OAuth JWKS verification e2e tests with Keycloak

Add end-to-end tests for the OAuth access token verification via JWKS
feature on virtual server MCP endpoints. Tests run against a real
ContextForge + Keycloak docker-compose stack and cover:

- Valid Keycloak JWT accepted on oauth_enabled server
- Non-OAuth server rejects IdP JWT (feature disabled deny-path)
- Wrong issuer rejected (issuer allowlist deny-path)
- Invalid/garbage token rejected (unauthenticated deny-path)
- Unregistered user rejected (user not in CF DB deny-path)

Requires: docker compose --profile sso up -d

Signed-off-by: kimsehwan96 <[email protected]>

* fix(auth): harden OAuth access token verification against replay and bypass

Follow-up security hardening on top of the OAuth/JWKS verification feature
for virtual server MCP endpoints. Closes multiple replay and bypass paths
surfaced across several review rounds, and extends test coverage to lock
the resulting invariants.

Audience binding (RFC 8707/9728):
- Always enforce a non-empty expected_audience containing the canonical MCP
  resource URL; callers no longer pass None when oauth_config.client_id is
  absent.
- Derive the resource URL from settings.app_domain, not the caller-controlled
  Host / X-Forwarded-Host headers. Operators must set app_domain to the
  gateway's public URL; the helper fails closed (401) when it is empty.
- oauth_config.resource (scalar or list) and legacy client_id extend the
  expected-audience list rather than replacing the resource URL.

OIDC ID token rejection:
- verify_oauth_access_token now rejects tokens carrying nonce or at_hash
  claims before the JWKS signing-key lookup, so a front-channel OIDC ID
  token obtained via SSO cannot be replayed as an MCP bearer token on a
  server configured with a matching client_id in aud.

Routing and fall-through:
- OAuth dispatch in _route_idp_issued_token is independent of the
  JWT_ISSUER_VERIFICATION toggle; that setting only governs how internal
  ContextForge JWTs are checked.
- _try_oauth_access_token decodes the token once (threaded from the
  router) and returns NOT_APPLICABLE when the issuer is missing or outside
  the server's allowlist, so legacy gateway JWTs whose iss predates
  settings.jwt_issuer still flow to verify_credentials when issuer
  verification is disabled.
- oauth_enabled=True with empty oauth_config or empty authorization_servers
  fails closed with 503 instead of falling through to internal
  verification — no internal JWT can reach an advertised-OAuth resource.

Discovery:
- _discover_oidc_metadata probes both the RFC 8414 OAuth authorization
  server metadata URL and the OIDC discovery URL. Non-OIDC OAuth servers
  are no longer blackholed by a single OIDC probe failure.
- Negative caching distinguishes transient failures (network errors,
  5xx, 408, 429; cached 5s) from permanent failures (404, malformed
  JSON; cached 30s) so a brief IdP restart does not blackhole every
  virtual server sharing that issuer.

Observability:
- New oauth_verify_events_counter with success / failed / not_applicable /
  error outcomes. _route_idp_issued_token emits the error label on
  unhandled exceptions before re-raising.
- Allowlist-deferral, successful verification, and undecodable-token
  paths log at DEBUG/INFO with sanitized server_id and issuer so auth
  floods do not pollute WARN-level observability.
- _build_public_base_url narrows its exception catch and logs malformed
  ASGI scopes at WARNING with request path and client tuple.

Tests:
- 14 new regression tests across TestOAuthAudienceEnforcement,
  TestLegacyJwtOnOauthEnabledServer, TestOAuthServerMisconfigurationRejected,
  TestRouteIdpIssuedToken, and TestVerifyOauthAccessToken.
- Invariants locked: audience binding to app_domain, forwarded-host
  header rejection (parametrized over Host / X-Forwarded-Host / Forwarded
  / X-Original-Host), ID-token rejection ordering (asserting the JWKS
  client is never consulted), RFC 8414 + OIDC dual-probe outcomes,
  OAuth routing decoupled from JWT_ISSUER_VERIFICATION, metrics counter
  labels, non-string iss handling, list-audience any-of semantics.

730 unit tests passing.

Signed-off-by: Jonathan Springer <[email protected]>

* security(auth): SSRF defense, issuer verification, log hardening, and coverage

Final security hardening pass plus coverage for all new OAuth/JWKS
error branches. Addresses three findings from an independent pre-merge
audit and raises test coverage to 99%/97% on the two changed files.

SSRF defense-in-depth:
- _resolve_authorization_servers rejects non-HTTPS issuer URLs with a
  logged warning.
- verify_oauth_access_token validates that jwks_uri shares the issuer's
  scheme (https) and origin (netloc).
- _discover_oidc_metadata validates the metadata issuer field against
  the expected issuer per RFC 8414 section 3.3.

Post-decode issuer re-verification:
- After signature verification, the verified payload's iss claim is
  re-checked against the normalized issuer used for JWKS resolution,
  with trailing-slash normalization.

Log-injection hardening:
- All logger calls in verify_oauth_access_token that interpolate the
  issuer URL or jwks_uri now pass through sanitize_for_log().

Coverage (18 new tests):
- TestTryOauthAccessTokenErrorBranches: missing server_id, DB error,
  disabled server, empty oauth_config, missing email, unregistered user,
  inactive user, team-resolution exception, full SUCCESS path.
- TestBuildServerResourceUrlAppDomainError: app_domain __str__ raises.
- TestAuthJwtRoutingReturn: _auth_jwt returns routed True/False.
- TestVerifyOauthAccessToken extensions: cache-expiry pop, transient
  probe failure, invalid JSON, non-dict metadata, missing jwks_uri,
  PyJWKClient lazy construction.

748 unit tests passing.

Signed-off-by: Jonathan Springer <[email protected]>

---------

Signed-off-by: kimsehwan96 <[email protected]>
Signed-off-by: Jonathan Springer <[email protected]>
Co-authored-by: Jonathan Springer <[email protected]>
msureshkumar88 pushed a commit that referenced this pull request May 13, 2026
#3715)

* feat(auth): verify OAuth access tokens via JWKS for virtual server MCP endpoints

Add OAuth access token verification for virtual servers with
oauth_enabled=True (RFC 9728). Routes to ContextForge-issued or
IdP-issued verification based on token issuer claim. IdP-issued
tokens are verified via OIDC discovery + JWKS. Validates audience
when oauth_config.client_id is configured. Requires pre-existing
ContextForge user (no auto-creation).

Signed-off-by: kimsehwan96 <[email protected]>

* test(e2e): add OAuth JWKS verification e2e tests with Keycloak

Add end-to-end tests for the OAuth access token verification via JWKS
feature on virtual server MCP endpoints. Tests run against a real
ContextForge + Keycloak docker-compose stack and cover:

- Valid Keycloak JWT accepted on oauth_enabled server
- Non-OAuth server rejects IdP JWT (feature disabled deny-path)
- Wrong issuer rejected (issuer allowlist deny-path)
- Invalid/garbage token rejected (unauthenticated deny-path)
- Unregistered user rejected (user not in CF DB deny-path)

Requires: docker compose --profile sso up -d

Signed-off-by: kimsehwan96 <[email protected]>

* fix(auth): harden OAuth access token verification against replay and bypass

Follow-up security hardening on top of the OAuth/JWKS verification feature
for virtual server MCP endpoints. Closes multiple replay and bypass paths
surfaced across several review rounds, and extends test coverage to lock
the resulting invariants.

Audience binding (RFC 8707/9728):
- Always enforce a non-empty expected_audience containing the canonical MCP
  resource URL; callers no longer pass None when oauth_config.client_id is
  absent.
- Derive the resource URL from settings.app_domain, not the caller-controlled
  Host / X-Forwarded-Host headers. Operators must set app_domain to the
  gateway's public URL; the helper fails closed (401) when it is empty.
- oauth_config.resource (scalar or list) and legacy client_id extend the
  expected-audience list rather than replacing the resource URL.

OIDC ID token rejection:
- verify_oauth_access_token now rejects tokens carrying nonce or at_hash
  claims before the JWKS signing-key lookup, so a front-channel OIDC ID
  token obtained via SSO cannot be replayed as an MCP bearer token on a
  server configured with a matching client_id in aud.

Routing and fall-through:
- OAuth dispatch in _route_idp_issued_token is independent of the
  JWT_ISSUER_VERIFICATION toggle; that setting only governs how internal
  ContextForge JWTs are checked.
- _try_oauth_access_token decodes the token once (threaded from the
  router) and returns NOT_APPLICABLE when the issuer is missing or outside
  the server's allowlist, so legacy gateway JWTs whose iss predates
  settings.jwt_issuer still flow to verify_credentials when issuer
  verification is disabled.
- oauth_enabled=True with empty oauth_config or empty authorization_servers
  fails closed with 503 instead of falling through to internal
  verification — no internal JWT can reach an advertised-OAuth resource.

Discovery:
- _discover_oidc_metadata probes both the RFC 8414 OAuth authorization
  server metadata URL and the OIDC discovery URL. Non-OIDC OAuth servers
  are no longer blackholed by a single OIDC probe failure.
- Negative caching distinguishes transient failures (network errors,
  5xx, 408, 429; cached 5s) from permanent failures (404, malformed
  JSON; cached 30s) so a brief IdP restart does not blackhole every
  virtual server sharing that issuer.

Observability:
- New oauth_verify_events_counter with success / failed / not_applicable /
  error outcomes. _route_idp_issued_token emits the error label on
  unhandled exceptions before re-raising.
- Allowlist-deferral, successful verification, and undecodable-token
  paths log at DEBUG/INFO with sanitized server_id and issuer so auth
  floods do not pollute WARN-level observability.
- _build_public_base_url narrows its exception catch and logs malformed
  ASGI scopes at WARNING with request path and client tuple.

Tests:
- 14 new regression tests across TestOAuthAudienceEnforcement,
  TestLegacyJwtOnOauthEnabledServer, TestOAuthServerMisconfigurationRejected,
  TestRouteIdpIssuedToken, and TestVerifyOauthAccessToken.
- Invariants locked: audience binding to app_domain, forwarded-host
  header rejection (parametrized over Host / X-Forwarded-Host / Forwarded
  / X-Original-Host), ID-token rejection ordering (asserting the JWKS
  client is never consulted), RFC 8414 + OIDC dual-probe outcomes,
  OAuth routing decoupled from JWT_ISSUER_VERIFICATION, metrics counter
  labels, non-string iss handling, list-audience any-of semantics.

730 unit tests passing.

Signed-off-by: Jonathan Springer <[email protected]>

* security(auth): SSRF defense, issuer verification, log hardening, and coverage

Final security hardening pass plus coverage for all new OAuth/JWKS
error branches. Addresses three findings from an independent pre-merge
audit and raises test coverage to 99%/97% on the two changed files.

SSRF defense-in-depth:
- _resolve_authorization_servers rejects non-HTTPS issuer URLs with a
  logged warning.
- verify_oauth_access_token validates that jwks_uri shares the issuer's
  scheme (https) and origin (netloc).
- _discover_oidc_metadata validates the metadata issuer field against
  the expected issuer per RFC 8414 section 3.3.

Post-decode issuer re-verification:
- After signature verification, the verified payload's iss claim is
  re-checked against the normalized issuer used for JWKS resolution,
  with trailing-slash normalization.

Log-injection hardening:
- All logger calls in verify_oauth_access_token that interpolate the
  issuer URL or jwks_uri now pass through sanitize_for_log().

Coverage (18 new tests):
- TestTryOauthAccessTokenErrorBranches: missing server_id, DB error,
  disabled server, empty oauth_config, missing email, unregistered user,
  inactive user, team-resolution exception, full SUCCESS path.
- TestBuildServerResourceUrlAppDomainError: app_domain __str__ raises.
- TestAuthJwtRoutingReturn: _auth_jwt returns routed True/False.
- TestVerifyOauthAccessToken extensions: cache-expiry pop, transient
  probe failure, invalid JSON, non-dict metadata, missing jwks_uri,
  PyJWKClient lazy construction.

748 unit tests passing.

Signed-off-by: Jonathan Springer <[email protected]>

---------

Signed-off-by: kimsehwan96 <[email protected]>
Signed-off-by: Jonathan Springer <[email protected]>
Co-authored-by: Jonathan Springer <[email protected]>
brian-hussey pushed a commit to brian-hussey/mcp-context-forge that referenced this pull request Oct 20, 2026
…C, tests

Review fixes for the OAuth access token verification feature (IBM#3715):

Security:
- Validate issuer URL and discovered jwks_uri against SSRF protections
  before outbound fetches (validate_core_url on both paths)
- Validate discovered metadata issuer matches queried issuer (RFC 8414 §3.3)
- Persist oauth_client_id from admin UI into oauth_config for audience
  validation; log warning when audience check is skipped

Correctness:
- Fall through to verify_credentials on jwt.DecodeError instead of
  early-rejecting (fixes 7 broken existing tests)
- Wrap _get_user_by_email_sync and _resolve_teams_from_db in try/except
  returning 503 on DB failures (parity with _auth_jwt path)
- Distinguish infra failures (503) from auth failures (401) via
  OAUTH_VERIFY_UNAVAILABLE sentinel in verify_oauth_access_token
- Fix internal MCP RPC RBAC to enable check_any_team for
  oauth_access_token (non-admin team-scoped users were denied)
- Add auth_method and set_trace_context_from_teams for observability
- Add TOOLS_MANAGE_PLUGINS to Permissions class (fixes team_admin
  bootstrap failure from IBM#4068, see IBM#4085)
- Fix DAR101 flake8 docstring issue in observability.py

Tests:
- 30+ new unit tests covering _auth_jwt OAuth routing,
  _try_oauth_access_token branches, verify_oauth_access_token edge
  cases, SSRF rejection, issuer mismatch, 503 vs 401 classification,
  DB error handling, and trace context

Signed-off-by: Mihai Criveti <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request mcp-protocol Alignment with MCP protocol or specification MUST P1: Non-negotiable, critical requirements without which the product is non-functional or unsafe security Improves security

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants