The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(mcp): enforce OAuth identity binding across credential lifetime
Joshua Valluru7c1d060b7af3
diff --git a/litellm/proxy/_experimental/mcp_server/db.py b/litellm/proxy/_experimental/mcp_server/db.pyindex 7379126983a..08f83aeb756 100644--- a/litellm/proxy/_experimental/mcp_server/db.py+++ b/litellm/proxy/_experimental/mcp_server/db.py@@ -6,10 +6,17 @@ from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequencefrom datetime import datetime, timedelta, timezonefrom typing import TYPE_CHECKING, Any, Final, Literal, Protocol, TypedDict, cast+from typing_extensions import ReadOnly+from litellm._logging import verbose_proxy_loggerfrom litellm._uuid import uuidfrom litellm.constants import MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDSfrom litellm.llms.custom_httpx.http_handler import get_async_httpx_client+from litellm.proxy._experimental.mcp_server.oauth_identity_binding import (+ RefreshTokenPresented,+ credential_binding_matches,+ enforce_oauth_identity_binding,+)from litellm.proxy._experimental.mcp_server.oauth_utils import build_upstream_oauth2_token_requestfrom litellm.proxy._types import (LiteLLM_MCPServerTable,@@ -117,6 +124,7 @@ class _OAuthCredentialAccessToken(TypedDict):class OAuthCredentialPayload(_OAuthCredentialAccessToken, total=False):+ identity_binding_proof: ReadOnly[str]type: strrefresh_token: strexpires_at: str@@ -1393,6 +1401,7 @@ async def store_user_oauth_credential(expires_in: int | None = None,scopes: list[str] | None = None,skip_byok_guard: bool = False,+ identity_binding_proof: str | None = None,) -> None:"""Persist an OAuth2 access token for a user+server pair.@@ -1409,6 +1418,7 @@ async def store_user_oauth_credential("type": "oauth2","access_token": access_token,"connected_at": datetime.now(timezone.utc).isoformat(),+ **({"identity_binding_proof": identity_binding_proof} if identity_binding_proof else {}),}if refresh_token:payload["refresh_token"] = refresh_token@@ -1628,6 +1638,11 @@ async def refresh_user_oauth_token(warning and returns ``None`` — the caller is responsible for clearing thestale credential and triggering re-authentication."""+ binding: Final = server.oauth_identity_binding+ if binding is not None and binding.mode == "enforce":+ if not await credential_binding_matches(binding, user_id, server.server_id, cred):+ return None+refresh_token: Final[str | None] = cred.get("refresh_token")token_url: Final[str | None] = getattr(server, "effective_token_url", None) or getattr(server, "token_url", None)server_id: Final[str] = getattr(server, "server_id", "")@@ -1677,6 +1692,14 @@ async def refresh_user_oauth_token()return None+ binding_proof: Final = await enforce_oauth_identity_binding(+ server=server,+ token_response=body,+ litellm_user_id=user_id,+ grant_type="refresh_token",+ refresh_ownership=RefreshTokenPresented(refresh_token),+ )+access_token: Final[str | None] = body.get("access_token")if not access_token:verbose_proxy_logger.warning(@@ -1709,6 +1732,7 @@ async def refresh_user_oauth_token(refresh_token=new_refresh_token,expires_in=expires_in,scopes=scopes,+ identity_binding_proof=binding_proof,skip_byok_guard=True, # Row is already OAuth2; skip the extra find_unique check)@@ -1742,6 +1766,10 @@ async def resolve_valid_user_oauth_token(grant: Final = oauth_grant_state(cred)if cred is None or grant == "absent":return None+ binding: Final = server.oauth_identity_binding+ if binding is not None and binding.mode == "enforce":+ if not await credential_binding_matches(binding, user_id, server.server_id, cred):+ return Noneif grant == "valid":return credif prisma_client is None:@@ -1782,7 +1810,11 @@ async def resolve_user_oauth_access_token(mcp_per_user_token_cache,)- if prefetched_creds is None:+ binding: Final = server.oauth_identity_binding+ enforce_binding: Final = binding is not None and binding.mode == "enforce"+ if enforce_binding:+ await mcp_per_user_token_cache.delete(user_id, server_id)+ if prefetched_creds is None and not enforce_binding:cached_token: Final = await mcp_per_user_token_cache.get(user_id, server_id)if cached_token is not None:return cached_tokendiff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.pyindex 9f6bc1860e1..c8e02be308b 100644--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py@@ -144,6 +144,7 @@ def encode_state_with_base_url(dcr_client_id: str | None = None,dcr_client_secret: str | None = None,dcr_token_endpoint_auth_method: MCPTokenEndpointAuthMethod | None = None,+ oauth_nonce: str | None = None,) -> str:"""Encode the base_url, original state, and PKCE parameters using encryption.@@ -154,9 +155,8 @@ def encode_state_with_base_url(code_challenge: PKCE code challenge from clientcode_challenge_method: PKCE code challenge method from clientclient_redirect_uri: Original redirect_uri from client- litellm_user_id: The SSO-authenticated litellm user captured at the bridge authorize- (interactive dcr_bridge oauth_delegate only); the callback seals it into the gateway- authorization code so the token mint can bind the envelope to this user+ litellm_user_id: The authenticated user captured for bridge or identity-bound per-user OAuth;+ the callback seals this credential owner into the authorization codemcp_server_id: The server the flow targets, sealed alongside litellm_user_id (bridge) ordcr_client_id (ephemeral mint) so the gateway code cannot be replayed against anotherserver@@ -174,6 +174,7 @@ def encode_state_with_base_url(An encrypted string that encodes all values"""state_data: Final = {+ "oauth_nonce": oauth_nonce,"base_url": base_url,"original_state": original_state,"code_challenge": code_challenge,@@ -215,10 +216,10 @@ _BRIDGE_AUTH_CODE_PREFIX: Final = "llm_bcode_"class _BridgeAuthorizationCode(BaseModel):- """The identity and upstream code the gateway seals into the authorization code it hands a DCR- client for an interactive dcr_bridge oauth_delegate sign-in, recovered at the token endpoint."""+ """Authenticated caller and upstream code sealed for bridge or identity-bound per-user OAuth."""model_config = ConfigDict(frozen=True)+ oauth_nonce: str | None = Noneupstream_code: str = Field(min_length=1)litellm_user_id: str = Field(min_length=1)mcp_server_id: str = Field(min_length=1)@@ -230,7 +231,12 @@ def is_bridge_authorization_code(code: str) -> bool:return code.startswith(_BRIDGE_AUTH_CODE_PREFIX)-def seal_bridge_authorization_code(upstream_code: str, litellm_user_id: str, mcp_server_id: str) -> str:+def seal_bridge_authorization_code(+ upstream_code: str,+ litellm_user_id: str,+ mcp_server_id: str,+ oauth_nonce: str | None = None,+) -> str:"""Seal the upstream authorization code and the SSO-captured litellm user into a gatewayauthorization code. The DCR client only echoes this opaque value back at the token endpoint; thegateway decrypts it there to recover the user (to bind the envelope) and the upstream code (to@@ -239,7 +245,12 @@ def seal_bridge_authorization_code(upstream_code: str, litellm_user_id: str, mcpauthenticated symmetric helper (the same family the OAuth state uses), so the client can neitherread nor forge it."""payload: Final = json.dumps(- {"upstream_code": upstream_code, "litellm_user_id": litellm_user_id, "mcp_server_id": mcp_server_id},+ {+ "upstream_code": upstream_code,+ "litellm_user_id": litellm_user_id,+ "mcp_server_id": mcp_server_id,+ "oauth_nonce": oauth_nonce,+ },sort_keys=True,)return _BRIDGE_AUTH_CODE_PREFIX + encrypt_value_helper(payload)@@ -552,6 +563,7 @@ async def _store_per_user_token_server_side(server: MCPServer,user_id: str,token_response: dict[str, Any],+ identity_binding_proof: str | None = None,) -> None:"""Persist the OAuth token server-side and warm the Redis cache.@@ -593,6 +605,7 @@ async def _store_per_user_token_server_side(refresh_token=refresh_token,expires_in=expires_in,scopes=scopes,+ identity_binding_proof=identity_binding_proof,)verbose_logger.info("_store_per_user_token_server_side: stored token for user=%s server=%s",@@ -859,6 +872,11 @@ async def authorize_with_server(),)+ binding: Final = resolved_server.oauth_identity_binding+ enforce_binding: Final = binding is not None and binding.mode == "enforce"+ if enforce_binding:+ _require_s256_pkce(code_challenge, code_challenge_method)+if resolved_server.is_dcr_bridge:# Enforce S256 PKCE on both bridge arms. The relay arm forwards the validated,# now-non-optional pair to the upstream authorize; the short-circuit arm keeps@@ -889,19 +907,16 @@ async def authorize_with_server(base_url: Final = urlunparse(parsed._replace(query=""))request_base_url: Final = get_request_base_url(request)- # Interactive dcr_bridge oauth_delegate sign-in: this arm runs the gateway /callback and /token in- # the loop, so the gateway can capture the litellm user here (from the browser's UI session) and- # carry it to the back-channel token mint. Seal the SSO user and the target server into the state;- # the callback reads them back to mint the gateway authorization code. A DCR client cannot present a- # litellm key, so the browser session is the only identity source; without one there is nothing to- # bind, so send the user through login first. Every other oauth2 server keeps the identity-less state.+ # Seal the authenticated caller into state so the token exchange cannot select another credential owner.litellm_user_id: str | None = None- if resolved_server.is_dcr_bridge and resolved_server.is_oauth_delegate:+ if enforce_binding or (resolved_server.is_dcr_bridge and resolved_server.is_oauth_delegate):from litellm.proxy._experimental.mcp_server.byok_oauth_endpoints import ( # noqa: PLC0415 # inline import avoids a module-load circular import_user_id_from_session_cookie,)- litellm_user_id = _user_id_from_session_cookie(request)+ litellm_user_id = (+ await _extract_user_id_from_request(request) if enforce_binding else None+ ) or _user_id_from_session_cookie(request)if litellm_user_id is None:return _redirect_to_litellm_login(request)denial: Final = await _bridge_authorize_access_denial(@@ -913,9 +928,11 @@ async def authorize_with_server(if denial is not None:return denial+ oauth_nonce: Final = secrets.token_urlsafe(32) if enforce_binding else Noneencoded_state: Final = encode_state_with_base_url(base_url=base_url,original_state=state,+ oauth_nonce=oauth_nonce,code_challenge=code_challenge,code_challenge_method=code_challenge_method,client_redirect_uri=redirect_uri,@@ -935,11 +952,16 @@ async def authorize_with_server("state": relay_state,"response_type": response_type or "code",}+ if oauth_nonce:+ params["nonce"] = oauth_nonceif scope:params["scope"] = scopeelif resolved_server.scopes:params["scope"] = " ".join(resolved_server.scopes)+ if enforce_binding and "openid" not in params.get("scope", "").split():+ params["scope"] = f"openid {params.get('scope', '')}".strip()+if code_challenge:params["code_challenge"] = code_challengeif code_challenge_method:@@ -1020,6 +1042,12 @@ async def exchange_token_with_server(except TokenEndpointAuthConfigError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc+ request_user_id: Final = (+ await _extract_user_id_from_request(request)+ if resolved_server.needs_user_oauth_token or resolved_server.oauth_identity_binding is not None+ else None+ )+bridge_identity: _BridgeAuthorizationCode | None = Nonebridge_mint_ready: _BridgeMintReady | None = Nonebridge_upstream_refresh: SecretStr | None = None@@ -1081,6 +1109,14 @@ async def exchange_token_with_server(detail="Authorization code was issued for a different MCP server",)code = bridge_identity.upstream_code+ binding: Final = resolved_server.oauth_identity_binding+ if binding is not None and binding.mode == "enforce":+ if bridge_identity is None or not bridge_identity.oauth_nonce:+ raise HTTPException(status_code=403, detail={"error": "oauth_identity_binding_failed"})+ if request_user_id is not None and request_user_id != bridge_identity.litellm_user_id:+ raise HTTPException(status_code=403, detail={"error": "oauth_principal_mismatch"})+ if not code_verifier:+ raise HTTPException(status_code=403, detail={"error": "oauth_identity_binding_failed"})bridge_token_relay: Final = _dcr_bridge_relays_client_registration(resolved_server)if bridge_token_relay and not redirect_uri:raise HTTPException(@@ -1108,6 +1144,16 @@ async def exchange_token_with_server(return _bridge_mint_error_response(prepared)bridge_mint_ready = prepared+ refresh_binding: Final = resolved_server.oauth_identity_binding+ if grant_type == "refresh_token" and refresh_binding is not None and refresh_binding.mode == "enforce":+ await enforce_oauth_identity_binding(+ server=resolved_server,+ token_response={},+ litellm_user_id=request_user_id,+ grant_type=grant_type,+ refresh_ownership=refresh_ownership,+ )+async_client: Final = get_async_httpx_client(llm_provider=httpxSpecialProvider.Oauth2Check)try:response: Final = await async_client.post(@@ -1150,19 +1196,19 @@ async def exchange_token_with_server(# Bind the exchanged token to the LiteLLM caller BEFORE it is returned, stored, or cached, so a# token minted for a different upstream principal never becomes usable under the caller's user_id.- resolved_user_id: Final = (- await _extract_user_id_from_request(request)- if resolved_server.needs_user_oauth_token or resolved_server.oauth_identity_binding is not None- else None- )- if isinstance(token_response, dict):+ resolved_user_id: Final = bridge_identity.litellm_user_id if bridge_identity else request_user_id+ binding_proof: Final = (await enforce_oauth_identity_binding(server=resolved_server,token_response=token_response,litellm_user_id=resolved_user_id,grant_type=grant_type,refresh_ownership=refresh_ownership,+ expected_nonce=bridge_identity.oauth_nonce if bridge_identity else None,)+ if isinstance(token_response, dict)+ else None+ )# Store server-side when the server is configured for per-user OAuth and# the calling client has provided a valid LiteLLM identity.@@ -1175,6 +1221,7 @@ async def exchange_token_with_server(server=resolved_server,user_id=user_id,token_response=token_response,+ identity_binding_proof=binding_proof,)except Exception as exc:verbose_logger.warning(@@ -2161,7 +2208,10 @@ async def callback(forwarded_code = codeif isinstance(litellm_user_id, str) and litellm_user_id and isinstance(mcp_server_id, str) and mcp_server_id:forwarded_code = seal_bridge_authorization_code(- upstream_code=code, litellm_user_id=litellm_user_id, mcp_server_id=mcp_server_id+ upstream_code=code,+ litellm_user_id=litellm_user_id,+ mcp_server_id=mcp_server_id,+ oauth_nonce=state_data.get("oauth_nonce"),)elif isinstance(dcr_client_id, str) and dcr_client_id and isinstance(mcp_server_id, str) and mcp_server_id:forwarded_code = seal_passthrough_authorization_code(diff --git a/litellm/proxy/_experimental/mcp_server/oauth_identity_binding.py b/litellm/proxy/_experimental/mcp_server/oauth_identity_binding.pyindex 58ec3cfdb4f..7ca9e6a23df 100644--- a/litellm/proxy/_experimental/mcp_server/oauth_identity_binding.py+++ b/litellm/proxy/_experimental/mcp_server/oauth_identity_binding.py@@ -8,9 +8,12 @@ claim is compared to the caller's trusted LiteLLM identity. Mismatches fail closand are logged in audit mode."""+import hashlib+import hmac+import jsonfrom collections.abc import Awaitable, Callable, Mapping, Sequencefrom dataclasses import dataclass-from typing import Final, Literal, TypeAlias+from typing import Final, Literal, Protocol, TypeAliasimport jwtfrom fastapi import HTTPException@@ -45,9 +48,17 @@ CallerPrincipalLoader: TypeAlias = Callable[[str, MCPOAuthIdentityBinding], # mutable-ok: Callable parameter syntax requires a listAwaitable[str | None],]+++@dataclass(frozen=True, slots=True)+class VerifiedRefreshToken:+ refresh_token: str+ binding_proof: str++StoredRefreshTokenLoader: TypeAlias = Callable[- [str, str], # mutable-ok: Callable parameter syntax requires a list- Awaitable[str | None],+ [str, str, MCPOAuthIdentityBinding], # mutable-ok: Callable parameter syntax requires a list+ Awaitable[VerifiedRefreshToken | None],]_RejectionCode: TypeAlias = Literal["oauth_principal_mismatch", "oauth_identity_binding_failed"]@@ -72,6 +83,18 @@ class RefreshTokenPresented:RefreshOwnership: TypeAlias = RefreshOwnershipProven | RefreshTokenPresented | None+class BindingValidator(Protocol):+ async def __call__(+ self,+ *,+ server: MCPServer,+ token_response: Mapping[str, object],+ litellm_user_id: str | None,+ grant_type: str,+ refresh_ownership: RefreshOwnership,+ ) -> str | None: ...++async def _fetch_issuer_jwks(binding: MCPOAuthIdentityBinding) -> Sequence[Mapping[str, object]]:jwks_url: Final[str] = binding.jwks_url or await _discover_jwks_url(binding.issuer)cached: Final = await _jwks_cache.async_get_cache(jwks_url)@@ -118,7 +141,7 @@ def _decode_id_token(signing_key: "jwt.PyJWK",) -> "Mapping[str, object] | _BindingRejection":try:- decode_options: Final[Options] = {"require": ("iss", "exp")}+ decode_options: Final[Options] = {"require": ("iss", "exp", "aud", "sub", "iat")}return jwt.decode(id_token,signing_key.key,@@ -169,7 +192,9 @@ async def _load_caller_principal(litellm_user_id: str, binding: MCPOAuthIdentityreturn loaded.user_email-async def _load_stored_refresh_token(litellm_user_id: str, server_id: str) -> str | None:+async def _load_stored_refresh_token(+ litellm_user_id: str, server_id: str, binding: MCPOAuthIdentityBinding+) -> VerifiedRefreshToken | None:try:from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 # keep database imports lazyget_user_oauth_credential,@@ -184,17 +209,89 @@ async def _load_stored_refresh_token(litellm_user_id: str, server_id: str) -> stuser_id=litellm_user_id,server_id=server_id,)- return cred.get("refresh_token") if cred else None+ if not cred or not await credential_binding_matches(binding, litellm_user_id, server_id, cred):+ return None+ refresh_token: Final = cred.get("refresh_token")+ proof: Final = cred.get("identity_binding_proof")+ return VerifiedRefreshToken(refresh_token, proof) if refresh_token and proof else Noneexcept Exception: # noqa: BLE001 # a credential lookup failure must fail closedreturn None+async def current_binding_proof(+ binding: MCPOAuthIdentityBinding,+ user_id: str,+ server_id: str,+ caller_principal_loader: CallerPrincipalLoader = _load_caller_principal,+) -> str | None:+ principal: Final = await caller_principal_loader(user_id, binding)+ if not principal:+ return None+ return _binding_proof(binding, user_id, server_id, principal)+++def _binding_proof(binding: MCPOAuthIdentityBinding, user_id: str, server_id: str, principal: str) -> str:+ payload: Final = json.dumps(+ ("oidc-nonce-v1", server_id, user_id, principal, binding.model_dump(mode="json")),+ sort_keys=True,+ )+ return hashlib.sha256(payload.encode()).hexdigest()+++async def credential_binding_matches(+ binding: MCPOAuthIdentityBinding,+ user_id: str,+ server_id: str,+ credential: Mapping[str, object],+ caller_principal_loader: CallerPrincipalLoader = _load_caller_principal,+) -> bool:+ stored: Final = credential.get("identity_binding_proof")+ if not isinstance(stored, str) or not stored:+ return False+ expected: Final = await current_binding_proof(binding, user_id, server_id, caller_principal_loader)+ return expected is not None and hmac.compare_digest(stored, expected)++def _principals_match(upstream: str, caller: str, binding: MCPOAuthIdentityBinding) -> bool:if binding.principal_claim == "email" or binding.caller_field == "user_email":return upstream.strip().casefold() == caller.strip().casefold()return upstream == caller+async def _evaluate_refresh_ownership(+ binding: MCPOAuthIdentityBinding,+ litellm_user_id: str | None,+ server_id: str,+ refresh_ownership: RefreshOwnership,+ stored_refresh_token_loader: StoredRefreshTokenLoader,+) -> _BindingRejection | str:+ match refresh_ownership:+ case RefreshOwnershipProven():+ return _BindingRejection(+ code="oauth_identity_binding_failed",+ description="an identity envelope alone does not prove upstream principal binding",+ )+ case None:+ return _BindingRejection(+ code="oauth_identity_binding_failed",+ description="refresh_token grant without an id_token carries no refresh token to prove ownership of",+ )+ case RefreshTokenPresented(refresh_token):+ if not litellm_user_id:+ return _BindingRejection(+ code="oauth_identity_binding_failed",+ description="the request carries no resolvable LiteLLM user identity to bind the credential to",+ )+ stored: Final = await stored_refresh_token_loader(litellm_user_id, server_id, binding)+ if stored is None or not hmac.compare_digest(stored.refresh_token, refresh_token):+ return _BindingRejection(+ code="oauth_identity_binding_failed",+ description="the presented refresh_token is not the caller's stored credential for this server",+ )+ return stored.binding_proof+ assert_never(refresh_ownership) # pragma: no cover++async def _evaluate_binding(binding: MCPOAuthIdentityBinding,token_response: Mapping[str, object],@@ -205,7 +302,8 @@ async def _evaluate_binding(jwks_fetcher: JwksFetcher,caller_principal_loader: CallerPrincipalLoader,stored_refresh_token_loader: StoredRefreshTokenLoader,-) -> _BindingRejection | None:+ expected_nonce: str | None,+) -> _BindingRejection | str:id_token: Final = token_response.get("id_token")if not isinstance(id_token, str) or not id_token:if grant_type != "refresh_token":@@ -213,28 +311,13 @@ async def _evaluate_binding(code="oauth_identity_binding_failed",description="the upstream token response carries no id_token to bind the credential to a principal",)- match refresh_ownership:- case RefreshOwnershipProven():- return None- case None:- return _BindingRejection(- code="oauth_identity_binding_failed",- description="refresh_token grant without an id_token carries no refresh token to prove ownership of",- )- case RefreshTokenPresented(refresh_token):- if not litellm_user_id:- return _BindingRejection(- code="oauth_identity_binding_failed",- description="the request carries no resolvable LiteLLM user identity to bind the credential to",- )- stored: Final = await stored_refresh_token_loader(litellm_user_id, server_id)- if stored is None or stored != refresh_token:- return _BindingRejection(- code="oauth_identity_binding_failed",- description="the presented refresh_token is not the caller's stored credential for this server",- )- return None- assert_never(refresh_ownership) # pragma: no cover+ return await _evaluate_refresh_ownership(+ binding,+ litellm_user_id,+ server_id,+ refresh_ownership,+ stored_refresh_token_loader,+ )if not litellm_user_id:return _BindingRejection(code="oauth_identity_binding_failed",@@ -247,12 +330,25 @@ async def _evaluate_binding(code="oauth_identity_binding_failed",description=f"could not fetch the issuer's JWKS: {exc}",)- signing_key: Final = _select_signing_key(id_token, keys)+ try:+ signing_key: Final = _select_signing_key(id_token, keys)+ except (jwt.PyJWTError, ValueError, TypeError):+ return _BindingRejection(+ code="oauth_identity_binding_failed",+ description="invalid id_token header or issuer signing key",+ )if isinstance(signing_key, _BindingRejection):return signing_keyclaims: Final = _decode_id_token(id_token, binding, signing_key)if isinstance(claims, _BindingRejection):return claims+ if grant_type == "authorization_code":+ nonce: Final = claims.get("nonce")+ if not expected_nonce or not isinstance(nonce, str) or not hmac.compare_digest(nonce, expected_nonce):+ return _BindingRejection(+ code="oauth_identity_binding_failed",+ description="id_token nonce does not match the authenticated authorization transaction",+ )upstream: Final = _upstream_principal(claims, binding)if isinstance(upstream, _BindingRejection):return upstream@@ -267,7 +363,7 @@ async def _evaluate_binding(code="oauth_principal_mismatch",description="The browser account does not match the selected credential owner.",)- return None+ return _binding_proof(binding, litellm_user_id, server_id, caller)async def enforce_oauth_identity_binding(@@ -279,16 +375,17 @@ async def enforce_oauth_identity_binding(jwks_fetcher: JwksFetcher = _fetch_issuer_jwks,caller_principal_loader: CallerPrincipalLoader = _load_caller_principal,stored_refresh_token_loader: StoredRefreshTokenLoader = _load_stored_refresh_token,-) -> None:+ expected_nonce: str | None = None,+) -> str | None:"""Validate the exchanged token's upstream principal against the LiteLLM caller.No-op when the server has no binding or it is disabled. In enforce mode a failure raises 403before the caller returns, stores, or caches the token; in audit mode failures are logged only.A refresh_token grant without an id_token is allowed only when the presented refresh token matches- the caller's stored credential or a sealed bridge envelope already proved ownership.+ the caller's stored credential and that credential was previously identity-validated."""binding: Final = server.oauth_identity_binding- if binding is None or binding.mode == "disabled":+ if binding is None or binding.mode not in ("audit", "enforce"):returnrejection: Final = await _evaluate_binding(binding=binding,@@ -300,9 +397,10 @@ async def enforce_oauth_identity_binding(jwks_fetcher=jwks_fetcher,caller_principal_loader=caller_principal_loader,stored_refresh_token_loader=stored_refresh_token_loader,+ expected_nonce=expected_nonce,)- if rejection is None:- return+ if isinstance(rejection, str):+ return rejection if binding.mode == "enforce" else Noneif binding.mode == "audit":verbose_logger.warning("oauth_identity_binding audit: server=%s user=%s grant=%s rejected=%s (%s)",diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/authz_code_refresher.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/authz_code_refresher.pyindex 92bd30694af..824459fd9b9 100644--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/authz_code_refresher.py+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/authz_code_refresher.py@@ -18,6 +18,11 @@ from litellm._logging import verbose_loggerfrom litellm.proxy._experimental.mcp_server.auth.token_endpoint_auth import (TokenEndpointAuthConfigError,)+from litellm.proxy._experimental.mcp_server.oauth_identity_binding import (+ BindingValidator,+ RefreshTokenPresented,+ enforce_oauth_identity_binding,+)from litellm.proxy._experimental.mcp_server.oauth_utils import build_upstream_oauth2_token_requestfrom litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import (OAuthToken,@@ -39,6 +44,7 @@ class CredentialPersist(Protocol):refresh_token: str | None,expires_in: int | None,scopes: tuple[str, ...] | None,+ identity_binding_proof: str | None = None,) -> None: ...@@ -78,11 +84,13 @@ class AuthorizationCodeRefresher:persist: CredentialPersist,*,clock: Callable[[], float] = time.time,+ identity_validator: BindingValidator = enforce_oauth_identity_binding,) -> None:self._server_lookup = server_lookupself._token_endpoint = token_endpointself._persist = persistself._clock = clock+ self._identity_validator = identity_validatorasync def refresh(self, user_id: str, server_id: str, token: OAuthToken) -> OAuthToken | None:if token.refresh_token is None:@@ -104,6 +112,15 @@ class AuthorizationCodeRefresher:except TokenEndpointAuthConfigError as exc:verbose_logger.warning("MCP OAuth refresh misconfigured for server %s: %s", server_id, exc)return None+ binding: Final = server.oauth_identity_binding+ if binding is not None and binding.mode == "enforce":+ await self._identity_validator(+ server=server,+ token_response={},+ litellm_user_id=user_id,+ grant_type="refresh_token",+ refresh_ownership=RefreshTokenPresented(token.refresh_token),+ )form: Final = {"grant_type": "refresh_token","refresh_token": token.refresh_token,@@ -116,12 +133,30 @@ class AuthorizationCodeRefresher:if not isinstance(access_token, str) or not access_token:return None+ binding_proof: Final = await self._identity_validator(+ server=server,+ token_response=body,+ litellm_user_id=user_id,+ grant_type="refresh_token",+ refresh_ownership=RefreshTokenPresented(token.refresh_token),+ )rotated: Final = body.get("refresh_token")new_refresh: Final = rotated if isinstance(rotated, str) and rotated else token.refresh_tokenexpires_in: Final = _parse_expires_in(body.get("expires_in"))scopes: Final = _parse_scopes(body.get("scope")) or token.scopes- await self._persist(user_id, server_id, access_token, new_refresh, expires_in, scopes or None)+ if binding_proof is not None:+ await self._persist(+ user_id,+ server_id,+ access_token,+ new_refresh,+ expires_in,+ scopes or None,+ identity_binding_proof=binding_proof,+ )+ else:+ await self._persist(user_id, server_id, access_token, new_refresh, expires_in, scopes or None)return OAuthToken(access_token=access_token,expires_at=self._clock() + expires_in if expires_in is not None else None,diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/per_user_oauth_store.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/per_user_oauth_store.pyindex 5e28396dcfb..efcc613c539 100644--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/per_user_oauth_store.py+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/per_user_oauth_store.py@@ -15,6 +15,7 @@ from collections.abc import Callable, Mappingfrom typing import TYPE_CHECKING, Finalfrom litellm._logging import verbose_logger+from litellm.proxy._experimental.mcp_server.oauth_identity_binding import credential_binding_matchesfrom litellm.proxy._experimental.mcp_server.outbound_credentials.authz_code_refresher import (AuthorizationCodeRefresher,)@@ -38,6 +39,7 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.token_cache_codOAuthTokenCacheCodec,)from litellm.proxy._experimental.mcp_server.outbound_credentials.v2_token_store import (+ CredentialReader,V2PerUserTokenStore,)@@ -69,6 +71,7 @@ async def _persist_credential(refresh_token: str | None,expires_in: int | None,scopes: tuple[str, ...] | None,+ identity_binding_proof: str | None = None,) -> None:from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415store_user_oauth_credential,@@ -86,6 +89,7 @@ async def _persist_credential(expires_in=expires_in,scopes=list(scopes) if scopes else None,skip_byok_guard=True,+ identity_binding_proof=identity_binding_proof,)@@ -172,8 +176,10 @@ class LazyPerUserOAuthTokenStore:*,store_builder: StoreBuilder = _build_per_user_oauth_token_store,redis_available: Callable[[], bool] = _redis_cache_is_available,+ credential_reader: CredentialReader = _read_credential,) -> None:self._server_lookup = server_lookup+ self._credential_reader = credential_readerself._store_builder = store_builderself._redis_available = redis_availableself._store: InvalidatableOAuthTokenStore | None = None@@ -182,6 +188,13 @@ class LazyPerUserOAuthTokenStore:self._local_fetches = 0async def fetch(self, user_id: str, server_id: str) -> OAuthToken | None:+ server: Final = self._server_lookup(server_id)+ binding: Final = server.oauth_identity_binding if server else None+ if binding is not None and binding.mode == "enforce":+ credential: Final = await self._credential_reader(user_id, server_id)+ await self.invalidate(user_id, server_id)+ if credential is None or not await credential_binding_matches(binding, user_id, server_id, credential):+ return Noneif self._uses_redis:store = self._storeif store is not None:diff --git a/litellm/types/mcp_server/mcp_server_manager.py b/litellm/types/mcp_server/mcp_server_manager.pyindex 117d95a09de..f6b5441a626 100644--- a/litellm/types/mcp_server/mcp_server_manager.py+++ b/litellm/types/mcp_server/mcp_server_manager.py@@ -1,7 +1,8 @@from datetime import datetimefrom typing import Any, Final, Literal-from pydantic import BaseModel, ConfigDict, Field, field_validator+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator+from typing_extensions import Selffrom litellm.types.mcp import (DEFAULT_SUBJECT_TOKEN_TYPE,@@ -42,7 +43,7 @@ class MCPOAuthIdentityBinding(BaseModel):"""Per-server policy binding stored per-user OAuth credentials to the authenticated LiteLLM caller.When enabled for an interactive oauth2 server, the token relay validates the upstream OIDC- ``id_token`` (signature via the pinned issuer's JWKS, issuer, audience, expiry) and compares its+ ``id_token`` (signature via the pinned issuer's JWKS, issuer, audience, expiry, nonce) and compares itsprincipal claim to the LiteLLM caller's trusted identity before the token is returned, stored,or cached. ``audit`` logs mismatches without changing behavior; ``enforce`` fails closed with403 ``oauth_principal_mismatch`` and disables the direct ``oauth-user-credential`` POST, which@@ -246,6 +247,14 @@ class MCPServer(BaseModel):"""return self.oauth2_flow == "client_credentials"+ @model_validator(mode="after")+ def validate_identity_binding_mode(self) -> Self:+ binding: Final = self.oauth_identity_binding+ if binding is not None and binding.mode != "disabled":+ if not self.needs_user_oauth_token or self.delegate_auth_to_upstream:+ raise ValueError("oauth_identity_binding requires gateway-managed per-user OAuth2 credentials")+ return self+@propertydef needs_user_oauth_token(self) -> bool:"""True if this is an OAuth2 server that relies on per-user tokens (no client_credentials)."""diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_authz_code_refresher.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_authz_code_refresher.pyindex bb2f2ff8b02..16707f6ace8 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_authz_code_refresher.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_authz_code_refresher.py@@ -22,6 +22,7 @@ class _Server:server_id="srv",configured_token_url=None,):+ self.oauth_identity_binding = Noneself.token_url = token_urlself.configured_token_url = configured_token_urlself.client_id = client_id@@ -287,3 +288,36 @@ async def test_refresh_uses_admin_entered_token_url_when_issuer_yield_empties_reassert token is not Noneassert token.access_token == "new-at"assert posted[0][0] == "https://idp.example.com/token"+++async def test_identity_rejection_never_persists_or_returns_refreshed_token():+ from unittest.mock import AsyncMock+ from fastapi import HTTPException++ validator = AsyncMock(side_effect=HTTPException(status_code=403, detail="oauth_principal_mismatch"))+ persist = AsyncMock()+ refresher = AuthorizationCodeRefresher(+ _lookup(_Server()), _endpoint({"access_token": "foreign-token", "id_token": "foreign-identity"}),+ persist, identity_validator=validator,+ )+ with pytest.raises(HTTPException) as error:+ await refresher.refresh("alice", "srv", OAuthToken(access_token="old", refresh_token="old-rt"))+ assert error.value.status_code == 403+ persist.assert_not_awaited()+++async def test_verified_refresh_preserves_binding_proof_in_storage():+ from unittest.mock import AsyncMock++ validator = AsyncMock(return_value="verified-binding")+ persist = AsyncMock()+ refresher = AuthorizationCodeRefresher(+ _lookup(_Server()), _endpoint({"access_token": "new", "refresh_token": "rotated"}),+ persist, identity_validator=validator,+ )+ token = await refresher.refresh("alice", "srv", OAuthToken(access_token="old", refresh_token="old-rt"))+ assert token.access_token == "new"+ assert token.refresh_token == "rotated"+ assert persist.await_args.kwargs["identity_binding_proof"] == "verified-binding"diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_per_user_oauth_store.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_per_user_oauth_store.pyindex ca32cf2bb8d..bd190b09c82 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_per_user_oauth_store.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_per_user_oauth_store.py@@ -246,3 +246,28 @@ async def test_lazy_store_invalidate_works_after_redis_chain_is_built() -> None:assert build_calls == 1assert redis_store.invalidations == [("u", "s")]+++async def test_enforcement_invalidates_cached_legacy_credentials_before_use():+ from litellm.types.mcp import MCPAuth, MCPTransport+ from litellm.types.mcp_server.mcp_server_manager import MCPOAuthIdentityBinding, MCPServer++ server = MCPServer(+ server_id="srv", name="srv", transport=MCPTransport.http, auth_type=MCPAuth.oauth2,+ oauth_identity_binding=MCPOAuthIdentityBinding(+ mode="enforce", issuer="https://idp.example.com", audiences=["client"],+ ),+ )+ cached = _RecordingStore("belongs-to-bob")++ async def read_legacy(user_id, server_id):+ return {"access_token": "belongs-to-bob", "refresh_token": "bobs-refresh"}++ store = LazyPerUserOAuthTokenStore(+ lambda server_id: server, store_builder=lambda lookup: (cached, False),+ redis_available=lambda: False, credential_reader=read_legacy,+ )+ assert await store.fetch("alice", "srv") is None+ assert cached.calls == []+ assert cached.invalidations == [("alice", "srv")]diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_db_credentials.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_db_credentials.pyindex 355b3bfd30e..8e2adbeb06e 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_db_credentials.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_db_credentials.py@@ -628,6 +628,7 @@ async def test_oauth_round_trip_returns_payload():access_token,refresh_token="rfr-xyz",scopes=["a", "b"],+ identity_binding_proof="verified-proof",)stored = _stored_value(prisma)@@ -642,6 +643,7 @@ async def test_oauth_round_trip_returns_payload():assert result["access_token"] == access_tokenassert result["refresh_token"] == "rfr-xyz"assert result["scopes"] == ["a", "b"]+ assert result["identity_binding_proof"] == "verified-proof"@pytest.mark.asyncio@@ -1184,6 +1186,7 @@ class _RefreshResponse:def _refresh_server(**overrides):base = dict(+ oauth_identity_binding=None,token_url="https://idp.example.com/token",server_id="srv-1",client_id="cid",@@ -1309,7 +1312,7 @@ async def test_refresh_user_oauth_token_uses_client_secret_basic(monkeypatch):sends HTTP Basic and keeps the secret out of the body."""import litellm.proxy._experimental.mcp_server.db as db_mod- server = MagicMock()+ server = MagicMock(oauth_identity_binding=None)server.token_url = "https://idp.example.com/oauth2/token"server.server_id = "srv"server.client_id = "cid"@@ -1348,7 +1351,7 @@ async def test_refresh_user_oauth_token_defaults_to_client_secret_post(monkeypatthe body (client_secret_post) and sends no Authorization header."""import litellm.proxy._experimental.mcp_server.db as db_mod- server = MagicMock()+ server = MagicMock(oauth_identity_binding=None)server.token_url = "https://idp.example.com/oauth2/token"server.server_id = "srv"server.client_id = "cid"@@ -1609,3 +1612,20 @@ def test_partial_update_defers_omitted_eligibility_fields_to_the_stored_row():request = UpdateMCPServerRequest(server_id="relay-update", per_server_oauth_discovery=True)assert request.per_server_oauth_discovery is True+++async def test_enforcement_rejects_preexisting_unverified_credential():+ from litellm.types.mcp_server.mcp_server_manager import MCPOAuthIdentityBinding, MCPServer++ server = MCPServer(+ server_id="srv-1", name="srv-1", url="https://mcp.example.com", transport=MCPTransport.http, auth_type=MCPAuth.oauth2,+ oauth_identity_binding=MCPOAuthIdentityBinding(+ mode="enforce", issuer="https://idp.example.com", audiences=["client"],+ ),+ )+ result = await resolve_valid_user_oauth_token(+ user_id="alice", server=server,+ cred={"access_token": "belongs-to-bob", "refresh_token": "bobs-refresh-token"},+ )+ assert result is Nonediff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.pyindex 590d6606154..42187cb1771 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py@@ -8194,15 +8194,17 @@ async def test_token_exchange_refresh_passes_presented_refresh_ownership():@pytest.mark.asyncio-async def test_token_exchange_authorization_code_passes_no_refresh_ownership():+async def test_token_exchange_authorization_code_passes_no_refresh_ownership(monkeypatch):from fastapi import Requestfrom litellm.proxy._experimental.mcp_server.discoverable_endpoints import (exchange_token_with_server,+ seal_bridge_authorization_code,)from litellm.proxy._types import MCPTransportfrom litellm.types.mcp_server.mcp_server_manager import MCPOAuthIdentityBinding, MCPServer+ monkeypatch.setenv("LITELLM_SALT_KEY", "identity-binding-test-salt")server = MCPServer(server_id="srv-1",name="srv-1",@@ -8244,16 +8246,17 @@ async def test_token_exchange_authorization_code_passes_no_refresh_ownership():request=request,mcp_server=server,grant_type="authorization_code",- code="auth-code",+ code=seal_bridge_authorization_code("auth-code", "user-a", "srv-1", "login-nonce"),redirect_uri="https://litellm.example.com/callback",client_id="cid",client_secret=None,- code_verifier=None,+ code_verifier="test-verifier",)assert result.status_code == 200assert json.loads(result.body)["access_token"] == "at"assert enforce.await_args.kwargs["refresh_ownership"] is None+ assert enforce.await_args.kwargs["expected_nonce"] == "login-nonce"def _upstream_token_response(status_code: int, *, json_body: object = None, text_body: str = "") -> "httpx.Response":@@ -11049,3 +11052,54 @@ def test_introspect_route_answers_for_authenticated_caller(monkeypatch):assert active.status_code == 200assert active.json()["active"] is Trueassert active.json()["sub"] == "u1"+++async def test_identity_bound_authorization_carries_nonce_and_caller_through_callback(monkeypatch):+ from http.cookies import SimpleCookie+ from urllib.parse import parse_qs, urlparse+ from fastapi import Request+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ _oauth_state_cookie_name, authorize_with_server, callback, open_bridge_authorization_code,+ )+ from litellm.types.mcp import MCPTransport+ from litellm.types.mcp_server.mcp_server_manager import MCPOAuthIdentityBinding, MCPServer++ monkeypatch.setenv("LITELLM_SALT_KEY", "identity-binding-test-salt")+ server = MCPServer(+ server_id="srv", name="srv", transport=MCPTransport.http, auth_type=MCPAuth.oauth2,+ client_id="client", authorization_url="https://idp.example.com/authorize",+ token_url="https://idp.example.com/token",+ oauth_identity_binding=MCPOAuthIdentityBinding(+ mode="enforce", issuer="https://idp.example.com", audiences=["client"],+ ),+ )+ request = Request({"type": "http", "scheme": "https", "server": ("proxy.example.com", 443),+ "path": "/authorize", "query_string": b"", "headers": []})+ with (+ patch( # test-quality-ok: isolate authenticated request resolution from the real encrypted OAuth round trip+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._extract_user_id_from_request",+ new=AsyncMock(return_value="alice")),+ patch( # test-quality-ok: isolate user access lookup while testing nonce and caller preservation+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._bridge_authorize_access_denial",+ new=AsyncMock(return_value=None)),+ ):+ authorized = await authorize_with_server(+ request, server, "client", "http://127.0.0.1:6274/callback", state="client-state",+ code_challenge="pkce-challenge", code_challenge_method="S256",+ )+ query = parse_qs(urlparse(authorized.headers["location"]).query)+ assert len(query["nonce"][0]) >= 32+ cookies = SimpleCookie()+ cookies.load(authorized.headers["set-cookie"])+ name = _oauth_state_cookie_name(query["state"][0])+ callback_request = Request({**request.scope, "path": "/callback",+ "headers": [(b"cookie", f"{name}={cookies[name].value}".encode())]})+ completed = await callback(callback_request, code="upstream-code", state=query["state"][0])+ returned = parse_qs(urlparse(completed.headers["location"]).query)+ sealed = open_bridge_authorization_code(returned["code"][0])+ assert sealed.litellm_user_id == "alice"+ assert sealed.mcp_server_id == "srv"+ assert sealed.upstream_code == "upstream-code"+ assert sealed.oauth_nonce == query["nonce"][0]+ assert returned["state"] == ["client-state"]diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_oauth_identity_binding.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_oauth_identity_binding.pyindex 36364c32ae5..6f291865e20 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_oauth_identity_binding.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_oauth_identity_binding.py@@ -13,7 +13,9 @@ from pydantic import ValidationErrorfrom litellm.proxy._experimental.mcp_server.oauth_identity_binding import (RefreshOwnershipProven,+ VerifiedRefreshToken,RefreshTokenPresented,+ current_binding_proof,_discover_jwks_url,_fetch_issuer_jwks,_load_caller_principal,@@ -21,7 +23,7 @@ from litellm.proxy._experimental.mcp_server.oauth_identity_binding import (_select_signing_key,enforce_oauth_identity_binding,)-from litellm.types.mcp import MCPTransport+from litellm.types.mcp import MCPAuth, MCPTransportfrom litellm.types.mcp_server.mcp_server_manager import MCPOAuthIdentityBinding, MCPServerISSUER: Final = "https://idp.example.com"@@ -48,6 +50,8 @@ def _sign_id_token(claims: Mapping[str, object]) -> str:"aud": AUDIENCE,"exp": int(time.time()) + 300,"iat": int(time.time()),+ "nonce": "test-nonce",+ "sub": "upstream-user",**claims,}return jwt.encode(payload, _PRIVATE_PEM, algorithm="RS256", headers={"kid": KID})@@ -65,8 +69,8 @@ def _caller_loader(email: str | None):def _stored_refresh_token_loader(refresh_token: str | None):- async def load(_user_id: str, _server_id: str) -> str | None:- return refresh_token+ async def load(_user_id: str, _server_id: str, _binding: MCPOAuthIdentityBinding) -> VerifiedRefreshToken | None:+ return VerifiedRefreshToken(refresh_token, "verified-binding") if refresh_token else Nonereturn load@@ -77,6 +81,7 @@ def _server(mode: str = "enforce", **binding_overrides: object) -> MCPServer:name="srv-1",url="https://mcp.example.com",transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2,oauth_identity_binding=MCPOAuthIdentityBinding(mode=mode,issuer=ISSUER,@@ -181,7 +186,9 @@ async def test_load_caller_principal_supports_user_id_and_database_email():@pytest.mark.asyncioasync def test_load_stored_refresh_token_returns_credential_and_fails_closed():- get_credential: Final = AsyncMock(return_value={"refresh_token": "rt-1"})+ binding: Final = _server(caller_field="user_id", principal_claim="sub").oauth_identity_binding+ proof: Final = await current_binding_proof(binding, "user-a", "srv-1")+ get_credential: Final = AsyncMock(return_value={"refresh_token": "rt-1", "identity_binding_proof": proof})with (patch( # test-quality-ok: stored-token loading is a lazy database boundary without injection"litellm.proxy._experimental.mcp_server.db.get_user_oauth_credential",@@ -192,13 +199,15 @@ async def test_load_stored_refresh_token_returns_credential_and_fails_closed():return_value="prisma",),):- assert await _load_stored_refresh_token("user-a", "srv-1") == "rt-1"+ assert await _load_stored_refresh_token("user-a", "srv-1", binding) == VerifiedRefreshToken("rt-1", proof)+ get_credential.return_value = {"refresh_token": "rt-1"}+ assert await _load_stored_refresh_token("user-a", "srv-1", binding) is Nonewith patch( # test-quality-ok: stored-token loading is a lazy database boundary without injection"litellm.proxy.utils.get_prisma_client_or_throw",side_effect=RuntimeError("database unavailable"),):- assert await _load_stored_refresh_token("user-a", "srv-1") is None+ assert await _load_stored_refresh_token("user-a", "srv-1", binding) is None@pytest.mark.asyncio@@ -209,11 +218,12 @@ async def test_matching_principal_passes():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader("[email protected]"),)- assert result is None+ assert result is not None@pytest.mark.asyncio@@ -225,6 +235,7 @@ async def test_mismatched_principal_rejected():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader("[email protected]"),@@ -243,6 +254,7 @@ async def test_missing_upstream_principal_rejected():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader("[email protected]"),@@ -263,6 +275,7 @@ async def test_jwks_fetch_failure_is_rejected():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=fail,caller_principal_loader=_caller_loader("[email protected]"),@@ -284,6 +297,7 @@ async def test_missing_signing_key_is_rejected():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=no_keys,caller_principal_loader=_caller_loader("[email protected]"),@@ -301,6 +315,7 @@ async def test_missing_caller_principal_is_rejected():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader(None),@@ -334,11 +349,12 @@ async def test_user_id_principal_matching_uses_exact_comparison():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader("user-a"),)- assert result is None+ assert result is not None@pytest.mark.asyncio@@ -349,6 +365,7 @@ async def test_missing_id_token_rejected_on_authorization_code():token_response={"access_token": "at"},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader("[email protected]"),@@ -369,7 +386,7 @@ async def test_refresh_without_id_token_allowed_when_presented_token_matches_stocaller_principal_loader=_caller_loader("[email protected]"),stored_refresh_token_loader=_stored_refresh_token_loader("rt-1"),)- assert result is None+ assert result is not None@pytest.mark.asyncio@@ -407,21 +424,18 @@ async def test_refresh_without_id_token_rejects_missing_stored_token():@pytest.mark.asyncio-async def test_refresh_without_id_token_passes_when_bridge_proves_ownership():- async def fail_if_called(_user_id: str, _server_id: str) -> str | None:- raise AssertionError("stored refresh token loader should not be called")-- result: Final = await enforce_oauth_identity_binding(- server=_server(),- token_response={"access_token": "at"},- litellm_user_id="user-a",- grant_type="refresh_token",- refresh_ownership=RefreshOwnershipProven(),- jwks_fetcher=_jwks_fetcher,- caller_principal_loader=_caller_loader("[email protected]"),- stored_refresh_token_loader=fail_if_called,- )- assert result is None+async def test_identity_envelope_does_not_prove_upstream_binding():+ with pytest.raises(HTTPException) as error:+ await enforce_oauth_identity_binding(+ server=_server(),+ token_response={"access_token": "at"},+ litellm_user_id="user-a",+ grant_type="refresh_token",+ refresh_ownership=RefreshOwnershipProven(),+ jwks_fetcher=_jwks_fetcher,+ caller_principal_loader=_caller_loader("[email protected]"),+ )+ assert error.value.status_code == 403@pytest.mark.asyncio@@ -464,6 +478,7 @@ async def test_audit_mode_logs_but_does_not_reject():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader("[email protected]"),@@ -480,6 +495,7 @@ async def test_unverified_email_rejected():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader("[email protected]"),@@ -503,6 +519,7 @@ async def test_wrong_issuer_rejected():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader("[email protected]"),@@ -519,6 +536,7 @@ async def test_no_litellm_identity_rejected():token_response={"access_token": "at", "id_token": token},litellm_user_id=None,grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader("[email protected]"),@@ -533,6 +551,7 @@ async def test_disabled_binding_is_noop():token_response={"access_token": "at"},litellm_user_id=None,grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader(None),@@ -553,6 +572,7 @@ async def test_no_binding_is_noop():token_response={"access_token": "at"},litellm_user_id=None,grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader(None),@@ -576,9 +596,52 @@ async def test_wrong_audience_rejected():token_response={"access_token": "at", "id_token": token},litellm_user_id="user-a",grant_type="authorization_code",+ expected_nonce="test-nonce",refresh_ownership=None,jwks_fetcher=_jwks_fetcher,caller_principal_loader=_caller_loader("[email protected]"),)assert exc_info.value.status_code == 403assert exc_info.value.detail["error"] == "oauth_identity_binding_failed"++[email protected]("nonce", [None, "another-login"])+async def test_authorization_code_rejects_missing_or_foreign_nonce(nonce):+ token = _sign_id_token({"email": "[email protected]", "email_verified": True, "nonce": nonce})+ with pytest.raises(HTTPException) as error:+ await enforce_oauth_identity_binding(+ server=_server(),+ token_response={"access_token": "at", "id_token": token},+ litellm_user_id="user-a",+ grant_type="authorization_code",+ refresh_ownership=None,+ expected_nonce="this-login",+ jwks_fetcher=_jwks_fetcher,+ caller_principal_loader=_caller_loader("[email protected]"),+ )+ assert error.value.status_code == 403+ assert error.value.detail["error"] == "oauth_identity_binding_failed"+++async def test_binding_proof_rejects_changed_user_or_policy():+ from litellm.proxy._experimental.mcp_server.oauth_identity_binding import credential_binding_matches++ binding = _server(caller_field="user_id", principal_claim="sub").oauth_identity_binding+ proof = await current_binding_proof(binding, "alice", "srv-1")+ credential = {"identity_binding_proof": proof}+ assert await credential_binding_matches(binding, "alice", "srv-1", credential)+ assert not await credential_binding_matches(binding, "bob", "srv-1", credential)+ assert not await credential_binding_matches(binding, "alice", "other-server", credential)+ changed = binding.model_copy(update={"audiences": ["different-client"]})+ assert not await credential_binding_matches(changed, "alice", "srv-1", credential)++[email protected]("auth_type", [MCPAuth.oauth_delegate, MCPAuth.true_passthrough])+def test_identity_binding_rejects_modes_without_gateway_credential_custody(auth_type):+ with pytest.raises(ValidationError, match="gateway-managed per-user"):+ MCPServer(+ server_id="srv", name="srv", transport=MCPTransport.http, auth_type=auth_type,+ oauth_identity_binding=_server().oauth_identity_binding,+ )diff --git a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.pyindex 6a20688c09d..5e00e7d75be 100644--- a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py@@ -4807,7 +4807,7 @@ async def test_store_mcp_oauth_user_credential_blocked_when_identity_binding_enf"""The direct opaque-token POST must be closed for enforce-mode identity-bound servers,otherwise it bypasses the token-relay principal check."""from litellm.proxy._types import MCPOAuthUserCredentialRequest- from litellm.types.mcp import MCPTransport+ from litellm.types.mcp import MCPAuth, MCPTransportfrom litellm.types.mcp_server.mcp_server_manager import MCPOAuthIdentityBinding, MCPServerif not mgmt_endpoints.MCP_AVAILABLE:@@ -4824,6 +4824,7 @@ async def test_store_mcp_oauth_user_credential_blocked_when_identity_binding_enfname=server_id,url="https://mcp.example.com",transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2,oauth_identity_binding=MCPOAuthIdentityBinding(mode="enforce",issuer="https://idp.example.com",