mcp-context-forge icon indicating copy to clipboard operation
mcp-context-forge copied to clipboard

[BUG]: OAuth token issuer validation blocks tool fetch when the MCP server is its own authorization server but issues tokens signed by an upstream IdP (iss differs from AS issuer)

Open EimantasPelikis opened this issue 1 month ago β€’ 1 comments

🐞 Bug Summary

For an MCP server that acts as its own OAuth authorization server (AS) but issues access tokens signed by an upstream IdP, the OAuth flow (DCR, authorization, code exchange) succeeds, but POST /oauth/fetch-tools/{gateway_id} fails with HTTP 400:

Refusing to forward OAuth token for gateway 'IBM Carbon Design System':
Token issuer mismatch: token iss='https://login.ibm.com/oidc/endpoint/default',
expected 'https://mcp.carbondesignsystem.com'.
Fix oauth_config (resource/scopes/issuer) or the IdP token request.

oauth_config.issuer is used for two different purposes that need different values here:

  1. AS issuer (DCR, endpoint discovery, registered_oauth_clients lookup): https://mcp.carbondesignsystem.com
  2. Expected token iss (validate_oauth_token_claims, callback audience pinning): https://login.ibm.com/oidc/endpoint/default

There is no way to configure them independently. Setting issuer to the token issuer makes validation pass but retargets DCR/discovery to the wrong server and orphans the existing client registration. Clearing issuer falls back to the token_url host, which is still the AS and still mismatches.


🧩 Affected Component

  • [x] mcpgateway - API
  • [x] mcpgateway - UI (admin panel)
  • [ ] Federation or Transports
  • [ ] CLI, Makefiles, or shell scripts
  • [ ] Container setup (Docker/Podman/Compose)
  • [ ] Other (explain below)

πŸ” Steps to Reproduce

  1. Register an MCP gateway with auth_type=oauth, grant_type=authorization_code, URL https://mcp.carbondesignsystem.com/mcp, issuer=https://mcp.carbondesignsystem.com, with no client_id so that DCR runs.
  2. Start the OAuth flow (/oauth/authorize/{gateway_id}). DCR registers a client and the user authenticates. The callback arrives with iss=https://mcp.carbondesignsystem.com (RFC 9207).
  3. POST https://mcp.carbondesignsystem.com/token returns 200. Tokens are stored successfully (/oauth/callback returns 200).
  4. Call POST /oauth/fetch-tools/{gateway_id}.

Result: HTTP 400, "Refusing to forward OAuth token…" (see logs). No tools are fetched.


πŸ€” Expected Behavior

The operator can keep issuer as the AS issuer (for DCR/discovery) and separately declare which iss the issued access tokens carry. Token validation and callback pinning would use that value, so the flow completes and tools are fetched. Strict issuer validation stays on for all other gateways.


πŸ““ Logs / Error Output

WARNING mcpgateway.services.gateway_service: OAuth token validation for gateway IBM Carbon Design System: Token audience mismatch: token aud does not match expected resource or gateway URL
WARNING mcpgateway.services.gateway_service: OAuth token validation for gateway IBM Carbon Design System: Token issuer mismatch: token iss='https://login.ibm.com/oidc/endpoint/default', expected 'https://mcp.carbondesignsystem.com'
ERROR   mcpgateway.services.gateway_service: GatewayConnectionError during OAuth fetch for <gateway_id>: Refusing to forward OAuth token for gateway 'IBM Carbon Design System': Token issuer mismatch: token iss='https://login.ibm.com/oidc/endpoint/default', expected 'https://mcp.carbondesignsystem.com'. Fix oauth_config (resource/scopes/issuer) or the IdP token request.
ERROR   mcpgateway.routers.oauth_router: FETCH-TOOLS FAILED [GatewayConnectionError] gateway=<gateway_id> error=Failed to fetch tools after OAuth: ...
INFO    mcpgateway.services.structured_logger: [http_gateway] Request completed: POST /oauth/fetch-tools/<gateway_id> - 400

Earlier, during the successful callback:

INFO  mcpgateway.services.oauth_manager: Successfully exchanged authorization code for tokens
DEBUG mcpgateway.services.oauth_manager: Skipping learned audience persistence for gateway <gateway_id>: token iss does not match configured issuer

Traceback origin (abridged):

mcpgateway/services/gateway_service.py, fetch_tools_after_oauth:
    raise GatewayConnectionError(f"Refusing to forward OAuth token for gateway '{gateway.name}': {detail}. ...")

🧠 Environment Info

Key Value
Version or commit v1.1.0 (also reproduced on v1.0.10; code path unchanged)
Runtime Python 3.x, uvicorn (local dev)
Platform / OS macOS (arm64)
Container none
Token storage Vault backend
DB SQLite

🧩 Additional Context (optional)

Root cause (code references)

  • mcpgateway/services/token_validation_service.py
    • _validate_issuer (~L297-321): expected issuer is oauth_config["issuer"], else the host of token_url (_derive_issuer_from_token_url).
    • blocking_errors (~L65-114): issuer_match is False is always blocking. Unlike audience, there is no advisory/"derived" mode.
  • mcpgateway/services/gateway_service.py: both fetch_tools_after_oauth (~L2649) and the authorization-code refresh path (~L7075) raise GatewayConnectionError.
  • mcpgateway/services/oauth_manager.py (~L1288-1305): callback pins the token iss against credentials["issuer"] for learned-audience persistence.
  • mcpgateway/routers/oauth_router.py (~L737) and mcpgateway/services/dcr_service.py (get_or_register_client): DCR runs when issuer is set and client_id is not, keyed by (gateway, issuer).

Why config alone cannot fix it

Attempt Result
issuer = token issuer (login.ibm.com) Validation passes, but DCR/discovery retarget login.ibm.com; existing registration orphaned
Clear issuer Falls back to token_url host (still the AS), still mismatches
OAUTH_REQUIRE_CONFIGURED_RESOURCE Affects audience only

Proposed fix (Option 1)

Add an optional oauth_config key (e.g. token_issuer):

  • _validate_issuer expected value: token_issuer, then issuer, then the token_url host (backward compatible).
  • Same precedence for callback pinning in oauth_manager.py / oauth_router.py.
  • URL validation in schemas.py next to issuer; Admin UI field; unit tests; a section in docs/docs/manage/oauth-troubleshooting.md.

For this gateway: issuer=https://mcp.carbondesignsystem.com, token_issuer=https://login.ibm.com/oidc/endpoint/default.

Alternatives considered

  • Make issuer mismatch advisory (optionally with an opt-in strict setting). Smallest change, but weakens the check for all gateways, and similar PRs (#4214, #4159) were closed unmerged.
  • Learn the token issuer per user (learned_iss, as done for aud). No operator input, but trust-on-first-use and a larger change touching callback, storage and validation.

Related issues / PRs

  • #4213: validation hard-blocks despite "advisory" docs. Amplitude example has the same shape: AS metadata issuer mcp.amplitude.com, token iss auth.amplitude.com. Fix PR #4214 was closed unmerged.
  • #4158: Azure AD v1/v2 issuer/audience false positives. Fix PR #4159 was closed unmerged.
  • #6669: epic "OAuth egress correctness and lifecycle" (Story B, claim-validation correctness).
  • #7333 (open): MCP 2026-07-28 authorization, adds an RFC 9207 callback iss check against the AS metadata issuer. This confirms issuer should remain the AS issuer, which is why a separate token-issuer key is needed rather than repurposing issuer.

EimantasPelikis avatar Oct 28 '26 13:10 EimantasPelikis

Heads up from LLM-assisted investigation of authentication/OAuth work:

PR #7333 (closes #6639) adds another reader of oauth_config.issuer, so it is worth checking how it interacts with this issue before either is merged.

OAuthManager._expected_issuer passes credentials["issuer"] to DcrService.discover_as_metadata() and checks the iss parameter of the authorization response against the issuer in the returned metadata (RFC 9207). If discovery fails, it uses the configured value instead. GatewayService._flag_credentials_kept_across_issuer_change also treats issuer as the authorization server identity: it logs a warning and a security event when issuer changes but a static client_id does not.

These checks require issuer to remain the authorization server issuer, which is purpose 1 in this issue. #7333 therefore does not affect the reproduction: the callback carries iss=https://mcp.carbondesignsystem.com, which matches the configured issuer, and the failure still occurs in _validate_issuer (mcpgateway/services/token_validation_service.py:297) when tools are fetched.

The change is in the cost of the workaround. Setting issuer to the token issuer already changes the target of DCR and endpoint discovery. After #7333, the authorization response check reads the same field, so that edit can also reject the callback before the code is redeemed, with a generic "Authorization response issuer mismatch" error and a HIGH severity oauth_issuer_mismatch security event.

Suggested direction: keep issuer as the authorization server issuer and add a separate field for the expected token iss, read only by _validate_issuer. DCR, endpoint discovery, the registered client lookup, and the new RFC 9207 check then need no changes. Changing issuer instead would require updating each of those call sites.

Migration note: editing issuer while keeping client_id now logs a MEDIUM security event by design, so expect one for any row corrected manually.

#7333 does not depend on this issue and can merge first.

cc @madhu-mohan-jaishankar as #7333's author, for the constraint that a fix here keeps issuer as the authorization server issuer.

a-effort avatar Oct 28 '26 16:10 a-effort