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]

Merge remote-tracking branch 'origin/litellm_internal_staging' into codex/auth-sensitive-routes

user3fd0a2d7611a
diff --cc litellm/proxy/health_endpoints/_health_endpoints.py
index 0f7067b1c25,35c9edb937d..c9859ed25bb
--- a/litellm/proxy/health_endpoints/_health_endpoints.py
+++ b/litellm/proxy/health_endpoints/_health_endpoints.py
@@@ -1237,9 -1447,14 +1447,11 @@@ def callback_name(callback)
return str(callback)
- async def _get_health_readiness_details() -> Dict[str, Any]:
- "/health/readiness",
- tags=["health"],
- dependencies=[Depends(user_api_key_auth)],
-)
-async def health_readiness(response: Response):
++async def _get_health_readiness_details(
++ response: Optional[Response] = None,
++) -> Dict[str, Any]:
"""
- Unprotected endpoint for checking if worker can receive requests
+ Detailed health payload for authenticated diagnostics.
"""
from litellm.proxy.proxy_server import prisma_client, version
@@@ -1281,6 -1495,12 +1493,12 @@@
# check DB
if prisma_client is not None: # if db passed in, check if it's connected
db_health_status = await _db_health_readiness_check()
+ # A configured DB that is not reachable means the worker cannot
+ # serve requests that depend on persisted state (keys, budgets,
+ # spend logs). Return 503 so orchestrators take this pod out of
+ # rotation; "Not connected" (no DB configured at all) stays 200.
- if db_health_status["status"] != "connected":
++ if response is not None and db_health_status["status"] != "connected":
+ response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return {
"status": "healthy",
"db": db_health_status["status"],
@@@ -1306,39 -1526,6 +1524,39 @@@
raise HTTPException(status_code=503, detail=f"Service Unhealthy ({str(e)})")
+def _allow_public_health_readiness_details() -> bool:
+ from litellm.proxy.proxy_server import general_settings
+
+ return general_settings.get("allow_public_health_readiness_details") is True
+
+
+ "/health/readiness",
+ tags=["health"],
+)
- async def health_readiness():
++async def health_readiness(response: Response):
+ """
+ Public readiness probe. Keep this low-detail for unauthenticated load
+ balancers by default. Admins can opt into the legacy detailed public
+ payload with general_settings.allow_public_health_readiness_details.
+ """
+ if _allow_public_health_readiness_details():
- return await _get_health_readiness_details()
++ return await _get_health_readiness_details(response=response)
+ return {"status": "healthy"}
+
+
+ "/health/readiness/details",
+ tags=["health"],
+ dependencies=[Depends(user_api_key_auth)],
+)
- async def health_readiness_details():
++async def health_readiness_details(response: Response):
+ """
+ Authenticated readiness diagnostics with DB/cache/callback metadata.
+ """
- return await _get_health_readiness_details()
++ return await _get_health_readiness_details(response=response)
+
+
@router.get(
"/health/backlog",
tags=["health"],
diff --cc tests/test_litellm/proxy/auth/test_user_api_key_auth.py
index 3f28191bceb,dd24ac87495..398084fdc5e
--- a/tests/test_litellm/proxy/auth/test_user_api_key_auth.py
+++ b/tests/test_litellm/proxy/auth/test_user_api_key_auth.py
@@@ -15,8 -13,9 +14,10 @@@ import litell
import litellm.proxy.proxy_server
from litellm.caching.dual_cache import DualCache
from litellm.proxy._types import (
+ LiteLLMRoutes,
LiteLLM_JWTAuth,
+ LiteLLM_BudgetTable,
+ LiteLLM_EndUserTable,
LiteLLM_UserTable,
LitellmUserRoles,
ProxyErrorTypes,
@@@ -25,9 -24,10 +26,11 @@@
JWTRoutingOverride,
)
from litellm.proxy.auth.handle_jwt import JWTHandler
+ from litellm.proxy.auth.auth_checks import get_key_object, _cache_key_object
from litellm.proxy.auth.route_checks import RouteChecks
from litellm.proxy.auth.user_api_key_auth import (
+ _route_requires_auth_despite_public,
+ _reserve_budget_after_common_checks,
_run_centralized_common_checks,
_run_post_custom_auth_checks,
get_api_key,
@@@ -52,29 -59,74 +62,97 @@@ def test_get_api_key()
) == (api_key, passed_in_key)
+def test_route_requires_auth_despite_public_for_metrics(monkeypatch):
+ monkeypatch.setattr(litellm, "require_auth_for_metrics_endpoint", True)
+
+ assert _route_requires_auth_despite_public("/metrics", {}) is True
+ assert _route_requires_auth_despite_public("/metrics/", {}) is True
+
+ monkeypatch.setattr(litellm, "require_auth_for_metrics_endpoint", False)
+
+ assert _route_requires_auth_despite_public("/metrics", {}) is False
+
+
+def test_public_ai_hub_routes_remain_public():
+ for route in (
+ "/public/model_hub",
+ "/public/model_hub/info",
+ "/public/agent_hub",
+ "/public/mcp_hub",
+ "/public/skill_hub",
+ ):
+ assert route in LiteLLMRoutes.public_routes.value
+ assert _route_requires_auth_despite_public(route, {}) is False
+
+
+ @pytest.mark.asyncio
+ async def test_should_clear_stale_budget_reservation_when_budget_checks_skip():
+ user_api_key_auth_obj = UserAPIKeyAuth(
+ token="test_token",
+ budget_reservation={
+ "reserved_cost": 0.5,
+ "entries": [{"counter_key": "spend:key:test_token"}],
+ },
+ )
+
+ await _reserve_budget_after_common_checks(
+ user_api_key_auth_obj=user_api_key_auth_obj,
+ request_data={"model": "free-model"},
+ route="/v1/chat/completions",
+ llm_router=None,
+ team_object=None,
+ user_object=None,
+ prisma_client=None,
+ user_api_key_cache=MagicMock(),
+ proxy_logging_obj=MagicMock(),
+ skip_budget_checks=True,
+ )
+
+ assert user_api_key_auth_obj.budget_reservation is None
+
+
+ @pytest.mark.asyncio
+ async def test_should_not_reuse_cached_key_object_for_request_state():
+ key_cache = DualCache()
+ cached_key = UserAPIKeyAuth(
+ token="cached-token",
+ request_route="/old-route",
+ budget_reservation={
+ "reserved_cost": 0.5,
+ "entries": [{"counter_key": "spend:key:cached-token"}],
+ },
+ )
+
+ await _cache_key_object(
+ hashed_token="cached-token",
+ user_api_key_obj=cached_key,
+ user_api_key_cache=key_cache,
+ proxy_logging_obj=None,
+ )
+
+ first_request_key = await get_key_object(
+ hashed_token="cached-token",
+ prisma_client=MagicMock(),
+ user_api_key_cache=key_cache,
+ )
+ first_request_key.budget_reservation = {
+ "reserved_cost": 0.9,
+ "entries": [{"counter_key": "spend:key:cached-token"}],
+ }
+ first_request_key.request_route = "/chat/completions"
+
+ second_request_key = await get_key_object(
+ hashed_token="cached-token",
+ prisma_client=MagicMock(),
+ user_api_key_cache=key_cache,
+ )
+
+ assert first_request_key is not cached_key
+ assert second_request_key is not first_request_key
+ assert second_request_key.budget_reservation is None
+ assert second_request_key.request_route is None
+
+
@pytest.mark.asyncio
async def test_custom_auth_does_not_enforce_key_model_access_by_default():
valid_token = UserAPIKeyAuth(token="test_token", models=["gpt-4o-mini"])