From 4829bb3a151c4b4e58580313784862eb966921e1 Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Wed, 19 Aug 2026 21:25:06 -0700 Subject: [PATCH 01/35] fix(prompt_management): don't route requests without prompt_id to prompt managers that can't run them UI-injected empty vector_store_ids/tags/guardrails on a DB model tripped the dynamic-param check, and the prompt-management fallback then handed the request to the first registered prompt manager (e.g. a saved dotprompt), whose sync path raised "prompt_id is required" as a 500 on every /chat/completions call. Empty dynamic params no longer count as a trigger, the fallback skips managers whose should_run_prompt_management declines a None prompt_id, and the sync base path returns the request unchanged for a None prompt_id like the async path. --- .../integrations/prompt_management_base.py | 2 +- litellm/litellm_core_utils/litellm_logging.py | 30 ++++++- .../test_litellm_logging.py | 78 +++++++++++++++++++ 3 files changed, 105 insertions(+), 5 deletions(-) diff --git a/litellm/integrations/prompt_management_base.py b/litellm/integrations/prompt_management_base.py index d16afa92ec2..81c01599e77 100644 --- a/litellm/integrations/prompt_management_base.py +++ b/litellm/integrations/prompt_management_base.py @@ -165,7 +165,7 @@ class PromptManagementBase(ABC): ignore_prompt_manager_optional_params: bool | None = False, ) -> tuple[str, list[AllMessageValues], dict]: if prompt_id is None: - raise ValueError("prompt_id is required for Prompt Management Base class") + return model, messages, non_default_params if not self.should_run_prompt_management( prompt_id=prompt_id, prompt_spec=prompt_spec, diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py index 91a312b4f45..9b7707eabe1 100644 --- a/litellm/litellm_core_utils/litellm_logging.py +++ b/litellm/litellm_core_utils/litellm_logging.py @@ -832,8 +832,8 @@ class Logging(LiteLLMLoggingBaseClass): eg. AnthropicCacheControlHook and BedrockKnowledgeBaseHook both don't require a `prompt_id` to be passed in, they are triggered by dynamic params """ - for param in non_default_params: - if param in DynamicPromptManagementParamLiteral.list_all_params(): + for param in DynamicPromptManagementParamLiteral.list_all_params(): + if non_default_params.get(param): return True ############################################################################# @@ -966,6 +966,23 @@ class Logging(LiteLLMLoggingBaseClass): return None + @staticmethod + def _prompt_manager_runs_without_prompt_id( + logger: CustomLogger, + prompt_spec: PromptSpec | None, + dynamic_callback_params: StandardCallbackDynamicParams | None, + ) -> bool: + if not isinstance(logger, CustomPromptManagement): + return False + try: + return logger.should_run_prompt_management( + prompt_id=None, + prompt_spec=prompt_spec, + dynamic_callback_params=dynamic_callback_params or StandardCallbackDynamicParams(), + ) + except Exception: + return False + def get_custom_logger_for_prompt_management( self, model: str, @@ -1016,8 +1033,13 @@ class Logging(LiteLLMLoggingBaseClass): callback_type=CustomPromptManagement ) - if prompt_management_loggers: - logger: Final = prompt_management_loggers[0] + for logger in prompt_management_loggers: + if prompt_id is None and not self._prompt_manager_runs_without_prompt_id( + logger=logger, + prompt_spec=prompt_spec, + dynamic_callback_params=dynamic_callback_params, + ): + continue self.model_call_details["prompt_integration"] = logger.__class__.__name__ return logger diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py index c2d73ea467d..05aa65034fb 100644 --- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py +++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py @@ -5105,3 +5105,81 @@ def test_set_cost_breakdown_stores_vertex_location(): cost_for_built_in_tools_cost_usd_dollar=0.0, ) assert no_location.cost_breakdown.get("vertex_location") is None + + +def test_prompt_hooks_skip_prompt_managers_when_no_prompt_id(logging_obj, tmp_path, monkeypatch): + """ + Regression for UI-injected `vector_store_ids: []` and always-on non-empty `vector_store_ids` + with a registered prompt manager (e.g. dotprompt): requests without a prompt_id 500'd with + "prompt_id is required for Prompt Management Base class" instead of completing normally. + """ + from litellm.integrations.dotprompt.dotprompt_manager import DotpromptManager + from litellm.integrations.vector_store_integrations.vector_store_pre_call_hook import ( + VectorStorePreCallHook, + ) + from litellm.types.vector_stores import LiteLLM_ManagedVectorStore + from litellm.vector_stores.vector_store_registry import VectorStoreRegistry + + (tmp_path / "stem.prompt").write_text("---\nmodel: gemini-2.5-flash\n---\nyou are a stem tutor\n") + dotprompt_manager = DotpromptManager(prompt_directory=str(tmp_path)) + litellm.logging_callback_manager.add_litellm_callback(dotprompt_manager) + monkeypatch.setattr( + litellm, + "vector_store_registry", + VectorStoreRegistry( + vector_stores=[LiteLLM_ManagedVectorStore(vector_store_id="vs_123", custom_llm_provider="openai")] + ), + ) + + messages = [{"role": "user", "content": "hi"}] + try: + assert not logging_obj.should_run_prompt_management_hooks( + prompt_id=None, non_default_params={"vector_store_ids": []} + ) + + assert logging_obj.get_chat_completion_prompt( + model="gemini-2.5-flash", + messages=messages, + non_default_params={"vector_store_ids": []}, + prompt_variables=None, + prompt_id=None, + ) == ("gemini-2.5-flash", messages, {"vector_store_ids": []}) + + assert dotprompt_manager.get_chat_completion_prompt( + model="gemini-2.5-flash", + messages=messages, + non_default_params={}, + prompt_id=None, + prompt_variables=None, + dynamic_callback_params={}, + ) == ("gemini-2.5-flash", messages, {}) + + assert logging_obj.should_run_prompt_management_hooks( + prompt_id=None, non_default_params={"vector_store_ids": ["vs_123"]} + ) + assert isinstance( + logging_obj.get_custom_logger_for_prompt_management( + model="gemini-2.5-flash", + non_default_params={"vector_store_ids": ["vs_123"]}, + prompt_id=None, + dynamic_callback_params={}, + ), + VectorStorePreCallHook, + ) + + assert isinstance( + logging_obj.get_custom_logger_for_prompt_management( + model="gemini-2.5-flash", + non_default_params={}, + prompt_id="stem", + dynamic_callback_params={}, + ), + DotpromptManager, + ) + finally: + litellm.logging_callback_manager.remove_callback_from_list_by_object(litellm.callbacks, dotprompt_manager) + litellm.logging_callback_manager.remove_callback_from_list_by_object( + litellm._async_success_callback, dotprompt_manager + ) + for hook in [cb for cb in litellm.callbacks if isinstance(cb, VectorStorePreCallHook)]: + litellm.logging_callback_manager.remove_callback_from_list_by_object(litellm.callbacks, hook) From b780b1e23c160ee8b8eb3effe471c280547fa10f Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Wed, 19 Aug 2026 21:38:15 -0700 Subject: [PATCH 02/35] fix(arize): decline prompt management runs without a prompt_id Arize Phoenix claimed it could run without a prompt_id while its compiler requires one, so the no-prompt_id fallback could select it and fail instead of reaching the vector-store hook. It now declines like the other managers. --- .../arize/arize_phoenix_prompt_manager.py | 6 +++--- .../litellm_core_utils/test_litellm_logging.py | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/litellm/integrations/arize/arize_phoenix_prompt_manager.py b/litellm/integrations/arize/arize_phoenix_prompt_manager.py index fa178a02752..71f4902bbe5 100644 --- a/litellm/integrations/arize/arize_phoenix_prompt_manager.py +++ b/litellm/integrations/arize/arize_phoenix_prompt_manager.py @@ -359,10 +359,10 @@ class ArizePhoenixPromptManager(CustomPromptManagement): """ Determine if prompt management should run based on the prompt_id. - For Arize Phoenix, we always return True and handle the prompt loading - in the _compile_prompt_helper method. + Arize Phoenix needs a prompt_id to compile, so it declines requests without one; + prompt loading itself happens in the _compile_prompt_helper method. """ - return True + return prompt_id is not None def _compile_prompt_helper( self, diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py index 05aa65034fb..db64340f895 100644 --- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py +++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py @@ -5113,6 +5113,7 @@ def test_prompt_hooks_skip_prompt_managers_when_no_prompt_id(logging_obj, tmp_pa with a registered prompt manager (e.g. dotprompt): requests without a prompt_id 500'd with "prompt_id is required for Prompt Management Base class" instead of completing normally. """ + from litellm.integrations.arize.arize_phoenix_prompt_manager import ArizePhoenixPromptManager from litellm.integrations.dotprompt.dotprompt_manager import DotpromptManager from litellm.integrations.vector_store_integrations.vector_store_pre_call_hook import ( VectorStorePreCallHook, @@ -5122,7 +5123,9 @@ def test_prompt_hooks_skip_prompt_managers_when_no_prompt_id(logging_obj, tmp_pa (tmp_path / "stem.prompt").write_text("---\nmodel: gemini-2.5-flash\n---\nyou are a stem tutor\n") dotprompt_manager = DotpromptManager(prompt_directory=str(tmp_path)) + arize_manager = ArizePhoenixPromptManager(api_key="fake-key", api_base="http://127.0.0.1:9") litellm.logging_callback_manager.add_litellm_callback(dotprompt_manager) + litellm.logging_callback_manager.add_litellm_callback(arize_manager) monkeypatch.setattr( litellm, "vector_store_registry", @@ -5154,6 +5157,10 @@ def test_prompt_hooks_skip_prompt_managers_when_no_prompt_id(logging_obj, tmp_pa dynamic_callback_params={}, ) == ("gemini-2.5-flash", messages, {}) + assert not arize_manager.should_run_prompt_management( + prompt_id=None, prompt_spec=None, dynamic_callback_params={} + ) + assert logging_obj.should_run_prompt_management_hooks( prompt_id=None, non_default_params={"vector_store_ids": ["vs_123"]} ) @@ -5177,9 +5184,10 @@ def test_prompt_hooks_skip_prompt_managers_when_no_prompt_id(logging_obj, tmp_pa DotpromptManager, ) finally: - litellm.logging_callback_manager.remove_callback_from_list_by_object(litellm.callbacks, dotprompt_manager) - litellm.logging_callback_manager.remove_callback_from_list_by_object( - litellm._async_success_callback, dotprompt_manager - ) + for manager in (dotprompt_manager, arize_manager): + litellm.logging_callback_manager.remove_callback_from_list_by_object(litellm.callbacks, manager) + litellm.logging_callback_manager.remove_callback_from_list_by_object( + litellm._async_success_callback, manager + ) for hook in [cb for cb in litellm.callbacks if isinstance(cb, VectorStorePreCallHook)]: litellm.logging_callback_manager.remove_callback_from_list_by_object(litellm.callbacks, hook) From 5c7604d7facd84df1767a8c2b65a3fb0cfb3873d Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Wed, 19 Aug 2026 23:05:30 -0700 Subject: [PATCH 03/35] test(prompt_management): cover _prompt_manager_runs_without_prompt_id directly --- .../test_litellm_logging.py | 28 +++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py index db64340f895..82de634b488 100644 --- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py +++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py @@ -5115,6 +5115,7 @@ def test_prompt_hooks_skip_prompt_managers_when_no_prompt_id(logging_obj, tmp_pa """ from litellm.integrations.arize.arize_phoenix_prompt_manager import ArizePhoenixPromptManager from litellm.integrations.dotprompt.dotprompt_manager import DotpromptManager + from litellm.integrations.vector_store_integrations.base_vector_store import BaseVectorStore from litellm.integrations.vector_store_integrations.vector_store_pre_call_hook import ( VectorStorePreCallHook, ) @@ -5164,14 +5165,25 @@ def test_prompt_hooks_skip_prompt_managers_when_no_prompt_id(logging_obj, tmp_pa assert logging_obj.should_run_prompt_management_hooks( prompt_id=None, non_default_params={"vector_store_ids": ["vs_123"]} ) - assert isinstance( - logging_obj.get_custom_logger_for_prompt_management( - model="gemini-2.5-flash", - non_default_params={"vector_store_ids": ["vs_123"]}, - prompt_id=None, - dynamic_callback_params={}, - ), - VectorStorePreCallHook, + selected_logger = logging_obj.get_custom_logger_for_prompt_management( + model="gemini-2.5-flash", + non_default_params={"vector_store_ids": ["vs_123"]}, + prompt_id=None, + dynamic_callback_params={}, + ) + assert isinstance(selected_logger, VectorStorePreCallHook) + + assert logging_obj._prompt_manager_runs_without_prompt_id( + logger=BaseVectorStore(), prompt_spec=None, dynamic_callback_params=None + ) + assert not logging_obj._prompt_manager_runs_without_prompt_id( + logger=selected_logger, prompt_spec=None, dynamic_callback_params=None + ) + assert not logging_obj._prompt_manager_runs_without_prompt_id( + logger=dotprompt_manager, prompt_spec=None, dynamic_callback_params=None + ) + assert not logging_obj._prompt_manager_runs_without_prompt_id( + logger=arize_manager, prompt_spec=None, dynamic_callback_params=None ) assert isinstance( From 021a09b1560d9bd79c5abc102d919aa9e18c867b Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 20 Aug 2026 02:00:29 -0700 Subject: [PATCH 04/35] fix(passthrough): resolve vertex live credentials from db model deployments The /vertex_ai/live WebSocket passthrough only ever looked at default_vertex_config and the DEFAULT_VERTEXAI_* env vars, so a proxy whose Vertex credentials live in the DB as a model entry with use_in_pass_through had nothing to authenticate with. The upgrade still succeeded and the socket then closed with a bare 1000 on the first client frame, which gave the client no way to tell a misconfiguration from a normal end of session. Credentials now also resolve from the router deployments flagged use_in_pass_through, preferring the one matching the requested model, and a failure to mint an access token closes 1011 with a reason naming both ways to configure it. Upstream closes other than a plain 1000 are relayed to the client with their code and reason, so Google's own errors reach the caller. The setup frame's model is rewritten to the full projects/.../publishers/google/models resource path, which is what Vertex expects and what lets a bare model id or a gateway alias work over this route. --- litellm/constants.py | 3 + .../llm_passthrough_endpoints.py | 152 ++++++++++--- .../pass_through_endpoints.py | 75 ++++++- .../passthrough_endpoint_router.py | 65 +++++- .../test_llm_pass_through_endpoints.py | 101 +++++++++ .../test_pass_through_endpoints.py | 206 ++++++++++++++++++ .../test_passthrough_endpoint_router.py | 141 ++++++++++++ 7 files changed, 701 insertions(+), 42 deletions(-) diff --git a/litellm/constants.py b/litellm/constants.py index facfc6f7c19..3ce2cfd35a5 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -244,6 +244,9 @@ AIOHTTP_NEEDS_CLEANUP_CLOSED: Final = (3, 13, 0) <= sys.version_info < ( _max_size_env: Final = os.getenv("REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES") REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES: Final = int(_max_size_env) if _max_size_env is not None else None +# RFC 6455 caps the close frame payload at 125 bytes, 2 of which carry the status code +WEBSOCKET_CLOSE_REASON_MAX_BYTES: Final = 123 + # SSL/TLS cipher configuration for faster handshakes # Strategy: Strongly prefer fast modern ciphers, but allow fallback to commonly supported ones # This balances performance with broad compatibility diff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py index c5ab7f1fc63..050ad0fd627 100644 --- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py @@ -9,8 +9,9 @@ Use litellm with Anthropic SDK, Vertex AI SDK, Cohere SDK, etc. import json import os import re +from collections.abc import Callable from types import MappingProxyType -from typing import Annotated, Any, Final, cast +from typing import TYPE_CHECKING, Annotated, Any, Final, cast import httpx from fastapi import APIRouter, Depends, HTTPException, Request, Response, WebSocket @@ -55,11 +56,15 @@ from litellm.types.passthrough_endpoints.pass_through_endpoints import ( LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY, LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY, ) +from litellm.types.passthrough_endpoints.vertex_ai import VertexPassThroughCredentials from litellm.types.utils import LlmProviders from litellm.utils import ProviderConfigManager from .passthrough_endpoint_router import PassthroughEndpointRouter +if TYPE_CHECKING: + from litellm.router import Router + vertex_llm_base: Final = VertexBase() router: Final = APIRouter() openai_passthrough_router: Final = APIRouter() @@ -2373,6 +2378,89 @@ async def cursor_proxy_route( return received_value +VERTEX_LIVE_UNCONFIGURED_CLOSE_REASON: Final = ( + "Vertex AI auth failed: set a use_in_pass_through vertex model, default_vertex_config, or DEFAULT_VERTEXAI_* env" +) + +VERTEX_PUBLISHER_MODEL_PREFIX: Final = "publishers/google/models/" + + +def _get_llm_router() -> "Router | None": + from litellm.proxy.proxy_server import llm_router + + return llm_router + + +def _resolve_vertex_live_credentials( + vertex_project: str | None, + vertex_location: str | None, + model: str | None, +) -> VertexPassThroughCredentials | None: + """ + Resolution order: credentials registered for the requested project/location, then any DB model entry + flagged ``use_in_pass_through``, then ``default_vertex_config`` and the ``DEFAULT_VERTEXAI_*`` env vars + """ + keyed: Final = passthrough_endpoint_router.get_vertex_credentials( + project_id=vertex_project, + location=vertex_location, + ) + if keyed is not None and keyed.vertex_project is not None: + return keyed + from_deployments: Final = passthrough_endpoint_router.get_vertex_credentials_from_router_deployments(model=model) + if from_deployments is not None: + return from_deployments + if keyed is not None: + return keyed + passthrough_endpoint_router.set_default_vertex_config() + return passthrough_endpoint_router.get_vertex_credentials( + project_id=vertex_project, + location=vertex_location, + ) + + +def _build_vertex_live_setup_model_rewriter( + vertex_project: str | None, + vertex_location: str | None, + llm_router: "Router | None", +) -> Callable[[str], str] | None: + """ + Rewrite the ``setup`` frame's model into the full Vertex resource path the Live API requires. + + Clients address the gateway the way they address LiteLLM (bare id or model alias); Vertex reads anything + that is not a ``projects/...`` path as a project name and closes the socket + """ + if vertex_project is None or vertex_location is None: + return None + + def rewrite(setup_model: str) -> str: + if setup_model.startswith("projects/"): + return setup_model + aliased: Final = _resolve_alias_to_upstream_model(setup_model, llm_router) + return ( + f"projects/{vertex_project}/locations/{vertex_location}/" + f"{VERTEX_PUBLISHER_MODEL_PREFIX}{aliased.removeprefix(VERTEX_PUBLISHER_MODEL_PREFIX)}" + ) + + return rewrite + + +def _resolve_alias_to_upstream_model(setup_model: str, llm_router: "Router | None") -> str: + if llm_router is None: + return setup_model + upstream: Final = next( + ( + deployment["litellm_params"]["model"] + for deployment in (llm_router.get_model_list() or ()) + if deployment.get("model_name") == setup_model + ), + None, + ) + if upstream is None: + return setup_model + _, provider, _, _ = litellm.get_llm_provider(model=upstream) + return upstream.removeprefix(f"{provider}/") + + async def vertex_ai_live_websocket_passthrough( websocket: WebSocket, model: str | None = None, @@ -2396,51 +2484,40 @@ async def vertex_ai_live_websocket_passthrough( await websocket.accept() incoming_headers: Final = dict(websocket.headers) - vertex_credentials_config = passthrough_endpoint_router.get_vertex_credentials( - project_id=vertex_project, - location=vertex_location, + vertex_credentials_config: Final = _resolve_vertex_live_credentials( + vertex_project=vertex_project, + vertex_location=vertex_location, + model=model, ) - if vertex_credentials_config is None: - # Attempt to load defaults from environment/config if not already initialised - passthrough_endpoint_router.set_default_vertex_config() - vertex_credentials_config = passthrough_endpoint_router.get_vertex_credentials( - project_id=vertex_project, - location=vertex_location, - ) - - resolved_project = vertex_project - resolved_location: str | None = vertex_location - credentials_value: str | None = None - - if vertex_credentials_config is not None: - resolved_project = resolved_project or vertex_credentials_config.vertex_project - temp_location: Final = resolved_location or vertex_credentials_config.vertex_location - # Ensure resolved_location is a string - if isinstance(temp_location, dict) or temp_location is not None: - resolved_location = str(temp_location) - else: - resolved_location = None - credentials_value = ( - str(vertex_credentials_config.vertex_credentials) - if vertex_credentials_config.vertex_credentials is not None - else None - ) + configured_project: Final = vertex_project or ( + vertex_credentials_config.vertex_project if vertex_credentials_config is not None else None + ) + configured_location: Final = vertex_location or ( + vertex_credentials_config.vertex_location if vertex_credentials_config is not None else None + ) + credentials_value: Final = ( + str(vertex_credentials_config.vertex_credentials) + if vertex_credentials_config is not None and vertex_credentials_config.vertex_credentials is not None + else None + ) try: - resolved_location = resolved_location or (vertex_llm_base.get_default_vertex_location()) - if model: - resolved_location = vertex_llm_base.get_vertex_region( - vertex_region=resolved_location, + resolved_location: Final = ( + vertex_llm_base.get_vertex_region( + vertex_region=configured_location or vertex_llm_base.get_default_vertex_location(), model=model, ) + if model + else configured_location or vertex_llm_base.get_default_vertex_location() + ) ( access_token, resolved_project, ) = await vertex_llm_base._ensure_access_token_async( credentials=credentials_value, - project_id=resolved_project, + project_id=configured_project, custom_llm_provider="vertex_ai_beta", ) except Exception as e: @@ -2453,7 +2530,7 @@ async def vertex_ai_live_websocket_passthrough( request_data={}, ) if websocket.client_state != WebSocketState.DISCONNECTED: - await websocket.close(code=1011, reason="Vertex AI authentication failed") + await websocket.close(code=1011, reason=VERTEX_LIVE_UNCONFIGURED_CLOSE_REASON) return host_location: Final = resolved_location or vertex_llm_base.get_default_vertex_location() @@ -2485,6 +2562,11 @@ async def vertex_ai_live_websocket_passthrough( forward_headers=False, endpoint="/vertex_ai/live", accept_websocket=False, + setup_model_rewriter=_build_vertex_live_setup_model_rewriter( + vertex_project=resolved_project, + vertex_location=resolved_location, + llm_router=_get_llm_router(), + ), ) diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py index 0df0aaa1bcd..d68ef8019d2 100644 --- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py @@ -5,7 +5,7 @@ import json import posixpath import traceback from base64 import b64encode -from collections.abc import AsyncGenerator, Callable, Mapping +from collections.abc import AsyncGenerator, Callable, Iterable, Mapping from datetime import datetime from itertools import groupby from typing import Any, Final, TypedDict, cast @@ -32,11 +32,15 @@ from websockets.exceptions import ( ConnectionClosedOK, InvalidStatus, ) +from websockets.frames import Close import litellm from litellm._logging import verbose_proxy_logger from litellm._uuid import uuid -from litellm.constants import MAXIMUM_TRACEBACK_LINES_TO_LOG +from litellm.constants import ( + MAXIMUM_TRACEBACK_LINES_TO_LOG, + WEBSOCKET_CLOSE_REASON_MAX_BYTES, +) from litellm.integrations.custom_guardrail import CustomGuardrail from litellm.integrations.custom_logger import CustomLogger from litellm.litellm_core_utils.core_helpers import ( @@ -1890,6 +1894,52 @@ def create_websocket_passthrough_route( return websocket_endpoint_func +def _rewrite_vertex_live_setup_model(text_data: str, setup_model_rewriter: Callable[[str], str] | None) -> str: + """ + Rewrite the model of a Vertex AI Live ``setup`` frame, leaving every other frame byte-identical + """ + if setup_model_rewriter is None: + return text_data + try: + message: Final = json.loads(text_data) + except json.JSONDecodeError: + return text_data + if not isinstance(message, dict): + return text_data + setup: Final = message.get("setup") + if not isinstance(setup, dict): + return text_data + setup_model: Final = setup.get("model") + if not isinstance(setup_model, str): + return text_data + rewritten_model: Final = setup_model_rewriter(setup_model) + if rewritten_model == setup_model: + return text_data + return json.dumps({**message, "setup": {**setup, "model": rewritten_model}}) # mutable-ok: one-shot json payload + + +def _truncated_close_reason(reason: str) -> str: + """ + Fit a close reason inside the byte budget a WebSocket close frame allows, without splitting a character + """ + encoded: Final = reason.encode("utf-8") + if len(encoded) <= WEBSOCKET_CLOSE_REASON_MAX_BYTES: + return reason + return encoded[:WEBSOCKET_CLOSE_REASON_MAX_BYTES].decode("utf-8", errors="ignore") + + +def _upstream_close_to_relay(task_results: Iterable[object]) -> Close | None: + """ + The upstream close worth telling the client about: anything other than a plain, reasonless normal close + """ + upstream_close: Final = next((result for result in task_results if isinstance(result, Close)), None) + if upstream_close is None: + return None + if upstream_close.code == 1000 and upstream_close.reason == "": + return None + return upstream_close + + async def websocket_passthrough_request( websocket: WebSocket, target: str, @@ -1899,6 +1949,7 @@ async def websocket_passthrough_request( endpoint: str | None = None, cost_per_request: float | None = None, accept_websocket: bool = True, + setup_model_rewriter: Callable[[str], str] | None = None, ): """ WebSocket passthrough request handler. @@ -1911,6 +1962,7 @@ async def websocket_passthrough_request( forward_headers: Whether to forward incoming headers endpoint: The endpoint path (for logging purposes) cost_per_request: Optional field - cost per request to the target endpoint + setup_model_rewriter: Optional rewrite of the setup frame's model before it reaches the upstream """ from litellm.litellm_core_utils.litellm_logging import Logging from litellm.proxy.proxy_server import proxy_logging_obj @@ -2100,7 +2152,7 @@ async def websocket_passthrough_request( ) # Not a JSON message or doesn't contain setup data - await upstream_ws.send(text_data) + await upstream_ws.send(_rewrite_vertex_live_setup_model(text_data, setup_model_rewriter)) elif bytes_data is not None: await upstream_ws.send(bytes_data) except asyncio.CancelledError: @@ -2111,8 +2163,8 @@ async def websocket_passthrough_request( ) await upstream_ws.close() - async def forward_upstream_to_client() -> None: - """Forward messages from upstream to client WebSocket""" + async def forward_upstream_to_client() -> Close | None: + """Forward messages from upstream to client WebSocket, returning the upstream's close frame""" try: # Wait for the first response from upstream raw_response = await upstream_ws.recv(decode=False) @@ -2177,6 +2229,7 @@ async def websocket_passthrough_request( except (ConnectionClosedOK, ConnectionClosedError) as e: verbose_proxy_logger.debug("Upstream WebSocket connection closed: %s", e) + return e.rcvd except asyncio.CancelledError: verbose_proxy_logger.debug("asyncio.CancelledError in forward_upstream_to_client") raise @@ -2209,6 +2262,13 @@ async def websocket_passthrough_request( if exception is not None: raise exception + upstream_close: Final = _upstream_close_to_relay(task.result() for task in done) + if upstream_close is not None and websocket.application_state != WebSocketState.DISCONNECTED: + await websocket.close( + code=upstream_close.code, + reason=_truncated_close_reason(upstream_close.reason), + ) + end_time: Final = datetime.now() # Update passthrough logging payload with response data @@ -2325,7 +2385,10 @@ async def websocket_passthrough_request( if websocket.client_state != WebSocketState.DISCONNECTED: await websocket.close(code=1011, reason="WebSocket passthrough error") finally: - if websocket.client_state != WebSocketState.DISCONNECTED: + if ( + websocket.client_state != WebSocketState.DISCONNECTED + and websocket.application_state != WebSocketState.DISCONNECTED + ): await websocket.close() diff --git a/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py b/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py index 1d2b4504d61..e7887e33ca6 100644 --- a/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py +++ b/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py @@ -10,7 +10,7 @@ from litellm.litellm_core_utils.credential_accessor import CredentialAccessor from litellm.secret_managers.main import get_secret_str from litellm.types.llms.vertex_ai import VERTEX_CREDENTIALS_TYPES from litellm.types.passthrough_endpoints.vertex_ai import VertexPassThroughCredentials -from litellm.types.router import LiteLLMParamsTypedDict +from litellm.types.router import DeploymentTypedDict, LiteLLMParamsTypedDict if TYPE_CHECKING: from litellm.router import Router @@ -120,6 +120,69 @@ class PassthroughEndpointRouter: return None return provider + def get_vertex_credentials_from_router_deployments(self, model: str | None) -> VertexPassThroughCredentials | None: + """ + Resolve vertex pass-through credentials from the live router deployments flagged ``use_in_pass_through``. + + ``deployment_key_to_vertex_credentials`` is only reachable when the caller names a project and location, + which WebSocket clients never do, so DB-stored deployments need this lookup to be usable at all. + """ + llm_router: Final = self.llm_router_getter() + if llm_router is None: + return None + resolved: Final = tuple( + (deployment, credentials) + for deployment in (llm_router.get_model_list() or ()) + if (credentials := self._resolve_vertex_deployment_credentials(deployment["litellm_params"])) is not None + ) + if len(resolved) == 0: + return None + return next( + ( + credentials + for deployment, credentials in resolved + if model is not None and self._deployment_matches_model(deployment, model) + ), + resolved[0][1], + ) + + def _resolve_vertex_deployment_credentials( + self, litellm_params: LiteLLMParamsTypedDict + ) -> VertexPassThroughCredentials | None: + if litellm_params.get("use_in_pass_through") is not True: + return None + if self._get_deployment_provider(litellm_params) != "vertex_ai": + return None + credential_name: Final = litellm_params.get("litellm_credential_name") + credential_values: Final = ( + CredentialAccessor.get_credential_values(credential_name) if credential_name is not None else None + ) + vertex_project: Final = _get_str_value(credential_values, "vertex_project") or litellm_params.get( + "vertex_project" + ) + vertex_location: Final = _get_str_value(credential_values, "vertex_location") or litellm_params.get( + "vertex_location" + ) + vertex_credentials: Final = _get_str_value(credential_values, "vertex_credentials") or litellm_params.get( + "vertex_credentials" + ) + if vertex_project is None or vertex_location is None: + return None + return VertexPassThroughCredentials( + vertex_project=vertex_project, + vertex_location=vertex_location, + vertex_credentials=vertex_credentials, + ) + + @staticmethod + def _deployment_matches_model(deployment: DeploymentTypedDict, model: str) -> bool: + upstream_model: Final = deployment["litellm_params"].get("model") + return model in ( + deployment.get("model_name"), + upstream_model, + upstream_model.split("/", 1)[-1] if upstream_model is not None else None, + ) + def _get_vertex_env_vars(self) -> VertexPassThroughCredentials: """ Helper to get vertex pass through config from environment variables diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py index a9454854948..5ed974c7a47 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py @@ -3887,3 +3887,104 @@ class TestComprehendMedicalProxyRoute: user_api_key_dict=Mock(), ) assert exc_info.value.status_code == 400 + + +class TestVertexAILiveWebsocketPassthrough: + def _websocket(self): + from starlette.websockets import WebSocketState + + websocket = MagicMock() + websocket.accept = AsyncMock() + websocket.close = AsyncMock() + websocket.headers = {} + websocket.client_state = WebSocketState.CONNECTED + return websocket + + def _clear_vertex_env(self, monkeypatch): + monkeypatch.delenv("DEFAULT_VERTEXAI_PROJECT", raising=False) + monkeypatch.delenv("DEFAULT_VERTEXAI_LOCATION", raising=False) + monkeypatch.delenv("DEFAULT_GOOGLE_APPLICATION_CREDENTIALS", raising=False) + + @pytest.mark.asyncio + async def test_uses_db_deployment_credentials_without_query_params(self, monkeypatch): + from litellm.proxy.pass_through_endpoints import ( + llm_passthrough_endpoints as passthrough_module, + ) + + llm_router = litellm.Router( + model_list=[ + { + "model_name": "gemini-live", + "litellm_params": { + "model": "vertex_ai/gemini-live-2.5-flash", + "use_in_pass_through": True, + "vertex_project": "proj-db", + "vertex_location": "global", + "vertex_credentials": '{"type": "service_account"}', + }, + } + ] + ) + monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", llm_router) + monkeypatch.setattr( + passthrough_module.passthrough_endpoint_router, "default_vertex_config", None + ) + self._clear_vertex_env(monkeypatch) + websocket = self._websocket() + ensure_token = AsyncMock(return_value=("token-abc", "proj-db")) + ws_passthrough = AsyncMock() + + with ( + patch.object(passthrough_module.vertex_llm_base, "_ensure_access_token_async", ensure_token), + patch.object(passthrough_module, "websocket_passthrough_request", ws_passthrough), + ): + await passthrough_module.vertex_ai_live_websocket_passthrough( + websocket=websocket, + user_api_key_dict=UserAPIKeyAuth(), + ) + + ensure_token.assert_awaited_once_with( + credentials='{"type": "service_account"}', + project_id="proj-db", + custom_llm_provider="vertex_ai_beta", + ) + passthrough_kwargs = ws_passthrough.await_args.kwargs + assert passthrough_kwargs["target"] == ( + "wss://aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent" + ) + assert passthrough_kwargs["custom_headers"]["Authorization"] == "Bearer token-abc" + rewriter = passthrough_kwargs["setup_model_rewriter"] + assert rewriter("gemini-live") == ( + "projects/proj-db/locations/global/publishers/google/models/gemini-live-2.5-flash" + ) + websocket.close.assert_not_awaited() + + @pytest.mark.asyncio + async def test_credential_failure_close_names_configuration_options(self, monkeypatch): + from litellm.proxy.pass_through_endpoints import ( + llm_passthrough_endpoints as passthrough_module, + ) + + monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None) + monkeypatch.setattr( + passthrough_module.passthrough_endpoint_router, "default_vertex_config", None + ) + self._clear_vertex_env(monkeypatch) + websocket = self._websocket() + ensure_token = AsyncMock(side_effect=Exception("Unable to find your credentials")) + + with ( + patch.object(passthrough_module.vertex_llm_base, "_ensure_access_token_async", ensure_token), + patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy_logging, + ): + mock_proxy_logging.post_call_failure_hook = AsyncMock() + await passthrough_module.vertex_ai_live_websocket_passthrough( + websocket=websocket, + user_api_key_dict=UserAPIKeyAuth(), + ) + + close_kwargs = websocket.close.await_args.kwargs + assert close_kwargs["code"] == 1011 + assert "use_in_pass_through" in close_kwargs["reason"] + assert "default_vertex_config" in close_kwargs["reason"] + assert len(close_kwargs["reason"].encode("utf-8")) <= 123 diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py index b1b934b0949..844aa099541 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py @@ -4994,6 +4994,212 @@ async def test_websocket_passthrough_forwards_non_ascii_first_frame(): assert all(call.kwargs.get("code") != 1011 for call in websocket.close.await_args_list) +class ClosingUpstreamWebSocket: + def __init__(self, close_exc: Exception): + self._close_exc = close_exc + self.close = AsyncMock() + self.send = AsyncMock() + + async def recv(self, decode: bool = True): + raise self._close_exc + + def __aiter__(self): + return self + + async def __anext__(self): + raise StopAsyncIteration + + +class RecordingUpstreamWebSocket: + def __init__(self): + self.close = AsyncMock() + self.send = AsyncMock() + + async def recv(self, decode: bool = True): + await asyncio.Event().wait() + + def __aiter__(self): + return self + + async def __anext__(self): + raise StopAsyncIteration + + +def _client_websocket(receive): + from starlette.websockets import WebSocketState + + websocket = MagicMock() + websocket.accept = AsyncMock() + websocket.send_text = AsyncMock() + websocket.send_bytes = AsyncMock() + websocket.receive = receive + websocket.headers = {} + websocket.client_state = WebSocketState.CONNECTED + websocket.application_state = WebSocketState.CONNECTED + + def _mark_closed(*args, **kwargs): + websocket.application_state = WebSocketState.DISCONNECTED + + websocket.close = AsyncMock(side_effect=_mark_closed) + return websocket + + +@contextmanager +def _patched_websocket_passthrough_environment(upstream_ws): + with ( + patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy_logging, + patch( + "litellm.proxy.pass_through_endpoints.pass_through_endpoints.connect", + return_value=FakeUpstreamConnect(upstream_ws), + ), + patch( + "litellm.proxy.pass_through_endpoints.pass_through_endpoints.GLOBAL_LOGGING_WORKER" + ) as mock_worker, + ): + mock_proxy_logging.pre_call_hook = AsyncMock(return_value={}) + mock_proxy_logging.post_call_success_hook = AsyncMock() + mock_proxy_logging.post_call_failure_hook = AsyncMock() + mock_worker.ensure_initialized_and_enqueue = MagicMock( + side_effect=lambda async_coroutine: async_coroutine.close() + ) + yield + + +async def _pending_receive(): + await asyncio.Event().wait() + + +@pytest.mark.asyncio +async def test_websocket_passthrough_relays_upstream_policy_close_to_client(): + from websockets.exceptions import ConnectionClosedError + from websockets.frames import Close + + upstream_reason = "Publisher Model `projects/p/locations/global/publishers/google/models/nope` was not found" + upstream_ws = ClosingUpstreamWebSocket( + ConnectionClosedError( + rcvd=Close(1008, upstream_reason), + sent=Close(1008, ""), + rcvd_then_sent=True, + ) + ) + websocket = _client_websocket(_pending_receive) + + with _patched_websocket_passthrough_environment(upstream_ws): + await websocket_passthrough_request( + websocket=websocket, + target="wss://aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent", + custom_headers={"Authorization": "Bearer token"}, + user_api_key_dict=UserAPIKeyAuth(), + forward_headers=False, + endpoint="/vertex_ai/live", + accept_websocket=False, + ) + + websocket.close.assert_awaited_once_with(code=1008, reason=upstream_reason) + + +@pytest.mark.asyncio +async def test_websocket_passthrough_keeps_normal_upstream_close_normal(): + from websockets.exceptions import ConnectionClosedOK + from websockets.frames import Close + + upstream_ws = ClosingUpstreamWebSocket( + ConnectionClosedOK(rcvd=Close(1000, ""), sent=Close(1000, ""), rcvd_then_sent=True) + ) + websocket = _client_websocket(_pending_receive) + + with _patched_websocket_passthrough_environment(upstream_ws): + await websocket_passthrough_request( + websocket=websocket, + target="wss://aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent", + custom_headers={"Authorization": "Bearer token"}, + user_api_key_dict=UserAPIKeyAuth(), + forward_headers=False, + endpoint="/vertex_ai/live", + accept_websocket=False, + ) + + websocket.close.assert_awaited_once_with() + + +async def _run_setup_rewrite_passthrough(setup_model: str, llm_router) -> str: + from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import ( + _build_vertex_live_setup_model_rewriter, + ) + + upstream_ws = RecordingUpstreamWebSocket() + setup_frame = json.dumps({"setup": {"model": setup_model, "generationConfig": {"responseModalities": ["TEXT"]}}}) + websocket = _client_websocket( + AsyncMock( + side_effect=[ + {"type": "websocket.receive", "text": setup_frame}, + {"type": "websocket.disconnect"}, + ] + ) + ) + + with _patched_websocket_passthrough_environment(upstream_ws): + await websocket_passthrough_request( + websocket=websocket, + target="wss://aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent", + custom_headers={"Authorization": "Bearer token"}, + user_api_key_dict=UserAPIKeyAuth(), + forward_headers=False, + endpoint="/vertex_ai/live", + accept_websocket=False, + setup_model_rewriter=_build_vertex_live_setup_model_rewriter( + vertex_project="proj-db", + vertex_location="global", + llm_router=llm_router, + ), + ) + + upstream_ws.send.assert_awaited_once() + return upstream_ws.send.await_args.args[0] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "setup_model", + ["gemini-live-2.5-flash", "publishers/google/models/gemini-live-2.5-flash"], +) +async def test_websocket_passthrough_rewrites_setup_model_to_full_resource(setup_model): + sent_frame = await _run_setup_rewrite_passthrough(setup_model, llm_router=None) + + sent_setup = json.loads(sent_frame)["setup"] + assert sent_setup["model"] == "projects/proj-db/locations/global/publishers/google/models/gemini-live-2.5-flash" + assert sent_setup["generationConfig"] == {"responseModalities": ["TEXT"]} + + +@pytest.mark.asyncio +async def test_websocket_passthrough_rewrites_gateway_alias_setup_model(): + llm_router = litellm.Router( + model_list=[ + { + "model_name": "gemini-live", + "litellm_params": {"model": "vertex_ai/gemini-live-2.5-flash"}, + } + ] + ) + + sent_frame = await _run_setup_rewrite_passthrough("gemini-live", llm_router=llm_router) + + sent_setup = json.loads(sent_frame)["setup"] + assert sent_setup["model"] == "projects/proj-db/locations/global/publishers/google/models/gemini-live-2.5-flash" + + +@pytest.mark.asyncio +async def test_websocket_passthrough_leaves_full_resource_setup_model_untouched(): + full_resource = "projects/other/locations/us-central1/publishers/google/models/gemini-2.0-flash-live-preview-04-09" + + sent_frame = await _run_setup_rewrite_passthrough(full_resource, llm_router=None) + + assert json.loads(sent_frame)["setup"]["model"] == full_resource + assert sent_frame == json.dumps( + {"setup": {"model": full_resource, "generationConfig": {"responseModalities": ["TEXT"]}}} + ) + + def _passthrough_kwargs_for_reservation( user_api_key_dict: UserAPIKeyAuth, parsed_body: Optional[dict] = None ) -> dict: diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py b/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py index d7266ecd9ed..7816178471f 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py @@ -172,3 +172,144 @@ def test_returns_none_when_no_router_and_no_env(): passthrough_router = _passthrough_router(None) assert passthrough_router.get_credentials(custom_llm_provider="openai", region_name=None) is None + + +def _vertex_credential(name: str, values: dict) -> CredentialItem: + return CredentialItem(credential_name=name, credential_values=values, credential_info={}) + + +def _vertex_deployment(model_name: str, model: str, **litellm_params) -> dict: + return { + "model_name": model_name, + "litellm_params": {"model": model, "use_in_pass_through": True, **litellm_params}, + } + + +def test_vertex_deployment_resolves_via_named_credential(): + CredentialAccessor.upsert_credentials( + [ + _vertex_credential( + "cred_gcp", + { + "vertex_project": "proj-db", + "vertex_location": "global", + "vertex_credentials": '{"type": "service_account"}', + }, + ) + ] + ) + llm_router = litellm.Router( + model_list=[ + _vertex_deployment( + "gemini-live", "vertex_ai/gemini-live-2.5-flash", litellm_credential_name="cred_gcp" + ) + ] + ) + passthrough_router = _passthrough_router(llm_router) + + resolved = passthrough_router.get_vertex_credentials_from_router_deployments(model=None) + + assert resolved is not None + assert resolved.vertex_project == "proj-db" + assert resolved.vertex_location == "global" + assert resolved.vertex_credentials == '{"type": "service_account"}' + + +def test_vertex_deployment_resolves_from_inline_litellm_params(): + llm_router = litellm.Router( + model_list=[ + _vertex_deployment( + "gemini-live", + "vertex_ai/gemini-live-2.5-flash", + vertex_project="proj-inline", + vertex_location="us-east4", + vertex_credentials='{"type": "service_account", "project_id": "proj-inline"}', + ) + ] + ) + passthrough_router = _passthrough_router(llm_router) + + resolved = passthrough_router.get_vertex_credentials_from_router_deployments(model=None) + + assert resolved is not None + assert resolved.vertex_project == "proj-inline" + assert resolved.vertex_location == "us-east4" + assert resolved.vertex_credentials == '{"type": "service_account", "project_id": "proj-inline"}' + + +def _two_vertex_deployments_router() -> litellm.Router: + return litellm.Router( + model_list=[ + _vertex_deployment( + "gemini-flash", + "vertex_ai/gemini-2.5-flash", + vertex_project="proj-first", + vertex_location="us-central1", + ), + _vertex_deployment( + "gemini-live", + "vertex_ai/gemini-live-2.5-flash", + vertex_project="proj-live", + vertex_location="global", + ), + ] + ) + + +def test_vertex_model_hint_prefers_matching_deployment(): + passthrough_router = _passthrough_router(_two_vertex_deployments_router()) + + by_alias = passthrough_router.get_vertex_credentials_from_router_deployments(model="gemini-live") + by_upstream_id = passthrough_router.get_vertex_credentials_from_router_deployments( + model="gemini-live-2.5-flash" + ) + + assert by_alias is not None and by_alias.vertex_project == "proj-live" + assert by_upstream_id is not None and by_upstream_id.vertex_project == "proj-live" + + +def test_vertex_unmatched_hint_falls_back_to_first_flagged_deployment(): + passthrough_router = _passthrough_router(_two_vertex_deployments_router()) + + unmatched = passthrough_router.get_vertex_credentials_from_router_deployments(model="unknown-model") + no_hint = passthrough_router.get_vertex_credentials_from_router_deployments(model=None) + + assert unmatched is not None and unmatched.vertex_project == "proj-first" + assert no_hint is not None and no_hint.vertex_project == "proj-first" + + +def test_no_flagged_vertex_deployment_returns_none(): + llm_router = litellm.Router( + model_list=[ + { + "model_name": "gemini-live", + "litellm_params": { + "model": "vertex_ai/gemini-live-2.5-flash", + "vertex_project": "proj-unflagged", + "vertex_location": "global", + }, + }, + _flagged_deployment("openai/gpt-4o", api_key="sk-flagged"), + ] + ) + passthrough_router = _passthrough_router(llm_router) + + assert passthrough_router.get_vertex_credentials_from_router_deployments(model=None) is None + assert _passthrough_router(None).get_vertex_credentials_from_router_deployments(model=None) is None + + +def test_vertex_deployment_with_deleted_credential_is_skipped(monkeypatch): + CredentialAccessor.upsert_credentials( + [_vertex_credential("cred_gone", {"vertex_project": "proj-db", "vertex_location": "global"})] + ) + llm_router = litellm.Router( + model_list=[ + _vertex_deployment( + "gemini-live", "vertex_ai/gemini-live-2.5-flash", litellm_credential_name="cred_gone" + ) + ] + ) + passthrough_router = _passthrough_router(llm_router) + monkeypatch.setattr(litellm, "credential_list", []) + + assert passthrough_router.get_vertex_credentials_from_router_deployments(model=None) is None From 9271133bebedd2ece0fe23535fd783d69cae2547 Mon Sep 17 00:00:00 2001 From: Mateo Date: Thu, 20 Aug 2026 02:02:00 -0700 Subject: [PATCH 05/35] fix(realtime): bound Vertex credential resolution and make realtime failures loud A /v1/realtime connection to a Vertex AI Live model accepted the WebSocket upgrade and then went silent: a stalled Google OAuth token fetch blocked the handler before any session event, and the eventual failure closed the socket with a bare 1011 and no error event, so callers saw an open socket, no frames, and no reason. Bound the pre-session token fetch with REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS (20s default) and, on any realtime failure, send an OpenAI-style error event before closing with a reason that names the failure. Close reasons are truncated by bytes, not characters, since an over-long reason makes the close frame itself fail. --- litellm/constants.py | 3 + litellm/litellm_core_utils/realtime_errors.py | 31 +++++ litellm/llms/custom_httpx/llm_http_handler.py | 14 ++- litellm/proxy/proxy_server.py | 21 +++- litellm/realtime_api/main.py | 35 +++++- litellm/types/realtime.py | 12 +- .../test_realtime_errors.py | 47 ++++++++ .../custom_httpx/test_llm_http_handler.py | 68 +++++++++++ .../test_realtime_webrtc_endpoints.py | 108 ++++++++++++++++++ tests/test_litellm/realtime_api/test_main.py | 63 ++++++++++ 10 files changed, 392 insertions(+), 10 deletions(-) create mode 100644 litellm/litellm_core_utils/realtime_errors.py create mode 100644 tests/test_litellm/litellm_core_utils/test_realtime_errors.py diff --git a/litellm/constants.py b/litellm/constants.py index facfc6f7c19..eff82bc268b 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -243,6 +243,9 @@ AIOHTTP_NEEDS_CLEANUP_CLOSED: Final = (3, 13, 0) <= sys.version_info < ( # https://github.com/openai/openai-agents-python/blob/cf1b933660e44fd37b4350c41febab8221801409/src/agents/realtime/openai_realtime.py#L235 _max_size_env: Final = os.getenv("REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES") REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES: Final = int(_max_size_env) if _max_size_env is not None else None +REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS: Final = float( + os.getenv("REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS", "20.0") +) # SSL/TLS cipher configuration for faster handshakes # Strategy: Strongly prefer fast modern ciphers, but allow fallback to commonly supported ones diff --git a/litellm/litellm_core_utils/realtime_errors.py b/litellm/litellm_core_utils/realtime_errors.py new file mode 100644 index 00000000000..e1b957f4325 --- /dev/null +++ b/litellm/litellm_core_utils/realtime_errors.py @@ -0,0 +1,31 @@ +"""Loud-failure helpers for the realtime WebSocket paths. + +A realtime caller that only gets a bare close frame has nothing to act on, so +every failure surfaces as an OpenAI-style ``error`` event plus a close frame +whose reason names the failure. Close reasons are capped at +``WEBSOCKET_CLOSE_REASON_MAX_BYTES``: RFC 6455 control frames carry at most 125 +bytes, two of which hold the status code, and a longer reason makes the close +frame itself fail, which is how a loud failure turns back into a silent one. +""" + +import json +from typing import Final + +from litellm.types.realtime import RealtimeErrorDetail, RealtimeErrorEvent + +WEBSOCKET_CLOSE_REASON_MAX_BYTES: Final = 123 + + +def realtime_error_event(message: str, error_type: str) -> str: + detail: Final[RealtimeErrorDetail] = {"type": error_type, "message": message} + event: Final[RealtimeErrorEvent] = {"type": "error", "error": detail} + return json.dumps(event) + + +def websocket_close_reason(message: str, fallback: str) -> str: + encoded: Final = message.encode("utf-8") + if not encoded: + return fallback + if len(encoded) <= WEBSOCKET_CLOSE_REASON_MAX_BYTES: + return message + return encoded[:WEBSOCKET_CLOSE_REASON_MAX_BYTES].decode("utf-8", errors="ignore") diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index cc522aed1ee..9a950d7f920 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -20,6 +20,7 @@ from litellm._logging import _redact_string, verbose_logger from litellm.anthropic_beta_headers_manager import update_headers_with_filtered_beta from litellm.constants import REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES from litellm.litellm_core_utils.asyncify import run_async_function +from litellm.litellm_core_utils.realtime_errors import realtime_error_event, websocket_close_reason from litellm.litellm_core_utils.realtime_streaming import RealTimeStreaming from litellm.litellm_core_utils.url_utils import encode_url_path_segment from litellm.llms.base_llm.anthropic_messages.transformation import ( @@ -5976,8 +5977,19 @@ class BaseLLMHTTPHandler: await websocket.close(code=e.status_code, reason=_redact_string(str(e))) except Exception as e: verbose_logger.exception("Error connecting to backend: %s", e) + redacted_error: Final = _redact_string(str(e)) try: - await websocket.close(code=1011, reason=_redact_string(f"Internal server error: {e}")) + await websocket.send_text(realtime_error_event(redacted_error, error_type="server_error")) + except Exception: # noqa: BLE001 # best-effort notice: a dead client socket must not skip the close below + verbose_logger.debug("Could not send realtime error event to client; closing anyway") + try: + await websocket.close( + code=1011, + reason=websocket_close_reason( + _redact_string(f"Internal server error: {e}"), + fallback="Internal server error", + ), + ) except RuntimeError as close_error: if "already completed" in str(close_error) or "websocket.close" in str(close_error): # The WebSocket is already closed or the response is completed, so we can ignore this error diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index af082f04706..4a342174277 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -222,7 +222,7 @@ from functools import lru_cache import litellm import litellm._redis from litellm import Router -from litellm._logging import verbose_proxy_logger, verbose_router_logger +from litellm._logging import _redact_string, verbose_proxy_logger, verbose_router_logger from litellm.caching.caching import DualCache, RedisCache from litellm.caching.redis_cluster_cache import RedisClusterCache from litellm.constants import ( @@ -259,6 +259,10 @@ from litellm.litellm_core_utils.core_helpers import ( ) from litellm.litellm_core_utils.credential_accessor import CredentialAccessor from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.litellm_core_utils.realtime_errors import ( + realtime_error_event, + websocket_close_reason, +) from litellm.litellm_core_utils.sensitive_data_masker import ( SensitiveDataMasker, mask_sensitive_keys, @@ -10993,9 +10997,20 @@ async def realtime_websocket_endpoint( except websockets.exceptions.InvalidStatusCode as e: verbose_proxy_logger.exception("Invalid status code") await websocket.close(code=e.status_code, reason="Invalid status code") - except Exception: + except Exception as e: verbose_proxy_logger.exception("Internal server error") - await websocket.close(code=1011, reason="Internal server error") + redacted_error: Final = _redact_string(str(e)) + try: + await websocket.send_text(realtime_error_event(redacted_error, error_type="server_error")) + except Exception: # noqa: BLE001 # best-effort notice: a dead client socket must not skip the close below + verbose_proxy_logger.debug("Could not send realtime error event to client; closing anyway") + try: + await websocket.close( + code=1011, + reason=websocket_close_reason(redacted_error, fallback="Internal server error"), + ) + except Exception: # noqa: BLE001 # the lower layer may have closed the socket already; closing twice is not an error + verbose_proxy_logger.debug("Could not close realtime client websocket; it is already gone") ###################################################################### diff --git a/litellm/realtime_api/main.py b/litellm/realtime_api/main.py index d5195659b1c..8fde7cb75c5 100644 --- a/litellm/realtime_api/main.py +++ b/litellm/realtime_api/main.py @@ -1,15 +1,21 @@ """Abstraction function for OpenAI's realtime API""" +import asyncio import os from typing import Any, Final, cast import litellm -from litellm.constants import REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES, request_timeout +from litellm.constants import ( + REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS, + REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES, + request_timeout, +) from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider from litellm.llms.base_llm.realtime.transformation import BaseRealtimeConfig from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler from litellm.llms.xai.common_utils import XAIModelInfo from litellm.secret_managers.main import get_secret_str +from litellm.types.llms.vertex_ai import VERTEX_CREDENTIALS_TYPES from litellm.types.realtime import ( RealtimeClientSecretRequest, RealtimeExpiresAfter, @@ -281,6 +287,27 @@ async def arealtime_calls( ) +async def _resolve_vertex_access_token_bounded( + credentials: VERTEX_CREDENTIALS_TYPES | None, + project_id: str | None, +) -> tuple[str, str]: + try: + return await asyncio.wait_for( + vertex_llm_base._ensure_access_token_async( + credentials=credentials, + project_id=project_id, + custom_llm_provider="vertex_ai", + ), + timeout=REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS, + ) + except asyncio.TimeoutError as e: + raise ValueError( + "Vertex AI realtime: timed out fetching Google OAuth access token after " + f"{REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS}s; check network egress from the proxy " + "to the OAuth token endpoint (oauth2.googleapis.com)" + ) from e + + @wrapper_client async def _arealtime( model: str, @@ -478,10 +505,9 @@ async def _arealtime( ( access_token, resolved_project, - ) = await vertex_llm_base._ensure_access_token_async( + ) = await _resolve_vertex_access_token_bounded( credentials=vertex_credentials, project_id=vertex_project, - custom_llm_provider="vertex_ai", ) vertex_realtime_config: Final = VertexAIRealtimeConfig( @@ -559,10 +585,9 @@ async def _realtime_health_check( ( access_token, resolved_project, - ) = await vertex_llm_base._ensure_access_token_async( + ) = await _resolve_vertex_access_token_bounded( credentials=VertexBase.safe_get_vertex_ai_credentials(vertex_model_params), project_id=VertexBase.safe_get_vertex_ai_project(vertex_model_params), - custom_llm_provider="vertex_ai", ) vertex_realtime_config: Final = VertexAIRealtimeConfig( access_token=access_token, diff --git a/litellm/types/realtime.py b/litellm/types/realtime.py index 15238f7e13f..cbd7a8b7ecb 100644 --- a/litellm/types/realtime.py +++ b/litellm/types/realtime.py @@ -1,7 +1,7 @@ from typing import Any, Literal from pydantic import BaseModel -from typing_extensions import TypedDict +from typing_extensions import ReadOnly, TypedDict from .llms.openai import ( OpenAIRealtimeEvents, @@ -152,3 +152,13 @@ class RealtimeTranscriptionSessionResponse(BaseModel): model_config = {"extra": "allow"} client_secret: dict[str, Any] | None = None + + +class RealtimeErrorDetail(TypedDict): + type: ReadOnly[str] + message: ReadOnly[str] + + +class RealtimeErrorEvent(TypedDict): + type: ReadOnly[Literal["error"]] + error: ReadOnly[RealtimeErrorDetail] diff --git a/tests/test_litellm/litellm_core_utils/test_realtime_errors.py b/tests/test_litellm/litellm_core_utils/test_realtime_errors.py new file mode 100644 index 00000000000..263d1654f65 --- /dev/null +++ b/tests/test_litellm/litellm_core_utils/test_realtime_errors.py @@ -0,0 +1,47 @@ +import json +import os +import sys + +sys.path.insert(0, os.path.abspath("../../..")) + +from litellm.litellm_core_utils.realtime_errors import ( + WEBSOCKET_CLOSE_REASON_MAX_BYTES, + realtime_error_event, + websocket_close_reason, +) + + +def test_realtime_error_event_shape(): + event = json.loads(realtime_error_event("token refresh failed", error_type="server_error")) + + assert event == { + "type": "error", + "error": {"type": "server_error", "message": "token refresh failed"}, + } + + +def test_websocket_close_reason_keeps_short_messages_intact(): + assert websocket_close_reason("boom", fallback="Internal server error") == "boom" + + +def test_websocket_close_reason_falls_back_on_empty_message(): + assert websocket_close_reason("", fallback="Internal server error") == "Internal server error" + + +def test_websocket_close_reason_truncates_long_ascii_message(): + reason = websocket_close_reason("x" * 500, fallback="Internal server error") + + assert len(reason.encode("utf-8")) <= WEBSOCKET_CLOSE_REASON_MAX_BYTES + assert reason == "x" * WEBSOCKET_CLOSE_REASON_MAX_BYTES + + +def test_websocket_close_reason_truncates_multibyte_message_by_bytes(): + """A close frame carries at most 123 bytes of reason, not 123 characters: + truncating by characters lets a multibyte message overflow the control + frame, which makes the close itself fail and leaves the caller with a bare + abnormal closure and no reason at all.""" + reason = websocket_close_reason("あ" * 200, fallback="Internal server error") + + assert len(reason.encode("utf-8")) <= WEBSOCKET_CLOSE_REASON_MAX_BYTES + assert reason == "あ" * (WEBSOCKET_CLOSE_REASON_MAX_BYTES // 3) + assert "�" not in reason diff --git a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py index 9e9242137e6..c568b82ebba 100644 --- a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py +++ b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py @@ -1738,6 +1738,74 @@ async def test_realtime_backend_open_does_not_retry_auth_failure(rejection): assert fake.attempts == 1 +class _FakeClientWebSocket: + def __init__(self, send_error=None): + self.events = [] + self._send_error = send_error + + async def send_text(self, payload): + if self._send_error is not None: + raise self._send_error + self.events.append(("send_text", payload)) + + async def close(self, code=None, reason=None): + self.events.append(("close", (code, reason))) + + +async def _run_async_realtime_with_backend_failure(client_ws): + import websockets.exceptions # noqa: F401 # binds the submodule so async_realtime's except clause resolves, as in the proxy process + + handler = BaseLLMHTTPHandler() + provider_config = Mock() + provider_config.get_complete_url.return_value = "wss://backend.example/live" + provider_config.validate_environment.return_value = {} + + with patch.object( + handler, + "_open_realtime_backend_ws", + AsyncMock(side_effect=Exception("vertex token refresh exploded")), + ): + await handler.async_realtime( + model="gemini-live-2.5-flash", + websocket=client_ws, + logging_obj=Mock(), + provider_config=provider_config, + headers={}, + ) + + +@pytest.mark.asyncio +async def test_async_realtime_generic_failure_sends_error_event_then_reasoned_close(): + """Regression for the realtime accept-then-silence hang: a generic backend + failure used to close the client socket without any error event, so callers + only saw a bare 1011. The client must receive an OpenAI-style error event + before the reasoned close.""" + client_ws = _FakeClientWebSocket() + + await _run_async_realtime_with_backend_failure(client_ws) + + assert [name for name, _ in client_ws.events] == ["send_text", "close"] + + error_event = json.loads(client_ws.events[0][1]) + assert error_event["type"] == "error" + assert error_event["error"]["type"] == "server_error" + assert "vertex token refresh exploded" in error_event["error"]["message"] + + assert client_ws.events[1][1] == (1011, "Internal server error: vertex token refresh exploded") + + +@pytest.mark.asyncio +async def test_async_realtime_error_event_send_failure_still_closes(): + """A client socket that already dropped must not turn the loud-failure path + into a new exception: the error-event send may fail, but the reasoned close + must still be attempted.""" + client_ws = _FakeClientWebSocket(send_error=RuntimeError("client already disconnected")) + + await _run_async_realtime_with_backend_failure(client_ws) + + assert client_ws.events == [("close", (1011, "Internal server error: vertex token refresh exploded"))] + + class _JSONBodyAudioTranscriptionConfig(BaseAudioTranscriptionConfig): def get_supported_openai_params(self, model): return [] diff --git a/tests/test_litellm/proxy/realtime_endpoints/test_realtime_webrtc_endpoints.py b/tests/test_litellm/proxy/realtime_endpoints/test_realtime_webrtc_endpoints.py index e0e51e7b966..9840de8bcb1 100644 --- a/tests/test_litellm/proxy/realtime_endpoints/test_realtime_webrtc_endpoints.py +++ b/tests/test_litellm/proxy/realtime_endpoints/test_realtime_webrtc_endpoints.py @@ -818,6 +818,114 @@ async def test_realtime_transcription_websocket_default_model_checks_team_scope( assert "not allowed to access model" in close_kwargs["reason"] +@pytest.mark.asyncio +async def test_realtime_websocket_phase2_failure_sends_error_event_and_reasoned_close(): + """Regression for the realtime accept-then-silence hang: a phase-2 failure + (routing / upstream credential resolution) used to close 1011 with the bare + reason "Internal server error" and no error event, leaving the client with + no clue what happened. The client must get an OpenAI-style error event and + a close reason naming the failure.""" + from litellm.proxy import proxy_server + + events = [] + + websocket = MagicMock() + websocket.headers = {} + websocket.scope = {"headers": []} + websocket.accept = AsyncMock() + websocket.send_text = AsyncMock(side_effect=lambda payload: events.append(("send_text", payload))) + websocket.close = AsyncMock(side_effect=lambda **kwargs: events.append(("close", kwargs))) + + mock_processor = MagicMock() + mock_processor.common_processing_pre_call_logic = AsyncMock( + return_value=({"model": "gpt-4o-realtime-preview"}, MagicMock()) + ) + + with ( + patch( + "litellm.proxy.proxy_server.can_key_call_resolved_model", + new=AsyncMock(return_value=None), + ), + patch( + "litellm.proxy.proxy_server.ProxyBaseLLMRequestProcessing", + return_value=mock_processor, + ), + patch( + "litellm.proxy.proxy_server.route_request", + new=AsyncMock(side_effect=RuntimeError("vertex token refresh exploded")), + ), + ): + await proxy_server.realtime_websocket_endpoint( + websocket=websocket, + model="gpt-4o-realtime-preview", + intent=None, + guardrails=None, + user_api_key_dict=UserAPIKeyAuth(models=["*"]), + ) + + websocket.accept.assert_awaited_once() + assert [name for name, _ in events] == ["send_text", "close"] + + error_event = json.loads(events[0][1]) + assert error_event["type"] == "error" + assert error_event["error"]["type"] == "server_error" + assert "vertex token refresh exploded" in error_event["error"]["message"] + + close_kwargs = events[1][1] + assert close_kwargs["code"] == 1011 + assert "vertex token refresh exploded" in close_kwargs["reason"] + assert len(close_kwargs["reason"].encode("utf-8")) <= 123 + + +@pytest.mark.asyncio +async def test_realtime_websocket_phase2_failure_on_closed_socket_does_not_escape(): + """The lower handler layer may have already closed the client socket before + the phase-2 handler runs (it closes on backend failures itself, then can + re-raise). Send and close must each be guarded: the close is still + attempted after a failed send, and neither failure escapes to the ASGI + layer.""" + from litellm.proxy import proxy_server + + websocket = MagicMock() + websocket.headers = {} + websocket.scope = {"headers": []} + websocket.accept = AsyncMock() + websocket.send_text = AsyncMock(side_effect=RuntimeError('Cannot call "send" once a close message has been sent.')) + websocket.close = AsyncMock(side_effect=RuntimeError('Cannot call "send" once a close message has been sent.')) + + mock_processor = MagicMock() + mock_processor.common_processing_pre_call_logic = AsyncMock( + return_value=({"model": "gpt-4o-realtime-preview"}, MagicMock()) + ) + + with ( + patch( + "litellm.proxy.proxy_server.can_key_call_resolved_model", + new=AsyncMock(return_value=None), + ), + patch( + "litellm.proxy.proxy_server.ProxyBaseLLMRequestProcessing", + return_value=mock_processor, + ), + patch( + "litellm.proxy.proxy_server.route_request", + new=AsyncMock(side_effect=RuntimeError("vertex token refresh exploded")), + ), + ): + await proxy_server.realtime_websocket_endpoint( + websocket=websocket, + model="gpt-4o-realtime-preview", + intent=None, + guardrails=None, + user_api_key_dict=UserAPIKeyAuth(models=["*"]), + ) + + websocket.close.assert_awaited_once() + _, close_kwargs = websocket.close.call_args + assert close_kwargs["code"] == 1011 + assert "vertex token refresh exploded" in close_kwargs["reason"] + + @pytest.mark.asyncio async def test_transcription_sessions_encrypts_client_secret( proxy_app, diff --git a/tests/test_litellm/realtime_api/test_main.py b/tests/test_litellm/realtime_api/test_main.py index 406f5ef56d9..8ed7fb06e84 100644 --- a/tests/test_litellm/realtime_api/test_main.py +++ b/tests/test_litellm/realtime_api/test_main.py @@ -1,6 +1,8 @@ import asyncio import os import sys +import time +from unittest.mock import MagicMock sys.path.insert(0, os.path.abspath("../../..")) @@ -91,6 +93,67 @@ def test_client_secret_session_model_takes_priority_over_top_level(monkeypatch): assert captured["request_data"]["session"]["model"] == "gpt-realtime-session" +@pytest.mark.asyncio +async def test_arealtime_vertex_hung_credential_resolution_raises_promptly(monkeypatch): + """Regression for the realtime accept-then-silence hang: a stalled Google + OAuth token refresh used to block _arealtime's vertex branch unbounded + (minutes of zero frames for the client). It must instead raise a clear, + prompt error naming the credential-resolution timeout.""" + + async def hanging_token_refresh(**kwargs): + await asyncio.sleep(30) + + def mock_get_llm_provider(model, api_base, api_key): + return model, "vertex_ai", None, api_base + + monkeypatch.setattr(realtime_main, "get_llm_provider", mock_get_llm_provider) + monkeypatch.setattr(realtime_main.vertex_llm_base, "_ensure_access_token_async", hanging_token_refresh) + monkeypatch.setattr(realtime_main, "REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS", 0.05) + + start = time.monotonic() + with pytest.raises(ValueError, match="timed out fetching Google OAuth access token"): + await realtime_main._arealtime.__wrapped__( + model="gemini-live-2.5-flash", + websocket=MagicMock(), + litellm_logging_obj=FakeLogging(), + vertex_credentials="fake-credentials", + vertex_project="fake-project", + vertex_location="us-central1", + ) + assert time.monotonic() - start < 5 + + +@pytest.mark.asyncio +async def test_arealtime_vertex_credential_timeout_survives_thread_offloaded_refresh(monkeypatch): + """The real stall is a blocking google-auth refresh that runs in a worker + thread via asyncify, not a plain awaitable sleep. A timeout that only bounds + cancellable awaits would leave that shape hanging, so bound the shape the + proxy actually runs.""" + from litellm.litellm_core_utils.asyncify import asyncify + + async def thread_offloaded_hanging_refresh(**kwargs): + return await asyncify(time.sleep)(30) + + def mock_get_llm_provider(model, api_base, api_key): + return model, "vertex_ai", None, api_base + + monkeypatch.setattr(realtime_main, "get_llm_provider", mock_get_llm_provider) + monkeypatch.setattr(realtime_main.vertex_llm_base, "_ensure_access_token_async", thread_offloaded_hanging_refresh) + monkeypatch.setattr(realtime_main, "REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS", 0.05) + + start = time.monotonic() + with pytest.raises(ValueError, match="timed out fetching Google OAuth access token"): + await realtime_main._arealtime.__wrapped__( + model="gemini-live-2.5-flash", + websocket=MagicMock(), + litellm_logging_obj=FakeLogging(), + vertex_credentials="fake-credentials", + vertex_project="fake-project", + vertex_location="us-central1", + ) + assert time.monotonic() - start < 5 + + def test_client_secret_forwards_nested_transcription_model_untouched(monkeypatch): captured = _run_client_secret( session={ From b9d977aeeefc94e249b0ea63106ee81c399ecf1a Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 20 Aug 2026 02:15:17 -0700 Subject: [PATCH 06/35] fix: guard vertex live passthrough provider lookup and close-code relay --- .../llm_passthrough_endpoints.py | 9 ++-- .../pass_through_endpoints.py | 9 +++- .../test_pass_through_endpoints.py | 43 +++++++++++++++++++ 3 files changed, 56 insertions(+), 5 deletions(-) diff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py index 050ad0fd627..c2b221b1f7a 100644 --- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py @@ -2397,8 +2397,8 @@ def _resolve_vertex_live_credentials( model: str | None, ) -> VertexPassThroughCredentials | None: """ - Resolution order: credentials registered for the requested project/location, then any DB model entry - flagged ``use_in_pass_through``, then ``default_vertex_config`` and the ``DEFAULT_VERTEXAI_*`` env vars + Resolution order: an explicit project/location registration or ``default_vertex_config``, then any DB model + entry flagged ``use_in_pass_through``, then the ``DEFAULT_VERTEXAI_*`` env vars """ keyed: Final = passthrough_endpoint_router.get_vertex_credentials( project_id=vertex_project, @@ -2457,7 +2457,10 @@ def _resolve_alias_to_upstream_model(setup_model: str, llm_router: "Router | Non ) if upstream is None: return setup_model - _, provider, _, _ = litellm.get_llm_provider(model=upstream) + try: + _, provider, _, _ = litellm.get_llm_provider(model=upstream) + except litellm.exceptions.BadRequestError: + return upstream return upstream.removeprefix(f"{provider}/") diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py index d68ef8019d2..5608e8b384d 100644 --- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py @@ -32,7 +32,7 @@ from websockets.exceptions import ( ConnectionClosedOK, InvalidStatus, ) -from websockets.frames import Close +from websockets.frames import EXTERNAL_CLOSE_CODES, Close import litellm from litellm._logging import verbose_proxy_logger @@ -1930,13 +1930,18 @@ def _truncated_close_reason(reason: str) -> str: def _upstream_close_to_relay(task_results: Iterable[object]) -> Close | None: """ - The upstream close worth telling the client about: anything other than a plain, reasonless normal close + The upstream close worth telling the client about: anything other than a plain, reasonless normal close. + + Codes outside ``EXTERNAL_CLOSE_CODES`` and the private range never travel on the wire (1006 for a socket that + died without a close frame, 1005 for one that sent no code), so relaying them would build an invalid frame """ upstream_close: Final = next((result for result in task_results if isinstance(result, Close)), None) if upstream_close is None: return None if upstream_close.code == 1000 and upstream_close.reason == "": return None + if upstream_close.code not in EXTERNAL_CLOSE_CODES and not 3000 <= upstream_close.code < 5000: + return None return upstream_close diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py index 844aa099541..2663396bf53 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py @@ -5188,6 +5188,49 @@ async def test_websocket_passthrough_rewrites_gateway_alias_setup_model(): assert sent_setup["model"] == "projects/proj-db/locations/global/publishers/google/models/gemini-live-2.5-flash" +@pytest.mark.asyncio +@pytest.mark.parametrize("rcvd_close", [None, "abnormal", "no_status"]) +async def test_websocket_passthrough_does_not_relay_unsendable_upstream_close(rcvd_close): + from websockets.exceptions import ConnectionClosedError + from websockets.frames import Close + + rcvd = { + None: None, + "abnormal": Close(1006, "connection died"), + "no_status": Close(1005, ""), + }[rcvd_close] + upstream_ws = ClosingUpstreamWebSocket( + ConnectionClosedError(rcvd=rcvd, sent=None, rcvd_then_sent=None) + ) + websocket = _client_websocket(_pending_receive) + + with _patched_websocket_passthrough_environment(upstream_ws): + await websocket_passthrough_request( + websocket=websocket, + target="wss://aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent", + custom_headers={"Authorization": "Bearer token"}, + user_api_key_dict=UserAPIKeyAuth(), + forward_headers=False, + endpoint="/vertex_ai/live", + accept_websocket=False, + ) + + websocket.close.assert_awaited_once_with() + + +@pytest.mark.asyncio +async def test_websocket_passthrough_rewrites_alias_of_unrecognised_upstream_model(): + llm_router = MagicMock() + llm_router.get_model_list.return_value = [ + {"model_name": "gemini-live", "litellm_params": {"model": "self-hosted-live-endpoint"}} + ] + + sent_frame = await _run_setup_rewrite_passthrough("gemini-live", llm_router=llm_router) + + sent_setup = json.loads(sent_frame)["setup"] + assert sent_setup["model"] == "projects/proj-db/locations/global/publishers/google/models/self-hosted-live-endpoint" + + @pytest.mark.asyncio async def test_websocket_passthrough_leaves_full_resource_setup_model_untouched(): full_resource = "projects/other/locations/us-central1/publishers/google/models/gemini-2.0-flash-live-preview-04-09" From d434787a20e5e170bf94cfb89393c691f1ad0054 Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 20 Aug 2026 02:19:38 -0700 Subject: [PATCH 07/35] fix: refuse to guess a vertex project when live passthrough has no model hint --- .../passthrough_endpoint_router.py | 17 ++++++++++--- .../test_passthrough_endpoint_router.py | 25 +++++++++++++++---- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py b/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py index e7887e33ca6..28067c842cd 100644 --- a/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py +++ b/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py @@ -126,6 +126,9 @@ class PassthroughEndpointRouter: ``deployment_key_to_vertex_credentials`` is only reachable when the caller names a project and location, which WebSocket clients never do, so DB-stored deployments need this lookup to be usable at all. + + With no model to go on, only deployments that agree on a project and location answer: guessing between + two Vertex projects would mint a token for one and later send the other one's model name """ llm_router: Final = self.llm_router_getter() if llm_router is None: @@ -135,16 +138,22 @@ class PassthroughEndpointRouter: for deployment in (llm_router.get_model_list() or ()) if (credentials := self._resolve_vertex_deployment_credentials(deployment["litellm_params"])) is not None ) - if len(resolved) == 0: - return None - return next( + matched: Final = next( ( credentials for deployment, credentials in resolved if model is not None and self._deployment_matches_model(deployment, model) ), - resolved[0][1], + None, ) + if matched is not None: + return matched + targets: Final = frozenset( + (credentials.vertex_project, credentials.vertex_location) for _, credentials in resolved + ) + if len(targets) != 1: + return None + return resolved[0][1] def _resolve_vertex_deployment_credentials( self, litellm_params: LiteLLMParamsTypedDict diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py b/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py index 7816178471f..f86bfb8bb1b 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py @@ -268,14 +268,29 @@ def test_vertex_model_hint_prefers_matching_deployment(): assert by_upstream_id is not None and by_upstream_id.vertex_project == "proj-live" -def test_vertex_unmatched_hint_falls_back_to_first_flagged_deployment(): +def test_vertex_without_usable_hint_refuses_to_guess_between_projects(): passthrough_router = _passthrough_router(_two_vertex_deployments_router()) - unmatched = passthrough_router.get_vertex_credentials_from_router_deployments(model="unknown-model") - no_hint = passthrough_router.get_vertex_credentials_from_router_deployments(model=None) + assert passthrough_router.get_vertex_credentials_from_router_deployments(model="unknown-model") is None + assert passthrough_router.get_vertex_credentials_from_router_deployments(model=None) is None - assert unmatched is not None and unmatched.vertex_project == "proj-first" - assert no_hint is not None and no_hint.vertex_project == "proj-first" + +def test_vertex_without_hint_falls_back_when_deployments_share_a_target(): + llm_router = litellm.Router( + model_list=[ + _vertex_deployment( + "gemini-flash", "vertex_ai/gemini-2.5-flash", vertex_project="proj-one", vertex_location="global" + ), + _vertex_deployment( + "gemini-live", "vertex_ai/gemini-live-2.5-flash", vertex_project="proj-one", vertex_location="global" + ), + ] + ) + passthrough_router = _passthrough_router(llm_router) + + resolved = passthrough_router.get_vertex_credentials_from_router_deployments(model=None) + + assert resolved is not None and resolved.vertex_project == "proj-one" def test_no_flagged_vertex_deployment_returns_none(): From 58844d3bda3c74ba35c3a571de0a8d2fcf2b6a79 Mon Sep 17 00:00:00 2001 From: mateo-berri Date: Thu, 20 Aug 2026 02:36:47 -0700 Subject: [PATCH 08/35] refactor(realtime): inject the vertex access token resolver Take the resolver and its timeout as parameters of the bounded helper and bind the vertex one once at module level, so the timeout tests drive an injected fake instead of patching a shared singleton. --- litellm/realtime_api/main.py | 15 ++- litellm/types/llms/vertex_ai.py | 13 ++- tests/test_litellm/realtime_api/test_main.py | 99 +++++++++++++------- 3 files changed, 86 insertions(+), 41 deletions(-) diff --git a/litellm/realtime_api/main.py b/litellm/realtime_api/main.py index 8fde7cb75c5..56b3931711e 100644 --- a/litellm/realtime_api/main.py +++ b/litellm/realtime_api/main.py @@ -15,7 +15,7 @@ from litellm.llms.base_llm.realtime.transformation import BaseRealtimeConfig from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler from litellm.llms.xai.common_utils import XAIModelInfo from litellm.secret_managers.main import get_secret_str -from litellm.types.llms.vertex_ai import VERTEX_CREDENTIALS_TYPES +from litellm.types.llms.vertex_ai import VERTEX_CREDENTIALS_TYPES, VertexAccessTokenResolver from litellm.types.realtime import ( RealtimeClientSecretRequest, RealtimeExpiresAfter, @@ -43,6 +43,7 @@ openai_realtime: Final = OpenAIRealtime() bedrock_realtime: Final = BedrockRealtime() xai_realtime: Final = XAIRealtime() vertex_llm_base: Final = VertexBase() +vertex_access_token_resolver: Final[VertexAccessTokenResolver] = vertex_llm_base._ensure_access_token_async base_llm_http_handler = BaseLLMHTTPHandler() @@ -290,20 +291,22 @@ async def arealtime_calls( async def _resolve_vertex_access_token_bounded( credentials: VERTEX_CREDENTIALS_TYPES | None, project_id: str | None, + resolver: VertexAccessTokenResolver, + timeout_seconds: float, ) -> tuple[str, str]: try: return await asyncio.wait_for( - vertex_llm_base._ensure_access_token_async( + resolver( credentials=credentials, project_id=project_id, custom_llm_provider="vertex_ai", ), - timeout=REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS, + timeout=timeout_seconds, ) except asyncio.TimeoutError as e: raise ValueError( "Vertex AI realtime: timed out fetching Google OAuth access token after " - f"{REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS}s; check network egress from the proxy " + f"{timeout_seconds}s; check network egress from the proxy " "to the OAuth token endpoint (oauth2.googleapis.com)" ) from e @@ -508,6 +511,8 @@ async def _arealtime( ) = await _resolve_vertex_access_token_bounded( credentials=vertex_credentials, project_id=vertex_project, + resolver=vertex_access_token_resolver, + timeout_seconds=REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS, ) vertex_realtime_config: Final = VertexAIRealtimeConfig( @@ -588,6 +593,8 @@ async def _realtime_health_check( ) = await _resolve_vertex_access_token_bounded( credentials=VertexBase.safe_get_vertex_ai_credentials(vertex_model_params), project_id=VertexBase.safe_get_vertex_ai_project(vertex_model_params), + resolver=vertex_access_token_resolver, + timeout_seconds=REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS, ) vertex_realtime_config: Final = VertexAIRealtimeConfig( access_token=access_token, diff --git a/litellm/types/llms/vertex_ai.py b/litellm/types/llms/vertex_ai.py index b750563432e..3b95b786631 100644 --- a/litellm/types/llms/vertex_ai.py +++ b/litellm/types/llms/vertex_ai.py @@ -1,5 +1,5 @@ from enum import Enum -from typing import Any, Final, Literal +from typing import Any, Final, Literal, Protocol from typing_extensions import ( Required, @@ -747,6 +747,17 @@ class VertexVideoGenerationResponse(TypedDict, total=False): VERTEX_CREDENTIALS_TYPES = str | dict[str, str] +class VertexAccessTokenResolver(Protocol): + """Resolves a Google OAuth access token and the project id it belongs to.""" + + async def __call__( + self, + credentials: VERTEX_CREDENTIALS_TYPES | None, + project_id: str | None, + custom_llm_provider: Literal["vertex_ai", "vertex_ai_beta", "gemini"], + ) -> tuple[str, str]: ... + + class VertexPartnerProvider(str, Enum): mistralai = "mistralai" llama = "llama" diff --git a/tests/test_litellm/realtime_api/test_main.py b/tests/test_litellm/realtime_api/test_main.py index 8ed7fb06e84..9f48d4d427b 100644 --- a/tests/test_litellm/realtime_api/test_main.py +++ b/tests/test_litellm/realtime_api/test_main.py @@ -93,12 +93,70 @@ def test_client_secret_session_model_takes_priority_over_top_level(monkeypatch): assert captured["request_data"]["session"]["model"] == "gpt-realtime-session" +async def _hanging_resolver(credentials, project_id, custom_llm_provider) -> tuple[str, str]: + await asyncio.sleep(30) + return "", "" + + +async def _thread_offloaded_hanging_resolver(credentials, project_id, custom_llm_provider) -> tuple[str, str]: + from litellm.litellm_core_utils.asyncify import asyncify + + await asyncify(time.sleep)(30) + return "", "" + + +async def _instant_resolver(credentials, project_id, custom_llm_provider) -> tuple[str, str]: + return "token-abc", "resolved-project" + + @pytest.mark.asyncio -async def test_arealtime_vertex_hung_credential_resolution_raises_promptly(monkeypatch): +async def test_vertex_credential_resolution_returns_the_resolved_token_and_project(): + assert await realtime_main._resolve_vertex_access_token_bounded( + credentials="fake-credentials", + project_id="fake-project", + resolver=_instant_resolver, + timeout_seconds=5, + ) == ("token-abc", "resolved-project") + + +@pytest.mark.asyncio +async def test_vertex_credential_resolution_times_out_instead_of_hanging(): """Regression for the realtime accept-then-silence hang: a stalled Google - OAuth token refresh used to block _arealtime's vertex branch unbounded - (minutes of zero frames for the client). It must instead raise a clear, - prompt error naming the credential-resolution timeout.""" + OAuth token refresh used to block the vertex branch unbounded (minutes of + zero frames for the client). It must raise promptly and name the timeout.""" + start = time.monotonic() + with pytest.raises(ValueError, match="timed out fetching Google OAuth access token"): + await realtime_main._resolve_vertex_access_token_bounded( + credentials="fake-credentials", + project_id="fake-project", + resolver=_hanging_resolver, + timeout_seconds=0.05, + ) + assert time.monotonic() - start < 5 + + +@pytest.mark.asyncio +async def test_vertex_credential_resolution_bounds_a_thread_offloaded_refresh(): + """The real stall is a blocking google-auth refresh that runs in a worker + thread via asyncify, not a plain awaitable sleep. A timeout that only bounds + cancellable awaits would leave that shape hanging, so bound the shape the + proxy actually runs.""" + start = time.monotonic() + with pytest.raises(ValueError, match="timed out fetching Google OAuth access token"): + await realtime_main._resolve_vertex_access_token_bounded( + credentials="fake-credentials", + project_id="fake-project", + resolver=_thread_offloaded_hanging_resolver, + timeout_seconds=0.05, + ) + assert time.monotonic() - start < 5 + + +@pytest.mark.asyncio +async def test_arealtime_vertex_branch_resolves_credentials_under_a_bound(monkeypatch): + """The wiring half of the regression: the vertex branch of _arealtime must + go through the bounded resolver, so a hung token refresh surfaces as a + prompt error there rather than as an accepted-then-silent websocket.""" async def hanging_token_refresh(**kwargs): await asyncio.sleep(30) @@ -107,38 +165,7 @@ async def test_arealtime_vertex_hung_credential_resolution_raises_promptly(monke return model, "vertex_ai", None, api_base monkeypatch.setattr(realtime_main, "get_llm_provider", mock_get_llm_provider) - monkeypatch.setattr(realtime_main.vertex_llm_base, "_ensure_access_token_async", hanging_token_refresh) - monkeypatch.setattr(realtime_main, "REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS", 0.05) - - start = time.monotonic() - with pytest.raises(ValueError, match="timed out fetching Google OAuth access token"): - await realtime_main._arealtime.__wrapped__( - model="gemini-live-2.5-flash", - websocket=MagicMock(), - litellm_logging_obj=FakeLogging(), - vertex_credentials="fake-credentials", - vertex_project="fake-project", - vertex_location="us-central1", - ) - assert time.monotonic() - start < 5 - - -@pytest.mark.asyncio -async def test_arealtime_vertex_credential_timeout_survives_thread_offloaded_refresh(monkeypatch): - """The real stall is a blocking google-auth refresh that runs in a worker - thread via asyncify, not a plain awaitable sleep. A timeout that only bounds - cancellable awaits would leave that shape hanging, so bound the shape the - proxy actually runs.""" - from litellm.litellm_core_utils.asyncify import asyncify - - async def thread_offloaded_hanging_refresh(**kwargs): - return await asyncify(time.sleep)(30) - - def mock_get_llm_provider(model, api_base, api_key): - return model, "vertex_ai", None, api_base - - monkeypatch.setattr(realtime_main, "get_llm_provider", mock_get_llm_provider) - monkeypatch.setattr(realtime_main.vertex_llm_base, "_ensure_access_token_async", thread_offloaded_hanging_refresh) + monkeypatch.setattr(realtime_main, "vertex_access_token_resolver", hanging_token_refresh) monkeypatch.setattr(realtime_main, "REALTIME_CREDENTIAL_RESOLUTION_TIMEOUT_SECONDS", 0.05) start = time.monotonic() From d643136895d6d3c00f2339b75e63162098bc0802 Mon Sep 17 00:00:00 2001 From: Mateo Date: Thu, 20 Aug 2026 02:49:01 -0700 Subject: [PATCH 09/35] fix(realtime): resolve the vertex token resolver at call time Binding the bound method at import froze the module-level VertexBase instance, so callers that swap it no longer reached their replacement. --- litellm/realtime_api/main.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/litellm/realtime_api/main.py b/litellm/realtime_api/main.py index 56b3931711e..4e02be36daa 100644 --- a/litellm/realtime_api/main.py +++ b/litellm/realtime_api/main.py @@ -2,7 +2,7 @@ import asyncio import os -from typing import Any, Final, cast +from typing import Any, Final, Literal, cast import litellm from litellm.constants import ( @@ -43,7 +43,6 @@ openai_realtime: Final = OpenAIRealtime() bedrock_realtime: Final = BedrockRealtime() xai_realtime: Final = XAIRealtime() vertex_llm_base: Final = VertexBase() -vertex_access_token_resolver: Final[VertexAccessTokenResolver] = vertex_llm_base._ensure_access_token_async base_llm_http_handler = BaseLLMHTTPHandler() @@ -288,6 +287,18 @@ async def arealtime_calls( ) +async def vertex_access_token_resolver( + credentials: VERTEX_CREDENTIALS_TYPES | None, + project_id: str | None, + custom_llm_provider: Literal["vertex_ai", "vertex_ai_beta", "gemini"], +) -> tuple[str, str]: + return await vertex_llm_base._ensure_access_token_async( + credentials=credentials, + project_id=project_id, + custom_llm_provider=custom_llm_provider, + ) + + async def _resolve_vertex_access_token_bounded( credentials: VERTEX_CREDENTIALS_TYPES | None, project_id: str | None, From 4f04e59ca036860ed1a83eb6169b4bdd20b31bb1 Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 20 Aug 2026 03:05:48 -0700 Subject: [PATCH 10/35] fix: harden vertex live passthrough against client model forms and dict credentials - accept the Live SDK's models/ and LiteLLM's vertex_ai/ when rewriting the setup model - keep a dict service account intact instead of stringifying it - treat same-target deployments holding different credentials as ambiguous - guard both websocket states before every close so a second close cannot raise - build the sendable close codes from the public CloseCode enum --- .../llm_passthrough_endpoints.py | 40 +++++-- .../pass_through_endpoints.py | 32 ++++-- .../passthrough_endpoint_router.py | 28 ++++- .../test_llm_pass_through_endpoints.py | 107 ++++++++++++++++++ .../test_pass_through_endpoints.py | 32 ++++++ .../test_passthrough_endpoint_router.py | 53 +++++++++ 6 files changed, 266 insertions(+), 26 deletions(-) diff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py index c2b221b1f7a..7ce41c1d5b6 100644 --- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py @@ -2384,6 +2384,21 @@ VERTEX_LIVE_UNCONFIGURED_CLOSE_REASON: Final = ( VERTEX_PUBLISHER_MODEL_PREFIX: Final = "publishers/google/models/" +VERTEX_PUBLISHERS_SEGMENT: Final = "publishers/" + + +def _vertex_publisher_model_suffix(model: str) -> str: + """ + Turn whatever the client named into the ``publishers//models/`` tail of a Vertex resource name. + + Clients send bare ids, LiteLLM ids (``vertex_ai/gemini-live-2.5-flash``), and the Live SDK's ``models/``, + and a publisher model id never contains a slash, so anything ahead of the last one is addressing, not identity + """ + publishers_at: Final = model.find(VERTEX_PUBLISHERS_SEGMENT) + if publishers_at != -1: + return model[publishers_at:] + return f"{VERTEX_PUBLISHER_MODEL_PREFIX}{model.rsplit('/', 1)[-1]}" + def _get_llm_router() -> "Router | None": from litellm.proxy.proxy_server import llm_router @@ -2397,8 +2412,12 @@ def _resolve_vertex_live_credentials( model: str | None, ) -> VertexPassThroughCredentials | None: """ - Resolution order: an explicit project/location registration or ``default_vertex_config``, then any DB model - entry flagged ``use_in_pass_through``, then the ``DEFAULT_VERTEXAI_*`` env vars + Resolution order: an explicit project/location registration, then ``default_vertex_config`` (which the proxy + fills from the ``DEFAULT_VERTEXAI_*`` env vars whenever the yaml leaves it out), then any DB model entry + flagged ``use_in_pass_through``. + + DB entries come last on purpose: an operator who set a global default already said which project + pass-through traffic should bill to, and this route silently ignoring that would be the worse surprise """ keyed: Final = passthrough_endpoint_router.get_vertex_credentials( project_id=vertex_project, @@ -2436,22 +2455,23 @@ def _build_vertex_live_setup_model_rewriter( if setup_model.startswith("projects/"): return setup_model aliased: Final = _resolve_alias_to_upstream_model(setup_model, llm_router) - return ( - f"projects/{vertex_project}/locations/{vertex_location}/" - f"{VERTEX_PUBLISHER_MODEL_PREFIX}{aliased.removeprefix(VERTEX_PUBLISHER_MODEL_PREFIX)}" - ) + return f"projects/{vertex_project}/locations/{vertex_location}/{_vertex_publisher_model_suffix(aliased)}" return rewrite def _resolve_alias_to_upstream_model(setup_model: str, llm_router: "Router | None") -> str: + """ + The Live SDK wraps whatever the caller typed as ``models/``, so a gateway alias arrives prefixed + """ if llm_router is None: return setup_model + candidates: Final = (setup_model, setup_model.rsplit("/", 1)[-1]) upstream: Final = next( ( - deployment["litellm_params"]["model"] + deployment["litellm_params"].get("model") for deployment in (llm_router.get_model_list() or ()) - if deployment.get("model_name") == setup_model + if deployment.get("model_name") in candidates ), None, ) @@ -2500,9 +2520,7 @@ async def vertex_ai_live_websocket_passthrough( vertex_credentials_config.vertex_location if vertex_credentials_config is not None else None ) credentials_value: Final = ( - str(vertex_credentials_config.vertex_credentials) - if vertex_credentials_config is not None and vertex_credentials_config.vertex_credentials is not None - else None + vertex_credentials_config.vertex_credentials if vertex_credentials_config is not None else None ) try: diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py index 5608e8b384d..d45421489e7 100644 --- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py @@ -32,7 +32,7 @@ from websockets.exceptions import ( ConnectionClosedOK, InvalidStatus, ) -from websockets.frames import EXTERNAL_CLOSE_CODES, Close +from websockets.frames import Close, CloseCode import litellm from litellm._logging import verbose_proxy_logger @@ -1928,11 +1928,26 @@ def _truncated_close_reason(reason: str) -> str: return encoded[:WEBSOCKET_CLOSE_REASON_MAX_BYTES].decode("utf-8", errors="ignore") +SENDABLE_CLOSE_CODES: Final = frozenset(CloseCode) - frozenset( + {CloseCode.NO_STATUS_RCVD, CloseCode.ABNORMAL_CLOSURE, CloseCode.TLS_HANDSHAKE} +) + + +def _client_socket_is_open(websocket: WebSocket) -> bool: + """ + Starlette tracks the two halves separately and raises on a second close, so both have to still be live + """ + return ( + websocket.client_state != WebSocketState.DISCONNECTED + and websocket.application_state != WebSocketState.DISCONNECTED + ) + + def _upstream_close_to_relay(task_results: Iterable[object]) -> Close | None: """ The upstream close worth telling the client about: anything other than a plain, reasonless normal close. - Codes outside ``EXTERNAL_CLOSE_CODES`` and the private range never travel on the wire (1006 for a socket that + Codes outside ``SENDABLE_CLOSE_CODES`` and the private range never travel on the wire (1006 for a socket that died without a close frame, 1005 for one that sent no code), so relaying them would build an invalid frame """ upstream_close: Final = next((result for result in task_results if isinstance(result, Close)), None) @@ -1940,7 +1955,7 @@ def _upstream_close_to_relay(task_results: Iterable[object]) -> Close | None: return None if upstream_close.code == 1000 and upstream_close.reason == "": return None - if upstream_close.code not in EXTERNAL_CLOSE_CODES and not 3000 <= upstream_close.code < 5000: + if upstream_close.code not in SENDABLE_CLOSE_CODES and not 3000 <= upstream_close.code < 5000: return None return upstream_close @@ -2268,7 +2283,7 @@ async def websocket_passthrough_request( raise exception upstream_close: Final = _upstream_close_to_relay(task.result() for task in done) - if upstream_close is not None and websocket.application_state != WebSocketState.DISCONNECTED: + if upstream_close is not None and _client_socket_is_open(websocket): await websocket.close( code=upstream_close.code, reason=_truncated_close_reason(upstream_close.reason), @@ -2359,7 +2374,7 @@ async def websocket_passthrough_request( ), ) - if websocket.client_state != WebSocketState.DISCONNECTED: + if _client_socket_is_open(websocket): await websocket.close( code=getattr(exc, "status_code", 1011), reason="Upstream connection rejected", @@ -2387,13 +2402,10 @@ async def websocket_passthrough_request( ), ) - if websocket.client_state != WebSocketState.DISCONNECTED: + if _client_socket_is_open(websocket): await websocket.close(code=1011, reason="WebSocket passthrough error") finally: - if ( - websocket.client_state != WebSocketState.DISCONNECTED - and websocket.application_state != WebSocketState.DISCONNECTED - ): + if _client_socket_is_open(websocket): await websocket.close() diff --git a/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py b/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py index 28067c842cd..7fd607fc4d0 100644 --- a/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py +++ b/litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py @@ -1,3 +1,4 @@ +import json from collections.abc import Callable from typing import TYPE_CHECKING, Final @@ -27,6 +28,15 @@ def _get_str_value(values: dict[str, object] | None, key: str) -> str | None: return value if isinstance(value, str) else None +def _credential_identity(credentials: VERTEX_CREDENTIALS_TYPES | None) -> str | None: + """ + A hashable stand-in for a credential, so two deployments can be compared for holding the same one + """ + if isinstance(credentials, dict): + return json.dumps(credentials, sort_keys=True) + return credentials + + class PassthroughEndpointRouter: """ Use this class to Get credentials for pass-through endpoints @@ -127,8 +137,8 @@ class PassthroughEndpointRouter: ``deployment_key_to_vertex_credentials`` is only reachable when the caller names a project and location, which WebSocket clients never do, so DB-stored deployments need this lookup to be usable at all. - With no model to go on, only deployments that agree on a project and location answer: guessing between - two Vertex projects would mint a token for one and later send the other one's model name + With no model to go on, only deployments that agree on a project, a location, and a credential answer: + guessing between two Vertex projects would mint a token for one and later send the other one's model name """ llm_router: Final = self.llm_router_getter() if llm_router is None: @@ -149,7 +159,12 @@ class PassthroughEndpointRouter: if matched is not None: return matched targets: Final = frozenset( - (credentials.vertex_project, credentials.vertex_location) for _, credentials in resolved + ( + credentials.vertex_project, + credentials.vertex_location, + _credential_identity(credentials.vertex_credentials), + ) + for _, credentials in resolved ) if len(targets) != 1: return None @@ -172,9 +187,12 @@ class PassthroughEndpointRouter: vertex_location: Final = _get_str_value(credential_values, "vertex_location") or litellm_params.get( "vertex_location" ) - vertex_credentials: Final = _get_str_value(credential_values, "vertex_credentials") or litellm_params.get( - "vertex_credentials" + stored_credentials: Final = ( + credential_values.get("vertex_credentials") if credential_values is not None else None ) + vertex_credentials: Final = ( + stored_credentials if isinstance(stored_credentials, (str, dict)) else None + ) or litellm_params.get("vertex_credentials") if vertex_project is None or vertex_location is None: return None return VertexPassThroughCredentials( diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py index 5ed974c7a47..f994fba371b 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py @@ -3889,6 +3889,9 @@ class TestComprehendMedicalProxyRoute: assert exc_info.value.status_code == 400 +LIVE_RESOURCE_PATH = "projects/proj-db/locations/global/publishers/google/models/gemini-live-2.5-flash" + + class TestVertexAILiveWebsocketPassthrough: def _websocket(self): from starlette.websockets import WebSocketState @@ -3959,6 +3962,110 @@ class TestVertexAILiveWebsocketPassthrough: ) websocket.close.assert_not_awaited() + @pytest.mark.parametrize( + "setup_model, expected", + [ + ("gemini-live-2.5-flash", LIVE_RESOURCE_PATH), + ("models/gemini-live-2.5-flash", LIVE_RESOURCE_PATH), + ("vertex_ai/gemini-live-2.5-flash", LIVE_RESOURCE_PATH), + ("gemini-live", LIVE_RESOURCE_PATH), + ("models/gemini-live", LIVE_RESOURCE_PATH), + ( + "publishers/meta/models/llama-3.3-70b-instruct-maas", + "projects/proj-db/locations/global/publishers/meta/models/llama-3.3-70b-instruct-maas", + ), + ( + "projects/other/locations/us-central1/publishers/google/models/gemini-2.0-flash", + "projects/other/locations/us-central1/publishers/google/models/gemini-2.0-flash", + ), + ], + ) + def test_setup_model_rewriter_normalises_the_forms_clients_send(self, setup_model, expected): + from litellm.proxy.pass_through_endpoints import ( + llm_passthrough_endpoints as passthrough_module, + ) + + llm_router = litellm.Router( + model_list=[ + { + "model_name": "gemini-live", + "litellm_params": { + "model": "vertex_ai/gemini-live-2.5-flash", + "use_in_pass_through": True, + "vertex_project": "proj-db", + "vertex_location": "global", + }, + } + ] + ) + + rewriter = passthrough_module._build_vertex_live_setup_model_rewriter( + vertex_project="proj-db", + vertex_location="global", + llm_router=llm_router, + ) + + assert rewriter is not None + assert rewriter(setup_model) == expected + + @pytest.mark.asyncio + async def test_default_vertex_config_outranks_db_deployment(self, monkeypatch): + from litellm.proxy.pass_through_endpoints import ( + llm_passthrough_endpoints as passthrough_module, + ) + from litellm.types.passthrough_endpoints.vertex_ai import ( + VertexPassThroughCredentials, + ) + + llm_router = litellm.Router( + model_list=[ + { + "model_name": "gemini-live", + "litellm_params": { + "model": "vertex_ai/gemini-live-2.5-flash", + "use_in_pass_through": True, + "vertex_project": "proj-db", + "vertex_location": "global", + "vertex_credentials": '{"type": "db_account"}', + }, + } + ] + ) + monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", llm_router) + monkeypatch.setattr( + passthrough_module.passthrough_endpoint_router, + "default_vertex_config", + VertexPassThroughCredentials( + vertex_project="proj-env", + vertex_location="global", + vertex_credentials='{"type": "env_account"}', + ), + ) + self._clear_vertex_env(monkeypatch) + websocket = self._websocket() + ensure_token = AsyncMock(return_value=("token-abc", "proj-env")) + ws_passthrough = AsyncMock() + + with ( + patch.object(passthrough_module.vertex_llm_base, "_ensure_access_token_async", ensure_token), + patch.object(passthrough_module, "websocket_passthrough_request", ws_passthrough), + ): + await passthrough_module.vertex_ai_live_websocket_passthrough( + websocket=websocket, + model="gemini-live", + user_api_key_dict=UserAPIKeyAuth(), + ) + + ensure_token.assert_awaited_once_with( + credentials='{"type": "env_account"}', + project_id="proj-env", + custom_llm_provider="vertex_ai_beta", + ) + rewriter = ws_passthrough.await_args.kwargs["setup_model_rewriter"] + assert rewriter("gemini-live") == ( + "projects/proj-env/locations/global/publishers/google/models/gemini-live-2.5-flash" + ) + @pytest.mark.asyncio async def test_credential_failure_close_names_configuration_options(self, monkeypatch): from litellm.proxy.pass_through_endpoints import ( diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py index 2663396bf53..00097166c13 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py @@ -5243,6 +5243,38 @@ async def test_websocket_passthrough_leaves_full_resource_setup_model_untouched( ) +@pytest.mark.asyncio +async def test_websocket_passthrough_does_not_close_twice_when_success_logging_fails(): + from websockets.exceptions import ConnectionClosedError + from websockets.frames import Close + + upstream_reason = "Publisher Model `projects/p/locations/global/publishers/google/models/nope` was not found" + upstream_ws = ClosingUpstreamWebSocket( + ConnectionClosedError(rcvd=Close(1008, upstream_reason), sent=Close(1008, ""), rcvd_then_sent=True) + ) + websocket = _client_websocket(_pending_receive) + + with ( + _patched_websocket_passthrough_environment(upstream_ws), + patch( + "litellm.proxy.pass_through_endpoints.pass_through_endpoints." + "GLOBAL_LOGGING_WORKER.ensure_initialized_and_enqueue", + side_effect=RuntimeError("logging worker down"), + ), + ): + await websocket_passthrough_request( + websocket=websocket, + target="wss://aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent", + custom_headers={"Authorization": "Bearer token"}, + user_api_key_dict=UserAPIKeyAuth(), + forward_headers=False, + endpoint="/vertex_ai/live", + accept_websocket=False, + ) + + websocket.close.assert_awaited_once_with(code=1008, reason=upstream_reason) + + def _passthrough_kwargs_for_reservation( user_api_key_dict: UserAPIKeyAuth, parsed_body: Optional[dict] = None ) -> dict: diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py b/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py index f86bfb8bb1b..e3cbc2d507f 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_passthrough_endpoint_router.py @@ -293,6 +293,59 @@ def test_vertex_without_hint_falls_back_when_deployments_share_a_target(): assert resolved is not None and resolved.vertex_project == "proj-one" +def test_vertex_without_hint_refuses_to_guess_between_service_accounts(): + llm_router = litellm.Router( + model_list=[ + _vertex_deployment( + "gemini-flash", + "vertex_ai/gemini-2.5-flash", + vertex_project="proj-one", + vertex_location="global", + vertex_credentials='{"client_email": "flash@proj-one.iam"}', + ), + _vertex_deployment( + "gemini-live", + "vertex_ai/gemini-live-2.5-flash", + vertex_project="proj-one", + vertex_location="global", + vertex_credentials='{"client_email": "live@proj-one.iam"}', + ), + ] + ) + passthrough_router = _passthrough_router(llm_router) + + assert passthrough_router.get_vertex_credentials_from_router_deployments(model=None) is None + + +def test_vertex_named_credential_keeps_dict_service_account(): + service_account = {"type": "service_account", "client_email": "live@proj-db.iam"} + CredentialAccessor.upsert_credentials( + [ + _vertex_credential( + "cred_gcp_dict", + { + "vertex_project": "proj-db", + "vertex_location": "global", + "vertex_credentials": service_account, + }, + ) + ] + ) + llm_router = litellm.Router( + model_list=[ + _vertex_deployment( + "gemini-live", "vertex_ai/gemini-live-2.5-flash", litellm_credential_name="cred_gcp_dict" + ) + ] + ) + passthrough_router = _passthrough_router(llm_router) + + resolved = passthrough_router.get_vertex_credentials_from_router_deployments(model=None) + + assert resolved is not None + assert resolved.vertex_credentials == service_account + + def test_no_flagged_vertex_deployment_returns_none(): llm_router = litellm.Router( model_list=[ From cc2013e9660ab722fab9f8097497a121336a034f Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 20 Aug 2026 03:55:25 -0700 Subject: [PATCH 11/35] fix(anthropic): map metadata.user_id to prompt_cache_key on the /v1/messages bridge Both /v1/messages bridges (Responses API adapter for openai/* and the chat-completions adapter) now derive prompt_cache_key from the first 64 characters of metadata.user_id, next to the existing user mapping. The chat bridge only sets it when the resolved provider advertises prompt_cache_key in its supported params, so providers that reject unknown params are unaffected. A prompt_cache_key sent explicitly by the client always wins over the derived value. Fixes #37508 --- .../adapters/handler.py | 10 ++- .../adapters/transformation.py | 31 +++++++- .../responses_adapters/handler.py | 7 +- .../responses_adapters/transformation.py | 6 +- .../experimental_pass_through/utils.py | 9 +++ litellm/types/llms/openai.py | 1 + ...al_pass_through_adapters_transformation.py | 79 +++++++++++++++++++ .../adapters/test_handler_prompt_cache_key.py | 64 +++++++++++++++ .../test_responses_adapters_handler.py | 45 +++++++++++ .../test_responses_adapters_transformation.py | 24 ++++++ 10 files changed, 270 insertions(+), 6 deletions(-) create mode 100644 tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_handler_prompt_cache_key.py create mode 100644 tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_handler.py diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py index 48d8a03d549..89066e33cbc 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py @@ -484,10 +484,14 @@ class LiteLLMMessagesToCompletionTransformationHandler: if "output_config" in extra_kwargs: request_data["output_config"] = extra_kwargs["output_config"] + custom_llm_provider: Final = extra_kwargs.get("custom_llm_provider") ( openai_request, tool_name_mapping, - ) = ANTHROPIC_ADAPTER.translate_completion_input_params_with_tool_mapping(request_data) + ) = ANTHROPIC_ADAPTER.translate_completion_input_params_with_tool_mapping( + request_data, + custom_llm_provider=custom_llm_provider if isinstance(custom_llm_provider, str) else None, + ) if openai_request is None: raise ValueError("Failed to translate request to OpenAI format") @@ -526,6 +530,10 @@ class LiteLLMMessagesToCompletionTransformationHandler: if key not in excluded_keys and key not in completion_kwargs and value is not None: completion_kwargs[key] = value + explicit_prompt_cache_key: Final = extra_kwargs.get("prompt_cache_key") + if explicit_prompt_cache_key is not None: + completion_kwargs["prompt_cache_key"] = explicit_prompt_cache_key + # Normalize reasoning_effort based on model capabilities # (e.g. "max" → "xhigh"/"high", "minimal" → "low" if unsupported) # Must run BEFORE _route_openai_thinking, which prepends "responses/" diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py index e45414b4a73..5c72fee25a0 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py @@ -4,8 +4,10 @@ import json from collections.abc import AsyncIterator, Iterator, Mapping from typing import TYPE_CHECKING, Any, Final, Literal, cast +import litellm from litellm.llms.anthropic.experimental_pass_through.utils import ( is_reasoning_auto_summary_enabled, + prompt_cache_key_from_user_id, ) # OpenAI has a 64-character limit for function/tool names @@ -148,7 +150,7 @@ class AnthropicAdapter: return result def translate_completion_input_params_with_tool_mapping( - self, kwargs + self, kwargs, *, custom_llm_provider: str | None = None ) -> tuple[ChatCompletionRequest | None, dict[str, str]]: """ Translate Anthropic request params to OpenAI format, returning tool name mapping. @@ -179,7 +181,10 @@ class AnthropicAdapter: ( translated_body, tool_name_mapping, - ) = LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai(anthropic_message_request=request_body) + ) = LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai( + anthropic_message_request=request_body, + custom_llm_provider=custom_llm_provider, + ) return translated_body, tool_name_mapping @@ -907,16 +912,32 @@ class LiteLLMAnthropicMessagesAdapter: ChatCompletionSystemMessage(role="system", content=openai_system_content), ) + @staticmethod + def _supports_prompt_cache_key(model: str | None, custom_llm_provider: str | None) -> bool: + if not model or not custom_llm_provider: + return False + supported_params: Final = litellm.get_supported_openai_params( + model=model, custom_llm_provider=custom_llm_provider + ) + return "prompt_cache_key" in (supported_params or ()) + def _translate_metadata_to_openai( self, anthropic_message_request: AnthropicMessagesRequest, new_kwargs: ChatCompletionRequest, + *, + custom_llm_provider: str | None = None, ) -> None: """Translate metadata fields from Anthropic request to OpenAI request.""" if "metadata" in anthropic_message_request: metadata: Final = anthropic_message_request["metadata"] if metadata and "user_id" in metadata: new_kwargs["user"] = metadata["user_id"] + prompt_cache_key: Final = prompt_cache_key_from_user_id(metadata["user_id"]) + if prompt_cache_key is not None and self._supports_prompt_cache_key( + anthropic_message_request.get("model"), custom_llm_provider + ): + new_kwargs["prompt_cache_key"] = prompt_cache_key if "litellm_metadata" in anthropic_message_request: # metadata will be passed to litellm.acompletion(), it's a litellm_param @@ -1069,7 +1090,10 @@ class LiteLLMAnthropicMessagesAdapter: new_kwargs[k] = v def translate_anthropic_to_openai( - self, anthropic_message_request: AnthropicMessagesRequest + self, + anthropic_message_request: AnthropicMessagesRequest, + *, + custom_llm_provider: str | None = None, ) -> tuple[ChatCompletionRequest, dict[str, str]]: """ This is used by the beta Anthropic Adapter, for translating anthropic `/v1/messages` requests to the openai format. @@ -1103,6 +1127,7 @@ class LiteLLMAnthropicMessagesAdapter: self._translate_metadata_to_openai( anthropic_message_request=anthropic_message_request, new_kwargs=new_kwargs, + custom_llm_provider=custom_llm_provider, ) ## CONVERT TOOL CHOICE self._translate_tool_choice_to_openai( diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py index e6d8686b466..843cda249c5 100644 --- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py +++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py @@ -105,7 +105,8 @@ def _build_responses_kwargs( # Forward litellm-specific kwargs (api_key, api_base, logging obj, etc.) excluded: Final = {"anthropic_messages"} - for key, value in _forwarded_kwargs(extra_kwargs).items(): + forwarded_kwargs: Final = _forwarded_kwargs(extra_kwargs) + for key, value in forwarded_kwargs.items(): if key == "litellm_logging_obj" and value is not None: from litellm.litellm_core_utils.litellm_logging import ( Logging as LiteLLMLoggingObject, @@ -121,6 +122,10 @@ def _build_responses_kwargs( elif key not in excluded and key not in responses_kwargs and value is not None: responses_kwargs[key] = value + explicit_prompt_cache_key: Final = forwarded_kwargs.get("prompt_cache_key") + if explicit_prompt_cache_key is not None: + responses_kwargs["prompt_cache_key"] = explicit_prompt_cache_key + return responses_kwargs diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py index 21a8cb9501e..9238433151a 100644 --- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py @@ -18,6 +18,7 @@ from litellm.litellm_core_utils.reasoning_effort_utils import ( ) from litellm.llms.anthropic.experimental_pass_through.utils import ( is_reasoning_auto_summary_enabled, + prompt_cache_key_from_user_id, ) from litellm.types.llms.anthropic import ( AllAnthropicPassThroughMessageValues, @@ -452,10 +453,13 @@ class LiteLLMAnthropicToResponsesAPIAdapter: if openai_cm is not None: responses_kwargs["context_management"] = openai_cm - # metadata user_id -> user + # metadata user_id -> user and prompt_cache_key metadata: Final = anthropic_request.get("metadata") if isinstance(metadata, dict) and "user_id" in metadata: responses_kwargs["user"] = str(metadata["user_id"])[:64] + prompt_cache_key: Final = prompt_cache_key_from_user_id(metadata["user_id"]) + if prompt_cache_key is not None: + responses_kwargs["prompt_cache_key"] = prompt_cache_key return responses_kwargs diff --git a/litellm/llms/anthropic/experimental_pass_through/utils.py b/litellm/llms/anthropic/experimental_pass_through/utils.py index 46091cd89a2..c5abcf8c04c 100644 --- a/litellm/llms/anthropic/experimental_pass_through/utils.py +++ b/litellm/llms/anthropic/experimental_pass_through/utils.py @@ -1,8 +1,17 @@ import os +from typing import Final import litellm from litellm.types.utils import ModelInfo +OPENAI_MAX_PROMPT_CACHE_KEY_LENGTH: Final = 64 + + +def prompt_cache_key_from_user_id(user_id: object) -> str | None: + if user_id is None: + return None + return str(user_id)[:OPENAI_MAX_PROMPT_CACHE_KEY_LENGTH] or None + def is_reasoning_auto_summary_enabled() -> bool: """Check whether the default 'summary: detailed' injection is enabled (opt-in).""" diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py index edfc50c99f6..beb6612497c 100644 --- a/litellm/types/llms/openai.py +++ b/litellm/types/llms/openai.py @@ -917,6 +917,7 @@ class ChatCompletionRequest(TypedDict, total=False): seed: int service_tier: str safety_identifier: str + prompt_cache_key: str # writable-ok: the /v1/messages adapter assigns it after construction stop: str | list[str] stream_options: dict temperature: float diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py index 1185893d428..dd1e8a93280 100644 --- a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py +++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py @@ -635,6 +635,85 @@ def test_translate_anthropic_to_openai_orders_top_level_and_midturn_system(): ] +def _translate_with_metadata( + model: str, metadata: dict[str, Any], custom_llm_provider: str | None +) -> dict[str, Any]: + openai_request, _ = LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai( + anthropic_message_request={ + "model": model, + "max_tokens": 100, + "metadata": metadata, + "messages": [{"role": "user", "content": "hi"}], + }, + custom_llm_provider=custom_llm_provider, + ) + return cast(dict[str, Any], openai_request) + + +def test_translate_anthropic_to_openai_maps_user_id_to_prompt_cache_key_for_openai(): + openai_request = _translate_with_metadata("openai/gpt-5.6-luna", {"user_id": "session-abc"}, "openai") + assert openai_request["user"] == "session-abc" + assert openai_request["prompt_cache_key"] == "session-abc" + + +def test_translate_anthropic_to_openai_truncates_prompt_cache_key_but_keeps_full_user(): + long_id = "".join(str(i % 10) for i in range(100)) + openai_request = _translate_with_metadata("openai/gpt-5.6-luna", {"user_id": long_id}, "openai") + assert openai_request["user"] == long_id + assert openai_request["prompt_cache_key"] == long_id[:64] + assert len(openai_request["prompt_cache_key"]) == 64 + + +@pytest.mark.parametrize("model", ["azure/my-gpt-5-deployment", "my-gpt-5-deployment"]) +def test_translate_anthropic_to_openai_sets_prompt_cache_key_for_azure(model: str): + openai_request = _translate_with_metadata(model, {"user_id": "session-abc"}, "azure") + assert openai_request["prompt_cache_key"] == "session-abc" + + +@pytest.mark.parametrize( + "model, custom_llm_provider", + [ + ("gemini/gemini-2.5-pro", "gemini"), + ("vertex_ai/gemini-2.5-pro", "vertex_ai"), + ("anthropic/claude-sonnet-4-5", "anthropic"), + ("bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0", "bedrock"), + ("no-such-model-lit5875", "no-such-provider-lit5875"), + ], +) +def test_translate_anthropic_to_openai_skips_prompt_cache_key_when_provider_lacks_it( + model: str, custom_llm_provider: str +): + openai_request = _translate_with_metadata(model, {"user_id": "session-abc"}, custom_llm_provider) + assert openai_request["user"] == "session-abc" + assert "prompt_cache_key" not in openai_request + + +def test_translate_anthropic_to_openai_skips_prompt_cache_key_without_provider(): + openai_request = _translate_with_metadata("openai/gpt-5.6-luna", {"user_id": "session-abc"}, None) + assert openai_request["user"] == "session-abc" + assert "prompt_cache_key" not in openai_request + + +@pytest.mark.parametrize("user_id", ["", None]) +def test_translate_anthropic_to_openai_skips_prompt_cache_key_for_empty_or_null_user_id(user_id: str | None): + openai_request = _translate_with_metadata("openai/gpt-5.6-luna", {"user_id": user_id}, "openai") + assert openai_request["user"] == user_id + assert "prompt_cache_key" not in openai_request + + +def test_translate_anthropic_to_openai_without_metadata_sets_neither_user_nor_prompt_cache_key(): + openai_request, _ = LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai( + anthropic_message_request={ + "model": "openai/gpt-5.6-luna", + "max_tokens": 100, + "messages": [{"role": "user", "content": "hi"}], + }, + custom_llm_provider="openai", + ) + assert "user" not in openai_request + assert "prompt_cache_key" not in openai_request + + def test_translate_openai_content_to_anthropic_empty_function_arguments(): """Test that empty function arguments are handled safely and don't cause JSON parsing errors.""" diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_handler_prompt_cache_key.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_handler_prompt_cache_key.py new file mode 100644 index 00000000000..ad6fc04217f --- /dev/null +++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_handler_prompt_cache_key.py @@ -0,0 +1,64 @@ +import os +import sys + +import pytest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../../.."))) + +from litellm.llms.anthropic.experimental_pass_through.adapters.handler import ( + LiteLLMMessagesToCompletionTransformationHandler, +) + +MESSAGES = [{"role": "user", "content": "hello"}] + + +def _prepare(model: str, extra_kwargs: dict[str, object], thinking: dict[str, object] | None = None): + completion_kwargs, _ = LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs( + max_tokens=1024, + messages=MESSAGES, + model=model, + metadata={"user_id": "session-abc"}, + thinking=thinking, + extra_kwargs=extra_kwargs, + ) + return completion_kwargs + + +def test_prepare_completion_kwargs_derives_prompt_cache_key_for_openai_provider(): + completion_kwargs = _prepare("openai/gpt-5.6-luna", {"custom_llm_provider": "openai"}) + assert completion_kwargs["user"] == "session-abc" + assert completion_kwargs["prompt_cache_key"] == "session-abc" + + +def test_prepare_completion_kwargs_prefers_explicit_prompt_cache_key_over_derived(): + completion_kwargs = _prepare( + "openai/gpt-5.6-luna", + {"custom_llm_provider": "openai", "prompt_cache_key": "explicit-key"}, + ) + assert completion_kwargs["user"] == "session-abc" + assert completion_kwargs["prompt_cache_key"] == "explicit-key" + + +@pytest.mark.parametrize( + "model, extra_kwargs", + [ + ("gemini/gemini-2.5-pro", {"custom_llm_provider": "gemini"}), + ("openai/gpt-5.6-luna", {}), + ], +) +def test_prepare_completion_kwargs_skips_prompt_cache_key_without_provider_support( + model: str, extra_kwargs: dict[str, object] +): + completion_kwargs = _prepare(model, extra_kwargs) + assert completion_kwargs["user"] == "session-abc" + assert "prompt_cache_key" not in completion_kwargs + + +def test_prepare_completion_kwargs_keeps_prompt_cache_key_through_responses_reroute(): + completion_kwargs = _prepare( + "openai/gpt-5.6-luna", + {"custom_llm_provider": "openai"}, + thinking={"type": "enabled", "budget_tokens": 1024}, + ) + assert completion_kwargs["model"] == "responses/openai/gpt-5.6-luna" + assert completion_kwargs["prompt_cache_key"] == "session-abc" diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_handler.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_handler.py new file mode 100644 index 00000000000..7ef3077f9d7 --- /dev/null +++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_handler.py @@ -0,0 +1,45 @@ +import os +import sys + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../../.."))) + +from litellm.llms.anthropic.experimental_pass_through.responses_adapters.handler import ( + _build_responses_kwargs, +) + +MESSAGES = [{"role": "user", "content": "hello"}] + + +def test_build_responses_kwargs_derives_prompt_cache_key_from_user_id(): + responses_kwargs = _build_responses_kwargs( + max_tokens=1024, + messages=MESSAGES, + model="openai/gpt-5.6-luna", + metadata={"user_id": "session-abc"}, + extra_kwargs={"custom_llm_provider": "openai"}, + ) + assert responses_kwargs["user"] == "session-abc" + assert responses_kwargs["prompt_cache_key"] == "session-abc" + + +def test_build_responses_kwargs_prefers_explicit_prompt_cache_key_over_derived(): + responses_kwargs = _build_responses_kwargs( + max_tokens=1024, + messages=MESSAGES, + model="openai/gpt-5.6-luna", + metadata={"user_id": "session-abc"}, + extra_kwargs={"custom_llm_provider": "openai", "prompt_cache_key": "explicit-key"}, + ) + assert responses_kwargs["user"] == "session-abc" + assert responses_kwargs["prompt_cache_key"] == "explicit-key" + + +def test_build_responses_kwargs_without_metadata_sets_no_prompt_cache_key(): + responses_kwargs = _build_responses_kwargs( + max_tokens=1024, + messages=MESSAGES, + model="openai/gpt-5.6-luna", + extra_kwargs={"custom_llm_provider": "openai"}, + ) + assert "user" not in responses_kwargs + assert "prompt_cache_key" not in responses_kwargs diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_transformation.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_transformation.py index 876213eda3f..297f2052b83 100644 --- a/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_transformation.py +++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_transformation.py @@ -992,6 +992,29 @@ class TestTranslateRequestBroaderCoverage: kwargs = _ADAPTER.translate_request(req) assert len(kwargs["user"]) == 64 + def test_metadata_user_id_mapped_to_prompt_cache_key(self): + req = _make_request(metadata={"user_id": "user-42"}) + kwargs = _ADAPTER.translate_request(req) + assert kwargs["prompt_cache_key"] == "user-42" + + def test_metadata_user_id_prompt_cache_key_truncated_to_first_64_chars(self): + long_id = "".join(str(i % 10) for i in range(100)) + req = _make_request(metadata={"user_id": long_id}) + kwargs = _ADAPTER.translate_request(req) + assert kwargs["prompt_cache_key"] == long_id[:64] + assert len(kwargs["prompt_cache_key"]) == 64 + + def test_metadata_empty_user_id_sets_no_prompt_cache_key(self): + req = _make_request(metadata={"user_id": ""}) + kwargs = _ADAPTER.translate_request(req) + assert kwargs["user"] == "" + assert "prompt_cache_key" not in kwargs + + def test_metadata_null_user_id_sets_no_prompt_cache_key(self): + req = _make_request(metadata={"user_id": None}) + kwargs = _ADAPTER.translate_request(req) + assert "prompt_cache_key" not in kwargs + def test_no_optional_fields_does_not_add_spurious_keys(self): req = _make_request() kwargs = _ADAPTER.translate_request(req) @@ -1005,6 +1028,7 @@ class TestTranslateRequestBroaderCoverage: "text", "context_management", "user", + "prompt_cache_key", ): assert key not in kwargs, f"unexpected key: {key}" From 2c691d3820e25fa66224b89bccfcaf8476416ae5 Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 20 Aug 2026 04:10:10 -0700 Subject: [PATCH 12/35] feat(proxy): native CLI login with OAuth authorization code + PKCE The proxy's OAuth authorization server (dynamic registration, PKCE S256, loopback redirects, single-use codes, refresh rotation) gains a proxy-API audience: /authorize?resource= renders a consent page with team selection and /token mints the same per-user credential lite login mints, so a native CLI can sign a user in through the system browser and call /v1/* with user and team attribution. Adds GET /.well-known/litellm-cli-auth as the versioned discovery contract for non-Python clients, POST /revoke (RFC 7009) for logout, and lite login --pkce, lite logout, and lite auth print-token on the CLI side. Proxy-API grants only ever redirect to a loopback address and the server never picks a team on the user's behalf. Fixes #37332 --- litellm/litellm_core_utils/cli_token_utils.py | 3 + .../mcp_server/bridge_token_flow.py | 11 +- .../mcp_server/discoverable_endpoints.py | 53 +- .../mcp_server/gateway_dcr_flow.py | 500 +++++++++++++--- .../outbound_credentials/session_token.py | 19 +- .../mcp_server/proxy_api_credentials.py | 84 +++ litellm/proxy/_lazy_features.py | 2 + litellm/proxy/client/cli/commands/auth.py | 91 ++- .../proxy/client/cli/commands/pkce_login.py | 471 +++++++++++++++ .../html_forms/native_client_consent.py | 91 +++ litellm/proxy/management_endpoints/ui_sso.py | 22 +- .../test_cli_token_utils.py | 27 + .../test_session_token.py | 52 ++ .../mcp_server/test_discoverable_endpoints.py | 229 +++++++ .../mcp_server/test_gateway_dcr_flow.py | 564 +++++++++++++++++- .../mcp_server/test_proxy_api_credentials.py | 167 ++++++ .../proxy/client/cli/test_auth_commands.py | 323 +++++++++- .../proxy/client/cli/test_pkce_login.py | 553 +++++++++++++++++ .../html_forms/test_native_client_consent.py | 70 +++ .../proxy/management_endpoints/test_ui_sso.py | 20 +- 20 files changed, 3209 insertions(+), 143 deletions(-) create mode 100644 litellm/proxy/_experimental/mcp_server/proxy_api_credentials.py create mode 100644 litellm/proxy/client/cli/commands/pkce_login.py create mode 100644 litellm/proxy/common_utils/html_forms/native_client_consent.py create mode 100644 tests/test_litellm/proxy/_experimental/mcp_server/test_proxy_api_credentials.py create mode 100644 tests/test_litellm/proxy/client/cli/test_pkce_login.py create mode 100644 tests/test_litellm/proxy/common_utils/html_forms/test_native_client_consent.py diff --git a/litellm/litellm_core_utils/cli_token_utils.py b/litellm/litellm_core_utils/cli_token_utils.py index a44ce431f4e..0043bc31204 100644 --- a/litellm/litellm_core_utils/cli_token_utils.py +++ b/litellm/litellm_core_utils/cli_token_utils.py @@ -79,6 +79,9 @@ def is_cli_token_fresh(token_data: Mapping[str, object], buffer_hours: float = 0 `LITELLM_CLI_JWT_EXPIRATION_HOURS`.""" from litellm.constants import CLI_JWT_EXPIRATION_HOURS + expires_at: Final = token_data.get("expires_at") + if isinstance(expires_at, (int, float)): + return time.time() < expires_at - buffer_hours * 3600 timestamp: Final = token_data.get("timestamp") if not isinstance(timestamp, (int, float)): return False diff --git a/litellm/proxy/_experimental/mcp_server/bridge_token_flow.py b/litellm/proxy/_experimental/mcp_server/bridge_token_flow.py index 1d8d545023d..b8c25236b0d 100644 --- a/litellm/proxy/_experimental/mcp_server/bridge_token_flow.py +++ b/litellm/proxy/_experimental/mcp_server/bridge_token_flow.py @@ -15,6 +15,7 @@ from litellm.proxy._experimental.mcp_server.oauth_utils import TOKEN_NO_CACHE_HE from litellm.types.mcp_server.mcp_server_manager import MCPServer if TYPE_CHECKING: + from litellm.models.user import LiteLLM_UserTable from litellm.proxy._experimental.mcp_server.discoverable_endpoints import _BridgeAuthorizationCode from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import ( EnvelopeIdentity, @@ -181,7 +182,13 @@ async def _reload_active_key_by_hash(key_hash: str) -> "_ResolvedKey | _KeyResol async def _reload_active_user_by_id(user_id: str) -> "_KeyResolutionFailure | None": - """Re-validate a live litellm user by id, returning ``None`` when the user is active or a precise + """``None`` when the user is live, else the precise failure ``load_active_user_by_id`` found.""" + loaded: Final = await load_active_user_by_id(user_id) + return loaded if isinstance(loaded, str) else None + + +async def load_active_user_by_id(user_id: str) -> "LiteLLM_UserTable | _KeyResolutionFailure": + """Load a live litellm user by id, returning the record when the user is active or a precise failure otherwise. The interactive DCR client authenticates via SSO, so its refresh envelope seals a user subject; renewing it must re-check the user is still live (present and not SCIM-deactivated) so a deactivated user cannot keep refreshing, mirroring how admission re-validates the same user subject on @@ -226,7 +233,7 @@ async def _reload_active_user_by_id(user_id: str) -> "_KeyResolutionFailure | No return "no_active_key" if isinstance(user_object.metadata, dict) and user_object.metadata.get("scim_active") is False: return "no_active_key" - return None + return user_object async def _key_owner_scim_deactivated(key: "UserAPIKeyAuth") -> bool: diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py index 1ca4c657706..f9c5db76fa0 100644 --- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py @@ -47,8 +47,12 @@ from litellm.proxy._experimental.mcp_server.gateway_dcr_flow import ( aggregate_token, complete_connect_flow, is_gateway_dcr_client_id, + is_proxy_api_resource, + native_client_auth_contract, + native_client_authorize, register_aggregate_client, relative_request_url, + revoke_refresh_token, ) from litellm.proxy._experimental.mcp_server.oauth_utils import ( TOKEN_NO_CACHE_HEADERS, @@ -58,6 +62,10 @@ from litellm.proxy._experimental.mcp_server.oauth_utils import ( validate_trusted_redirect_uri, well_known_root_suffix, ) +from litellm.proxy._experimental.mcp_server.proxy_api_credentials import ( + lookup_consent_teams, + mint_proxy_credential, +) from litellm.proxy.auth.ip_address_utils import IPAddressUtils from litellm.proxy.common_utils.encrypt_decrypt_utils import ( decrypt_value_helper, @@ -1663,6 +1671,18 @@ async def authorize( ) if mcp_server_name is None and client_id and is_gateway_dcr_client_id(client_id): + if is_proxy_api_resource(request, resource): + return await native_client_authorize( + request=request, + client_id=client_id, + redirect_uri=redirect_uri, + state=state, + code_challenge=code_challenge, + code_challenge_method=code_challenge_method, + response_type=response_type, + session_user_id=_session_cookie_user_id(request), + lookup_consent_teams=lookup_consent_teams, + ) return aggregate_authorize( request=request, client_id=client_id, @@ -1764,6 +1784,7 @@ async def token_endpoint( reload_user=_reload_active_user_by_id, cache=user_api_key_cache, resource=resource, + mint_proxy_credential=mint_proxy_credential, ) lookup_name: Final = mcp_server_name or client_id @@ -1793,12 +1814,19 @@ async def token_endpoint( @router.post("/authorize/complete") -async def authorize_complete(request: Request, flow: str = Form(...), delivery: str | None = Form(None)): +async def authorize_complete( + request: Request, + flow: str = Form(...), + delivery: str | None = Form(None), + team_id: str | None = Form(None), + decision: str | None = Form(None), +) -> Response: """Finish an aggregate connect flow: mint the gateway authorization code for the signed-in user and hand it back to the DCR client, by 303 redirect (default) or, for a loopback client on a different machine, as a copyable callback URL (``delivery=manual``). POST plus the per-flow HttpOnly cookie set at /authorize; an - anonymous or bad-flow request just 400s.""" + anonymous or bad-flow request just 400s. The native-client consent page adds + ``decision`` (approve or deny) and the ``team_id`` the credential is attributed to.""" from litellm.proxy.proxy_server import user_api_key_cache # noqa: PLC0415 # circular import at module load return await complete_connect_flow( @@ -1807,9 +1835,30 @@ async def authorize_complete(request: Request, flow: str = Form(...), delivery: session_user_id=_session_cookie_user_id(request), cache=user_api_key_cache, delivery=delivery, + team_id=team_id, + decision=decision, ) +@router.post("/revoke") +async def revoke_endpoint(request: Request, token: str = Form(...), client_id: str = Form(...)) -> Response: + """RFC 7009 revocation for the gateway's refresh tokens (``lite logout``). Always 200 + for a known client, whatever the token's state; access tokens expire on their own.""" + from litellm.proxy.proxy_server import ( # noqa: PLC0415 # circular import at module load + master_key, + user_api_key_cache, + ) + + return await revoke_refresh_token(token=token, client_id=client_id, master_key=master_key, cache=user_api_key_cache) + + +@router.get("/.well-known/litellm-cli-auth") +async def native_client_auth_discovery(request: Request) -> JSONResponse: + """The versioned contract a native client (``lite login --pkce``, or a CLI in any other + language) reads to sign a user in through the browser and obtain a proxy credential.""" + return JSONResponse(native_client_auth_contract(request), headers=TOKEN_NO_CACHE_HEADERS) + + # Per RFC 6749 §4.1.2.1, an IdP that rejects an OAuth authorization request # redirects back to the configured redirect URI with ``error`` / # ``error_description`` / ``error_uri`` query params and no ``code``. The MCP diff --git a/litellm/proxy/_experimental/mcp_server/gateway_dcr_flow.py b/litellm/proxy/_experimental/mcp_server/gateway_dcr_flow.py index 85885fc75f5..53db6fbf9d1 100644 --- a/litellm/proxy/_experimental/mcp_server/gateway_dcr_flow.py +++ b/litellm/proxy/_experimental/mcp_server/gateway_dcr_flow.py @@ -42,15 +42,16 @@ import hmac import html import secrets from base64 import urlsafe_b64encode -from collections.abc import Awaitable, Callable, Mapping +from collections.abc import Awaitable, Callable, Iterable, Mapping from datetime import datetime, timezone -from typing import Final, Literal, TypeVar +from types import MappingProxyType +from typing import Final, Literal, Protocol, TypeVar from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse from fastapi import HTTPException, Request from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response from pydantic import BaseModel, ConfigDict, Field, ValidationError -from typing_extensions import assert_never +from typing_extensions import ReadOnly, TypedDict, assert_never from litellm._logging import verbose_logger from litellm.caching.caching import DualCache @@ -70,6 +71,7 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.session_credent from litellm.proxy._experimental.mcp_server.outbound_credentials.session_token import ( SESSION_REFRESH_TTL_SECONDS, MintedSessionToken, + SessionAudience, SessionKeys, SessionPrincipal, mint_session_refresh_token, @@ -79,6 +81,9 @@ from litellm.proxy.common_utils.encrypt_decrypt_utils import ( decrypt_value_helper, encrypt_value_helper, ) +from litellm.proxy.common_utils.html_forms.native_client_consent import ( + render_native_client_consent_page, +) from litellm.types.mcp_server.mcp_server_manager import MCPServer GATEWAY_DCR_CLIENT_ID_PREFIX: Final = "llm_dcrc_" @@ -144,6 +149,46 @@ ReloadUser = Callable[[str], Awaitable[ReloadUserFailure | None]] ``None`` means the user is active; ``unavailable`` is a retryable DB outage; anything else fails the grant closed.""" +PROXY_API_AUDIENCE: Final[SessionAudience] = "proxy_api" +"""The audience a native client (``lite login --pkce``, a Go CLI) asks for by sending the +proxy base URL itself as the RFC 8707 ``resource``: the grant then mints the proxy-API CLI +credential that LLM routes accept, instead of the MCP-only session pair.""" + +ProxyCredentialMintFailure = Literal[ReloadUserFailure, "not_a_member"] + + +class MintedProxyCredential(BaseModel): + model_config = ConfigDict(frozen=True) + key: str = Field(min_length=1) + expires_in: int = Field(gt=0) + user_id: str = Field(min_length=1) + team_id: str | None = None + + +class MintProxyCredential(Protocol): + """Injected proxy-API credential minter ``(user_id, team_id)``: reloads the user live, + checks team membership, and mints the same credential ``lite login`` mints.""" + + def __call__( + self, user_id: str, team_id: str | None, / + ) -> Awaitable[MintedProxyCredential | ProxyCredentialMintFailure]: ... + + +class ConsentTeam(BaseModel): + model_config = ConfigDict(frozen=True) + team_id: str = Field(min_length=1) + team_alias: str | None = None + + +class LookupConsentTeams(Protocol): + """Injected lookup of the teams a signed-in user may bind a proxy-API credential to.""" + + def __call__(self, user_id: str, /) -> Awaitable[tuple[ConsentTeam, ...] | ReloadUserFailure]: ... + + +async def _refuse_proxy_credential(user_id: str, team_id: str | None) -> ProxyCredentialMintFailure: + return "unresolvable" + class GatewayDcrClient(BaseModel): """The registration record sealed into a gateway DCR ``client_id``. @@ -173,6 +218,7 @@ class _ConnectFlow(BaseModel): jti: str = Field(min_length=1) exp: int resource_server_id: str | None = None + audience: SessionAudience | None = None class _GatewayAuthCode(BaseModel): @@ -190,6 +236,8 @@ class _GatewayAuthCode(BaseModel): iat: int exp: int resource_server_id: str | None = None + audience: SessionAudience | None = None + team_id: str | None = None def is_gateway_dcr_client_id(client_id: str | None) -> bool: @@ -318,9 +366,9 @@ def _cookie_path_and_secure(request: Request) -> tuple[str, bool]: return parsed.path or "/", parsed.scheme == "https" -def _append_query_params(url: str, params: dict[str, str]) -> str: +def _append_query_params(url: str, params: Iterable[tuple[str, str]]) -> str: parsed: Final = urlparse(url) - query: Final = parse_qsl(parsed.query, keep_blank_values=True) + list(params.items()) + query: Final = (*parse_qsl(parsed.query, keep_blank_values=True), *params) return urlunparse(parsed._replace(query=urlencode(query))) @@ -392,6 +440,155 @@ def aggregate_authorize( section 4.1.2.1 an unvalidated redirect URI must not receive an error redirect, and once the client is at fault there is no trusted place to send the browser. """ + rejected: Final = _rejected_authorize_request( + client_id, redirect_uri, state, code_challenge, code_challenge_method, response_type + ) + if rejected is not None: + return rejected + base_url: Final = get_request_base_url(request) + if session_user_id is None: + return _login_redirect(base_url, request) + scoped_server: Final = resolve_scoped_resource_server(request, resource) + handle: Final = secrets.token_urlsafe(24) + flow: Final = _new_connect_flow( + session_user_id=session_user_id, + client_id=client_id, + redirect_uri=redirect_uri, + state=state, + code_challenge=code_challenge or "", + resource_server_id=scoped_server.server_id if scoped_server is not None else None, + audience=None, + ) + connect_url: Final = _append_query_params( + f"{base_url}/ui/connect", + (("connect_flow", handle), ("connect_client", _origin_only(redirect_uri))), + ) + response: Final = RedirectResponse(connect_url, status_code=303) + _set_flow_cookie(response, request, handle, flow) + return response + + +async def native_client_authorize( + request: Request, + client_id: str, + redirect_uri: str, + state: str, + code_challenge: str | None, + code_challenge_method: str | None, + response_type: str | None, + session_user_id: str | None, + lookup_consent_teams: LookupConsentTeams, +) -> Response: + """The authorize verb for a native client that named the proxy API itself as its + RFC 8707 ``resource``: the same client, redirect, PKCE, and sign-in checks as the + aggregate verb plus a loopback-only redirect (the credential this grant mints is the + user's personal proxy key, which belongs on their own machine and never behind a hosted + callback), then the consent page rendered right here (no connect-page interlude, since + there is no per-server vaulting to do) with the flow sealed into the per-flow cookie + and its handle carried only in the form, never in a URL.""" + rejected: Final = _rejected_authorize_request( + client_id, redirect_uri, state, code_challenge, code_challenge_method, response_type + ) + if rejected is not None: + return rejected + if not is_loopback_redirect_host(urlparse(redirect_uri)): + return _oauth_error(400, "invalid_request", "a proxy-API grant may only redirect to a loopback address") + base_url: Final = get_request_base_url(request) + if session_user_id is None: + return _login_redirect(base_url, request) + teams: Final = await lookup_consent_teams(session_user_id) + if not isinstance(teams, tuple): + return _consent_lookup_failure_response(teams) + handle: Final = secrets.token_urlsafe(24) + flow: Final = _new_connect_flow( + session_user_id=session_user_id, + client_id=client_id, + redirect_uri=redirect_uri, + state=state, + code_challenge=code_challenge or "", + resource_server_id=None, + audience=PROXY_API_AUDIENCE, + ) + page: Final = render_native_client_consent_page( + client_origin=_origin_only(redirect_uri), + user_id=session_user_id, + teams=tuple((team.team_id, team.team_alias or team.team_id) for team in teams), + flow_handle=handle, + complete_url=f"{base_url}/authorize/complete", + ) + response: Final = HTMLResponse(page, headers=_CONSENT_PAGE_HEADERS) + _set_flow_cookie(response, request, handle, flow) + return response + + +_CONSENT_PAGE_HEADERS: Final = MappingProxyType( + { + **TOKEN_NO_CACHE_HEADERS, + "X-Frame-Options": "DENY", + "Content-Security-Policy": "frame-ancestors 'none'", + } +) + +NATIVE_CLIENT_AUTH_CONTRACT_VERSION: Final = 1 +"""The version a native client checks before trusting the rest of the discovery document. +Bump it only when an existing field changes meaning or goes away; adding fields is free.""" + + +class NativeClientAuthContract(TypedDict): + contract_version: ReadOnly[int] + issuer: ReadOnly[str] + authorization_endpoint: ReadOnly[str] + token_endpoint: ReadOnly[str] + registration_endpoint: ReadOnly[str] + revocation_endpoint: ReadOnly[str] + resource: ReadOnly[str] + response_types_supported: ReadOnly[tuple[str, ...]] + grant_types_supported: ReadOnly[tuple[str, ...]] + code_challenge_methods_supported: ReadOnly[tuple[str, ...]] + token_endpoint_auth_methods_supported: ReadOnly[tuple[str, ...]] + revocation_endpoint_auth_methods_supported: ReadOnly[tuple[str, ...]] + + +def native_client_auth_contract(request: Request) -> NativeClientAuthContract: + """The versioned discovery document at ``/.well-known/litellm-cli-auth``: everything a + native client (in any language) needs to run the sign-in without reading LiteLLM + source. ``resource`` is the exact value to send as the RFC 8707 ``resource`` parameter + on authorize and token requests so the grant is issued for the proxy API.""" + base_url: Final = get_request_base_url(request) + contract: Final[NativeClientAuthContract] = { + "contract_version": NATIVE_CLIENT_AUTH_CONTRACT_VERSION, + "issuer": base_url, + "authorization_endpoint": f"{base_url}/authorize", + "token_endpoint": f"{base_url}/token", + "registration_endpoint": f"{base_url}/register", + "revocation_endpoint": f"{base_url}/revoke", + "resource": base_url, + "response_types_supported": ("code",), + "grant_types_supported": ("authorization_code", "refresh_token"), + "code_challenge_methods_supported": ("S256",), + "token_endpoint_auth_methods_supported": ("none",), + "revocation_endpoint_auth_methods_supported": ("none",), + } + return contract + + +def is_proxy_api_resource(request: Request, resource: str | None) -> bool: + """True when the RFC 8707 ``resource`` names the proxy itself (its base URL), which is + how a native client asks for the proxy-API audience rather than an MCP session.""" + if resource is None: + return False + canonical: Final = canonical_resource_uri(resource) + return canonical is not None and canonical == canonicalize_url_identity(get_request_base_url(request)) + + +def _rejected_authorize_request( + client_id: str, + redirect_uri: str, + state: str, + code_challenge: str | None, + code_challenge_method: str | None, + response_type: str | None, +) -> Response | None: client: Final = open_gateway_dcr_client(client_id) if client is None: return _oauth_error(400, "invalid_client", "unknown or malformed client_id") @@ -407,14 +604,25 @@ def aggregate_authorize( ) if len(state) > MAX_STATE_LENGTH: return _oauth_error(400, "invalid_request", f"state must be at most {MAX_STATE_LENGTH} characters") - base_url: Final = get_request_base_url(request) - if session_user_id is None: - login_url: Final = f"{base_url}/sso/key/generate?{urlencode({'return_to': relative_request_url(request)})}" - return RedirectResponse(login_url, status_code=303) + return None + + +def _login_redirect(base_url: str, request: Request) -> Response: + return_to: Final = urlencode((("return_to", relative_request_url(request)),)) + return RedirectResponse(f"{base_url}/sso/key/generate?{return_to}", status_code=303) + + +def _new_connect_flow( + session_user_id: str, + client_id: str, + redirect_uri: str, + state: str, + code_challenge: str, + resource_server_id: str | None, + audience: SessionAudience | None, +) -> _ConnectFlow: now: Final = datetime.now(timezone.utc) - scoped_server: Final = resolve_scoped_resource_server(request, resource) - handle: Final = secrets.token_urlsafe(24) - flow: Final = _ConnectFlow( + return _ConnectFlow( user_id=session_user_id, client_id=client_id, redirect_uri=redirect_uri, @@ -422,13 +630,12 @@ def aggregate_authorize( code_challenge=code_challenge, jti=secrets.token_urlsafe(24), exp=int(now.timestamp()) + CONNECT_FLOW_TTL_SECONDS, - resource_server_id=scoped_server.server_id if scoped_server is not None else None, + resource_server_id=resource_server_id, + audience=audience, ) - connect_url: Final = _append_query_params( - f"{base_url}/ui/connect", - {"connect_flow": handle, "connect_client": _origin_only(redirect_uri)}, - ) - response: Final = RedirectResponse(connect_url, status_code=303) + + +def _set_flow_cookie(response: Response, request: Request, handle: str, flow: _ConnectFlow) -> None: path, secure = _cookie_path_and_secure(request) response.set_cookie( key=_flow_cookie_name(handle), @@ -439,7 +646,18 @@ def aggregate_authorize( httponly=True, samesite="lax", ) - return response + + +def _consent_lookup_failure_response(failure: ReloadUserFailure) -> Response: + match failure: + case "unavailable": + return _oauth_error(503, "temporarily_unavailable", "the gateway database is unavailable; retry") + case "unresolvable": + return _oauth_error(500, "server_error", "the gateway is not configured to resolve users") + case "no_active_key": + return _oauth_error(403, "access_denied", "the signed-in user is not active") + case _: + assert_never(failure) def _origin_only(url: str) -> str: @@ -455,6 +673,8 @@ async def complete_connect_flow( session_user_id: str | None, cache: DualCache, delivery: str | None = None, + team_id: str | None = None, + decision: str | None = None, ) -> Response: """The deliberate finish step of the connect flow: mint the gateway authorization code and send the browser back to the client. @@ -479,9 +699,16 @@ async def complete_connect_flow( party. Unknown ``delivery`` values are rejected rather than defaulted: a client that asked for manual delivery and got a dead redirect instead would silently lose its code. + + ``decision`` and ``team_id`` come from the native-client consent page. ``"deny"`` + burns the flow and sends the client ``error=access_denied`` so it stops waiting; + ``team_id`` is sealed into the code only for proxy-API flows, where it picks which of + the user's teams the minted credential is attributed to. """ if delivery not in (None, "redirect", "manual"): return _oauth_error(400, "invalid_request", "delivery must be 'redirect' or 'manual'") + if decision not in (None, "approve", "deny"): + return _oauth_error(400, "invalid_request", "decision must be 'approve' or 'deny'") sealed_flow: Final = request.cookies.get(_flow_cookie_name(flow_handle)) if sealed_flow is None: return _oauth_error(400, "invalid_request", "unknown or expired connect flow") @@ -499,6 +726,24 @@ async def complete_connect_flow( f"{_USED_FLOW_CACHE_PREFIX}{flow.jti}", CONNECT_FLOW_TTL_SECONDS + _CLAIM_TTL_BUFFER_SECONDS ): return _oauth_error(400, "invalid_request", "this connect flow was already completed; restart the connection") + response: Final = ( + _denied_flow_response(flow) if decision == "deny" else _approved_flow_response(flow, delivery, team_id, now) + ) + path, secure = _cookie_path_and_secure(request) + response.delete_cookie(key=_flow_cookie_name(flow_handle), path=path, secure=secure, httponly=True, samesite="lax") + return response + + +def _state_param(flow: _ConnectFlow) -> tuple[tuple[str, str], ...]: + return (("state", flow.state),) if flow.state else () + + +def _denied_flow_response(flow: _ConnectFlow) -> Response: + params: Final = (("error", "access_denied"), *_state_param(flow)) + return RedirectResponse(_append_query_params(flow.redirect_uri, params), status_code=303) + + +def _approved_flow_response(flow: _ConnectFlow, delivery: str | None, team_id: str | None, now: datetime) -> Response: manual_delivery: Final = delivery == "manual" and is_loopback_redirect_host(urlparse(flow.redirect_uri)) code_ttl: Final = MANUAL_DELIVERY_AUTH_CODE_TTL_SECONDS if manual_delivery else GATEWAY_AUTH_CODE_TTL_SECONDS code: Final = _seal( @@ -512,16 +757,14 @@ async def complete_connect_flow( iat=int(now.timestamp()), exp=int(now.timestamp()) + code_ttl, resource_server_id=flow.resource_server_id, + audience=flow.audience, + team_id=(team_id or None) if flow.audience == PROXY_API_AUDIENCE else None, ), ) - params: Final = {"code": code, **({"state": flow.state} if flow.state else {})} - callback_url: Final = _append_query_params(flow.redirect_uri, params) - response: Final[Response] = ( - _manual_delivery_response(callback_url) if manual_delivery else RedirectResponse(callback_url, status_code=303) - ) - path, secure = _cookie_path_and_secure(request) - response.delete_cookie(key=_flow_cookie_name(flow_handle), path=path, secure=secure, httponly=True, samesite="lax") - return response + callback_url: Final = _append_query_params(flow.redirect_uri, (("code", code), *_state_param(flow))) + if manual_delivery: + return _manual_delivery_response(callback_url) + return RedirectResponse(callback_url, status_code=303) def _manual_delivery_response(callback_url: str) -> Response: @@ -630,6 +873,37 @@ def _session_token_pair(principal: SessionPrincipal, keys: SessionKeys, now: dat ) +class _ProxyCredentialTokenResponse(TypedDict): + access_token: ReadOnly[str] + token_type: ReadOnly[Literal["Bearer"]] + expires_in: ReadOnly[int] + refresh_token: ReadOnly[str] + user_id: ReadOnly[str] + team_id: ReadOnly[str | None] + + +def _proxy_credential_response( + minted: MintedProxyCredential, principal: SessionPrincipal, keys: SessionKeys, now: datetime +) -> Response: + """The proxy-API token response: the access token is the very credential ``lite + login`` stores (accepted on every proxy route with user and team attribution), and + the refresh token is a gateway-sealed rotating token bound to the team the credential + was minted for, so a renewal keeps the team the user consented to.""" + bound_principal: Final = principal.model_copy(update=MappingProxyType({"team_id": minted.team_id})) + refresh: Final = mint_session_refresh_token(bound_principal, keys, now) + if not isinstance(refresh, MintedSessionToken): + return _oauth_error(500, "server_error", "failed to mint the session credential") + body: Final[_ProxyCredentialTokenResponse] = { + "access_token": minted.key, + "token_type": "Bearer", + "expires_in": minted.expires_in, + "refresh_token": refresh.token.get_secret_value(), + "user_id": minted.user_id, + "team_id": minted.team_id, + } + return JSONResponse(status_code=200, content=body, headers=TOKEN_NO_CACHE_HEADERS) + + def _reload_failure_response(failure: ReloadUserFailure) -> Response: """Map the live-user revalidation failure onto its OAuth error, exhaustively, so a new ``ReloadUserFailure`` member is a type error here rather than silently 400ing.""" @@ -644,6 +918,18 @@ def _reload_failure_response(failure: ReloadUserFailure) -> Response: assert_never(failure) +def _mint_failure_response(failure: ProxyCredentialMintFailure) -> Response: + match failure: + case "not_a_member": + return _oauth_error( + 400, "invalid_grant", "the user is no longer a member of the team this grant was issued for" + ) + case "unavailable" | "unresolvable" | "no_active_key": + return _reload_failure_response(failure) + case _: + assert_never(failure) + + def _resource_conflicts_with_scope( request: Request, resource: str | None, sealed_resource_server_id: str | None ) -> bool: @@ -670,15 +956,26 @@ async def aggregate_token( reload_user: ReloadUser, cache: DualCache, resource: str | None = None, + mint_proxy_credential: MintProxyCredential = _refuse_proxy_credential, ) -> Response: """The aggregate token verb: authorization_code and refresh_token grants for the - identity-only session pair. Every path re-validates the litellm user live before - minting, so a deactivated user cannot obtain or renew a session.""" + identity-only session pair, or for the proxy-API credential when the grant was issued + with that audience. Every path re-validates the litellm user live before minting, so a + deactivated user cannot obtain or renew a session.""" if master_key is None: verbose_logger.error("mcp_gateway_dcr token grant rejected: no master_key configured") return _oauth_error(500, "server_error", "the gateway has no master key configured") keys: Final = session_keys_from_master_key(master_key) now: Final = datetime.now(timezone.utc) + issue: Final = _GrantIssuer( + request=request, + resource=resource, + keys=keys, + now=now, + reload_user=reload_user, + mint_proxy_credential=mint_proxy_credential, + guard=_SingleUseGuard(cache), + ) if grant_type == "authorization_code": return await _authorization_code_grant( request=request, @@ -687,10 +984,8 @@ async def aggregate_token( client_id=client_id, code_verifier=code_verifier, resource=resource, - keys=keys, now=now, - reload_user=reload_user, - guard=_SingleUseGuard(cache), + issue=issue, ) if grant_type == "refresh_token": return await _refresh_token_grant( @@ -700,12 +995,71 @@ async def aggregate_token( resource=resource, keys=keys, now=now, - reload_user=reload_user, - guard=_SingleUseGuard(cache), + issue=issue, ) return _oauth_error(400, "unsupported_grant_type", "grant_type must be authorization_code or refresh_token") +class _GrantIssuer: + """The tail every grant shares once its own proof (code + PKCE, or a refresh token) + has checked out: revalidate the user live, claim the single-use marker, mint. The + claim comes AFTER revalidation and minting so a transient DB 503 never burns a + still-valid code or refresh token, and fails closed when it cannot be recorded.""" + + def __init__( + self, + request: Request, + resource: str | None, + keys: SessionKeys, + now: datetime, + reload_user: ReloadUser, + mint_proxy_credential: MintProxyCredential, + guard: _SingleUseGuard, + ) -> None: + self._request: Final = request + self._resource: Final = resource + self._keys: Final = keys + self._now: Final = now + self._reload_user: Final = reload_user + self._mint_proxy_credential: Final = mint_proxy_credential + self._guard: Final = guard + + async def __call__( + self, principal: SessionPrincipal, claim_key: str, claim_ttl_seconds: int, replayed: str + ) -> Response: + match principal.audience: + case None: + return await self._issue_session_pair(principal, claim_key, claim_ttl_seconds, replayed) + case "proxy_api": + return await self._issue_proxy_credential(principal, claim_key, claim_ttl_seconds, replayed) + case _: + assert_never(principal.audience) + + async def _issue_session_pair( + self, principal: SessionPrincipal, claim_key: str, claim_ttl_seconds: int, replayed: str + ) -> Response: + failure: Final = await self._reload_user(principal.user_id) + if failure is not None: + return _reload_failure_response(failure) + if not await self._guard.claim(claim_key, claim_ttl_seconds): + return _oauth_error(400, "invalid_grant", replayed) + return _session_token_pair(principal, self._keys, self._now) + + async def _issue_proxy_credential( + self, principal: SessionPrincipal, claim_key: str, claim_ttl_seconds: int, replayed: str + ) -> Response: + if self._resource is not None and not is_proxy_api_resource(self._request, self._resource): + return _oauth_error( + 400, "invalid_target", "resource does not match the proxy API this grant was issued for" + ) + minted: Final = await self._mint_proxy_credential(principal.user_id, principal.team_id) + if not isinstance(minted, MintedProxyCredential): + return _mint_failure_response(minted) + if not await self._guard.claim(claim_key, claim_ttl_seconds): + return _oauth_error(400, "invalid_grant", replayed) + return _proxy_credential_response(minted, principal, self._keys, self._now) + + async def _authorization_code_grant( request: Request, code: str | None, @@ -713,10 +1067,8 @@ async def _authorization_code_grant( client_id: str, code_verifier: str | None, resource: str | None, - keys: SessionKeys, now: datetime, - reload_user: ReloadUser, - guard: _SingleUseGuard, + issue: _GrantIssuer, ) -> Response: if not code or not redirect_uri or not code_verifier: return _oauth_error(400, "invalid_request", "code, redirect_uri, and code_verifier are required") @@ -733,23 +1085,19 @@ async def _authorization_code_grant( return _oauth_error(400, "invalid_target", "resource does not match the scope this code was issued for") if not _pkce_verifier_matches(code_verifier, parsed.code_challenge): return _oauth_error(400, "invalid_grant", "PKCE verification failed") - # Revalidate the user BEFORE claiming the code, so a transient DB outage (a retryable - # 503) does not consume a still-valid code and force the client to restart sign-in. - failure: Final = await reload_user(parsed.user_id) - if failure is not None: - return _reload_failure_response(failure) - # Atomic single-use claim is the gate: on a concurrent double-redeem exactly one caller - # wins, and a claim that cannot be recorded fails closed. The marker's TTL derives from - # the code's own remaining lifetime so it outlives whichever lifetime the code was minted with. - if not await guard.claim( - f"{_USED_CODE_CACHE_PREFIX}{parsed.jti}", - parsed.exp - int(now.timestamp()) + _CLAIM_TTL_BUFFER_SECONDS, - ): - return _oauth_error(400, "invalid_grant", "the authorization code was already used") - return _session_token_pair( - SessionPrincipal(user_id=parsed.user_id, client_id=client_id, resource_server_id=parsed.resource_server_id), - keys, - now, + # The marker's TTL derives from the code's own remaining lifetime so it outlives + # whichever lifetime the code was minted with. + return await issue( + SessionPrincipal( + user_id=parsed.user_id, + client_id=client_id, + resource_server_id=parsed.resource_server_id, + audience=parsed.audience, + team_id=parsed.team_id, + ), + claim_key=f"{_USED_CODE_CACHE_PREFIX}{parsed.jti}", + claim_ttl_seconds=parsed.exp - int(now.timestamp()) + _CLAIM_TTL_BUFFER_SECONDS, + replayed="the authorization code was already used", ) @@ -760,8 +1108,7 @@ async def _refresh_token_grant( resource: str | None, keys: SessionKeys, now: datetime, - reload_user: ReloadUser, - guard: _SingleUseGuard, + issue: _GrantIssuer, ) -> Response: if not refresh_token: return _oauth_error(400, "invalid_request", "refresh_token is required") @@ -770,16 +1117,33 @@ async def _refresh_token_grant( return _oauth_error(400, "invalid_grant", "the refresh token is invalid for this client") if _resource_conflicts_with_scope(request, resource, opened.principal.resource_server_id): return _oauth_error(400, "invalid_target", "resource does not match the scope this token was issued for") - failure: Final = await reload_user(opened.principal.user_id) - if failure is not None: - return _reload_failure_response(failure) # Refresh-token rotation (OAuth 2.0 Security BCP section 4.13): the presented refresh token is - # single-use. Claim its jti before issuing the replacement pair, so a captured or replayed - # refresh token cannot mint a second pair after the legitimate holder rotated. Claimed AFTER - # user revalidation so a transient DB 503 does not burn a still-valid token; a claim that - # cannot be recorded fails closed, exactly like the authorization-code path. - if not await guard.claim( - f"{_USED_REFRESH_CACHE_PREFIX}{opened.jti}", SESSION_REFRESH_TTL_SECONDS + _CLAIM_TTL_BUFFER_SECONDS - ): - return _oauth_error(400, "invalid_grant", "the refresh token was already used") - return _session_token_pair(opened.principal, keys, now) + # single-use, so a captured or replayed refresh token cannot mint a second pair after the + # legitimate holder rotated. + return await issue( + opened.principal, + claim_key=f"{_USED_REFRESH_CACHE_PREFIX}{opened.jti}", + claim_ttl_seconds=SESSION_REFRESH_TTL_SECONDS + _CLAIM_TTL_BUFFER_SECONDS, + replayed="the refresh token was already used", + ) + + +async def revoke_refresh_token(token: str, client_id: str, master_key: str | None, cache: DualCache) -> Response: + """RFC 7009 revocation for the gateway's refresh tokens: burn the presented token's + ``jti`` so neither the holder nor a thief can rotate it again. Access tokens are + stateless and expire on their own (the proxy-API credential within + ``CLI_JWT_EXPIRATION_HOURS``), so per RFC 7009 section 2.2 an unrecognized or already + dead token still answers 200; only an unknown client is refused.""" + if not is_gateway_dcr_client_id(client_id) or open_gateway_dcr_client(client_id) is None: + return _oauth_error(401, "invalid_client", "unknown or malformed client_id") + if master_key is None: + verbose_logger.error("mcp_gateway_dcr revoke rejected: no master_key configured") + return _oauth_error(500, "server_error", "the gateway has no master key configured") + keys: Final = session_keys_from_master_key(master_key) + now: Final = datetime.now(timezone.utc) + opened: Final = open_session_refresh_bearer(token, keys, now, expected_client_id=client_id) + if isinstance(opened, SessionRefreshOpened): + _ = await _SingleUseGuard(cache).claim( + f"{_USED_REFRESH_CACHE_PREFIX}{opened.jti}", SESSION_REFRESH_TTL_SECONDS + _CLAIM_TTL_BUFFER_SECONDS + ) + return Response(content="{}", media_type="application/json", headers=TOKEN_NO_CACHE_HEADERS) diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/session_token.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/session_token.py index 15f5f82c4b6..d6b0a462062 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/session_token.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/session_token.py @@ -76,6 +76,13 @@ SessionTokenKind = Literal["session", "session_refresh"] on open, so a signature-valid token of one kind cannot be replayed as the other even if its wire prefix is swapped (the prefix is not part of the signed payload; this claim is).""" +SessionAudience = Literal["proxy_api"] +"""The non-MCP audience a session REFRESH token can be minted for. ``None`` (the default and +the only value ever on an MCP wire) means the aggregate MCP gateway; ``"proxy_api"`` means the +refresh grant re-mints the proxy-API CLI credential instead of an MCP session pair. The audience +is read only from the signed claims, never from the request, so a token of one audience can +never be redeemed as the other.""" + class SessionPrincipal(BaseModel): """The litellm user a session token identifies and the DCR client it was issued to. @@ -97,6 +104,8 @@ class SessionPrincipal(BaseModel): user_id: str = Field(min_length=1) client_id: str = Field(min_length=1) resource_server_id: str | None = None + audience: SessionAudience | None = None + team_id: str | None = None class SessionKeys(BaseModel): @@ -194,6 +203,8 @@ class _SessionClaims(BaseModel): user_id: str = Field(min_length=1) client_id: str = Field(min_length=1) resource_server_id: str | None = None + audience: SessionAudience | None = None + team_id: str | None = None def is_session_token(candidate: str) -> bool: @@ -295,6 +306,8 @@ def _mint( user_id=principal.user_id, client_id=principal.client_id, resource_server_id=principal.resource_server_id, + audience=principal.audience, + team_id=principal.team_id, ) token: Final = prefix + jwt.encode( claims.model_dump(exclude_none=True), keys.signing_key.get_secret_value(), algorithm=_SESSION_JWT_ALGORITHM @@ -333,7 +346,11 @@ def _open( return SessionExpired() return OpenedSessionToken( principal=SessionPrincipal( - user_id=claims.user_id, client_id=claims.client_id, resource_server_id=claims.resource_server_id + user_id=claims.user_id, + client_id=claims.client_id, + resource_server_id=claims.resource_server_id, + audience=claims.audience, + team_id=claims.team_id, ), jti=claims.jti, ) diff --git a/litellm/proxy/_experimental/mcp_server/proxy_api_credentials.py b/litellm/proxy/_experimental/mcp_server/proxy_api_credentials.py new file mode 100644 index 00000000000..a24afc529bd --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/proxy_api_credentials.py @@ -0,0 +1,84 @@ +"""The proxy-API side of the native-client sign-in: turning a consented OAuth grant into +the same per-user credential ``lite login`` stores, so the bearer a CLI obtains through +the browser flow is accepted on every proxy route with user and team attribution.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Final + +from litellm.constants import CLI_JWT_EXPIRATION_HOURS +from litellm.proxy._experimental.mcp_server.bridge_token_flow import load_active_user_by_id +from litellm.proxy._experimental.mcp_server.gateway_dcr_flow import ( + ConsentTeam, + MintedProxyCredential, + ProxyCredentialMintFailure, + ReloadUserFailure, +) +from litellm.proxy._types import LiteLLM_UserTable +from litellm.proxy.auth.auth_checks import ExperimentalUIJWTToken +from litellm.proxy.management_endpoints.ui_sso import ( + CliSsoTeamDetail, + fetch_cli_sso_team_details, + selected_cli_sso_team_detail, +) + + +async def lookup_consent_teams(user_id: str) -> tuple[ConsentTeam, ...] | ReloadUserFailure: + user: Final = await load_active_user_by_id(user_id) + if isinstance(user, str): + return user + details: Final = await _team_details(user.teams) + if details is None: + return "unavailable" + return tuple( + ConsentTeam(team_id=detail.team_id, team_alias=detail.team_alias) + for detail in details + if detail.team_id is not None + ) + + +async def mint_proxy_credential( + user_id: str, team_id: str | None +) -> MintedProxyCredential | ProxyCredentialMintFailure: + """Mint the ``lite login`` credential for a consented grant. Membership is checked + live, so a team the user left between consent and redemption (or between refreshes) + refuses the grant instead of minting a credential attributed to a team they are no + longer on. The team is exactly the one the consent page sealed into the grant; nothing + is picked on the user's behalf here, so a refresh can never move the credential. The + user row handed to the minter carries no team list, exactly like ``lite login``'s, so + the minter's own first-team fallback stays inert.""" + user: Final = await load_active_user_by_id(user_id) + if isinstance(user, str): + return user + if user.user_role is None: + return "no_active_key" + if team_id is not None and team_id not in user.teams: + return "not_a_member" + details: Final = await _team_details(user.teams) if team_id is not None else () + if details is None: + return "unavailable" + selected: Final = selected_cli_sso_team_detail(details, team_id) + if selected is None: + return "not_a_member" + key: Final = ExperimentalUIJWTToken.get_cli_jwt_auth_token( + user_info=LiteLLM_UserTable(user_id=user.user_id, user_role=user.user_role, models=user.models), + team_id=team_id, + team_alias=selected.team_alias, + team_models=selected.team_models, + team_model_aliases=selected.team_model_aliases, + ) + return MintedProxyCredential( + key=key, + expires_in=CLI_JWT_EXPIRATION_HOURS * 3600, + user_id=user.user_id, + team_id=team_id, + ) + + +async def _team_details(teams: Sequence[str]) -> tuple[CliSsoTeamDetail, ...] | None: + from litellm.proxy.proxy_server import prisma_client # noqa: PLC0415 # rebound after startup, so read it per call + + if prisma_client is None: + return None + return await fetch_cli_sso_team_details(prisma_client, teams) diff --git a/litellm/proxy/_lazy_features.py b/litellm/proxy/_lazy_features.py index 262d97e4579..fdd15a89aa5 100644 --- a/litellm/proxy/_lazy_features.py +++ b/litellm/proxy/_lazy_features.py @@ -155,10 +155,12 @@ LAZY_FEATURES: Final[tuple[LazyFeature, ...]] = ( "/.well-known/oauth-", "/.well-known/openid-configuration", "/.well-known/jwks.json", + "/.well-known/litellm-cli-auth", "/authorize", "/token", "/callback", "/register", + "/revoke", ), # Catches the /{mcp_server_name}/authorize|token|register variants. path_suffixes=("/authorize", "/token", "/register"), diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.py index 0a0bcf80ee5..aee715686b7 100644 --- a/litellm/proxy/client/cli/commands/auth.py +++ b/litellm/proxy/client/cli/commands/auth.py @@ -11,7 +11,7 @@ import click import requests from rich.console import Console from rich.table import Table -from typing_extensions import NotRequired, TypedDict +from typing_extensions import NotRequired, ReadOnly, TypedDict from litellm.constants import CLI_JWT_EXPIRATION_HOURS from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh @@ -22,6 +22,13 @@ from .claude_settings import ( ClaudeSettingsError, write_claude_settings, ) +from .pkce_login import ( + PkceFailure, + fresh_api_key, + pkce_token_record, + revoke_stored_credential, + run_pkce_login, +) from .private_json import write_private_json @@ -34,6 +41,13 @@ class CliTokenData(TypedDict): auth_header_name: str jwt_token: str timestamp: float + expires_at: ReadOnly[NotRequired[float]] + refresh_token: ReadOnly[NotRequired[str]] + client_id: ReadOnly[NotRequired[str]] + token_endpoint: ReadOnly[NotRequired[str]] + revocation_endpoint: ReadOnly[NotRequired[str]] + resource: ReadOnly[NotRequired[str]] + team_id: ReadOnly[NotRequired[str | None]] class CliTeam(TypedDict, total=False): @@ -79,10 +93,7 @@ class CliAuthResult(TypedDict): # Token storage utilities def get_token_file_path() -> str: """Get the path to store the authentication token""" - home_dir: Final = Path.home() - config_dir: Final = home_dir / ".litellm" - config_dir.mkdir(exist_ok=True) - return str(config_dir / "token.json") + return str(Path.home() / ".litellm" / "token.json") def save_token(token_data: CliTokenData) -> None: @@ -115,11 +126,15 @@ def get_stored_api_key(expected_base_url: str | None = None) -> str | None: If expected_base_url is provided, the key is only returned when it was originally issued for that URL. This prevents credential leakage when the - CLI is pointed at a different (possibly malicious) server. + CLI is pointed at a different (possibly malicious) server. A key obtained by + ``lite login --pkce`` is refreshed here once it nears expiry. """ - from litellm.litellm_core_utils.cli_token_utils import get_litellm_gateway_api_key - - return get_litellm_gateway_api_key(expected_base_url=expected_base_url) + token_data: Final = load_token() + if token_data is None: + return None + if expected_base_url is not None and token_data.get("base_url") != expected_base_url.rstrip("/"): + return None + return fresh_api_key(token_data, save_token, requests.Session(), reload=load_token) # Team selection utilities @@ -645,6 +660,27 @@ def _configure_claude_code(base_url: str) -> None: click.echo("Your other Claude Code settings were left untouched. Restart Claude Code to pick this up.") +def _finish_login(base_url: str, api_key: str, config_claude: bool) -> None: + from litellm.proxy.client.cli.interface import show_commands + + click.echo("\nLogin successful!") + click.echo(f"JWT Token: {api_key[:20]}...") + click.echo("You can now use the CLI without specifying --api-key") + if config_claude: + _configure_claude_code(base_url) + click.echo("\n" + "=" * 60) + show_commands() + + +def _pkce_login(base_url: str, config_claude: bool) -> None: + credential: Final = run_pkce_login(base_url, requests.Session(), echo=click.echo) + if isinstance(credential, PkceFailure): + click.echo(f"Authentication failed: {credential.reason}") + return + save_token(pkce_token_record(base_url, credential)) + _finish_login(base_url, credential.access_token, config_claude) + + @click.command(name="login") @click.option( "--config-claude", @@ -655,16 +691,28 @@ def _configure_claude_code(base_url: str) -> None: "Unrelated settings are preserved." ), ) +@click.option( + "--pkce", + is_flag=True, + default=False, + help=( + "Sign in with OAuth authorization code + PKCE through your system browser (loopback redirect), " + "with a refresh token that renews the key automatically. Requires a proxy that serves " + "/.well-known/litellm-cli-auth." + ), +) @click.pass_context -def login(ctx: click.Context, config_claude: bool): +def login(ctx: click.Context, config_claude: bool, pkce: bool) -> None: """Login to LiteLLM proxy using SSO authentication""" from litellm.constants import LITELLM_CLI_SOURCE_IDENTIFIER - from litellm.proxy.client.cli.interface import show_commands ctx_obj: Final[CliContextObj] = ctx.obj base_url: Final = ctx_obj["base_url"] try: + if pkce: + _pkce_login(base_url, config_claude) + return cli_sso_flow: Final = _start_cli_sso_flow(base_url=base_url) key_id: Final = cli_sso_flow["login_id"] poll_secret: Final = cli_sso_flow["poll_secret"] @@ -704,16 +752,7 @@ def login(ctx: click.Context, config_claude: bool): } ) - click.echo("\nLogin successful!") - click.echo(f"JWT Token: {api_key[:20]}...") - click.echo("You can now use the CLI without specifying --api-key") - - if config_claude: - _configure_claude_code(base_url) - - # Show available commands after successful login - click.echo("\n" + "=" * 60) - show_commands() + _finish_login(base_url, api_key, config_claude) return else: click.echo("Authentication timed out. Please try again.") @@ -738,7 +777,11 @@ def login(ctx: click.Context, config_claude: bool): @click.command(name="logout") def logout(): """Logout and clear stored authentication""" + token_data: Final = load_token() + revocation: Final = revoke_stored_credential(token_data, requests.Session()) if token_data is not None else None clear_token() + if revocation is not None: + click.echo(f"Could not revoke the refresh token on the proxy ({revocation.reason}); it expires on its own.") click.echo("Logged out successfully. Authentication token cleared.") @@ -769,13 +812,13 @@ def print_token(ctx: click.Context): click.echo("Not authenticated for this server. Run 'lite login'.", err=True) sys.exit(1) - if not is_cli_token_fresh(token_data): + if not is_cli_token_fresh(token_data) and "refresh_token" not in token_data: click.echo("Token expired. Run 'lite login' again.", err=True) sys.exit(1) - api_key: Final = token_data.get("key") + api_key: Final = fresh_api_key(token_data, save_token, requests.Session(), reload=load_token) if not api_key: - click.echo("No token available. Run 'lite login'.", err=True) + click.echo("Token expired. Run 'lite login' again.", err=True) sys.exit(1) click.echo(api_key) diff --git a/litellm/proxy/client/cli/commands/pkce_login.py b/litellm/proxy/client/cli/commands/pkce_login.py new file mode 100644 index 00000000000..6d6646a886c --- /dev/null +++ b/litellm/proxy/client/cli/commands/pkce_login.py @@ -0,0 +1,471 @@ +"""Browser sign-in for ``lite login --pkce``: OAuth 2.1 authorization code + PKCE S256 +against the proxy's own authorization server, as a public client on a loopback redirect. +The proxy publishes everything this needs at ``/.well-known/litellm-cli-auth``, so a CLI +in any other language can run the same steps from that document alone.""" + +from __future__ import annotations + +import hashlib +import secrets +import socket +import threading +import time +import webbrowser +from base64 import urlsafe_b64encode +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from http.server import BaseHTTPRequestHandler, HTTPServer +from types import MappingProxyType +from typing import TYPE_CHECKING, Final, Literal, Protocol +from urllib.parse import parse_qs, urlencode, urlparse + +import requests +from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError +from typing_extensions import ReadOnly, TypedDict + +if TYPE_CHECKING: + from .auth import CliTokenData + +CLI_AUTH_DISCOVERY_PATH: Final = "/.well-known/litellm-cli-auth" +CALLBACK_PATH: Final = "/callback" +LOGIN_TIMEOUT_SECONDS: Final = 300 +REFRESH_LEEWAY_SECONDS: Final = 60 +_HTTP_TIMEOUT_SECONDS: Final = 15 +_CLIENT_NAME: Final = "litellm-cli" + + +class CliAuthContract(BaseModel): + model_config = ConfigDict(frozen=True) + + contract_version: Literal[1] + issuer: str + authorization_endpoint: str + token_endpoint: str + registration_endpoint: str + revocation_endpoint: str + resource: str + code_challenge_methods_supported: tuple[str, ...] + + +class _RegisteredClient(BaseModel): + model_config = ConfigDict(frozen=True) + + client_id: str = Field(min_length=1) + + +class _TokenResponse(BaseModel): + model_config = ConfigDict(frozen=True) + + access_token: str = Field(min_length=1) + expires_in: int = Field(gt=0) + refresh_token: str = Field(min_length=1) + user_id: str | None = None + team_id: str | None = None + + +@dataclass(frozen=True, slots=True) +class PkceFailure: + reason: str + + +@dataclass(frozen=True, slots=True) +class PkceCredential: + access_token: str + refresh_token: str + expires_at: float + client_id: str + token_endpoint: str + revocation_endpoint: str + resource: str + user_id: str | None + team_id: str | None + + +@dataclass(frozen=True, slots=True) +class CallbackCode: + code: str + + +@dataclass(frozen=True, slots=True) +class CallbackDenied: + error: str + description: str | None + + +CallbackOutcome = CallbackCode | CallbackDenied + + +class Http(Protocol): + def get(self, url: str, *, timeout: float) -> requests.Response: ... + + def post( + self, + url: str, + *, + data: Mapping[str, str] | None = None, + json: Mapping[str, object] | None = None, + timeout: float, + ) -> requests.Response: ... + + +class LoopbackServer(HTTPServer): + """The OS-assigned loopback listener the browser is sent back to. Only the response + carrying the pending sign-in's ``state`` settles it; anything else (a stray request, a + stale tab, an attacker poking the port) gets a 400 and the wait continues. A connection + that opens and then sends nothing is dropped after ``connection_timeout_seconds`` so it + cannot hold the single-threaded wait past its deadline.""" + + def __init__(self, expected_state: str, connection_timeout_seconds: float = 5) -> None: + super().__init__(("127.0.0.1", 0), _CallbackHandler) + self.expected_state: Final = expected_state + self.connection_timeout_seconds: Final = connection_timeout_seconds + self.outcome: CallbackOutcome | None = None + self.timeout = 1 + + @property + def redirect_uri(self) -> str: + return f"http://127.0.0.1:{self.server_address[1]}{CALLBACK_PATH}" + + def get_request(self) -> tuple[socket.socket, object]: + accepted: Final[tuple[socket.socket, object]] = super().get_request() + accepted[0].settimeout(self.connection_timeout_seconds) + return accepted + + def wait( + self, timeout_seconds: float, clock: Callable[[], float] = time.monotonic + ) -> CallbackOutcome | PkceFailure: + deadline: Final = clock() + timeout_seconds + while self.outcome is None: + if clock() >= deadline: + return PkceFailure("timed out waiting for the browser sign-in to finish") + self.handle_request() + return self.outcome + + +class _CallbackHandler(BaseHTTPRequestHandler): + server: LoopbackServer # pyright: ignore[reportIncompatibleVariableOverride] # only ever constructed by LoopbackServer + + def do_GET(self) -> None: + parsed: Final = urlparse(self.path) + if parsed.path != CALLBACK_PATH: + self._respond(404, "Not found.") + return + params: Final = parse_qs(parsed.query) + if _first(params, "state") != self.server.expected_state: + self._respond(400, "This response does not belong to the pending sign-in; still waiting.") + return + error: Final = _first(params, "error") + if error is not None: + self.server.outcome = CallbackDenied(error=error, description=_first(params, "error_description")) + self._respond(200, "Sign-in was not approved. You can close this window.") + return + code: Final = _first(params, "code") + if code is None: + self._respond(400, "The sign-in response carried no authorization code; still waiting.") + return + self.server.outcome = CallbackCode(code=code) + self._respond(200, "Signed in to LiteLLM. You can close this window and return to the terminal.") + + def log_message(self, format: str, *args: object) -> None: + return + + def _respond(self, status: int, text: str) -> None: + body: Final = text.encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "text/plain; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(body) + + +def _first(params: Mapping[str, Sequence[str]], key: str) -> str | None: + values: Final = params.get(key) + return values[0] if values else None + + +def discover_cli_auth(base_url: str, http: Http) -> CliAuthContract | PkceFailure: + url: Final = f"{base_url.rstrip('/')}{CLI_AUTH_DISCOVERY_PATH}" + try: + response: Final = http.get(url, timeout=_HTTP_TIMEOUT_SECONDS) + except requests.RequestException as exc: + return PkceFailure(f"could not reach {url}: {exc}") + if response.status_code != 200: + return PkceFailure( + f"{url} answered {response.status_code}; this proxy version does not support `lite login --pkce`" + ) + try: + contract: Final = CliAuthContract.model_validate(response.json()) + except (ValueError, ValidationError) as exc: + return PkceFailure(f"{url} returned an unsupported discovery document: {exc}") + if "S256" not in contract.code_challenge_methods_supported: + return PkceFailure("the proxy does not support PKCE S256") + return contract + + +class _ClientRegistration(TypedDict): + client_name: ReadOnly[str] + redirect_uris: ReadOnly[tuple[str, ...]] + grant_types: ReadOnly[tuple[str, ...]] + response_types: ReadOnly[tuple[str, ...]] + token_endpoint_auth_method: ReadOnly[Literal["none"]] + + +def _form(**fields: str) -> Mapping[str, str]: + return MappingProxyType(fields) + + +def register_client(contract: CliAuthContract, redirect_uri: str, http: Http) -> str | PkceFailure: + registration: Final[_ClientRegistration] = { + "client_name": _CLIENT_NAME, + "redirect_uris": (redirect_uri,), + "grant_types": ("authorization_code", "refresh_token"), + "response_types": ("code",), + "token_endpoint_auth_method": "none", + } + try: + response: Final = http.post(contract.registration_endpoint, json=registration, timeout=_HTTP_TIMEOUT_SECONDS) + except requests.RequestException as exc: + return PkceFailure(f"client registration failed: {exc}") + if response.status_code not in (200, 201): + return PkceFailure(f"client registration failed with {response.status_code}: {_error_detail(response)}") + try: + return _RegisteredClient.model_validate(response.json()).client_id + except (ValueError, ValidationError) as exc: + return PkceFailure(f"client registration returned an unexpected body: {exc}") + + +def pkce_pair() -> tuple[str, str]: + verifier: Final = secrets.token_urlsafe(64) + digest: Final = hashlib.sha256(verifier.encode("ascii")).digest() + return verifier, urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") + + +def authorize_url(contract: CliAuthContract, client_id: str, redirect_uri: str, state: str, code_challenge: str) -> str: + query: Final = urlencode( + _form( + response_type="code", + client_id=client_id, + redirect_uri=redirect_uri, + state=state, + code_challenge=code_challenge, + code_challenge_method="S256", + resource=contract.resource, + ) + ) + return f"{contract.authorization_endpoint}?{query}" + + +def redeem_code( + contract: CliAuthContract, + client_id: str, + redirect_uri: str, + code: str, + code_verifier: str, + http: Http, + now: Callable[[], float] = time.time, +) -> PkceCredential | PkceFailure: + return _token_request( + token_endpoint=contract.token_endpoint, + revocation_endpoint=contract.revocation_endpoint, + resource=contract.resource, + client_id=client_id, + form=_form( + grant_type="authorization_code", + code=code, + redirect_uri=redirect_uri, + client_id=client_id, + code_verifier=code_verifier, + resource=contract.resource, + ), + http=http, + now=now, + ) + + +def refresh_credential( + token_endpoint: str, + revocation_endpoint: str, + resource: str, + client_id: str, + refresh_token: str, + http: Http, + now: Callable[[], float] = time.time, +) -> PkceCredential | PkceFailure: + return _token_request( + token_endpoint=token_endpoint, + revocation_endpoint=revocation_endpoint, + resource=resource, + client_id=client_id, + form=_form(grant_type="refresh_token", refresh_token=refresh_token, client_id=client_id, resource=resource), + http=http, + now=now, + ) + + +def _token_request( + token_endpoint: str, + revocation_endpoint: str, + resource: str, + client_id: str, + form: Mapping[str, str], + http: Http, + now: Callable[[], float], +) -> PkceCredential | PkceFailure: + try: + response: Final = http.post(token_endpoint, data=form, timeout=_HTTP_TIMEOUT_SECONDS) + except requests.RequestException as exc: + return PkceFailure(f"token request failed: {exc}") + if response.status_code != 200: + return PkceFailure(f"token request failed with {response.status_code}: {_error_detail(response)}") + try: + token: Final = _TokenResponse.model_validate(response.json()) + except (ValueError, ValidationError) as exc: + return PkceFailure(f"token endpoint returned an unexpected body: {exc}") + return PkceCredential( + access_token=token.access_token, + refresh_token=token.refresh_token, + expires_at=now() + token.expires_in, + client_id=client_id, + token_endpoint=token_endpoint, + revocation_endpoint=revocation_endpoint, + resource=resource, + user_id=token.user_id, + team_id=token.team_id, + ) + + +def revoke_credential(revocation_endpoint: str, client_id: str, refresh_token: str, http: Http) -> PkceFailure | None: + try: + response: Final = http.post( + revocation_endpoint, + data=_form(token=refresh_token, token_type_hint="refresh_token", client_id=client_id), + timeout=_HTTP_TIMEOUT_SECONDS, + ) + except requests.RequestException as exc: + return PkceFailure(f"revocation request failed: {exc}") + if response.status_code != 200: + return PkceFailure(f"revocation failed with {response.status_code}: {_error_detail(response)}") + return None + + +_ERROR_BODY: Final = TypeAdapter(Mapping[str, object]) + + +def _error_detail(response: requests.Response) -> str: + try: + body: Final = _ERROR_BODY.validate_json(response.content) + except ValidationError: + return response.text[:200] + return str(body.get("error_description") or body.get("error") or body.get("detail") or body)[:200] + + +def run_pkce_login( + base_url: str, + http: Http, + open_browser: Callable[[str], object] = webbrowser.open, + echo: Callable[[str], None] = print, + timeout_seconds: float = LOGIN_TIMEOUT_SECONDS, +) -> PkceCredential | PkceFailure: + contract: Final = discover_cli_auth(base_url, http) + if isinstance(contract, PkceFailure): + return contract + state: Final = secrets.token_urlsafe(32) + verifier, challenge = pkce_pair() + with LoopbackServer(state) as server: + client_id: Final = register_client(contract, server.redirect_uri, http) + if isinstance(client_id, PkceFailure): + return client_id + url: Final = authorize_url(contract, client_id, server.redirect_uri, state, challenge) + echo(f"Opening browser to: {url}") + echo("Approve the sign-in in your browser. Waiting...") + threading.Thread(target=open_browser, args=(url,), name="lite-login-browser", daemon=True).start() + outcome: Final = server.wait(timeout_seconds) + match outcome: + case PkceFailure(): + return outcome + case CallbackDenied(): + return PkceFailure(f"sign-in was not approved ({outcome.error}): {outcome.description or 'no details'}") + case CallbackCode(): + return redeem_code(contract, client_id, server.redirect_uri, outcome.code, verifier, http) + + +def pkce_token_record(base_url: str, credential: PkceCredential) -> CliTokenData: + record: Final[CliTokenData] = { + "base_url": base_url.rstrip("/"), + "key": credential.access_token, + "user_id": credential.user_id or "cli-user", + "user_email": "unknown", + "user_role": "cli", + "auth_header_name": "Authorization", + "jwt_token": "", + "timestamp": time.time(), + "expires_at": credential.expires_at, + "refresh_token": credential.refresh_token, + "client_id": credential.client_id, + "token_endpoint": credential.token_endpoint, + "revocation_endpoint": credential.revocation_endpoint, + "resource": credential.resource, + "team_id": credential.team_id, + } + return record + + +def fresh_api_key( + token_data: Mapping[str, object], + save: Callable[[CliTokenData], None], + http: Http, + *, + reload: Callable[[], Mapping[str, object] | None], + now: Callable[[], float] = time.time, +) -> str | None: + """The stored key, refreshed first when it is about to expire and a refresh token is + on file. The rotated pair is saved before the new key is returned, so a crash after + this point never strands the CLI with a burned refresh token. A refresh that fails + reads the record again, because a sibling ``lite`` process may have rotated the pair + first, in which case the key it saved is the live one. A record without + ``expires_at`` (the classic ``lite login`` credential) is returned as stored.""" + key: Final = token_data.get("key") + if not isinstance(key, str) or not key: + return None + expires_at: Final = token_data.get("expires_at") + if not isinstance(expires_at, (int, float)): + return key + if now() < expires_at - REFRESH_LEEWAY_SECONDS: + return key + still_valid: Final = key if now() < expires_at else None + refresh_inputs: Final = _refresh_inputs(token_data) + if refresh_inputs is None: + return still_valid + refreshed: Final = refresh_credential(*refresh_inputs, http=http, now=now) + if isinstance(refreshed, PkceFailure): + return _key_rotated_by_a_sibling(reload(), token_data.get("refresh_token")) or still_valid + base_url: Final = token_data.get("base_url") + save(pkce_token_record(base_url if isinstance(base_url, str) else "", refreshed)) + return refreshed.access_token + + +def _key_rotated_by_a_sibling(record: Mapping[str, object] | None, sent_refresh_token: object) -> str | None: + if record is None or record.get("refresh_token") == sent_refresh_token: + return None + key: Final = record.get("key") + return key if isinstance(key, str) and key else None + + +def _refresh_inputs(token_data: Mapping[str, object]) -> tuple[str, str, str, str, str] | None: + values: Final = tuple( + token_data.get(field) + for field in ("token_endpoint", "revocation_endpoint", "resource", "client_id", "refresh_token") + ) + if not all(isinstance(value, str) and value for value in values): + return None + token_endpoint, revocation_endpoint, resource, client_id, refresh_token = values + return str(token_endpoint), str(revocation_endpoint), str(resource), str(client_id), str(refresh_token) + + +def revoke_stored_credential(token_data: Mapping[str, object], http: Http) -> PkceFailure | None: + refresh_inputs: Final = _refresh_inputs(token_data) + if refresh_inputs is None: + return None + _, revocation_endpoint, _, client_id, refresh_token = refresh_inputs + return revoke_credential(revocation_endpoint, client_id, refresh_token, http) diff --git a/litellm/proxy/common_utils/html_forms/native_client_consent.py b/litellm/proxy/common_utils/html_forms/native_client_consent.py new file mode 100644 index 00000000000..dac92c4e787 --- /dev/null +++ b/litellm/proxy/common_utils/html_forms/native_client_consent.py @@ -0,0 +1,91 @@ +from collections.abc import Sequence +from html import escape +from typing import Final + +from litellm.constants import CLI_JWT_EXPIRATION_HOURS + + +def render_native_client_consent_page( + *, + client_origin: str, + user_id: str, + teams: Sequence[tuple[str, str]], + flow_handle: str, + complete_url: str, +) -> str: + """The consent page a native client's sign-in lands on: who is signed in, which + loopback client asked, which team the credential is attributed to, and an explicit + Approve or Deny that POSTs back to ``complete_url``. Every value is client- or + user-influenced and HTML-escaped; the flow handle travels only in the form body.""" + return f""" + + + + + +Authorize CLI access - LiteLLM + + + +
+

Authorize CLI access

+

A command-line client at {escape(client_origin)} wants to call LiteLLM as {escape(user_id)}.

+

Approving issues it a personal credential that expires within {CLI_JWT_EXPIRATION_HOURS} hours. lite logout stops it from being renewed. Only approve if you started this sign-in yourself.

+
+ +{_team_field(teams)} +
+ + +
+
+
+ + +""" + + +def _team_field(teams: Sequence[tuple[str, str]]) -> str: + if not teams: + return "" + if len(teams) == 1: + team_id, team_label = teams[0] + return ( + f'' + f"

Requests are attributed to team {escape(team_label)}.

" + ) + options: Final = "".join( + f'' for team_id, team_label in teams + ) + return ( + f'' + ) diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py index 46af5dd80e1..1ebcb53fd6b 100644 --- a/litellm/proxy/management_endpoints/ui_sso.py +++ b/litellm/proxy/management_endpoints/ui_sso.py @@ -270,7 +270,7 @@ class _TeamRowGrants(BaseModel): litellm_model_table: _TeamModelAliasTable | None = None -class _CliSsoTeamDetail(BaseModel): +class CliSsoTeamDetail(BaseModel): """The per-team snapshot cached in the CLI SSO flow and echoed to the CLI on poll.""" team_id: str | None = None @@ -279,8 +279,8 @@ class _CliSsoTeamDetail(BaseModel): team_model_aliases: Mapping[str, str] | None = None -_CLI_SSO_TEAM_DETAILS_ADAPTER: Final = TypeAdapter(tuple[_CliSsoTeamDetail, ...]) -_TEAMLESS_CLI_SSO_TEAM_DETAIL: Final = _CliSsoTeamDetail(team_models=()) +_CLI_SSO_TEAM_DETAILS_ADAPTER: Final = TypeAdapter(tuple[CliSsoTeamDetail, ...]) +_TEAMLESS_CLI_SSO_TEAM_DETAIL: Final = CliSsoTeamDetail(team_models=()) class _CustomSsoCall(Protocol): @@ -2192,10 +2192,10 @@ async def _build_cli_sso_user_defined_values( ) -def _cli_sso_team_detail(team_row: Mapping[str, object]) -> _CliSsoTeamDetail: +def _cli_sso_team_detail(team_row: Mapping[str, object]) -> CliSsoTeamDetail: team: Final = _TeamRowGrants.model_validate(team_row) alias_table: Final = team.litellm_model_table - return _CliSsoTeamDetail( + return CliSsoTeamDetail( team_id=team.team_id, team_alias=team.team_alias, team_models=team.models, @@ -2203,10 +2203,10 @@ def _cli_sso_team_detail(team_row: Mapping[str, object]) -> _CliSsoTeamDetail: ) -async def _fetch_cli_sso_team_details( +async def fetch_cli_sso_team_details( prisma_client: PrismaClient, teams: Sequence[str], -) -> tuple[_CliSsoTeamDetail, ...] | None: +) -> tuple[CliSsoTeamDetail, ...] | None: """``None`` means the lookup itself failed, which is not the same as the user having no teams.""" if not teams: return () @@ -2221,7 +2221,7 @@ async def _fetch_cli_sso_team_details( return tuple(_cli_sso_team_detail(team_row.model_dump()) for team_row in prisma_teams) -def _cli_sso_session_teams(team_details: Sequence[_CliSsoTeamDetail]) -> list[str]: +def _cli_sso_session_teams(team_details: Sequence[CliSsoTeamDetail]) -> list[str]: """The teams a login may bind to: only those whose row still exists. A team deleted out from under a membership, which is what deleting an organization @@ -2231,7 +2231,7 @@ def _cli_sso_session_teams(team_details: Sequence[_CliSsoTeamDetail]) -> list[st return [detail.team_id for detail in team_details if detail.team_id is not None] -def _selected_cli_sso_team_detail(team_details: object, team_id: str | None) -> _CliSsoTeamDetail | None: +def selected_cli_sso_team_detail(team_details: object, team_id: str | None) -> CliSsoTeamDetail | None: """``None`` means the team's grants are unknown. An empty grant is a real value meaning unrestricted, so an unknown one must not be minted as empty.""" if team_id is None: @@ -2282,7 +2282,7 @@ async def _complete_cli_sso_callback_session( if hasattr(user_info, "teams") and user_info.teams: teams = user_info.teams if isinstance(user_info.teams, list) else [] - team_details: Final = await _fetch_cli_sso_team_details(prisma_client=prisma_client, teams=teams) + team_details: Final = await fetch_cli_sso_team_details(prisma_client=prisma_client, teams=teams) if team_details is None: raise HTTPException( status_code=500, @@ -2483,7 +2483,7 @@ async def cli_poll_key( # If no team_id provided and user has 0 or 1 team, use first team (or None) team_id = user_teams[0] if len(user_teams) > 0 else None - selected_team: Final = _selected_cli_sso_team_detail( + selected_team: Final = selected_cli_sso_team_detail( team_details=user_team_details, team_id=team_id, ) diff --git a/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py b/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py index 27fc5eb4bd0..5593211ba6f 100644 --- a/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py +++ b/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py @@ -5,6 +5,7 @@ Unit tests for CLI token utilities import json import os import tempfile +import time from pathlib import Path from unittest.mock import mock_open, patch @@ -87,3 +88,29 @@ class TestCLITokenUtils: result = get_litellm_gateway_api_key() assert result is None + + +class TestIsCliTokenFreshWithExpiresAt: + """A ``lite login --pkce`` record carries the proxy's own ``expires_at``, which wins + over the age-based guess made from ``timestamp``.""" + + def test_future_expiry_is_fresh(self): + from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh + + assert is_cli_token_fresh({"expires_at": time.time() + 3600, "timestamp": 0}) is True + + def test_expiry_inside_the_buffer_is_stale(self): + from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh + + assert is_cli_token_fresh({"expires_at": time.time() + 100}) is False + assert is_cli_token_fresh({"expires_at": time.time() + 100}, buffer_hours=0) is True + + def test_past_expiry_is_stale_even_with_a_fresh_timestamp(self): + from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh + + assert is_cli_token_fresh({"expires_at": time.time() - 1, "timestamp": time.time()}) is False + + def test_non_numeric_expiry_falls_back_to_the_timestamp(self): + from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh + + assert is_cli_token_fresh({"expires_at": "soon", "timestamp": time.time()}) is True diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_session_token.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_session_token.py index a43592ebe18..36280530eac 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_session_token.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_session_token.py @@ -212,3 +212,55 @@ def test_minted_token_repr_never_leaks_value(): minted = mint_session_token(PRINCIPAL, KEYS, NOW) assert isinstance(minted, MintedSessionToken) assert minted.token.get_secret_value() not in repr(minted) + + +def _decoded_claims(token: str, prefix: str) -> dict: + return jwt.decode( + token.removeprefix(prefix), + KEYS.signing_key.get_secret_value(), + algorithms=["HS256"], + options={"verify_exp": False}, + ) + + +def test_mcp_principal_wire_claims_carry_no_audience_or_team_keys(): + access_claims = _decoded_claims(_mint_access(), SESSION_TOKEN_PREFIX) + refresh_claims = _decoded_claims(_mint_refresh(), SESSION_REFRESH_PREFIX) + for claims in (access_claims, refresh_claims): + assert "audience" not in claims + assert "team_id" not in claims + + +def test_legacy_signed_claims_open_with_no_audience_and_no_team(): + opened = open_session_token(_sign_claims(_valid_claims()), KEYS, NOW) + assert isinstance(opened, OpenedSessionToken) + assert opened.principal.audience is None + assert opened.principal.team_id is None + + +def test_proxy_api_audience_and_team_round_trip_through_the_refresh_token(): + principal = SessionPrincipal(user_id="user-123", client_id="llm_client_abc", audience="proxy_api", team_id="team-b") + minted = mint_session_refresh_token(principal, KEYS, NOW) + assert isinstance(minted, MintedSessionToken) + token = minted.token.get_secret_value() + claims = _decoded_claims(token, SESSION_REFRESH_PREFIX) + assert claims["audience"] == "proxy_api" + assert claims["team_id"] == "team-b" + opened = open_session_refresh_token(token, KEYS, NOW) + assert isinstance(opened, OpenedSessionToken) + assert opened.principal == principal + + +def test_signed_claims_with_an_unknown_audience_are_rejected(): + token = _sign_claims(_valid_claims(audience="bogus")) + assert isinstance(open_session_token(token, KEYS, NOW), SessionMalformed) + + +def test_signed_claims_with_a_non_string_team_are_rejected(): + token = _sign_claims(_valid_claims(team_id=42)) + assert isinstance(open_session_token(token, KEYS, NOW), SessionMalformed) + + +def test_principal_rejects_an_unknown_audience_at_construction(): + with pytest.raises(ValidationError): + SessionPrincipal(user_id="user-123", client_id="llm_client_abc", audience="mcp") 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 424b993de85..bdaf1458fb0 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 @@ -1,6 +1,9 @@ """Tests for MCP OAuth discoverable endpoints""" +import hashlib import json +import time +from base64 import urlsafe_b64encode from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -9432,3 +9435,229 @@ async def test_upstream_resource_sent_on_dcr_bridge_relay_authorize(): query = await _authorize_query(server) assert query["resource"] == ["https://mcp.example.com/mcp"] assert query["client_id"] == ["caller-client"] + + +def _s256(verifier: str) -> str: + return urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii") + + +_NATIVE_CLIENT_MASTER_KEY = "sk-test-salt-for-LIT-5874" + + +def _native_client_app(monkeypatch): + """The unauthenticated discoverable router served over TestClient with a signed UI session + cookie available, plus fakes for the two database-backed hooks the native-client flow calls.""" + import jwt + from fastapi import FastAPI + from fastapi.testclient import TestClient + + from litellm.proxy._experimental.mcp_server.discoverable_endpoints import router + from litellm.proxy._experimental.mcp_server.gateway_dcr_flow import ConsentTeam, MintedProxyCredential + from litellm.proxy._experimental.mcp_server.mcp_server_manager import global_mcp_server_manager + + monkeypatch.setenv("LITELLM_SALT_KEY", _NATIVE_CLIENT_MASTER_KEY) + monkeypatch.setattr("litellm.proxy.proxy_server.master_key", _NATIVE_CLIENT_MASTER_KEY, raising=False) + minted = [] + + async def fake_mint(user_id, team_id): + minted.append((user_id, team_id)) + return MintedProxyCredential(key=f"sk-cli-{len(minted)}", expires_in=3600, user_id=user_id, team_id=team_id) + + async def fake_lookup(user_id): + return (ConsentTeam(team_id="team-a", team_alias="Team A"), ConsentTeam(team_id="team-b")) + + monkeypatch.setattr( + "litellm.proxy._experimental.mcp_server.discoverable_endpoints.mint_proxy_credential", fake_mint + ) + monkeypatch.setattr( + "litellm.proxy._experimental.mcp_server.discoverable_endpoints.lookup_consent_teams", fake_lookup + ) + global_mcp_server_manager.registry.clear() + app = FastAPI() + app.include_router(router) + client = TestClient(app) + session_cookie = jwt.encode( + {"user_id": "u1", "login_method": "username_password", "exp": int(time.time()) + 600}, + _NATIVE_CLIENT_MASTER_KEY, + algorithm="HS256", + ) + return client, session_cookie, minted + + +def _consent_flow_handle(page: str) -> str: + import re + + match = re.search(r'name="flow" value="([^"]+)"', page) + assert match is not None, page + return match.group(1) + + +def test_native_client_login_walks_discovery_consent_token_refresh_and_revoke(monkeypatch): + """The whole ``lite login --pkce`` server side over the real router: a Go CLI reads the versioned + discovery document, registers a loopback public client, the signed-in user consents to a team, + the code redeems for the ``lite login`` credential, the refresh token rotates, and revocation + kills it.""" + from http.cookies import SimpleCookie + from urllib.parse import parse_qs, urlparse + + client, session_cookie, minted = _native_client_app(monkeypatch) + redirect_uri = "http://127.0.0.1:51234/callback" + + discovery = client.get("/.well-known/litellm-cli-auth") + assert discovery.status_code == 200 + assert discovery.headers["cache-control"] == "no-store" + contract = discovery.json() + assert contract["contract_version"] == 1 + assert contract["resource"] == "http://testserver" + assert contract["code_challenge_methods_supported"] == ["S256"] + assert contract["token_endpoint_auth_methods_supported"] == ["none"] + for endpoint in ("authorization_endpoint", "token_endpoint", "registration_endpoint", "revocation_endpoint"): + assert contract[endpoint].startswith("http://testserver/") + + registered = client.post( + contract["registration_endpoint"], + json={ + "client_name": "litellm-cli", + "redirect_uris": [redirect_uri], + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "token_endpoint_auth_method": "none", + }, + ) + assert registered.status_code == 201 + client_id = registered.json()["client_id"] + verifier = "v" * 43 + authorize_params = { + "response_type": "code", + "client_id": client_id, + "redirect_uri": redirect_uri, + "state": "cli-state", + "code_challenge": _s256(verifier), + "code_challenge_method": "S256", + "resource": contract["resource"], + } + + anonymous = client.get(contract["authorization_endpoint"], params=authorize_params, follow_redirects=False) + assert anonymous.status_code == 303 + login_target = urlparse(anonymous.headers["location"]) + assert login_target.path == "/sso/key/generate" + assert parse_qs(login_target.query)["return_to"][0].startswith("/authorize?") + + client.cookies.set("token", session_cookie) + consent = client.get(contract["authorization_endpoint"], params=authorize_params, follow_redirects=False) + assert consent.status_code == 200 + assert consent.headers["x-frame-options"] == "DENY" + assert consent.headers["cache-control"] == "no-store" + assert "http://127.0.0.1:51234" in consent.text + assert '' in consent.text + jar = SimpleCookie() + jar.load(consent.headers["set-cookie"]) + assert all(morsel["httponly"] for morsel in jar.values()) + + denied = client.post( + "/authorize/complete", + data={"flow": _consent_flow_handle(consent.text), "decision": "deny", "team_id": "team-a"}, + follow_redirects=False, + ) + assert denied.status_code == 303 + denied_query = parse_qs(urlparse(denied.headers["location"]).query) + assert denied.headers["location"].startswith(redirect_uri) + assert denied_query["error"] == ["access_denied"] + assert denied_query["state"] == ["cli-state"] + assert minted == [] + + consent_again = client.get(contract["authorization_endpoint"], params=authorize_params, follow_redirects=False) + approved = client.post( + "/authorize/complete", + data={"flow": _consent_flow_handle(consent_again.text), "decision": "approve", "team_id": "team-b"}, + follow_redirects=False, + ) + assert approved.status_code == 303 + assert approved.headers["location"].startswith(redirect_uri) + approved_query = parse_qs(urlparse(approved.headers["location"]).query) + assert approved_query["state"] == ["cli-state"] + code = approved_query["code"][0] + + token = client.post( + contract["token_endpoint"], + data={ + "grant_type": "authorization_code", + "code": code, + "redirect_uri": redirect_uri, + "client_id": client_id, + "code_verifier": verifier, + "resource": contract["resource"], + }, + ) + assert token.status_code == 200, token.text + assert token.headers["cache-control"] == "no-store" + body = token.json() + assert body["access_token"] == "sk-cli-1" + assert body["token_type"] == "Bearer" + assert body["expires_in"] == 3600 + assert body["user_id"] == "u1" + assert body["team_id"] == "team-b" + assert body["refresh_token"].startswith("llm_srefresh_") + assert minted == [("u1", "team-b")] + + refreshed = client.post( + contract["token_endpoint"], + data={ + "grant_type": "refresh_token", + "refresh_token": body["refresh_token"], + "client_id": client_id, + "resource": contract["resource"], + }, + ) + assert refreshed.status_code == 200, refreshed.text + assert refreshed.json()["access_token"] == "sk-cli-2" + assert refreshed.json()["team_id"] == "team-b" + assert refreshed.json()["refresh_token"] != body["refresh_token"] + assert minted == [("u1", "team-b"), ("u1", "team-b")] + + revoked = client.post( + contract["revocation_endpoint"], + data={"token": refreshed.json()["refresh_token"], "token_type_hint": "refresh_token", "client_id": client_id}, + ) + assert revoked.status_code == 200 + assert revoked.json() == {} + + after_revoke = client.post( + contract["token_endpoint"], + data={ + "grant_type": "refresh_token", + "refresh_token": refreshed.json()["refresh_token"], + "client_id": client_id, + "resource": contract["resource"], + }, + ) + assert after_revoke.status_code == 400 + assert after_revoke.json()["error"] == "invalid_grant" + + stranger = client.post( + contract["revocation_endpoint"], data={"token": "whatever", "client_id": "llm_dcrc_not_a_client"} + ) + assert stranger.status_code == 401 + assert stranger.json()["error"] == "invalid_client" + + +def test_native_client_authorize_without_the_proxy_resource_keeps_the_mcp_flow(monkeypatch): + """A registered client asking for the MCP resource (or no resource) never sees the consent + page, so existing MCP clients are untouched by the native-client arm.""" + client, session_cookie, minted = _native_client_app(monkeypatch) + registered = client.post("/register", json={"redirect_uris": ["http://127.0.0.1:51234/callback"]}) + client.cookies.set("token", session_cookie) + for resource in (None, "http://testserver/mcp"): + params = { + "response_type": "code", + "client_id": registered.json()["client_id"], + "redirect_uri": "http://127.0.0.1:51234/callback", + "state": "s", + "code_challenge": _s256("v" * 43), + "code_challenge_method": "S256", + **({"resource": resource} if resource else {}), + } + response = client.get("/authorize", params=params, follow_redirects=False) + assert 'name="decision"' not in response.text + assert "team-b" not in response.text + assert minted == [] diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_gateway_dcr_flow.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_gateway_dcr_flow.py index cc65970a180..4e665c552f3 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/test_gateway_dcr_flow.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_gateway_dcr_flow.py @@ -1,8 +1,8 @@ """Tests for the aggregate gateway DCR flow (register, authorize, complete, token).""" import hashlib -import html import json +import re from base64 import urlsafe_b64encode from datetime import datetime, timedelta, timezone from http.cookies import SimpleCookie @@ -13,12 +13,13 @@ from starlette.requests import Request from litellm.caching.caching import DualCache from litellm.proxy._experimental.mcp_server.gateway_dcr_flow import ( + _AUTH_CODE_DEBUG_KEY, CONNECT_FLOW_COOKIE_PREFIX, GATEWAY_AUTH_CODE_PREFIX, GATEWAY_AUTH_CODE_TTL_SECONDS, - GATEWAY_DCR_CLIENT_ID_PREFIX, MANUAL_DELIVERY_AUTH_CODE_TTL_SECONDS, - _AUTH_CODE_DEBUG_KEY, + ConsentTeam, + MintedProxyCredential, _GatewayAuthCode, _open_sealed, _seal, @@ -26,14 +27,21 @@ from litellm.proxy._experimental.mcp_server.gateway_dcr_flow import ( aggregate_token, complete_connect_flow, is_gateway_dcr_client_id, + is_proxy_api_resource, + native_client_auth_contract, + native_client_authorize, open_gateway_dcr_client, register_aggregate_client, + revoke_refresh_token, ) from litellm.proxy._experimental.mcp_server.outbound_credentials.session_credentials import ( + SessionBearerAdmitted, + SessionRefreshOpened, + open_session_refresh_bearer, resolve_session_bearer, session_keys_from_master_key, - SessionBearerAdmitted, ) +from litellm.proxy._experimental.mcp_server.outbound_credentials.session_token import SESSION_REFRESH_PREFIX MASTER_KEY = "sk-gateway-dcr-flow-tests" REDIRECT_URI = "https://claude.ai/api/mcp/auth_callback" @@ -888,9 +896,14 @@ async def test_scoped_authorize_runs_connect_page_with_sealed_scope(): assert response.status_code == 303 assert "/ui/connect" in response.headers["location"] _, cookies = _flow_cookie_from(response) - assert _sealed_wire_json(next(iter(cookies.values())), "", "gateway_connect_flow")["resource_server_id"] == "github-id" + assert ( + _sealed_wire_json(next(iter(cookies.values())), "", "gateway_connect_flow")["resource_server_id"] == "github-id" + ) code = await _finish_connect_page(response) - assert _sealed_wire_json(code, GATEWAY_AUTH_CODE_PREFIX, "gateway_authorization_code")["resource_server_id"] == "github-id" + assert ( + _sealed_wire_json(code, GATEWAY_AUTH_CODE_PREFIX, "gateway_authorization_code")["resource_server_id"] + == "github-id" + ) token_response = await _redeem(code, client_id) assert token_response.status_code == 200 principal = _opened_principal(json.loads(token_response.body)) @@ -1039,3 +1052,542 @@ async def test_resource_resolution_is_identity_not_ip_filtered_access(): result = resolve_scoped_resource_server(_request(), SCOPED_RESOURCE) assert result is not None manager.get_mcp_server_by_name.assert_called_once_with("github") + + +LOOPBACK_REDIRECT_URI = "http://127.0.0.1:51234/callback" +PROXY_API_RESOURCE = "https://llm.example.com" +CONSENT_TEAMS = (ConsentTeam(team_id="team-a", team_alias="Team A"), ConsentTeam(team_id="team-b")) + + +class _Minter: + def __init__(self, result=None): + self.calls = [] + self.result = result + + async def __call__(self, user_id, team_id): + self.calls.append((user_id, team_id)) + if self.result is not None: + return self.result + return MintedProxyCredential(key=f"sk-cli-{user_id}", expires_in=3600, user_id=user_id, team_id=team_id) + + +class _ConsentTeams: + def __init__(self, result=CONSENT_TEAMS): + self.calls = [] + self.result = result + + async def __call__(self, user_id): + self.calls.append(user_id) + return self.result + + +async def _native_authorize(client_id, session_user_id="u1", lookup=None, **overrides): + arguments = { + "request": _request(query=f"resource={PROXY_API_RESOURCE}"), + "client_id": client_id, + "redirect_uri": LOOPBACK_REDIRECT_URI, + "state": "client-state-123", + "code_challenge": CODE_CHALLENGE, + "code_challenge_method": "S256", + "response_type": "code", + "session_user_id": session_user_id, + "lookup_consent_teams": lookup if lookup is not None else _ConsentTeams(), + } + return await native_client_authorize(**{**arguments, **overrides}) + + +def _consent_cookie_from(response) -> tuple: + match = re.search(r'name="flow" value="([^"]+)"', response.body.decode()) + assert match is not None + handle = match.group(1) + cookie = SimpleCookie() + cookie.load(response.headers["set-cookie"]) + name = f"{CONNECT_FLOW_COOKIE_PREFIX}{handle}" + return handle, {name: cookie[name].value} + + +async def _complete_consent(consent, cache=None, session_user_id="u1", **overrides): + handle, cookies = _consent_cookie_from(consent) + return await complete_connect_flow( + request=_request("/authorize/complete", cookies=cookies, method="POST"), + flow_handle=handle, + session_user_id=session_user_id, + cache=cache or DualCache(), + **overrides, + ) + + +def _code_from(response) -> str: + return parse_qs(urlparse(response.headers["location"]).query)["code"][0] + + +async def _native_code(client_id, team_id="team-b", cache=None) -> str: + approved = await _complete_consent( + await _native_authorize(client_id), cache=cache, decision="approve", team_id=team_id + ) + assert approved.status_code == 303 + return _code_from(approved) + + +async def _redeem_native(code, client_id, minter, cache=None, resource=PROXY_API_RESOURCE, **overrides): + return await _redeem( + code, + client_id, + cache=cache, + redirect_uri=LOOPBACK_REDIRECT_URI, + resource=resource, + mint_proxy_credential=minter, + **overrides, + ) + + +async def _refresh_native(refresh_token, client_id, minter, cache, **overrides): + return await _redeem_native( + None, client_id, minter, cache=cache, grant_type="refresh_token", refresh_token=refresh_token, **overrides + ) + + +def _opened_refresh(refresh_token, client_id): + opened = open_session_refresh_bearer( + refresh_token, + session_keys_from_master_key(MASTER_KEY), + datetime.now(timezone.utc), + expected_client_id=client_id, + ) + assert isinstance(opened, SessionRefreshOpened) + return opened.principal + + +@pytest.mark.asyncio +async def test_native_authorize_renders_consent_page_and_sets_flow_cookie(): + """A native client (RFC 8707 resource = the proxy itself) gets the server-rendered consent + page instead of the MCP connect-page redirect: the flow handle rides only in the hidden + field, the sealed flow in an HttpOnly cookie, and the page can never be framed or cached.""" + client_id = (await _register([LOOPBACK_REDIRECT_URI]))["client_id"] + lookup = _ConsentTeams() + response = await _native_authorize(client_id, lookup=lookup) + assert response.status_code == 200 + assert response.headers["content-type"].startswith("text/html") + assert response.headers["cache-control"] == "no-store" + assert response.headers["x-frame-options"] == "DENY" + assert response.headers["content-security-policy"] == "frame-ancestors 'none'" + assert lookup.calls == ["u1"] + body = response.body.decode() + assert "http://127.0.0.1:51234" in body + assert "/callback" not in body + assert "u1" in body + assert '' in body + assert '' in body + assert 'action="https://llm.example.com/authorize/complete"' in body + handle, cookies = _consent_cookie_from(response) + assert "httponly" in response.headers["set-cookie"].lower() + flow = _sealed_wire_json(next(iter(cookies.values())), "", "gateway_connect_flow") + assert flow["audience"] == "proxy_api" + assert flow["client_id"] == client_id + assert flow["redirect_uri"] == LOOPBACK_REDIRECT_URI + assert flow["user_id"] == "u1" + assert "resource_server_id" not in flow + assert handle not in body.replace(f'value="{handle}"', "") + + +@pytest.mark.asyncio +async def test_native_authorize_without_session_redirects_to_login_before_any_lookup(): + client_id = (await _register([LOOPBACK_REDIRECT_URI]))["client_id"] + lookup = _ConsentTeams() + response = await _native_authorize(client_id, session_user_id=None, lookup=lookup) + assert response.status_code == 303 + location = response.headers["location"] + assert location.startswith("https://llm.example.com/sso/key/generate?return_to=") + assert "return_to=%2Fauthorize%3Fresource%3D" in location + assert lookup.calls == [] + assert "set-cookie" not in response.headers + + +@pytest.mark.asyncio +async def test_native_authorize_validation_failures_never_reach_consent(): + client_id = (await _register([LOOPBACK_REDIRECT_URI]))["client_id"] + lookup = _ConsentTeams() + for presented_client_id, overrides, expected_error in ( + ("llm_dcrc_bogus", {}, "invalid_client"), + (client_id, {"redirect_uri": "http://127.0.0.1:51235/callback"}, "invalid_request"), + (client_id, {"response_type": "token"}, "unsupported_response_type"), + (client_id, {"code_challenge": None}, "invalid_request"), + (client_id, {"code_challenge_method": "plain"}, "invalid_request"), + ): + response = await _native_authorize(presented_client_id, lookup=lookup, **overrides) + assert response.status_code == 400 + assert json.loads(response.body)["error"] == expected_error + assert "set-cookie" not in response.headers + assert lookup.calls == [] + + +@pytest.mark.asyncio +async def test_native_authorize_refuses_a_hosted_redirect_for_the_proxy_api(): + """Registration accepts any https redirect because MCP clients can be hosted, but a + proxy-API grant hands out the user's personal key, so it only ever goes back to loopback.""" + hosted = "https://evil.example/cb" + client_id = (await _register([hosted]))["client_id"] + lookup = _ConsentTeams() + response = await _native_authorize(client_id, redirect_uri=hosted, lookup=lookup) + assert response.status_code == 400 + assert json.loads(response.body) == { + "error": "invalid_request", + "error_description": "a proxy-API grant may only redirect to a loopback address", + } + assert "set-cookie" not in response.headers + assert lookup.calls == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "failure, status, error", + [ + ("unavailable", 503, "temporarily_unavailable"), + ("unresolvable", 500, "server_error"), + ("no_active_key", 403, "access_denied"), + ], +) +async def test_native_authorize_consent_lookup_failures_are_oauth_errors_without_a_flow(failure, status, error): + client_id = (await _register([LOOPBACK_REDIRECT_URI]))["client_id"] + response = await _native_authorize(client_id, lookup=_ConsentTeams(failure)) + assert response.status_code == status + assert json.loads(response.body)["error"] == error + assert "set-cookie" not in response.headers + + +@pytest.mark.asyncio +async def test_native_consent_escapes_untrusted_identifiers(): + client_id = (await _register([LOOPBACK_REDIRECT_URI]))["client_id"] + hostile = (ConsentTeam(team_id='t">