Skip to content

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]

test(mcp): cover OAuth identity binding paths

yassin7ca9f2857502
diff --git a/litellm/proxy/_experimental/mcp_server/oauth_identity_binding.py b/litellm/proxy/_experimental/mcp_server/oauth_identity_binding.py
index b73227f3413..58ec3cfdb4f 100644
--- a/litellm/proxy/_experimental/mcp_server/oauth_identity_binding.py
+++ b/litellm/proxy/_experimental/mcp_server/oauth_identity_binding.py
@@ -234,7 +234,7 @@ async def _evaluate_binding(
description="the presented refresh_token is not the caller's stored credential for this server",
)
return None
- assert_never(refresh_ownership)
+ assert_never(refresh_ownership) # pragma: no cover
if not litellm_user_id:
return _BindingRejection(
code="oauth_identity_binding_failed",
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py
index 598e9276423..4ae1b105dbf 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
@@ -7816,6 +7816,132 @@ async def test_token_exchange_pairs_client_secret_with_server_client_id():
assert "client_secret" not in sent
+async def test_token_exchange_refresh_passes_presented_refresh_ownership():
+ from fastapi import Request
+
+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (
+ exchange_token_with_server,
+ )
+ from litellm.proxy._experimental.mcp_server.oauth_identity_binding import RefreshTokenPresented
+ from litellm.proxy._types import MCPTransport
+ from litellm.types.mcp_server.mcp_server_manager import MCPOAuthIdentityBinding, MCPServer
+
+ server = MCPServer(
+ server_id="srv-1",
+ name="srv-1",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2,
+ client_id="cid",
+ token_url="https://provider.example/token",
+ oauth_identity_binding=MCPOAuthIdentityBinding(
+ mode="enforce",
+ issuer="https://provider.example",
+ audiences=["cid"],
+ ),
+ )
+ request = MagicMock(spec=Request)
+ request.base_url = "https://litellm.example.com/"
+ request.headers = {}
+ response = MagicMock()
+ response.json.return_value = {"access_token": "at"}
+ response.raise_for_status = MagicMock()
+ client = MagicMock()
+ client.post = AsyncMock(return_value=response)
+ enforce = AsyncMock()
+
+ with (
+ patch(
+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",
+ return_value=client,
+ ),
+ patch(
+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._extract_user_id_from_request",
+ new=AsyncMock(return_value="user-a"),
+ ),
+ patch(
+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.enforce_oauth_identity_binding",
+ new=enforce,
+ ),
+ ):
+ await exchange_token_with_server(
+ request=request,
+ mcp_server=server,
+ grant_type="refresh_token",
+ code=None,
+ redirect_uri=None,
+ client_id="cid",
+ client_secret=None,
+ code_verifier=None,
+ refresh_token="rt-1",
+ )
+
+ ownership = enforce.await_args.kwargs["refresh_ownership"]
+ assert isinstance(ownership, RefreshTokenPresented)
+ assert ownership.refresh_token == "rt-1"
+
+
+async def test_token_exchange_authorization_code_passes_no_refresh_ownership():
+ from fastapi import Request
+
+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (
+ exchange_token_with_server,
+ )
+ from litellm.proxy._types import MCPTransport
+ from litellm.types.mcp_server.mcp_server_manager import MCPOAuthIdentityBinding, MCPServer
+
+ server = MCPServer(
+ server_id="srv-1",
+ name="srv-1",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2,
+ client_id="cid",
+ token_url="https://provider.example/token",
+ oauth_identity_binding=MCPOAuthIdentityBinding(
+ mode="enforce",
+ issuer="https://provider.example",
+ audiences=["cid"],
+ ),
+ )
+ request = MagicMock(spec=Request)
+ request.base_url = "https://litellm.example.com/"
+ request.headers = {}
+ response = MagicMock()
+ response.json.return_value = {"access_token": "at"}
+ response.raise_for_status = MagicMock()
+ client = MagicMock()
+ client.post = AsyncMock(return_value=response)
+ enforce = AsyncMock()
+
+ with (
+ patch(
+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",
+ return_value=client,
+ ),
+ patch(
+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._extract_user_id_from_request",
+ new=AsyncMock(return_value="user-a"),
+ ),
+ patch(
+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.enforce_oauth_identity_binding",
+ new=enforce,
+ ),
+ ):
+ await exchange_token_with_server(
+ request=request,
+ mcp_server=server,
+ grant_type="authorization_code",
+ code="auth-code",
+ redirect_uri="https://litellm.example.com/callback",
+ client_id="cid",
+ client_secret=None,
+ code_verifier=None,
+ )
+
+ assert enforce.await_args.kwargs["refresh_ownership"] is None
+
+
def _upstream_token_response(status_code: int, *, json_body: object = None, text_body: str = "") -> "httpx.Response":
import httpx
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.py
index de59020c44c..c2662f9f298 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
@@ -1,6 +1,8 @@
import time
from collections.abc import Mapping
+from types import SimpleNamespace
from typing import Final
+from unittest.mock import AsyncMock, MagicMock, patch
import jwt
import pytest
@@ -12,6 +14,11 @@ from pydantic import ValidationError
from litellm.proxy._experimental.mcp_server.oauth_identity_binding import (
RefreshOwnershipProven,
RefreshTokenPresented,
+ _discover_jwks_url,
+ _fetch_issuer_jwks,
+ _load_caller_principal,
+ _load_stored_refresh_token,
+ _select_signing_key,
enforce_oauth_identity_binding,
)
from litellm.types.mcp import MCPTransport
@@ -79,6 +86,121 @@ def _server(mode: str = "enforce", **binding_overrides: object) -> MCPServer:
)
+async def test_fetch_issuer_jwks_fetches_and_caches_keys():
+ binding: Final = _server(jwks_url="https://idp.example.com/jwks-cache").oauth_identity_binding
+ assert binding is not None
+ response: Final = MagicMock()
+ response.json.return_value = {"keys": [_PUBLIC_JWK]}
+ client: Final = MagicMock()
+ client.get = AsyncMock(return_value=response)
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.oauth_identity_binding.get_async_httpx_client",
+ return_value=client,
+ ):
+ first: Final = await _fetch_issuer_jwks(binding)
+ second: Final = await _fetch_issuer_jwks(binding)
+
+ assert first == second == [_PUBLIC_JWK]
+ client.get.assert_awaited_once_with("https://idp.example.com/jwks-cache")
+
+
+async def test_fetch_issuer_jwks_rejects_malformed_document():
+ binding: Final = _server(jwks_url="https://idp.example.com/jwks-invalid").oauth_identity_binding
+ assert binding is not None
+ response: Final = MagicMock()
+ response.json.return_value = {}
+ client: Final = MagicMock()
+ client.get = AsyncMock(return_value=response)
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.oauth_identity_binding.get_async_httpx_client",
+ return_value=client,
+ ):
+ with pytest.raises(TypeError, match="has no 'keys' array"):
+ await _fetch_issuer_jwks(binding)
+
+
+async def test_discover_jwks_url_returns_provider_uri():
+ response: Final = MagicMock()
+ response.json.return_value = {"jwks_uri": "https://idp.example.com/jwks"}
+ client: Final = MagicMock()
+ client.get = AsyncMock(return_value=response)
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.oauth_identity_binding.get_async_httpx_client",
+ return_value=client,
+ ):
+ result: Final = await _discover_jwks_url("https://idp.example.com/")
+
+ assert result == "https://idp.example.com/jwks"
+ client.get.assert_awaited_once_with("https://idp.example.com/.well-known/openid-configuration")
+
+
+async def test_discover_jwks_url_rejects_missing_provider_uri():
+ response: Final = MagicMock()
+ response.json.return_value = {}
+ client: Final = MagicMock()
+ client.get = AsyncMock(return_value=response)
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.oauth_identity_binding.get_async_httpx_client",
+ return_value=client,
+ ):
+ with pytest.raises(ValueError, match="returned no jwks_uri"):
+ await _discover_jwks_url("https://idp.example.com")
+
+
+def test_select_signing_key_returns_matching_key_or_rejection():
+ token: Final = _sign_id_token({"email": "[email protected]", "email_verified": True})
+
+ selected: Final = _select_signing_key(token, [_PUBLIC_JWK])
+ rejected: Final = _select_signing_key(token, [])
+
+ assert selected.__class__.__name__ == "PyJWK"
+ assert rejected.code == "oauth_identity_binding_failed"
+
+
+async def test_load_caller_principal_supports_user_id_and_database_email():
+ user_id_binding: Final = _server(caller_field="user_id").oauth_identity_binding
+ assert user_id_binding is not None
+ assert await _load_caller_principal("user-a", user_id_binding) == "user-a"
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.bridge_token_flow.load_active_user_by_id",
+ new=AsyncMock(side_effect=["no_active_key", SimpleNamespace(user_email="[email protected]")]),
+ ):
+ assert await _load_caller_principal("user-a", _server().oauth_identity_binding) is None
+ assert await _load_caller_principal("user-a", _server().oauth_identity_binding) == "[email protected]"
+
+
+async def test_load_stored_refresh_token_returns_credential_and_fails_closed():
+ get_credential: Final = AsyncMock(return_value={"refresh_token": "rt-1"})
+ with (
+ patch(
+ "litellm.proxy._experimental.mcp_server.db.get_user_oauth_credential",
+ new=get_credential,
+ ),
+ patch(
+ "litellm.proxy.utils.get_prisma_client_or_throw",
+ return_value="prisma",
+ ),
+ ):
+ assert await _load_stored_refresh_token("user-a", "srv-1") == "rt-1"
+
+ with patch(
+ "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
+
+
@pytest.mark.asyncio
async def test_matching_principal_passes():
token: Final = _sign_id_token({"email": "[email protected]", "email_verified": True})
@@ -112,6 +234,113 @@ async def test_mismatched_principal_rejected():
assert exc_info.value.detail["credential_stored"] is False
+async def test_missing_upstream_principal_rejected():
+ token: Final = _sign_id_token({"email_verified": True})
+ with pytest.raises(HTTPException) as exc_info:
+ 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,
+ jwks_fetcher=_jwks_fetcher,
+ caller_principal_loader=_caller_loader("[email protected]"),
+ )
+ assert exc_info.value.detail["error"] == "oauth_identity_binding_failed"
+ assert "no usable" in exc_info.value.detail["error_description"]
+
+
+async def test_jwks_fetch_failure_is_rejected():
+ async def fail(_binding: MCPOAuthIdentityBinding) -> list[Mapping[str, object]]:
+ raise RuntimeError("jwks unavailable")
+
+ token: Final = _sign_id_token({"email": "[email protected]", "email_verified": True})
+ with pytest.raises(HTTPException) as exc_info:
+ 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,
+ jwks_fetcher=fail,
+ caller_principal_loader=_caller_loader("[email protected]"),
+ )
+ assert exc_info.value.detail["error"] == "oauth_identity_binding_failed"
+ assert "jwks unavailable" in exc_info.value.detail["error_description"]
+
+
+async def test_missing_signing_key_is_rejected():
+ token: Final = _sign_id_token({"email": "[email protected]", "email_verified": True})
+
+ async def no_keys(_binding: MCPOAuthIdentityBinding) -> tuple[Mapping[str, object], ...]:
+ return ()
+
+ with pytest.raises(HTTPException) as exc_info:
+ 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,
+ jwks_fetcher=no_keys,
+ caller_principal_loader=_caller_loader("[email protected]"),
+ )
+ assert exc_info.value.detail["error"] == "oauth_identity_binding_failed"
+ assert "signing key" in exc_info.value.detail["error_description"]
+
+
+async def test_missing_caller_principal_is_rejected():
+ token: Final = _sign_id_token({"email": "[email protected]", "email_verified": True})
+ with pytest.raises(HTTPException) as exc_info:
+ 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,
+ jwks_fetcher=_jwks_fetcher,
+ caller_principal_loader=_caller_loader(None),
+ )
+ assert exc_info.value.detail["error"] == "oauth_identity_binding_failed"
+ assert "has no" in exc_info.value.detail["error_description"]
+
+
+async def test_refresh_without_id_token_requires_litellm_identity_for_presented_token():
+ with pytest.raises(HTTPException) as exc_info:
+ await enforce_oauth_identity_binding(
+ server=_server(),
+ token_response={"access_token": "at"},
+ litellm_user_id=None,
+ grant_type="refresh_token",
+ refresh_ownership=RefreshTokenPresented("rt-1"),
+ jwks_fetcher=_jwks_fetcher,
+ caller_principal_loader=_caller_loader("[email protected]"),
+ stored_refresh_token_loader=_stored_refresh_token_loader("rt-1"),
+ )
+ assert exc_info.value.detail["error"] == "oauth_identity_binding_failed"
+ assert "no resolvable LiteLLM user identity" in exc_info.value.detail["error_description"]
+
+
+async def test_user_id_principal_matching_uses_exact_comparison():
+ token: Final = _sign_id_token({"sub": "user-a"})
+ result: Final = await enforce_oauth_identity_binding(
+ server=_server(principal_claim="sub", caller_field="user_id"),
+ token_response={"access_token": "at", "id_token": token},
+ litellm_user_id="user-a",
+ grant_type="authorization_code",
+ refresh_ownership=None,
+ jwks_fetcher=_jwks_fetcher,
+ caller_principal_loader=_caller_loader("user-a"),
+ )
+ assert result is None
+
+
@pytest.mark.asyncio
async def test_missing_id_token_rejected_on_authorization_code():
with pytest.raises(HTTPException) as exc_info: