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
Merge origin/litellm_internal_staging (#32980 bridge refresh envelope) into litellm_mcp_oauth_error_relay
Tin Chi Lob70de76df3dd
diff --cc litellm/proxy/_experimental/mcp_server/discoverable_endpoints.pyindex 6435db37645,80ffad487c5..b6e9a094cd5--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py@@@ -24,14 -24,6 +24,15 @@@ from litellm.proxy._experimental.mcp_seTokenEndpointAuthConfigError,build_token_endpoint_client_auth,)+from litellm.proxy._experimental.mcp_server.faults import (++ CallerRejected,+ CredentialSource,+ UpstreamProtocolFault,+ classify_upstream_dcr_rejection,+ classify_upstream_token_rejection,+ dcr_fault_detail,+ render_token_fault,+)from litellm.proxy._experimental.mcp_server.oauth_utils import (TOKEN_NO_CACHE_HEADERS,get_request_base_url,@@@ -988,13 -1281,78 +1290,70 @@@ def _finish_bridge_mintreturn JSONResponse(body, headers=TOKEN_NO_CACHE_HEADERS)+def _token_credential_source(mcp_server: MCPServer) -> CredentialSource:+ """Mirrors the resolved-client rule in :func:`exchange_token_with_server`: when the server has a+ stored client_id the gateway presents its own credentials upstream, so a credential rejection is+ the operator's fault, not the caller's."""+ return "gateway_stored" if mcp_server.client_id else "caller_supplied"+++ def _upstream_refresh_credential(token_response: object) -> "RefreshCredential | None":+ """Extract the upstream refresh grant from a token response, or ``None`` when there is none to seal.+ Each field is isinstance-checked so nothing untyped reaches the refresh envelope; ``refresh_expires_in``+ (the refresh token's own lifetime, when the upstream reports it) is classified like ``expires_in`` and+ bounds the refresh envelope's TTL. An upstream that reports the refresh token itself as already elapsed+ (``refresh_expires_in`` non-positive) yields ``None`` rather than a refresh envelope: sealing a dead+ token would hand the client a full-TTL-capped envelope the IdP will reject, so the exchange degrades to+ an access-only response (the client re-authenticates at access expiry), mirroring how+ :func:`_bridge_grant_from_token_response` refuses an already-elapsed access token instead of capping it."""+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import ( # noqa: PLC0415 # inline import avoids a module-load circular import+ RefreshCredential,+ )++ if not isinstance(token_response, dict):+ return None+ refresh = token_response.get("refresh_token")+ if not isinstance(refresh, str) or not refresh:+ return None+ lifetime = _classify_upstream_lifetime(token_response.get("refresh_expires_in"))+ if lifetime == "expired":+ return None+ scope = token_response.get("scope")+ return RefreshCredential(+ refresh_token=SecretStr(refresh),+ scope=scope if isinstance(scope, str) and scope else None,+ expires_in=lifetime if isinstance(lifetime, int) else None,+ )+++ def _mint_refresh_envelope_value(+ identity: "EnvelopeIdentity", token_response: object, keys: "EnvelopeKeys", now: datetime, mcp_server: MCPServer+ ) -> str | None:+ """Seal the upstream refresh grant (if any) into a refresh envelope and return its bearer string, or+ ``None`` when the upstream returned no refresh token or the refresh token is too large to seal. A+ too-large refresh token degrades to an access-only response (logged) rather than failing an exchange+ that already succeeded upstream: the client simply re-authenticates when the access envelope expires."""+ from litellm.proxy._experimental.mcp_server.outbound_credentials.bridge_credentials import ( # noqa: PLC0415 # inline import avoids a module-load circular import+ build_bridge_refresh_token_response,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import ( # noqa: PLC0415 # inline import avoids a module-load circular import+ SealedEnvelope,+ )++ refresh_credential = _upstream_refresh_credential(token_response)+ if refresh_credential is None:+ return None+ sealed = build_bridge_refresh_token_response(identity, refresh_credential, keys, now)+ if isinstance(sealed, SealedEnvelope):+ return sealed.token.get_secret_value()+ verbose_logger.warning(+ "bridge mint: the upstream refresh token is too large to seal into a refresh envelope for "+ "server=%s; issuing an access-only response, so the client re-authenticates at access expiry",+ mcp_server.server_id,+ )+ return None++-def _upstream_oauth_error(response: httpx.Response) -> str | None:- """The RFC 6749 5.2 ``error`` code from an upstream token-endpoint error body, or ``None`` when the- body is not a JSON object carrying a string ``error``. Reading the field beats substring-matching the- raw text, which would false-match a code that only appears inside ``error_description`` (a false- invalid_grant would trigger a needless authorization_code re-run)."""- try:- body = json.loads(response.text)- except (ValueError, TypeError):- return None- if not isinstance(body, dict):- return None- error = body.get("error")- return error if isinstance(error, str) else None--async def exchange_token_with_server(request: Request,mcp_server: MCPServer,@@@ -1067,39 -1461,50 +1462,48 @@@}if code_verifier:token_data["code_verifier"] = code_verifier-- # Phase 1: for a bridge oauth_delegate mint, validate all preconditions and resolve identity+keys- # BEFORE the exchange below consumes the single-use upstream code, and carry the ready context to- # phase 3. A failure here returns without ever touching the upstream credential.- bridge_mint_ready: _BridgeMintReady | None = None- if mcp_server.is_oauth_delegate and mcp_server.is_dcr_bridge:- prepared = await _prepare_bridge_mint(request, grant_type)- if not isinstance(prepared, _BridgeMintReady):- return _bridge_mint_error_response(prepared)- bridge_mint_ready = prepared-+ # Phase 1 for a bridge authorization_code mint: resolve identity (the SSO user recovered above, or+ # the presented litellm key) and the envelope keys BEFORE the exchange consumes the single-use code.+ if is_bridge:+ prepared = await _prepare_bridge_mint(request, mcp_server, bridge_identity)+ if not isinstance(prepared, _BridgeMintReady):+ return _bridge_mint_error_response(prepared)+ bridge_mint_ready = preparedasync_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.Oauth2Check)- response = await async_client.post(- mcp_server.token_url,- headers={"Accept": "application/json", **client_auth.headers},- data=token_data,- )- if response is None:- raise HTTPException(- status_code=502,- detail="MCP upstream token endpoint returned no response",- )-try:- response.raise_for_status()+ response = await async_client.post(+ mcp_server.token_url,+ headers={"Accept": "application/json", **client_auth.headers},+ data=token_data,+ )+ if response is not None:+ response.raise_for_status()except httpx.HTTPStatusError as exc:- return render_token_fault(- classify_upstream_token_rejection(- exc.response,- credential_source=_token_credential_source(mcp_server),- log_context=mcp_server.server_id,- if "invalid_target" in exc.response.text:- verbose_logger.warning(- "MCP server %s: the upstream authorization server rejected the token request with "- "invalid_target; it may require RFC 8707 resource indicators, which the gateway "- "does not send yet (tracked as LIT-4339)",- mcp_server.server_id,-- )++ fault = classify_upstream_token_rejection(++ exc.response,++ credential_source=_token_credential_source(mcp_server),++ log_context=mcp_server.server_id,++ )+ upstream_rejected_bridge_refresh = (+ is_bridge+ and grant_type == "refresh_token"- and exc.response.status_code == 400- and _upstream_oauth_error(exc.response) == "invalid_grant"++ and isinstance(fault, CallerRejected)++ and fault.code == "invalid_grant")+ if upstream_rejected_bridge_refresh:+ verbose_logger.info(+ "bridge refresh: the upstream rejected the sealed refresh token for server=%s with "+ "invalid_grant (revoked or expired at the IdP); returning invalid_grant so the client "+ "re-runs authorization_code rather than an opaque upstream error",+ mcp_server.server_id,+ )+ return _bridge_mint_error_response("invalid_refresh")- raise++ return render_token_fault(fault)+ if response is None:+ raise HTTPException(+ status_code=502,+ detail="MCP upstream token endpoint returned no response",+ )token_response = response.json()# Validate token response against server-configured rules before any storage.diff --cc tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.pyindex a67579c79ca,437fbc435a3..47a49b96327--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py@@@ -4559,6 -4744,553 +4752,560 @@@ async def test_bridge_refresh_grant_witfake_http_client.post.assert_not_called()+ def _mint_test_refresh_envelope(+ server_id="bridge_srv", key_hash="hashed-litellm-key-77", upstream_refresh="UPSTREAM-REFRESH", identity=None,+ scope=None,+ ):+ """Mint a refresh envelope the way the producer does, for driving the refresh_token grant in tests.+ Defaults to a key_hash subject; pass ``identity`` to seal a specific subject (e.g. a user_id), and+ ``scope`` to seal the scope to re-request on refresh."""+ from datetime import datetime, timezone++ from pydantic import SecretStr++ from litellm.proxy._experimental.mcp_server.outbound_credentials.bridge_credentials import (+ build_bridge_refresh_token_response,+ envelope_keys_from_master_key,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import (+ RefreshCredential,+ SealedEnvelope,+ key_hash_identity,+ )++ keys = envelope_keys_from_master_key(_BRIDGE_MASTER_KEY)+ identity = identity if identity is not None else key_hash_identity(server_id=server_id, key_hash=key_hash)+ sealed = build_bridge_refresh_token_response(+ identity, RefreshCredential(refresh_token=SecretStr(upstream_refresh), scope=scope), keys,+ datetime.now(timezone.utc),+ )+ assert isinstance(sealed, SealedEnvelope)+ return sealed.token.get_secret_value()+++ async def _refresh_for_bridge_server(+ server, refresh_envelope_value, upstream_body, revalidate_result=None, fake_client_out=None+ ):+ """Drive a refresh_token grant for a bridge server: the client presents ``refresh_envelope_value``,+ the sealed subject re-validates to ``revalidate_result`` (``None`` when the key or user is still+ active, or a failure literal like "no_active_key" when revoked/deactivated), and the upstream returns+ ``upstream_body``. Patching the single subject-revalidation dispatch covers both a key_hash and a+ user_id refresh envelope. Returns the response; the captured client exposes the POST call so a test+ can assert what refresh token was actually sent upstream."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import exchange_token_with_server++ fake_http_response = MagicMock()+ fake_http_response.json.return_value = upstream_body+ fake_http_response.raise_for_status = MagicMock()+ fake_http_client = MagicMock()+ fake_http_client.post = AsyncMock(return_value=fake_http_response)+ if fake_client_out is not None:+ fake_client_out["client"] = fake_http_client++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",+ return_value=fake_http_client,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._revalidate_active_subject",+ new=AsyncMock(return_value=revalidate_result),+ ),+ patch("litellm.proxy.proxy_server.master_key", _BRIDGE_MASTER_KEY),+ ):+ return await exchange_token_with_server(+ request=_bridge_mock_request(),+ mcp_server=server,+ grant_type="refresh_token",+ code=None,+ redirect_uri=None,+ client_id="dcr-client-123",+ client_secret=None,+ code_verifier=None,+ refresh_token=refresh_envelope_value,+ )+++ @pytest.mark.asyncio+ async def test_bridge_mint_returns_refresh_envelope_that_opens_to_upstream_refresh():+ """When the upstream returns a refresh token, the authorization_code mint returns a refresh envelope+ alongside the access envelope. The refresh envelope is a distinct llm_refresh_ credential that opens+ (under the same keys and server_id) to the upstream refresh token, so the client can renew later."""+ from datetime import datetime, timezone++ from litellm.proxy._experimental.mcp_server.outbound_credentials.bridge_credentials import (+ envelope_keys_from_master_key,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import (+ OpenedRefreshEnvelope,+ open_refresh_envelope,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ upstream = {"access_token": "UP", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "R-UP"}+ response = await _exchange_for_bridge_server(server, upstream, key_hash="hashed-litellm-key-77")++ body = json.loads(response.body)+ refresh_env = body["refresh_token"]+ assert refresh_env.startswith("llm_refresh_")+ keys = envelope_keys_from_master_key(_BRIDGE_MASTER_KEY)+ opened = open_refresh_envelope(refresh_env, keys, datetime.now(timezone.utc))+ assert isinstance(opened, OpenedRefreshEnvelope)+ assert opened.identity.server_id == server.server_id+ assert opened.refresh.refresh_token.get_secret_value() == "R-UP"+++ @pytest.mark.asyncio+ async def test_bridge_mint_omits_refresh_envelope_when_upstream_has_no_refresh():+ """No refresh envelope is issued when the upstream returns no refresh token, so the response carries+ only the access envelope; the client re-authenticates at access expiry (nothing to renew with)."""+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ upstream = {"access_token": "UP", "token_type": "Bearer", "expires_in": 3600}+ response = await _exchange_for_bridge_server(server, upstream, key_hash="hashed-litellm-key-77")++ body = json.loads(response.body)+ assert body["access_token"].startswith("llm_env_")+ assert "refresh_token" not in body+++ @pytest.mark.asyncio+ async def test_bridge_refresh_grant_sends_unwrapped_upstream_token_and_renews():+ """A refresh_token grant carrying a valid refresh envelope renews: the exchange unwraps the envelope+ and sends the REAL upstream refresh token upstream (never the envelope), then returns a fresh access+ envelope. This is the flow that lets the client renew without re-authenticating."""+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ refresh_env = _mint_test_refresh_envelope(server_id=server.server_id, upstream_refresh="UPSTREAM-REFRESH")+ upstream = {"access_token": "NEW-ACCESS", "token_type": "Bearer", "expires_in": 3600}+ captured: dict = {}+ response = await _refresh_for_bridge_server(server, refresh_env, upstream, None, fake_client_out=captured)++ assert response.status_code == 200+ body = json.loads(response.body)+ assert body["access_token"].startswith("llm_env_")+ # the upstream exchange received the unwrapped upstream refresh token, never the client's envelope+ sent = captured["client"].post.call_args.kwargs["data"]+ assert sent["grant_type"] == "refresh_token"+ assert sent["refresh_token"] == "UPSTREAM-REFRESH"+ assert not sent["refresh_token"].startswith("llm_refresh_")+++ @pytest.mark.asyncio+ async def test_bridge_refresh_grant_rotates_refresh_envelope_wrapping_new_upstream_token():+ """When the upstream rotates the refresh token on renewal, the client receives a new refresh envelope+ that wraps the NEW upstream refresh token, so the rotation is carried through faithfully."""+ from datetime import datetime, timezone++ from litellm.proxy._experimental.mcp_server.outbound_credentials.bridge_credentials import (+ envelope_keys_from_master_key,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import (+ OpenedRefreshEnvelope,+ open_refresh_envelope,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ refresh_env = _mint_test_refresh_envelope(server_id=server.server_id, upstream_refresh="OLD-UP-REFRESH")+ upstream = {+ "access_token": "NEW-ACCESS",+ "token_type": "Bearer",+ "expires_in": 3600,+ "refresh_token": "NEW-UP-REFRESH",+ }+ response = await _refresh_for_bridge_server(server, refresh_env, upstream, None)++ body = json.loads(response.body)+ keys = envelope_keys_from_master_key(_BRIDGE_MASTER_KEY)+ opened = open_refresh_envelope(body["refresh_token"], keys, datetime.now(timezone.utc))+ assert isinstance(opened, OpenedRefreshEnvelope)+ assert opened.refresh.refresh_token.get_secret_value() == "NEW-UP-REFRESH"+++ @pytest.mark.asyncio+ async def test_bridge_refresh_grant_with_revoked_key_is_invalid_grant_before_upstream():+ """A valid refresh envelope whose sealed litellm key has since been revoked cannot keep refreshing:+ the reload gate reports no_active_key and the refresh is invalid_grant, returned BEFORE the upstream+ exchange so the upstream refresh token is never consumed. Revocation kills renewal."""+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ refresh_env = _mint_test_refresh_envelope(server_id=server.server_id)+ captured: dict = {}+ response = await _refresh_for_bridge_server(+ server, refresh_env, {"access_token": "NEW"}, "no_active_key", fake_client_out=captured+ )++ assert response.status_code == 400+ assert json.loads(response.body)["error"] == "invalid_grant"+ captured["client"].post.assert_not_called()+++ @pytest.mark.asyncio+ async def test_bridge_refresh_envelope_for_another_server_is_invalid_grant():+ """A refresh envelope minted for one server cannot renew against another: the sealed server_id must+ match the server the refresh targets, so a cross-server refresh envelope is invalid_grant and never+ reaches the upstream exchange."""+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ foreign_env = _mint_test_refresh_envelope(server_id="some-other-server")+ captured: dict = {}+ response = await _refresh_for_bridge_server(+ server, foreign_env, {"access_token": "NEW"}, None, fake_client_out=captured+ )++ assert response.status_code == 400+ assert json.loads(response.body)["error"] == "invalid_grant"+ captured["client"].post.assert_not_called()+++ @pytest.mark.asyncio+ async def test_bridge_refresh_grant_renews_a_user_subject_envelope():+ """The interactive SSO client mints a user_id-subject envelope, so its refresh envelope carries a+ user subject too. Renewing it re-validates the user (still active here), unwraps the upstream refresh+ token, and returns a fresh access envelope that opens back to the same user_id subject; the upstream+ exchange received the real upstream refresh token, not the client's envelope."""+ from datetime import datetime, timezone++ from litellm.proxy._experimental.mcp_server.outbound_credentials.bridge_credentials import (+ BridgeEnvelopeAdmitted,+ envelope_keys_from_master_key,+ resolve_bridge_envelope,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import user_identity+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ user_env = _mint_test_refresh_envelope(+ identity=user_identity(server_id=server.server_id, user_id="sso-user-42"), upstream_refresh="UP-REFRESH-USER"+ )+ upstream = {"access_token": "NEW-ACCESS", "token_type": "Bearer", "expires_in": 3600}+ captured: dict = {}+ response = await _refresh_for_bridge_server(server, user_env, upstream, None, fake_client_out=captured)++ assert response.status_code == 200+ body = json.loads(response.body)+ keys = envelope_keys_from_master_key(_BRIDGE_MASTER_KEY)+ opened = resolve_bridge_envelope(body["access_token"], keys, datetime.now(timezone.utc), server.server_id)+ assert isinstance(opened, BridgeEnvelopeAdmitted)+ assert opened.identity.subject_type == "user_id"+ assert opened.identity.subject == "sso-user-42"+ assert captured["client"].post.call_args.kwargs["data"]["refresh_token"] == "UP-REFRESH-USER"+++ @pytest.mark.asyncio+ async def test_bridge_refresh_re_requests_the_sealed_scope_when_client_omits_it():+ """A DCR/MCP client omits scope on the refresh request, so the gateway must re-request the scope sealed+ at mint; dropping it lets a stricter upstream narrow the renewed token. The upstream POST must carry+ the sealed scope even though the client sent none. Regression for the dropped sealed refresh scope."""+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ refresh_env = _mint_test_refresh_envelope(+ server_id=server.server_id, upstream_refresh="UP-REFRESH", scope="read:tools write:tools"+ )+ captured: dict = {}+ response = await _refresh_for_bridge_server(+ server, refresh_env, {"access_token": "NEW-ACCESS", "token_type": "Bearer", "expires_in": 3600}, None,+ fake_client_out=captured,+ )++ assert response.status_code == 200+ assert captured["client"].post.call_args.kwargs["data"]["scope"] == "read:tools write:tools"+++ @pytest.mark.asyncio+ async def test_bridge_refresh_re_seals_scope_when_upstream_omits_it_so_the_chain_keeps_it():+ """RFC 6749 5.1 lets an upstream omit scope in a refresh response when it is unchanged. The re-minted+ refresh envelope must still seal the scope that was requested, otherwise the NEXT refresh loses it and+ a stricter upstream could narrow the token. The returned refresh envelope carries the scope even though+ the upstream response had none, and a second refresh off it still re-requests the scope."""+ from datetime import datetime, timezone++ from litellm.proxy._experimental.mcp_server.outbound_credentials.bridge_credentials import (+ envelope_keys_from_master_key,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import (+ OpenedRefreshEnvelope,+ open_refresh_envelope,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ refresh_env = _mint_test_refresh_envelope(+ server_id=server.server_id, upstream_refresh="UP-1", scope="mcp:read mcp:write"+ )+ # the upstream rotates the refresh token but OMITS scope (valid when unchanged)+ upstream_no_scope = {"access_token": "NEW", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "UP-2"}++ captured: dict = {}+ r1 = await _refresh_for_bridge_server(server, refresh_env, upstream_no_scope, None, fake_client_out=captured)+ assert r1.status_code == 200+ assert captured["client"].post.call_args.kwargs["data"]["scope"] == "mcp:read mcp:write"++ keys = envelope_keys_from_master_key(_BRIDGE_MASTER_KEY)+ new_env = json.loads(r1.body)["refresh_token"]+ opened = open_refresh_envelope(new_env, keys, datetime.now(timezone.utc))+ assert isinstance(opened, OpenedRefreshEnvelope)+ assert opened.refresh.scope == "mcp:read mcp:write"++ captured2: dict = {}+ r2 = await _refresh_for_bridge_server(server, new_env, upstream_no_scope, None, fake_client_out=captured2)+ assert r2.status_code == 200+ assert captured2["client"].post.call_args.kwargs["data"]["scope"] == "mcp:read mcp:write"+++ @pytest.mark.asyncio+ async def test_bridge_refresh_grant_with_deactivated_user_is_invalid_grant_before_upstream():+ """A user_id-subject refresh envelope whose user has since been deactivated (SCIM offboarding, or+ the user no longer exists) cannot keep refreshing: subject re-validation reports no_active_key and+ the refresh is invalid_grant, returned BEFORE the upstream exchange. Revocation kills renewal for the+ user subject exactly as it does for the key subject."""+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import user_identity+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ user_env = _mint_test_refresh_envelope(identity=user_identity(server_id=server.server_id, user_id="gone-user"))+ captured: dict = {}+ response = await _refresh_for_bridge_server(+ server, user_env, {"access_token": "NEW"}, "no_active_key", fake_client_out=captured+ )++ assert response.status_code == 400+ assert json.loads(response.body)["error"] == "invalid_grant"+ captured["client"].post.assert_not_called()+++ @pytest.mark.asyncio+ async def test_revalidate_active_subject_dispatches_on_subject_type():+ """Subject re-validation routes a key_hash envelope to the key reload and a user_id envelope to the+ user reload, so revocation gates renewal for either identity source through one dispatch point."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ _ResolvedKey,+ _revalidate_active_subject,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import key_hash_identity, user_identity++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._reload_active_key_by_hash",+ new=AsyncMock(return_value=_ResolvedKey(key_hash="kh", key=MagicMock())),+ ) as key_reload,+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._reload_active_user_by_id",+ new=AsyncMock(return_value=None),+ ) as user_reload,+ ):+ assert await _revalidate_active_subject(key_hash_identity(server_id="s", key_hash="kh")) is None+ key_reload.assert_awaited_once_with("kh")+ user_reload.assert_not_awaited()++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._reload_active_key_by_hash",+ new=AsyncMock(),+ ) as key_reload2,+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._reload_active_user_by_id",+ new=AsyncMock(return_value="no_active_key"),+ ) as user_reload2,+ ):+ assert await _revalidate_active_subject(user_identity(server_id="s", user_id="u42")) == "no_active_key"+ user_reload2.assert_awaited_once_with("u42")+ key_reload2.assert_not_awaited()+++ def test_upstream_refresh_credential_expired_refresh_token_is_not_sealed():+ """An upstream that reports its refresh token already elapsed (refresh_expires_in non-positive) must+ not be sealed: _upstream_refresh_credential returns None so the exchange degrades to an access-only+ response, mirroring how the access grant refuses an already-elapsed access token rather than capping a+ dead token to the full refresh TTL. A live or unspecified lifetime still yields a credential."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import _upstream_refresh_credential++ assert _upstream_refresh_credential({"access_token": "A", "refresh_token": "R", "refresh_expires_in": 0}) is None+ assert _upstream_refresh_credential({"refresh_token": "R", "refresh_expires_in": -5}) is None+ live = _upstream_refresh_credential({"refresh_token": "R", "refresh_expires_in": 1800})+ assert live is not None and live.expires_in == 1800+ unspecified = _upstream_refresh_credential({"refresh_token": "R"})+ assert unspecified is not None and unspecified.expires_in is None+++ @pytest.mark.asyncio+ async def test_bridge_refresh_upstream_invalid_grant_maps_to_invalid_grant():+ """When the sealed upstream refresh token has been revoked or expired at the IdP, the upstream returns+ 400 invalid_grant. The bridge refresh path maps that to an RFC 6749 invalid_grant response so the OAuth+ client re-runs authorization_code, rather than surfacing the opaque upstream error it cannot act on."""+ import httpx++ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import exchange_token_with_server+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ refresh_env = _mint_test_refresh_envelope(server_id=server.server_id, upstream_refresh="LIVE-ENVELOPE-REFRESH")++ error_response = MagicMock()+ error_response.status_code = 400+ error_response.text = '{"error": "invalid_grant", "error_description": "refresh token expired"}'++ error_response.json = MagicMock(return_value={"error": "invalid_grant", "error_description": "refresh token expired"})+ error_response.raise_for_status = MagicMock(+ side_effect=httpx.HTTPStatusError("bad", request=MagicMock(), response=error_response)+ )+ fake_http_client = MagicMock()+ fake_http_client.post = AsyncMock(return_value=error_response)++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",+ return_value=fake_http_client,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._revalidate_active_subject",+ new=AsyncMock(return_value=None),+ ),+ patch("litellm.proxy.proxy_server.master_key", _BRIDGE_MASTER_KEY),+ ):+ response = await exchange_token_with_server(+ request=_bridge_mock_request(),+ mcp_server=server,+ grant_type="refresh_token",+ code=None,+ redirect_uri=None,+ client_id="dcr-client-123",+ client_secret=None,+ code_verifier=None,+ refresh_token=refresh_env,+ )++ assert response.status_code == 400+ assert json.loads(response.body)["error"] == "invalid_grant"+++ @pytest.mark.asyncio+ async def test_bridge_refresh_upstream_error_detection_parses_json_not_substring():- """The upstream invalid_grant detection parses the RFC 6749 5.2 error field, not a substring of the- body. An upstream error whose code is not invalid_grant (here invalid_client, with the string- invalid_grant only inside error_description) must NOT be mistaken for a dead refresh token, so it- propagates as the upstream error rather than triggering a spurious authorization_code re-run."""++ """The upstream invalid_grant detection reads the classified RFC 6749 5.2 error code, not a substring++ of the body. An upstream error whose code is not invalid_grant (here invalid_client, with the string++ invalid_grant only inside error_description) must NOT be mistaken for a dead refresh token: it renders++ as the classified upstream rejection rather than triggering a spurious authorization_code re-run."""+ import httpx++ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import exchange_token_with_server+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ refresh_env = _mint_test_refresh_envelope(server_id=server.server_id, upstream_refresh="UP")++ error_response = MagicMock()+ error_response.status_code = 400+ error_response.text = '{"error": "invalid_client", "error_description": "this is not an invalid_grant problem"}'++ error_response.json = MagicMock(++ return_value={"error": "invalid_client", "error_description": "this is not an invalid_grant problem"}++ )+ error_response.raise_for_status = MagicMock(+ side_effect=httpx.HTTPStatusError("bad", request=MagicMock(), response=error_response)+ )+ fake_http_client = MagicMock()+ fake_http_client.post = AsyncMock(return_value=error_response)++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",+ return_value=fake_http_client,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._revalidate_active_subject",+ new=AsyncMock(return_value=None),+ ),+ patch("litellm.proxy.proxy_server.master_key", _BRIDGE_MASTER_KEY),+ ):- with pytest.raises(httpx.HTTPStatusError):- await exchange_token_with_server(- request=_bridge_mock_request(),- mcp_server=server,- grant_type="refresh_token",- code=None,- redirect_uri=None,- client_id="dcr-client-123",- client_secret=None,- code_verifier=None,- refresh_token=refresh_env,- )++ response = await exchange_token_with_server(++ request=_bridge_mock_request(),++ mcp_server=server,++ grant_type="refresh_token",++ code=None,++ redirect_uri=None,++ client_id="dcr-client-123",++ client_secret=None,++ code_verifier=None,++ refresh_token=refresh_env,++ )++++ assert response.status_code == 401++ body = json.loads(response.body)++ assert body["error"] == "invalid_client"+++ @pytest.mark.asyncio+ async def test_revalidate_key_subject_revoked_when_owner_scim_deactivated(proxy_globals):+ """A key_hash refresh envelope whose key is still active but whose OWNING user was SCIM-deactivated must+ fail closed to no_active_key, mirroring how admission's _reject_if_admitted_owner_scim_deactivated+ revokes an offboarded owner's key. Without this, an offboarded user keeps renewing a live key."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import _ResolvedKey, _revalidate_active_subject+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import key_hash_identity+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache++ proxy_globals.user_api_key_cache = UserApiKeyCache()+ proxy_globals.prisma_client = object()++ resolved = _ResolvedKey(key_hash="kh", key=MagicMock(user_id="offboarded-owner"))+ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._reload_active_key_by_hash",+ new=AsyncMock(return_value=resolved),+ ),+ patch(+ "litellm.proxy.auth.auth_checks.get_user_object",+ new=AsyncMock(return_value=MagicMock(metadata={"scim_active": False})),+ ),+ ):+ result = await _revalidate_active_subject(key_hash_identity(server_id="s", key_hash="kh"))++ assert result == "no_active_key"+++ @pytest.mark.asyncio+ async def test_revalidate_key_subject_active_owner_renews_and_missing_owner_fails_open(proxy_globals):+ """The key-owner SCIM gate blocks only an explicit scim_active False: an active owner renews (None), and+ a missing owner (get_user_object's wrapped ValueError) fails OPEN, since a key may outlive its owner+ record and a transient blip must not revoke a live key."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import _ResolvedKey, _revalidate_active_subject+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import key_hash_identity+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache++ proxy_globals.user_api_key_cache = UserApiKeyCache()+ proxy_globals.prisma_client = object()+ resolved = _ResolvedKey(key_hash="kh", key=MagicMock(user_id="live-owner"))+ identity = key_hash_identity(server_id="s", key_hash="kh")++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._reload_active_key_by_hash",+ new=AsyncMock(return_value=resolved),+ ),+ patch(+ "litellm.proxy.auth.auth_checks.get_user_object",+ new=AsyncMock(return_value=MagicMock(metadata={"scim_active": True})),+ ),+ ):+ assert await _revalidate_active_subject(identity) is None++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._reload_active_key_by_hash",+ new=AsyncMock(return_value=resolved),+ ),+ patch(+ "litellm.proxy.auth.auth_checks.get_user_object",+ new=AsyncMock(side_effect=_wrapped_user_lookup_error(Exception())),+ ),+ ):+ assert await _revalidate_active_subject(identity) is None++@pytest.mark.asyncioasync def test_bridge_mint_fails_closed_before_upstream_when_master_key_unset():"""master_key is validated BEFORE the upstream exchange (in _prepare_bridge_mint), so a