Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(mcp): classify get_user_object's wrapped DB outage across the exception chain

Tin Chi Lo61c7e706dd24
diff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
index ac3e4439fa1..421f1dcfbea 100644
--- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
+++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
@@ -610,12 +610,16 @@ class MCPRequestHandler:
``get_allowed_mcp_servers`` does not do off one auth object). The caller's centralized policy
gate enforces the user's live budget and org state, and a SCIM-deactivated owner fails closed.
- Error handling mirrors the key path's retryable-503 contract, with one deliberate
- difference: ``get_key_object`` raises a ``ProxyException`` for a missing key, but
- ``get_user_object`` raises a bare ``Exception`` for a missing user (it does not surface as a
- ``ProxyException``/``HTTPException``). So a transient DB outage still surfaces as a retryable
- 503 via ``_raise_503_if_db_unavailable``, while a missing user, or any other non-outage
- resolution failure, fails closed as a 401 rather than propagating as an opaque 500."""
+ Error handling mirrors the key path's retryable-503 contract, but ``get_user_object`` defeats a
+ type-based check: where ``get_key_object`` raises a typed ``ProxyException`` for a missing key
+ and lets a DB outage propagate raw, ``get_user_object`` catches every DB failure and re-raises a
+ bare ``ValueError``, so a missing user and a real outage look identical and the original error
+ survives only as ``__context__``. ``_raise_503_if_db_unavailable`` therefore walks the cause
+ chain: a transient DB outage still surfaces as a retryable 503, while a missing user, or any
+ other non-outage resolution failure, fails closed as a 401 rather than an opaque 500. The
+ object-permission load shares this one boundary, so an outage there is classified the same
+ way (``get_object_permission`` itself swallows a failed load to ``None``, matching how
+ ``get_key_object`` best-effort-loads a key's object permission)."""
from litellm.proxy.auth.auth_checks import get_object_permission, get_user_object
from litellm.proxy.proxy_server import prisma_client, user_api_key_cache
@@ -628,25 +632,25 @@ class MCPRequestHandler:
user_api_key_cache=user_api_key_cache,
user_id_upsert=False,
)
+ # Resolve the user's own MCP object permission (get_user_object does not load it) so the shared
+ # get_allowed_mcp_servers can grant the user their litellm-granted servers. Reuses the same
+ # get_object_permission resolver the key and team paths use; no permission logic is duplicated.
+ object_permission = user_object.object_permission if user_object is not None else None
+ if user_object is not None and object_permission is None and user_object.object_permission_id:
+ object_permission = await get_object_permission(
+ object_permission_id=user_object.object_permission_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ )
except (ProxyException, HTTPException):
raise HTTPException(status_code=401, detail="Invalid or expired credential") from None
- except Exception as e: # noqa: BLE001 # DB outage -> retryable 503; a missing user (bare Exception) or any other resolution failure -> fail closed 401, never an opaque 500
+ except Exception as e: # noqa: BLE001 # a DB outage anywhere in the resolution is a retryable 503, not an opaque 500; anything else fails closed as 401
MCPRequestHandler._raise_503_if_db_unavailable(e)
raise HTTPException(status_code=401, detail="Invalid or expired credential") from None
if user_object is None:
raise HTTPException(status_code=401, detail="Invalid or expired credential")
if isinstance(user_object.metadata, dict) and user_object.metadata.get("scim_active") is False:
raise HTTPException(status_code=401, detail="Invalid or expired credential")
- # Resolve the user's own MCP object permission (get_user_object does not load it) so the shared
- # get_allowed_mcp_servers can grant the user their litellm-granted servers. Reuses the same
- # get_object_permission resolver the key and team paths use; no permission logic is duplicated.
- object_permission = user_object.object_permission
- if user_object.object_permission_id and object_permission is None:
- object_permission = await get_object_permission(
- object_permission_id=user_object.object_permission_id,
- prisma_client=prisma_client,
- user_api_key_cache=user_api_key_cache,
- )
return UserAPIKeyAuth(
user_id=user_object.user_id,
user_role=user_object.user_role,
@@ -697,10 +701,14 @@ class MCPRequestHandler:
"""Raise a retryable 503 when ``e`` means the auth database is unreachable, else return so the
caller applies its own fail-closed mapping. A DB outage must not masquerade as an auth failure
(401) or surface as an opaque 500; the caller retries. Mirrors ``UserAPIKeyAuthExceptionHandler``,
- which renders a service-unavailable database error as 503 on the standard pipeline."""
+ which renders a service-unavailable database error as 503 on the standard pipeline.
+
+ Classifies across the ``__cause__``/``__context__`` chain, not just ``e`` itself: ``get_user_object``
+ re-raises every DB failure as a bare ``ValueError``, so a type-based check on the top exception
+ would miss a real outage wrapped inside it."""
from litellm.proxy.db.exception_handler import PrismaDBExceptionHandler
- if PrismaDBExceptionHandler.is_database_service_unavailable_error(e):
+ if PrismaDBExceptionHandler.is_database_service_unavailable_error_in_chain(e):
raise HTTPException(
status_code=503,
detail="Service Unavailable, the authentication database is temporarily unreachable. Please retry shortly.",
diff --git a/litellm/proxy/db/exception_handler.py b/litellm/proxy/db/exception_handler.py
index 3a93896a206..e4c565e4464 100644
--- a/litellm/proxy/db/exception_handler.py
+++ b/litellm/proxy/db/exception_handler.py
@@ -8,6 +8,10 @@ from litellm.proxy._types import (
)
from litellm.secret_managers.main import str_to_bool
+# Bounds the __cause__/__context__ walk in is_database_service_unavailable_error_in_chain.
+# Real exception chains are a few links deep; the cap also makes the walk cycle-safe.
+_MAX_EXCEPTION_CHAIN_DEPTH = 20
+
class PrismaDBExceptionHandler:
"""
@@ -218,6 +222,32 @@ class PrismaDBExceptionHandler:
),
)
+ @staticmethod
+ def is_database_service_unavailable_error_in_chain(e: BaseException) -> bool:
+ """Like ``is_database_service_unavailable_error`` but also walks the
+ ``__cause__`` / ``__context__`` chain.
+
+ ``is_database_service_unavailable_error`` classifies a single exception
+ by type, which a caller that catches a raw DB failure and re-raises a
+ domain exception of a different type defeats. ``get_user_object`` in
+ ``litellm/proxy/auth/auth_checks.py`` is the concrete case: it wraps
+ every DB error, a genuine outage included, in a bare ``ValueError``
+ whose original error survives only as ``__context__``. A type check on
+ the ``ValueError`` misses the outage, so the caller would mistake an
+ infrastructure fault for an auth failure. Walking the chain recovers the
+ real signal, which is the PEP 3134 way to inspect a wrapped cause.
+
+ The walk is depth-bounded, which also makes it cycle-safe.
+ """
+ current: BaseException | None = e
+ for _ in range(_MAX_EXCEPTION_CHAIN_DEPTH):
+ if not isinstance(current, Exception):
+ return False
+ if PrismaDBExceptionHandler.is_database_service_unavailable_error(current):
+ return True
+ current = current.__cause__ or current.__context__
+ return False
+
@staticmethod
def handle_db_exception(e: Exception):
"""
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py
index 0b1905689ac..6f132aaae9c 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py
@@ -5022,6 +5022,22 @@ class TestMCPDcrBridgeDelegateAdmission:
):
yield get_user_object
+ @staticmethod
+ def _wrapped_user_lookup_error(original: BaseException) -> ValueError:
+ """Reproduce get_user_object's real exception contract (litellm/proxy/auth/auth_checks.py): it
+ catches every DB failure in a broad ``except`` and re-raises a bare ``ValueError``, so the
+ original error (a missing-user Exception or a real outage) survives only as ``__context__``.
+ Injecting a raw ConnectionError/Exception instead would exercise a shape production never
+ produces and let a chain-blind outage classifier pass. That wrapping fidelity is itself pinned by
+ test_get_user_object_wraps_db_outage_as_valueerror_preserving_context in test_auth_checks."""
+ try:
+ raise original
+ except BaseException:
+ try:
+ raise ValueError(f"User doesn't exist in db. Got error - {original}")
+ except ValueError as wrapped:
+ return wrapped
+
@staticmethod
def _mcp_request(path="/mcp/bridge_delegate_server"):
"""A minimal ``Request`` for direct ``_admit_dcr_bridge_delegate`` calls, mirroring how
@@ -5162,9 +5178,10 @@ class TestMCPDcrBridgeDelegateAdmission:
async def test_user_subject_envelope_missing_user_fails_closed_401(self):
"""A user_id envelope whose user has since been deleted must fail closed with a 401, not a 500.
- get_user_object raises a bare Exception for a missing user (it does not return None on the
- production path), so the reload must catch it and fail closed rather than let it propagate as an
- opaque 500. Regression for the missing-user path surfacing as a 500."""
+ get_user_object catches the missing row and re-raises a bare ValueError (it does not return None
+ on the production path), so the reload must fail closed rather than let it propagate as an opaque
+ 500, and must not mistake the wrapped ValueError for a DB outage. Regression for the missing-user
+ path surfacing as a 500."""
envelope = self._mint_bridge_envelope(user_id="ghost-user")
scope = {
"type": "http",
@@ -5175,7 +5192,7 @@ class TestMCPDcrBridgeDelegateAdmission:
with (
patch("litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager") as mock_mgr,
patch("litellm.proxy.proxy_server.master_key", self._MASTER_KEY),
- self._patch_user_reload(side_effect=Exception("user not found")),
+ self._patch_user_reload(side_effect=self._wrapped_user_lookup_error(Exception())),
):
mock_mgr.get_mcp_server_by_name.return_value = self._bridge_delegate_server()
with pytest.raises(HTTPException) as exc_info:
@@ -5186,7 +5203,9 @@ class TestMCPDcrBridgeDelegateAdmission:
async def test_user_subject_envelope_db_outage_is_retryable_503(self):
"""A transient database outage while reloading the envelope's user is a retryable 503, not an
opaque 500, matching the key path's contract so an interactive DCR client retries instead of
- treating a live identity as invalid. Regression for the user reload dropping the 503 arm."""
+ treating a live identity as invalid. get_user_object wraps the outage in a bare ValueError, so this
+ exercises the chain-aware classifier; a raw ConnectionError would falsely pass even the old
+ chain-blind check because it is an OSError. Regression for the user reload dropping the 503 arm."""
envelope = self._mint_bridge_envelope(user_id="sso-user-7")
scope = {
"type": "http",
@@ -5197,7 +5216,9 @@ class TestMCPDcrBridgeDelegateAdmission:
with (
patch("litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager") as mock_mgr,
patch("litellm.proxy.proxy_server.master_key", self._MASTER_KEY),
- self._patch_user_reload(side_effect=ConnectionError("auth database unreachable")),
+ self._patch_user_reload(
+ side_effect=self._wrapped_user_lookup_error(ConnectionError("auth database unreachable"))
+ ),
):
mock_mgr.get_mcp_server_by_name.return_value = self._bridge_delegate_server()
with pytest.raises(HTTPException) as exc_info:
diff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.py
index d12ff20ee5b..3433d7dc2d3 100644
--- a/tests/test_litellm/proxy/auth/test_auth_checks.py
+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py
@@ -701,6 +701,38 @@ async def test_default_internal_user_params_with_get_user_object(monkeypatch):
assert creation_args["user_role"] == "internal_user"
+async def test_get_user_object_wraps_db_outage_as_valueerror_preserving_context():
+ """Pin get_user_object's exception contract: it catches every DB failure in a broad except and
+ re-raises a bare ValueError, so a real outage survives only as __context__ rather than as the
+ exception type. The MCP dcr_bridge admission and refresh paths depend on this to tell a transient
+ outage (retry, 503) from a missing user (fail closed), which is why they classify across the cause
+ chain instead of the top exception's type. If this wrapping ever changes, that classification must
+ change with it, so this test guards the contract the callers rely on."""
+ from unittest.mock import AsyncMock, MagicMock, patch
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db = AsyncMock()
+ mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
+ side_effect=ConnectionError("can't reach database server")
+ )
+ mock_cache = MagicMock()
+ mock_cache.async_get_cache = AsyncMock(return_value=None)
+ mock_cache.async_set_cache = AsyncMock()
+
+ with patch("litellm.proxy.auth.auth_checks._should_check_db", return_value=True):
+ with pytest.raises(ValueError) as exc_info:
+ await get_user_object(
+ user_id="outage-contract-probe-user",
+ prisma_client=mock_prisma_client,
+ user_api_key_cache=mock_cache,
+ user_id_upsert=False,
+ proxy_logging_obj=None,
+ )
+
+ assert isinstance(exc_info.value.__context__, ConnectionError)
+
+
@pytest.mark.asyncio
async def test_get_user_object_upsert_includes_user_email():
"""Test that user_email is included when creating a new user via get_user_object upsert"""
diff --git a/tests/test_litellm/proxy/db/test_exception_handler.py b/tests/test_litellm/proxy/db/test_exception_handler.py
index 0634a01326c..23099177812 100644
--- a/tests/test_litellm/proxy/db/test_exception_handler.py
+++ b/tests/test_litellm/proxy/db/test_exception_handler.py
@@ -286,6 +286,46 @@ def test_is_database_service_unavailable_error_excludes_non_infra(error):
)
+def _wrapped_like_get_user_object(original):
+ """Reproduce get_user_object's exception contract (litellm/proxy/auth/auth_checks.py): it catches
+ every DB failure in a broad ``except`` and re-raises a bare ``ValueError``, so the original error
+ survives only as ``__context__``. Building it by raising inside an ``except`` sets ``__context__``
+ exactly as production does."""
+ try:
+ raise original
+ except BaseException:
+ try:
+ raise ValueError("User doesn't exist in db. Got error - x")
+ except ValueError as wrapped:
+ return wrapped
+
+
+def test_is_database_service_unavailable_error_in_chain_sees_through_wrapping():
+ """The chain-aware classifier must see a real outage that a caller wrapped in a different type.
+ get_user_object turns a connection error into a bare ValueError whose type check reads as non-infra,
+ so the single-exception check returns False and only the chain walk recovers the outage. A missing
+ user (whose wrapped cause is a plain Exception) must stay non-infra on both."""
+ outage = _wrapped_like_get_user_object(ConnectionError("can't reach database server"))
+ missing_user = _wrapped_like_get_user_object(Exception())
+
+ assert PrismaDBExceptionHandler.is_database_service_unavailable_error(outage) is False
+ assert PrismaDBExceptionHandler.is_database_service_unavailable_error_in_chain(outage) is True
+ assert PrismaDBExceptionHandler.is_database_service_unavailable_error_in_chain(missing_user) is False
+ # parity: a raw outage with no wrapper is still an outage, and a plain ValueError is not
+ assert PrismaDBExceptionHandler.is_database_service_unavailable_error_in_chain(ConnectionError("boom")) is True
+ assert PrismaDBExceptionHandler.is_database_service_unavailable_error_in_chain(ValueError("nope")) is False
+
+
+def test_is_database_service_unavailable_error_in_chain_terminates_on_a_cause_cycle():
+ """The walk must terminate on a pathological __cause__ cycle rather than hang. Neither link is an
+ outage, so the bounded walk returns False instead of looping forever."""
+ first = ValueError("first")
+ second = ValueError("second")
+ first.__cause__ = second
+ second.__cause__ = first
+ assert PrismaDBExceptionHandler.is_database_service_unavailable_error_in_chain(first) is False
+
+
def test_is_database_service_unavailable_error_asyncpg(monkeypatch):
"""asyncpg connection/interface errors map to service-unavailable. asyncpg
is not a hard dependency, so inject a stand-in module to exercise the