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): route bridge admission through the centralized policy gate and mirror the SCIM owner check
Tin Chi Lo9e6d6e509c79
diff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.pyindex bee621b3721..998aa4846c6 100644--- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py+++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py@@ -26,7 +26,11 @@ from litellm.proxy._types import (UserAPIKeyAuth,)from litellm.proxy.auth.ip_address_utils import IPAddressUtils-from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.auth.user_api_key_auth import (+ _run_centralized_common_checks,+ user_api_key_auth,+)+from litellm.proxy.common_utils.http_parsing_utils import _read_request_bodyfrom litellm.proxy.common_utils.user_api_key_cache import get_management_object_ttlfrom litellm.repositories.table_repositories import (AgentsRepository,@@ -256,6 +260,8 @@ class MCPRequestHandler:server=bridge_delegate_target,authorization_value=oauth2_headers["Authorization"],mcp_server_auth_headers=mcp_server_auth_headers,+ request=request,+ route=request_route,)elif oauth2_headers:# Authorization on a non-delegated server: the bearer must be a real@@ -496,19 +502,24 @@ class MCPRequestHandler:server: MCPServer,authorization_value: str,mcp_server_auth_headers: Optional[Dict[str, Dict[str, str]]],+ request: Request,+ route: str,) -> Tuple[UserAPIKeyAuth, Optional[Dict[str, Dict[str, str]]]]:"""Open the bridge envelope and admit the caller under the live key it references.The envelope's signature proves the user authenticated when it was minted, butauthorization is resolved fresh here rather than trusted from the envelope: the- sealed ``key_hash`` reloads the current ``UserAPIKeyAuth`` record, so the key's- present team/org/object-permission restrictions and its revocation state gate the- request instead of a snapshot frozen at mint time. The inner upstream token is- injected under the server's per-server auth-header key so egress forwards it via the+ sealed ``key_hash`` reloads the current ``UserAPIKeyAuth`` record, and the admitted+ identity then runs through the standard pipeline's centralized policy gate, so the+ key's present restrictions and revocation state gate the request instead of a+ snapshot frozen at mint time. The inner upstream token is injected under the+ server's per-server auth-header key so egress forwards it via the``PassthroughConfig`` override; the envelope ``Authorization`` the leak-defensestrips never reaches the upstream. A new headers dict is returned rather thanmutating the input. Fails closed with a 401 on an invalid or expired envelope, or- when the referenced key is missing, blocked, or expired, or its team is blocked.+ when the referenced key is missing, blocked, or expired, its owner is+ SCIM-deactivated, or the centralized policy gate rejects it (blocked team or+ project, org or budget limits).The sealed token is keyed alias-first, matching the order egress resolves(``lookup_mcp_server_auth_in_headers`` tries ``alias`` before ``server_name``). Keying@@ -529,6 +540,7 @@ class MCPRequestHandler:if header_key is None:raise HTTPException(status_code=500, detail="Server misconfigured: MCP server has no routable name")admitted = await MCPRequestHandler._reload_admitted_key(result.identity.key_hash)+ await MCPRequestHandler._enforce_admitted_live_policy(admitted=admitted, request=request, route=route)injected = {header_key: {"Authorization": result.upstream_authorization.get_secret_value()}}new_headers = {**(mcp_server_auth_headers or {}), **injected}return admitted, new_headers@@ -548,9 +560,11 @@ class MCPRequestHandler:unrestricted identity. ``get_key_object`` raises for a hash with no key row; ablocked or expired row is rejected explicitly because ``get_key_object`` resolves arow without applying those checks (the main ``user_api_key_auth`` pipeline enforces- them downstream, which this admission path bypasses). The key's team is reloaded and- rejected when blocked, mirroring ``common_checks``, so blocking a team revokes every- envelope minted under its keys rather than leaving them live until expiry.+ them downstream, which this admission path bypasses). The owner's SCIM state is the+ other builder-inline check mirrored here, so IdP offboarding revokes every envelope+ minted under the user's keys rather than leaving them live until expiry. Team,+ project, org, and budget state are NOT re-checked here; the caller runs the admitted+ identity through ``_enforce_admitted_live_policy`` for those."""from litellm.proxy.auth.auth_checks import get_key_objectfrom litellm.proxy.proxy_server import prisma_client, user_api_key_cache@@ -567,33 +581,57 @@ class MCPRequestHandler:raise HTTPException(status_code=401, detail="Invalid or expired credential") from Noneif not MCPRequestHandler._admitted_key_is_active(key_object):raise HTTPException(status_code=401, detail="Invalid or expired credential")- await MCPRequestHandler._reject_if_admitted_team_blocked(key_object)+ await MCPRequestHandler._reject_if_admitted_owner_scim_deactivated(key_object)return key_object@staticmethod- async def _reject_if_admitted_team_blocked(key_object: UserAPIKeyAuth) -> None:- """Reload the key's team and fail closed with a 401 when it is blocked or no longer- resolves. ``get_key_object`` returns the key row without any team validation, so this- admission path applies the same live team-block gate ``common_checks`` runs on the- standard auth pipeline; without it, blocking a team would not revoke envelopes already- minted under its keys until they expired."""- team_id = key_object.team_id- if not team_id:+ async def _reject_if_admitted_owner_scim_deactivated(key_object: UserAPIKeyAuth) -> None:+ """Fail closed with a 401 when the key's owning user was deactivated via SCIM.++ The standard pipeline enforces this inline in ``_user_api_key_auth_builder`` rather+ than in ``common_checks``, so the centralized policy gate does not cover it; without+ this mirror, IdP offboarding would leave the user's already-minted envelopes live+ until expiry. A failed user lookup skips the gate, matching the builder."""+ if key_object.user_id is None:return- from litellm.proxy.auth.auth_checks import get_team_object+ from litellm.proxy.auth.auth_checks import get_user_objectfrom litellm.proxy.proxy_server import prisma_client, user_api_key_cachetry:- team_object = await get_team_object(- team_id=team_id,+ user_object = await get_user_object(+ user_id=key_object.user_id,prisma_client=prisma_client,user_api_key_cache=user_api_key_cache,+ user_id_upsert=False,)- except (ProxyException, HTTPException):- raise HTTPException(status_code=401, detail="Invalid or expired credential") from None- if team_object.blocked is True:+ except Exception as e: # noqa: BLE001 # mirror the builder's fail-open user lookup; DB errors are of any type+ verbose_logger.debug(f"bridge admission: user lookup failed, skipping SCIM gate: {e}")+ user_object = None+ if user_object is None or not isinstance(user_object.metadata, dict):+ return+ if user_object.metadata.get("scim_active") is False:raise HTTPException(status_code=401, detail="Invalid or expired credential")+ @staticmethod+ async def _enforce_admitted_live_policy(admitted: UserAPIKeyAuth, request: Request, route: str) -> None:+ """Run the standard pipeline's single authorization point over the admitted identity.++ ``_run_centralized_common_checks`` is the same gate ``user_api_key_auth`` applies+ after every builder path, so the envelope identity gets team-block, project-block,+ org, and budget enforcement identical to the same key presented directly, and any+ policy dimension added to the standard pipeline applies here without this arm+ mirroring it. Every failure maps to the arm's uniform 401 so a caller probing with+ a stolen envelope learns nothing about why it stopped working."""+ try:+ await _run_centralized_common_checks(+ user_api_key_auth_obj=admitted,+ request=request,+ request_data=await _read_request_body(request=request),+ route=route,+ )+ except Exception: # noqa: BLE001 # common_checks raises bare Exception for blocked states; narrowing would fail open+ raise HTTPException(status_code=401, detail="Invalid or expired credential") from None+@staticmethoddef _admitted_key_is_active(key_object: UserAPIKeyAuth) -> bool:"""False when the referenced key is blocked or past its expiry, so a revoked keydiff --git a/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.pyindex d0d75231b59..58ef95f53a6 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py@@ -4962,22 +4962,57 @@ class TestMCPDcrBridgeDelegateAdmission:@staticmethod@contextlib.contextmanager- def _patch_key_reload(*, return_value=None, side_effect=None, team_blocked=False):- """Patch the live-key reload dependencies used by ``_reload_admitted_key``: the- ``get_key_object`` lookup, the ``get_team_object`` lookup its team-block gate runs, and the- ``prisma_client`` / ``user_api_key_cache`` globals they read. The team resolves unblocked by- default; ``team_blocked=True`` simulates an admin blocking the key's team. Yields the- ``get_key_object`` mock so callers can assert the sealed ``key_hash`` was the reload key."""+ def _patch_key_reload(*, return_value=None, side_effect=None, team_blocked=False, owner=None, project_object=None):+ """Patch the live-policy dependencies of the admission arm: the ``get_key_object`` reload,+ the ``prisma_client`` / ``user_api_key_cache`` globals, and optionally the live objects the+ policy gates re-check. ``team_blocked=True`` patches the centralized gate's+ ``get_team_object`` at the ``user_api_key_auth`` namespace it actually calls; ``owner``+ patches the SCIM gate's ``get_user_object`` (``auth_checks`` namespace); ``project_object``+ patches the centralized gate's ``get_project_object``. Unpatched lookups hit the MagicMock+ prisma and are swallowed (``_safe_fetch`` / the SCIM gate's fail-open), so their checks+ skip. Yields the ``get_key_object`` mock so callers can assert the sealed ``key_hash`` was+ the reload key."""get_key_object = AsyncMock(return_value=return_value, side_effect=side_effect)- get_team_object = AsyncMock(return_value=MagicMock(blocked=team_blocked))- with (+ patchers = [patch("litellm.proxy.auth.auth_checks.get_key_object", get_key_object),- patch("litellm.proxy.auth.auth_checks.get_team_object", get_team_object),patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),- ):+ ]+ if team_blocked:+ patchers.append(+ patch(+ "litellm.proxy.auth.user_api_key_auth.get_team_object",+ AsyncMock(return_value=MagicMock(blocked=True)),+ )+ )+ if owner is not None:+ patchers.append(patch("litellm.proxy.auth.auth_checks.get_user_object", AsyncMock(return_value=owner)))+ if project_object is not None:+ patchers.append(+ patch(+ "litellm.proxy.auth.user_api_key_auth.get_project_object",+ AsyncMock(return_value=project_object),+ )+ )+ with contextlib.ExitStack() as stack:+ for patcher in patchers:+ stack.enter_context(patcher)yield get_key_object+ @staticmethod+ def _mcp_request(path="/mcp/bridge_delegate_server"):+ """A minimal ``Request`` for direct ``_admit_dcr_bridge_delegate`` calls, mirroring how+ ``process_mcp_request`` builds one from the ASGI scope with a stubbed empty JSON body."""+ from starlette.requests import Request++ request = Request(scope={"type": "http", "method": "POST", "path": path, "headers": [], "query_string": b""})++ async def mock_body():+ return b"{}"++ request.body = mock_body+ return request+async def test_valid_envelope_reloads_live_key_and_admits_its_authorization_context(self):"""A valid envelope admits under the LIVE key record the sealed key_hash references, not ablank identity: the reload is keyed by that exact hash, and the admitted auth carries the@@ -5128,6 +5163,86 @@ class TestMCPDcrBridgeDelegateAdmission:assert exc_info.value.status_code == 401+ async def test_scim_deactivated_owner_envelope_fails_closed_401(self):+ """SCIM-deactivating the key's OWNER must revoke the user's envelopes immediately: the+ standard pipeline rejects every key of a deactivated user inline in the builder, so the+ admission arm mirrors that gate. Without it, IdP offboarding would leave the offboarded+ user's already-minted envelopes executing tools until they expired."""+ envelope = self._mint_bridge_envelope(key_hash=self._KEY_HASH)+ scope = {+ "type": "http",+ "method": "POST",+ "path": "/mcp/bridge_delegate_server",+ "headers": [(b"authorization", f"Bearer {envelope}".encode("latin-1"))],+ }++ with (+ patch("litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager") as mock_mgr,+ patch("litellm.proxy.proxy_server.master_key", self._MASTER_KEY),+ self._patch_key_reload(+ return_value=self._reloaded_key(),+ owner=MagicMock(metadata={"scim_active": False}),+ ),+ ):+ mock_mgr.get_mcp_server_by_name.return_value = self._bridge_delegate_server()+ with pytest.raises(HTTPException) as exc_info:+ await MCPRequestHandler.process_mcp_request(scope)++ assert exc_info.value.status_code == 401++ async def test_scim_active_owner_envelope_admits(self):+ """A SCIM-ACTIVE owner must still be admitted: the gate rejects only an explicit+ ``scim_active: False``, so SCIM-managed users whose accounts are in good standing keep+ working (and non-SCIM deployments, which never set the flag, are untouched)."""+ envelope = self._mint_bridge_envelope(key_hash=self._KEY_HASH)+ scope = {+ "type": "http",+ "method": "POST",+ "path": "/mcp/bridge_delegate_server",+ "headers": [(b"authorization", f"Bearer {envelope}".encode("latin-1"))],+ }++ with (+ patch("litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager") as mock_mgr,+ patch("litellm.proxy.proxy_server.master_key", self._MASTER_KEY),+ self._patch_key_reload(+ return_value=self._reloaded_key(),+ owner=MagicMock(metadata={"scim_active": True}),+ ),+ ):+ mock_mgr.get_mcp_server_by_name.return_value = self._bridge_delegate_server()+ (auth_result, _, _, _, _, _) = await MCPRequestHandler.process_mcp_request(scope)++ assert auth_result.user_id == "envelope-user-42"++ async def test_blocked_project_envelope_fails_closed_401(self):+ """Blocking the key's PROJECT must revoke its envelopes immediately: the admitted identity+ runs through the standard pipeline's centralized policy gate, which rejects a blocked+ project exactly as it would for the same key presented directly. This is the regression for+ the project half of the revocation finding; the gate also covers future policy dimensions+ without the admission arm mirroring them one by one."""+ envelope = self._mint_bridge_envelope(key_hash=self._KEY_HASH)+ scope = {+ "type": "http",+ "method": "POST",+ "path": "/mcp/bridge_delegate_server",+ "headers": [(b"authorization", f"Bearer {envelope}".encode("latin-1"))],+ }++ with (+ patch("litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager") as mock_mgr,+ patch("litellm.proxy.proxy_server.master_key", self._MASTER_KEY),+ self._patch_key_reload(+ return_value=self._reloaded_key(project_id="project-restricted"),+ project_object=MagicMock(blocked=True),+ ),+ ):+ mock_mgr.get_mcp_server_by_name.return_value = self._bridge_delegate_server()+ with pytest.raises(HTTPException) as exc_info:+ await MCPRequestHandler.process_mcp_request(scope)++ assert exc_info.value.status_code == 401+async def test_alias_only_server_injects_under_alias_egress_can_resolve(self):"""When server_name is None, the inner token must be keyed under the alias (which egressresolves), never under server.name (which egress never looks up), so the forwarded token is@@ -5171,12 +5286,53 @@ class TestMCPDcrBridgeDelegateAdmission:server=self._bridge_delegate_server(server_name="bridge_name", alias="bridge_alias"),authorization_value=f"Bearer {envelope}",mcp_server_auth_headers=attacker_forwarded,+ request=self._mcp_request(),+ route="/mcp/bridge_name",)# The sealed token owns the alias slot, overwriting the caller's value; the attacker token# survives nowhere egress would resolve.assert new_headers == {"bridge_alias": {"Authorization": "Bearer inner-upstream-access-token"}}+ @pytest.mark.parametrize(+ "server_name,alias",+ [+ (None, "bridge_alias"),+ ("bridge_delegate_server", None),+ ("bridge_name", "bridge_alias"),+ ],+ ids=["alias_only", "server_name_only", "both"],+ )+ async def test_injection_key_agrees_with_egress_lookup(self, server_name, alias):+ """Round-trip the injected headers through the REAL egress resolver for every admissible+ server shape: whatever identifier the admission arm keys the sealed token under,+ ``lookup_mcp_server_auth_in_headers`` called the way egress calls it (alias first, then+ server_name) must recover exactly that token. This pins the agreement between the two key+ hierarchies so neither side can drift and silently drop the forwarded token."""+ from litellm.proxy._experimental.mcp_server.utils import lookup_mcp_server_auth_in_headers++ envelope = self._mint_bridge_envelope()+ server = self._bridge_delegate_server(server_name=server_name, alias=alias)++ with (+ patch("litellm.proxy.proxy_server.master_key", self._MASTER_KEY),+ self._patch_key_reload(return_value=self._reloaded_key()),+ ):+ _auth, new_headers = await MCPRequestHandler._admit_dcr_bridge_delegate(+ server=server,+ authorization_value=f"Bearer {envelope}",+ mcp_server_auth_headers=None,+ request=self._mcp_request(),+ route="/mcp/bridge_delegate_server",+ )++ resolved = lookup_mcp_server_auth_in_headers(+ new_headers,+ alias=server.alias,+ server_name=server.server_name,+ )+ assert resolved == {"Authorization": "Bearer inner-upstream-access-token"}+async def test_server_with_no_alias_or_server_name_is_not_admitted_via_bridge_arm(self):"""A bridge server egress cannot route to (no alias and no server_name) must not take theenvelope arm; it fails closed to normal oauth2 admission rather than admitting and dropping@@ -5447,6 +5603,8 @@ class TestMCPDcrBridgeDelegateAdmission:server=self._bridge_delegate_server(),authorization_value=f"Bearer {envelope}",mcp_server_auth_headers=existing,+ request=self._mcp_request(),+ route="/mcp/bridge_delegate_server",)assert auth_result.user_id == "unit-user"@@ -5469,6 +5627,8 @@ class TestMCPDcrBridgeDelegateAdmission:server=self._bridge_delegate_server(),authorization_value=f"Bearer {envelope}",mcp_server_auth_headers=None,+ request=self._mcp_request(),+ route="/mcp/bridge_delegate_server",)assert exc_info.value.status_code == 500@@ -5485,5 +5645,7 @@ class TestMCPDcrBridgeDelegateAdmission:server=self._bridge_delegate_server(),authorization_value=f"Bearer {envelope}",mcp_server_auth_headers=None,+ request=self._mcp_request(),+ route="/mcp/bridge_delegate_server",)assert exc_info.value.status_code == 500