The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
chore(proxy): guard sensitive public endpoints
userc8325ff0072f
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex fd4d4df2410..e3b7b3a1164 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -611,7 +611,6 @@ class LiteLLMRoutes(enum.Enum):"/","/health/liveliness","/health/liveness",- "/health/readiness","/test","/config/yaml","/metrics",diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.pyindex f0c2a4514fd..49cc1b3b2cf 100644--- a/litellm/proxy/auth/user_api_key_auth.py+++ b/litellm/proxy/auth/user_api_key_auth.py@@ -86,6 +86,36 @@ except ImportError as e:user_api_key_service_logger_obj = ServiceLogging() # used for tracking latency on OTEL+_PUBLIC_AI_HUB_ROUTES = frozenset(+ {+ "/public/model_hub",+ "/public/model_hub/info",+ "/public/agent_hub",+ "/public/mcp_hub",+ "/public/skill_hub",+ }+)+++def _normalize_public_auth_route(route: str) -> str:+ if route != "/" and route.endswith("/"):+ return route.rstrip("/")+ return route+++def _route_requires_auth_despite_public(+ route: str, general_settings: Optional[dict]+) -> bool:+ normalized_route = _normalize_public_auth_route(route)+ if normalized_route == "/metrics":+ return litellm.require_auth_for_metrics_endpoint is True++ if normalized_route in _PUBLIC_AI_HUB_ROUTES:+ return (general_settings or {}).get("require_auth_for_public_ai_hub") is True++ return False++custom_litellm_key_header = APIKeyHeader(name=SpecialHeaders.custom_litellm_api_key.value,auto_error=False,@@ -685,7 +715,9 @@ async def _user_api_key_auth_builder( # noqa: PLR0915"""######## Route Checks Before Reading DB / Cache for "token" ################- if (+ if not _route_requires_auth_despite_public(+ route=route, general_settings=general_settings+ ) and (route in LiteLLMRoutes.public_routes.value # type: ignoreor route_in_additonal_public_routes(current_route=route)):@@ -1639,7 +1671,7 @@ async def _run_centralized_common_checks(user_custom_auth,)- # Public routes (e.g. /health/readiness, /metrics) are exempt from+ # Public routes (e.g. /health/liveness, /metrics) are exempt from# auth in the builder — the wrapper must not retroactively apply# authz on top, or k8s readiness probes and other unauthenticated# callers get 401.diff --git a/litellm/proxy/common_utils/debug_utils.py b/litellm/proxy/common_utils/debug_utils.pyindex 99eeeda1c86..9b2c3ddce46 100644--- a/litellm/proxy/common_utils/debug_utils.py+++ b/litellm/proxy/common_utils/debug_utils.py@@ -50,7 +50,10 @@ def configure_gc_thresholds():configure_gc_thresholds()[email protected]("/debug/asyncio-tasks")+ "/debug/asyncio-tasks",+ dependencies=[Depends(user_api_key_auth)],+)async def get_active_tasks_stats():"""Returns:@@ -103,7 +106,11 @@ if os.environ.get("LITELLM_PROFILE", "false").lower() == "true":tracemalloc.start(10)- @router.get("/memory-usage", include_in_schema=False)+ @router.get(+ "/memory-usage",+ dependencies=[Depends(user_api_key_auth)],+ include_in_schema=False,+ )async def memory_usage():# Take a snapshot of the current memory usagesnapshot = tracemalloc.take_snapshot()@@ -711,7 +718,11 @@ async def configure_gc_thresholds_endpoint(}[email protected]("/otel-spans", include_in_schema=False)+ "/otel-spans",+ dependencies=[Depends(user_api_key_auth)],+ include_in_schema=False,+)async def get_otel_spans():from litellm.proxy.proxy_server import open_telemetry_loggerdiff --git a/litellm/proxy/health_endpoints/_health_endpoints.py b/litellm/proxy/health_endpoints/_health_endpoints.pyindex b4b5de1746e..6387d1b546f 100644--- a/litellm/proxy/health_endpoints/_health_endpoints.py+++ b/litellm/proxy/health_endpoints/_health_endpoints.py@@ -1237,14 +1237,9 @@ def callback_name(callback):return str(callback)- "/health/readiness",- tags=["health"],- dependencies=[Depends(user_api_key_auth)],-)-async def health_readiness():+async def _get_health_readiness_details() -> 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@@ -1263,7 +1258,7 @@ async def health_readiness():success_callback_names = litellm.success_callback# check Cache- cache_type = None+ cache_type: Any = Noneif litellm.cache is not None:from litellm.caching.caching import RedisSemanticCache@@ -1272,6 +1267,7 @@ async def health_readiness():if isinstance(litellm.cache.cache, RedisSemanticCache):# ping the cache# TODO: @ishaan-jaff - we should probably not ping the cache on every /health/readiness check+ index_info: Anytry:index_info = await litellm.cache.cache._index_info()except Exception as e:@@ -1310,6 +1306,30 @@ async def health_readiness():raise HTTPException(status_code=503, detail=f"Service Unhealthy ({str(e)})")+ "/health/readiness",+ tags=["health"],+)+async def health_readiness():+ """+ Public readiness probe. Keep this low-detail for unauthenticated load+ balancers while preserving the existing unauthenticated probe contract.+ """+ return {"status": "healthy"}+++ "/health/readiness/details",+ tags=["health"],+ dependencies=[Depends(user_api_key_auth)],+)+async def health_readiness_details():+ """+ Authenticated readiness diagnostics with DB/cache/callback metadata.+ """+ return await _get_health_readiness_details()++@router.get("/health/backlog",tags=["health"],@@ -1345,7 +1365,6 @@ async def health_liveliness():@router.options("/health/readiness",tags=["health"],- dependencies=[Depends(user_api_key_auth)],)async def health_readiness_options():"""diff --git a/litellm/proxy/middleware/prometheus_auth_middleware.py b/litellm/proxy/middleware/prometheus_auth_middleware.pyindex 6bdff59da52..529076ea478 100644--- a/litellm/proxy/middleware/prometheus_auth_middleware.py+++ b/litellm/proxy/middleware/prometheus_auth_middleware.py@@ -42,10 +42,29 @@ class PrometheusAuthMiddleware:if litellm.require_auth_for_metrics_endpoint is True:# Construct Request only when auth is actually neededrequest = Request(scope, receive)- api_key = request.headers.get(_AUTHORIZATION_HEADER) or ""try:- await user_api_key_auth(request=request, api_key=api_key)+ await user_api_key_auth(+ request=request,+ api_key=request.headers.get(_AUTHORIZATION_HEADER) or "",+ azure_api_key_header=request.headers.get(+ SpecialHeaders.azure_authorization.value+ )+ or "",+ anthropic_api_key_header=request.headers.get(+ SpecialHeaders.anthropic_authorization.value+ ),+ google_ai_studio_api_key_header=request.headers.get(+ SpecialHeaders.google_ai_studio_authorization.value+ ),+ azure_apim_header=request.headers.get(+ SpecialHeaders.azure_apim_authorization.value+ )+ or "",+ custom_litellm_key_header=request.headers.get(+ SpecialHeaders.custom_litellm_api_key.value+ ),+ )except Exception as e:# Send 401 response directly via ASGI protocolerror_message = getattr(e, "message", str(e))diff --git a/litellm/proxy/public_endpoints/public_endpoints.py b/litellm/proxy/public_endpoints/public_endpoints.pyindex d6ce454682e..dceee418198 100644--- a/litellm/proxy/public_endpoints/public_endpoints.py+++ b/litellm/proxy/public_endpoints/public_endpoints.py@@ -5,7 +5,7 @@ from importlib.resources import filesfrom typing import Any, Dict, List, Optionalimport litellm-from fastapi import APIRouter, Depends, HTTPException+from fastapi import APIRouter, Depends, HTTPException, Requestfrom litellm._logging import verbose_loggerfrom litellm.litellm_core_utils.get_blog_posts import (@@ -14,7 +14,12 @@ from litellm.litellm_core_utils.get_blog_posts import (GetBlogPosts,get_blog_posts,)-from litellm.proxy._types import CommonProxyErrors+from litellm.proxy._types import (+ CommonProxyErrors,+ LitellmUserRoles,+ SpecialHeaders,+ UserAPIKeyAuth,+)from litellm.proxy.auth.user_api_key_auth import user_api_key_authfrom litellm.types.agents import AgentCardfrom litellm.types.mcp import MCPPublicServer@@ -31,6 +36,37 @@ from litellm.types.utils import LlmProvidersrouter = APIRouter()++async def public_ai_hub_auth_dependency(request: Request) -> UserAPIKeyAuth:+ from litellm.proxy.proxy_server import general_settings++ if (general_settings or {}).get("require_auth_for_public_ai_hub") is True:+ return await user_api_key_auth(+ request=request,+ api_key=request.headers.get(SpecialHeaders.openai_authorization.value)+ or "",+ azure_api_key_header=request.headers.get(+ SpecialHeaders.azure_authorization.value+ )+ or "",+ anthropic_api_key_header=request.headers.get(+ SpecialHeaders.anthropic_authorization.value+ ),+ google_ai_studio_api_key_header=request.headers.get(+ SpecialHeaders.google_ai_studio_authorization.value+ ),+ azure_apim_header=request.headers.get(+ SpecialHeaders.azure_apim_authorization.value+ )+ or "",+ custom_litellm_key_header=request.headers.get(+ SpecialHeaders.custom_litellm_api_key.value+ ),+ )++ return UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER_VIEW_ONLY)++# ---------------------------------------------------------------------------# /public/endpoints — helpers# ---------------------------------------------------------------------------@@ -153,7 +189,7 @@ def _load_endpoints() -> List[Dict[str, Any]]:@router.get("/public/model_hub",tags=["public", "model management"],- dependencies=[Depends(user_api_key_auth)],+ dependencies=[Depends(public_ai_hub_auth_dependency)],response_model=List[ModelGroupInfoProxy],)async def public_model_hub():@@ -208,7 +244,7 @@ async def public_model_hub():@router.get("/public/agent_hub",tags=["[beta] Agents", "public"],- dependencies=[Depends(user_api_key_auth)],+ dependencies=[Depends(public_ai_hub_auth_dependency)],response_model=List[AgentCard],)async def get_agents():@@ -230,7 +266,7 @@ async def get_agents():@router.get("/public/mcp_hub",tags=["[beta] MCP", "public"],- dependencies=[Depends(user_api_key_auth)],+ dependencies=[Depends(public_ai_hub_auth_dependency)],response_model=List[MCPPublicServer],)async def get_mcp_servers():@@ -250,6 +286,7 @@ async def get_mcp_servers():@router.get("/public/skill_hub",tags=["public", "Claude Code Marketplace"],+ dependencies=[Depends(public_ai_hub_auth_dependency)],)async def public_skill_hub():"""Return enabled (public) Claude Code skills — no auth required."""@@ -296,6 +333,7 @@ async def public_skill_hub():@router.get("/public/model_hub/info",tags=["public", "model management"],+ dependencies=[Depends(public_ai_hub_auth_dependency)],response_model=PublicModelHubInfo,)async def public_model_hub_info():diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.pyindex 4b8b341a4bf..d030fabe8b5 100644--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@ -3079,7 +3079,11 @@ async def global_spend_models(return response[email protected]("/provider/budgets", response_model=ProviderBudgetResponse)+ "/provider/budgets",+ dependencies=[Depends(user_api_key_auth)],+ response_model=ProviderBudgetResponse,+)async def provider_budgets() -> ProviderBudgetResponse:"""Provider Budget Routing - Get Budget, Spend Details https://docs.litellm.ai/docs/proxy/provider_budget_routingdiff --git a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.pyindex eed4f076467..7354971e527 100644--- a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py+++ b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py@@ -183,6 +183,7 @@ ALLOWED_UI_SETTINGS_FIELDS = {# Flags that must be synced from the persisted UISettings into# general_settings at runtime (on both read and write)._RUNTIME_GENERAL_SETTINGS_FLAGS = [+ "require_auth_for_public_ai_hub","forward_client_headers_to_llm_api","forward_llm_provider_auth_headers","disable_agents_for_internal_users",diff --git a/tests/spend_tracking_tests/test_spend_accuracy_tests.py b/tests/spend_tracking_tests/test_spend_accuracy_tests.pyindex 15e00d93356..b50afeb843a 100644--- a/tests/spend_tracking_tests/test_spend_accuracy_tests.py+++ b/tests/spend_tracking_tests/test_spend_accuracy_tests.py@@ -128,8 +128,8 @@ async def get_spend_info(session, entity_type: str, entity_id: str):async def get_proxy_readiness(session):- """Fetch /health/readiness. Used both as a fail-fast gate and as a diagnostic on poll timeout."""- url = "http://0.0.0.0:4000/health/readiness"+ """Fetch authenticated readiness details. Used both as a fail-fast gate and as a diagnostic on poll timeout."""+ url = "http://0.0.0.0:4000/health/readiness/details"headers = {"Authorization": "Bearer sk-1234"}async with session.get(url, headers=headers) as response:return response.status, await response.json()@@ -140,7 +140,7 @@ async def assert_proxy_healthy(session):status, body = await get_proxy_readiness(session)if status != 200 or body.get("db") != "connected":pytest.fail(- f"Proxy /health/readiness unhealthy (status={status}). "+ f"Proxy /health/readiness/details unhealthy (status={status}). "f"Cannot run spend accuracy test. Response: {body}")print(f"Proxy readiness OK: {body}")diff --git a/tests/test_health.py b/tests/test_health.pyindex 00f095022b9..39c249370fa 100644--- a/tests/test_health.py+++ b/tests/test_health.py@@ -73,7 +73,6 @@ async def test_health_readiness():response_json = await response.json()print(response_json)- assert "litellm_version" in response_jsonassert "status" in response_jsonif status != 200:diff --git a/tests/test_litellm/proxy/auth/test_user_api_key_auth.py b/tests/test_litellm/proxy/auth/test_user_api_key_auth.pyindex 08f4bd0ebff..ae5d01dc2a6 100644--- a/tests/test_litellm/proxy/auth/test_user_api_key_auth.py+++ b/tests/test_litellm/proxy/auth/test_user_api_key_auth.py@@ -11,6 +11,7 @@ sys.path.insert(import pytest+import litellmimport litellm.proxy.proxy_serverfrom litellm.caching.dual_cache import DualCachefrom litellm.proxy._types import (@@ -25,6 +26,7 @@ from litellm.proxy._types import (from litellm.proxy.auth.handle_jwt import JWTHandlerfrom litellm.proxy.auth.route_checks import RouteChecksfrom litellm.proxy.auth.user_api_key_auth import (+ _route_requires_auth_despite_public,_run_centralized_common_checks,_run_post_custom_auth_checks,get_api_key,@@ -49,6 +51,32 @@ 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_route_requires_auth_despite_public_for_public_ai_hub():+ settings = {"require_auth_for_public_ai_hub": True}++ assert _route_requires_auth_despite_public("/public/model_hub", settings) is True+ assert _route_requires_auth_despite_public("/public/model_hub/", settings) is True+ assert (+ _route_requires_auth_despite_public("/public/model_hub/info", settings) is True+ )+ assert _route_requires_auth_despite_public("/public/agent_hub", settings) is True+ assert _route_requires_auth_despite_public("/public/mcp_hub", settings) is True+ assert _route_requires_auth_despite_public("/public/skill_hub", settings) is True++ assert _route_requires_auth_despite_public("/public/model_hub", {}) is False++@pytest.mark.asyncioasync def test_custom_auth_does_not_enforce_key_model_access_by_default():valid_token = UserAPIKeyAuth(token="test_token", models=["gpt-4o-mini"])@@ -1752,7 +1780,11 @@ async def test_team_metadata_refreshed_from_team_object_during_auth():from starlette.datastructures import URLfrom starlette.requests import Request- from litellm.proxy._types import LiteLLM_TeamTableCachedObj, LitellmUserRoles, UserAPIKeyAuth+ from litellm.proxy._types import (+ LiteLLM_TeamTableCachedObj,+ LitellmUserRoles,+ UserAPIKeyAuth,+ )from litellm.proxy.auth.user_api_key_auth import _user_api_key_auth_builderapi_key = "sk-test-team-metadata-refresh"@@ -1833,16 +1865,17 @@ async def test_team_metadata_refreshed_from_team_object_during_auth():request_data={},)- assert result.team_metadata == {"guardrails": ["test-guardrail-333"]}, (- f"team_metadata was not updated from fresh team object. Got: {result.team_metadata}"- )+ assert result.team_metadata == {+ "guardrails": ["test-guardrail-333"]+ }, f"team_metadata was not updated from fresh team object. Got: {result.team_metadata}"finally:for k, v in _originals.items():setattr(_proxy_server_mod, k, v)-++# ----------------------------------------------------------------------------+# _run_centralized_common_checks — centralized authz gate# ---------------------------------------------------------------------------@@ -2161,18 +2194,18 @@ async def test_centralized_common_checks_short_circuits_when_master_key_unset():@pytest.mark.asyncioasync def test_centralized_common_checks_skips_public_routes():- """Regression: public routes (e.g. /health/readiness) are exempted+ """Regression: public routes (e.g. /health/liveness) are exemptedby the builder fast-path. The wrapper must not retroactively runcommon_checks on top — the synthetic INTERNAL_USER_VIEW_ONLY tokenhas no user_id, so common_checks would reject the request as- admin-only. Breaks k8s readiness probes when master_key is set."""+ admin-only."""import litellm.proxy.proxy_server as _proxy_server_modfrom fastapi import Requestfrom starlette.datastructures import URLtoken = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER_VIEW_ONLY)request = Request(scope={"type": "http"})- request._url = URL(url="/health/readiness")+ request._url = URL(url="/health/liveness")attrs = _proxy_attrs_for_centralized_checks(user_custom_auth=None)originals = {a: getattr(_proxy_server_mod, a, None) for a in attrs}@@ -2187,7 +2220,7 @@ async def test_centralized_common_checks_skips_public_routes():user_api_key_auth_obj=token,request=request,request_data={},- route="/health/readiness",+ route="/health/liveness",)mock_checks.assert_not_awaited()finally:diff --git a/tests/test_litellm/proxy/health_endpoints/test_health_endpoints.py b/tests/test_litellm/proxy/health_endpoints/test_health_endpoints.pyindex ba260142351..d3c22ad6091 100644--- a/tests/test_litellm/proxy/health_endpoints/test_health_endpoints.py+++ b/tests/test_litellm/proxy/health_endpoints/test_health_endpoints.py@@ -11,10 +11,14 @@ sys.path.insert(import httpximport pytest+from fastapi import FastAPI+from fastapi.testclient import TestClientfrom prisma.errors import ClientNotConnectedError, HTTPClientClosedError, PrismaErrorimport litellm.proxy.health_endpoints._health_endpoints as _health_endpoints_module+from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy.auth.user_api_key_auth import user_api_key_authfrom litellm.proxy.health_endpoints._health_endpoints import (_db_health_readiness_check,get_callback_identifier,@@ -512,7 +516,7 @@ def proxy_client(monkeypatch):Redis cache:- If REDIS_HOST is set in environment, Redis cache will be automatically configured- - Cache configuration is included in /health/readiness endpoint response+ - Cache diagnostics are included in the authenticated /health/readiness/details response"""client = create_proxy_test_client(monkeypatch)with client:@@ -588,11 +592,7 @@ def test_health_liveness_endpoint(proxy_client):def test_health_readiness(proxy_client):"""Test /health/readiness endpoint.- Database and Redis are optional - the endpoint should work whether they're available or not.-- If DATABASE_URL is set, the endpoint will check database connectivity.- If REDIS_HOST is set, the endpoint will report cache status.- If neither is set, the endpoint should still return a valid health status.+ Database and Redis are optional - the public endpoint should work whether they're available or not."""# Measure the time taken for the health check callstart_time = time.perf_counter()@@ -614,40 +614,33 @@ def test_health_readiness(proxy_client):duration_ms < 500), f"Health check took {duration_ms:.2f}ms, expected < 500ms for readiness endpoint"- # Assert response contains expected fields+ # Assert response contains only low-detail public probe fieldsresponse_data = response.json()- assert "status" in response_data, "Response should contain 'status' field"- assert (- "litellm_version" in response_data- ), "Response should contain 'litellm_version' field"-- # Display all health endpoint response fields (matches what /health/readiness returns)- print("\n" + "-" * 60)- print("HEALTH ENDPOINT RESPONSE")- print("-" * 60)- print(f"Status: {response_data.get('status', 'unknown')}")- print(f"Database: {response_data.get('db', 'not reported')}")- print(f"LiteLLM Version: {response_data.get('litellm_version', 'unknown')}")- print(f"Success Callbacks: {response_data.get('success_callbacks', [])}")- print(f"Cache: {response_data.get('cache', 'none')}")- print(- f"Use AioHTTP Transport: {response_data.get('use_aiohttp_transport', 'unknown')}"- )+ assert response_data == {"status": "healthy"}print(f"Response time: {duration_ms:.2f}ms")- # If database status is reported, verify it's a valid status- # Database may be "connected", "disconnected", "unknown", or "Not connected" (when prisma_client is None)- if "db" in response_data:- db_status = response_data["db"]- # Database status can be any of these valid states- assert db_status in [- "connected",- "disconnected",- "unknown",- "Not connected",- ], f"Unexpected db status: {db_status}"-- print("=" * 60 + "\n")++def test_health_readiness_details_returns_diagnostic_fields(monkeypatch):+ """+ Detailed readiness diagnostics stay available behind the auth dependency.+ """+ app = FastAPI()+ app.include_router(_health_endpoints_module.router)+ app.dependency_overrides[user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN+ )+ client = TestClient(app)++ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)++ response = client.get("/health/readiness/details")++ assert response.status_code == 200, response.text+ response_data = response.json()+ assert response_data["status"] == "healthy"+ assert "litellm_version" in response_data+ assert "success_callbacks" in response_data+ assert "cache" in response_datadef test_get_callback_identifier_string_and_object_with_callback_name():diff --git a/tests/test_litellm/proxy/middleware/test_prometheus_auth_middleware.py b/tests/test_litellm/proxy/middleware/test_prometheus_auth_middleware.pyindex 9fd244d9c3f..d2804250303 100644--- a/tests/test_litellm/proxy/middleware/test_prometheus_auth_middleware.py+++ b/tests/test_litellm/proxy/middleware/test_prometheus_auth_middleware.py@@ -21,12 +21,12 @@ from litellm.proxy.middleware.prometheus_auth_middleware import PrometheusAuthMi# Fake auth functions to simulate valid and invalid auth behavior.-async def fake_valid_auth(request, api_key):+async def fake_valid_auth(request, api_key, **kwargs):# Simulate valid authentication: do nothing (i.e. pass)return-async def fake_invalid_auth(request, api_key):+async def fake_invalid_auth(request, api_key, **kwargs):print("running fake invalid auth", request, api_key)# Simulate invalid auth by raising an exception.raise Exception("Invalid API key")@@ -107,6 +107,25 @@ def test_invalid_auth_metrics(app_with_middleware, monkeypatch):assert "Unauthorized access to metrics endpoint" in response.text+def test_metrics_auth_uses_real_auth_when_route_is_public(+ app_with_middleware, monkeypatch+):+ """+ Regression: /metrics is statically public, but require_auth_for_metrics_endpoint+ must still force the real auth path.+ """+ monkeypatch.setattr(litellm, "require_auth_for_metrics_endpoint", True)+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", "sk-master")+ monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})++ client = TestClient(app_with_middleware)++ response = client.get("/metrics")++ assert response.status_code == 401, response.text+ assert "Unauthorized access to metrics endpoint" in response.text++def test_no_auth_metrics_when_disabled(app_with_middleware, monkeypatch):"""Test that when require_auth_for_metrics_endpoint is False, requests to /metricsdiff --git a/tests/test_litellm/proxy/public_endpoints/test_public_endpoints.py b/tests/test_litellm/proxy/public_endpoints/test_public_endpoints.pyindex a65462d3f9b..68ff88d60f6 100644--- a/tests/test_litellm/proxy/public_endpoints/test_public_endpoints.py+++ b/tests/test_litellm/proxy/public_endpoints/test_public_endpoints.py@@ -9,9 +9,15 @@ sys.path.insert(0, os.path.abspath("../../.."))from fastapi import FastAPIfrom fastapi.testclient import TestClient+from starlette.datastructures import URL+from starlette.requests import Request+from litellm.proxy._types import ProxyExceptionfrom litellm.proxy.auth.user_api_key_auth import user_api_key_authfrom litellm.proxy.public_endpoints import router+from litellm.proxy.public_endpoints.public_endpoints import (+ public_ai_hub_auth_dependency,+)from litellm.types.proxy.management_endpoints.model_management_endpoints import (ModelGroupInfoProxy,)@@ -91,6 +97,40 @@ def test_get_litellm_model_cost_map_returns_cost_map():)+def test_public_ai_hub_info_stays_public_by_default(monkeypatch):+ app = FastAPI()+ app.include_router(router)+ client = TestClient(app)++ monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", "sk-master")++ response = client.get("/public/model_hub/info")++ assert response.status_code == 200, response.text+++async def test_public_ai_hub_info_requires_auth_when_configured(monkeypatch):+ monkeypatch.setattr(+ "litellm.proxy.proxy_server.general_settings",+ {"require_auth_for_public_ai_hub": True},+ )+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", "sk-master")+ request = Request(+ scope={+ "type": "http",+ "method": "GET",+ "path": "/public/model_hub/info",+ "headers": [],+ }+ )+ request._url = URL(url="/public/model_hub/info")++ with pytest.raises(ProxyException):+ await public_ai_hub_auth_dependency(request)++def test_watsonx_provider_fields():"""Test that Watsonx provider has all required credential fields including multiple auth options."""app = FastAPI()@@ -166,9 +206,9 @@ def test_anthropic_provider_fields_support_byok():"Anthropic api_key must be optional so admins can configure BYOK models ""without entering a key. See BYOK tutorial.")- assert fields_by_key["api_key"].get("tooltip"), (- "Anthropic api_key must have a tooltip explaining the BYOK use case."- )+ assert fields_by_key["api_key"].get(+ "tooltip"+ ), "Anthropic api_key must have a tooltip explaining the BYOK use case."assert "api_base" in fields_by_key, ("Anthropic provider form must expose api_base so cloud customers ""can override the upstream URL without env var access."@@ -176,16 +216,16 @@ def test_anthropic_provider_fields_support_byok():api_base_field = fields_by_key["api_base"]assert api_base_field["required"] is Falseassert api_base_field["field_type"] == "text"- assert api_base_field.get("tooltip"), (- "api_base should have a tooltip explaining it is optional."- )+ assert api_base_field.get(+ "tooltip"+ ), "api_base should have a tooltip explaining it is optional."# UI forms render fields in credential_fields order; api_base should come first# so an admin sees the URL override before the key field.field_order = [f["key"] for f in anthropic["credential_fields"]]- assert field_order.index("api_base") < field_order.index("api_key"), (- "api_base must appear before api_key in credential_fields (matches AI21 and ANTHROPIC_TEXT convention)."- )+ assert field_order.index("api_base") < field_order.index(+ "api_key"+ ), "api_base must appear before api_key in credential_fields (matches AI21 and ANTHROPIC_TEXT convention)."def test_public_model_hub_with_healthy_model():diff --git a/tests/test_litellm/proxy/test_sensitive_route_auth.py b/tests/test_litellm/proxy/test_sensitive_route_auth.pynew file mode 100644index 00000000000..19998e52779--- /dev/null+++ b/tests/test_litellm/proxy/test_sensitive_route_auth.py@@ -0,0 +1,34 @@+from fastapi.routing import APIRoute++from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.common_utils.debug_utils import router as debug_router+from litellm.proxy.spend_tracking.spend_management_endpoints import (+ router as spend_router,+)+++def _get_route_dependency_calls(router, path: str, method: str):+ for route in router.routes:+ if (+ isinstance(route, APIRoute)+ and route.path == path+ and method in route.methods+ ):+ return [dependency.call for dependency in route.dependant.dependencies]+ raise AssertionError(f"Route {method} {path} not found")+++def test_sensitive_debug_routes_require_auth_dependency():+ for path, method in (+ ("/debug/asyncio-tasks", "GET"),+ ("/otel-spans", "GET"),+ ):+ assert user_api_key_auth in _get_route_dependency_calls(+ debug_router, path, method+ )+++def test_provider_budgets_requires_auth_dependency():+ assert user_api_key_auth in _get_route_dependency_calls(+ spend_router, "/provider/budgets", "GET"+ )diff --git a/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py b/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.pyindex 5fdcb9456df..bd35488fc3f 100644--- a/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py+++ b/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py@@ -1147,6 +1147,43 @@ class TestProxySettingEndpoints:assert response.status_code == 200assert general_settings.get("forward_llm_provider_auth_headers") is True+ def test_update_ui_settings_syncs_public_ai_hub_auth_to_general_settings(+ self, mock_auth, monkeypatch+ ):+ """Public AI Hub auth flag must be synced so public-route auth checks see it."""+ from unittest.mock import AsyncMock, MagicMock++ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.proxy.auth.user_api_key_auth import user_api_key_auth++ mock_user_auth = UserAPIKeyAuth(+ user_id="test-user-123",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ )+ app.dependency_overrides[user_api_key_auth] = lambda: mock_user_auth++ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", True)++ general_settings: dict = {}+ monkeypatch.setattr(+ "litellm.proxy.proxy_server.general_settings", general_settings+ )++ mock_prisma = MagicMock()+ mock_prisma.db.litellm_uisettings.upsert = AsyncMock()+ mock_prisma.db.litellm_uisettings.find_unique = AsyncMock(return_value=None)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)++ payload = {"require_auth_for_public_ai_hub": True}++ try:+ response = client.patch("/update/ui_settings", json=payload)+ finally:+ app.dependency_overrides.clear()++ assert response.status_code == 200+ assert general_settings.get("require_auth_for_public_ai_hub") is True+def test_update_ui_settings_persists_and_syncs_disable_key_generate_for_org_admin(self, mock_auth, monkeypatch):