Repository navigation
feat(auth): verify OAuth access tokens via JWKS for virtual server MCP - #3715
Conversation
|
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. |
Tested and confirmed working ✅I applied this PR as a patch on top of Test setup
Results
Patch methodFROM 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.pyThis 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! 🚀 |
|
Works for my case with Okta. Apart from the above mentioned changes, the only patches/updates I need to make is:
This works for grant_types authorization_code & refresh_token. Not sure if it works for client credential flow but good work @kimsehwan96 |
|
Had to merge this into a custom build, but works great (small tweak for latest codebase). Looking forward to seeing it merged. |
e7bcc0c to
131eb72
Compare
|
Rebased onto latest main and applied the following updates:
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.
Notable issues encountered during e2e setup:
|
aef0e41 to
9a30860
Compare
|
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. ❌ Ref: #3535 |
…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]>
Maintainer review — changes appliedRebased onto main and applied the following fixes during review: Security hardening
Correctness
Observability
Other fixes (pre-existing, not from this PR)
Tests
|
crivetimihai
left a comment
There was a problem hiding this comment.
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.
…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]>
|
ADFS is not connecting, pls find the logs below Scenario 1: Cursor Log: Correct OAuth discovery endpoints : https://adfs.ds.*****.net/adfs/.well-known/openid-configuration Scenario 2: Authorization Server URL: https://adfs.ds.*****.net/adfs/oauth2/authorize 2026-04-09 22:02:13.843 [info] [V2] Handling CreateClient action ===== curl -i https://adfs.ds.*****.net/adfs/.well-known/openid-configuration |
User Stories Coverage Analysis: PR #3715 vs Issue #2659Analysis Date: 2026-04-09 Executive SummaryPR #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 MappingStatus: 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 permissionsWhat PR #3715 Implements:
Coverage: 0% - Different token type, different use case ❌ US-2: Platform Admin - Extract Keycloak Realm RolesStatus: 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 membershipWhat PR #3715 Implements:
Coverage: 0% - Different token type, no claims extraction
|
| 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_tokenverification during SSO callback - ✅ Claims Extraction: Groups, roles, custom claims from Entra ID/Keycloak
- ✅ Role Mapping: Automatic RBAC assignment from IdP groups
- ✅ Database Schema:
jwks_uricolumn onSSOProvider - ✅ Configuration:
SSO_REQUIRE_TOKEN_VERIFICATION, cache TTL settings
What PR #3715 Implements (NOT in Issue)
- ✅ Token Type:
access_tokenverification 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_enabledandauthorization_serverson 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.
|
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:
Would that work for you? |
9a30860 to
f3f4fba
Compare
|
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, |
abcb0e0 to
10945a7
Compare
…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]>
10945a7 to
8c314ad
Compare
#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]>
#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]>
…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]>
🔗 Related Issue
Partially addresses #2659
📝 Summary
Virtual servers with
oauth_enabled=Trueadvertise 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" becauseverify_credentials()only validates ContextForge-issued JWTs (iss: "mcpgateway").This PR adds IdP-issued OAuth access token verification via OIDC discovery + JWKS:
issclaim before verification. ContextForge-issued tokens (iss == settings.jwt_issuer) go through the existing path; IdP-issued tokens are routed to JWKS-based verification./.well-known/openid-configurationfrom the token's issuer, resolvesjwks_uri, and verifies the signature using the IdP's public keys. Metadata is cached (300s TTL).oauth_config.authorization_serversdetermines which issuers are trusted. Server A (Authentik) and Server B (Keycloak) are fully independent.oauth_config.client_idis configured, the token'saudclaim is validated. When not configured, audience check is skipped (opt-in).🏷️ Type of Change
🧪 Verification
make lintmake testmake coverage✅ Checklist
make black isort pre-commit)📓 Notes (optional)
sso_service.pyhas 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