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
[Security Bug Fix] Ensure only LLM API route fails get logged on Langfuse (and other loggers) (#12308)
Ishaan Jaffff7dd1756a9f
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex b5befbaeb83..5fddd47c071 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -54,8 +54,6 @@ from litellm import ()from litellm._logging import verbose_proxy_loggerfrom litellm._service_logger import ServiceLogging, ServiceTypes-from litellm.litellm_core_utils.safe_json_dumps import safe_dumps-from litellm.litellm_core_utils.safe_json_loads import safe_json_loadsfrom litellm.caching.caching import DualCache, RedisCachefrom litellm.exceptions import RejectedRequestErrorfrom litellm.integrations.custom_guardrail import CustomGuardrail@@ -63,6 +61,8 @@ from litellm.integrations.custom_logger import CustomLoggerfrom litellm.integrations.SlackAlerting.slack_alerting import SlackAlertingfrom litellm.integrations.SlackAlerting.utils import _add_langfuse_trace_id_to_alertfrom litellm.litellm_core_utils.litellm_logging import Logging+from litellm.litellm_core_utils.safe_json_dumps import safe_dumps+from litellm.litellm_core_utils.safe_json_loads import safe_json_loadsfrom litellm.llms.custom_httpx.httpx_handler import HTTPHandlerfrom litellm.proxy._types import (AlertType,@@ -71,6 +71,7 @@ from litellm.proxy._types import (Member,UserAPIKeyAuth,)+from litellm.proxy.auth.route_checks import RouteChecksfrom litellm.proxy.db.create_views import (create_missing_views,should_create_missing_views,@@ -843,8 +844,10 @@ class ProxyLogging:)### LOGGING ###- if self._is_proxy_only_error(- original_exception=original_exception, error_type=error_type+ if self._is_proxy_only_llm_api_error(+ original_exception=original_exception,+ error_type=error_type,+ route=user_api_key_dict.request_route,):await self._handle_logging_proxy_only_error(request_data=request_data,@@ -877,13 +880,14 @@ class ProxyLogging:)return- def _is_proxy_only_error(+ def _is_proxy_only_llm_api_error(self,original_exception: Exception,error_type: Optional[ProxyErrorTypes] = None,+ route: Optional[str] = None,) -> bool:"""- Return True if the error is a Proxy Only Error+ Return True if the error is a Proxy Only LLM API ErrorPrevents double logging of LLM API exceptions@@ -891,6 +895,19 @@ class ProxyLogging:- Authentication Errors from user_api_key_auth- HTTP HTTPException (rate limit errors)"""++ #########################################################+ # Only log LLM API errors for proxy level hooks+ # eg. Authentication errors, rate limit errors, etc.+ # Note: This fixes a security issue where we+ # would log temporary keys/auth info+ # from management endpoints+ #########################################################+ if route is None:+ return False+ if RouteChecks.is_llm_api_route(route) is not True:+ return False+return isinstance(original_exception, HTTPException) or (error_type == ProxyErrorTypes.auth_error)diff --git a/tests/proxy_unit_tests/test_proxy_reject_logging.py b/tests/proxy_unit_tests/test_proxy_reject_logging.pyindex aa43e245170..d4f8d6d9aaa 100644--- a/tests/proxy_unit_tests/test_proxy_reject_logging.py+++ b/tests/proxy_unit_tests/test_proxy_reject_logging.py@@ -163,7 +163,10 @@ async def test_chat_completion_request_with_redaction(route, body):response = await chat_completion(request=request,user_api_key_dict=UserAPIKeyAuth(- api_key="sk-12345", token="hashed_sk-12345", rpm_limit=0+ api_key="sk-12345",+ token="hashed_sk-12345",+ rpm_limit=0,+ request_route=route,),fastapi_response=Response(),)@@ -171,7 +174,7 @@ async def test_chat_completion_request_with_redaction(route, body):response = await completion(request=request,user_api_key_dict=UserAPIKeyAuth(- api_key="sk-12345", token="hashed_sk-12345", rpm_limit=0+ api_key="sk-12345", token="hashed_sk-12345", rpm_limit=0, request_route=route),fastapi_response=Response(),)@@ -179,7 +182,7 @@ async def test_chat_completion_request_with_redaction(route, body):response = await embeddings(request=request,user_api_key_dict=UserAPIKeyAuth(- api_key="sk-12345", token="hashed_sk-12345", rpm_limit=0+ api_key="sk-12345", token="hashed_sk-12345", rpm_limit=0, request_route=route),fastapi_response=Response(),)diff --git a/tests/proxy_unit_tests/test_proxy_utils.py b/tests/proxy_unit_tests/test_proxy_utils.pyindex 13b2f0e65b0..79dad600373 100644--- a/tests/proxy_unit_tests/test_proxy_utils.py+++ b/tests/proxy_unit_tests/test_proxy_utils.py@@ -1916,3 +1916,110 @@ async def test_get_admin_team_ids()else:mock_prisma_client.db.litellm_teamtable.find_many.assert_not_called()+++async def test_post_call_failure_hook_auth_error_key_info_route():+ """+ Test that post_call_failure_hook does NOT call _handle_logging_proxy_only_error+ when we get an auth error from /key/info route (since it's not an LLM API route).+ """+ from litellm.proxy.utils import ProxyLogging+ from litellm.proxy._types import ProxyErrorTypes+ from litellm.caching.caching import DualCache+ from fastapi import HTTPException+ from unittest.mock import Mock, patch, AsyncMock++ # Setup+ cache = DualCache()+ proxy_logging = ProxyLogging(user_api_key_cache=cache)++ # Mock the _handle_logging_proxy_only_error method+ with patch.object(proxy_logging, '_handle_logging_proxy_only_error', new_callable=AsyncMock) as mock_handle_logging:+ # Create an auth error (HTTPException)+ auth_error = HTTPException(+ status_code=401,+ detail="Authentication Error: invalid user key"+ )++ # Create request data for /key/info route+ request_data = {+ "route": "/key/info",+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "test"}],+ "litellm_call_id": "test_call_id_123"+ }++ # Create user API key dict+ user_api_key_dict = UserAPIKeyAuth(+ api_key="test_key",+ user_id="test_user",+ token="test_token"+ )++ # Call post_call_failure_hook with auth error from /key/info route+ await proxy_logging.post_call_failure_hook(+ request_data=request_data,+ original_exception=auth_error,+ user_api_key_dict=user_api_key_dict,+ error_type=ProxyErrorTypes.auth_error,+ route="/key/info"+ )++ # Assert that _handle_logging_proxy_only_error was NOT called+ # because /key/info is not an LLM API route+ mock_handle_logging.assert_not_called()+++async def test_post_call_failure_hook_auth_error_llm_api_route():+ """+ Test that post_call_failure_hook DOES call _handle_logging_proxy_only_error+ when we get an auth error from /v1/chat/completions route (since it is an LLM API route).+ """+ from litellm.proxy.utils import ProxyLogging+ from litellm.proxy._types import ProxyErrorTypes+ from litellm.caching.caching import DualCache+ from fastapi import HTTPException+ from unittest.mock import Mock, patch, AsyncMock++ # Setup+ cache = DualCache()+ proxy_logging = ProxyLogging(user_api_key_cache=cache)++ # Mock the _handle_logging_proxy_only_error method+ with patch.object(proxy_logging, '_handle_logging_proxy_only_error', new_callable=AsyncMock) as mock_handle_logging:+ # Create an auth error (HTTPException)+ auth_error = HTTPException(+ status_code=401,+ detail="Authentication Error: invalid user key"+ )++ # Create request data for /v1/chat/completions route+ request_data = {+ "route": "/v1/chat/completions",+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "test"}],+ "litellm_call_id": "test_call_id_123"+ }++ # Create user API key dict+ user_api_key_dict = UserAPIKeyAuth(+ api_key="test_key",+ user_id="test_user",+ token="test_token",+ request_route="/v1/chat/completions"+ )++ # Call post_call_failure_hook with auth error from /v1/chat/completions route+ await proxy_logging.post_call_failure_hook(+ request_data=request_data,+ original_exception=auth_error,+ user_api_key_dict=user_api_key_dict,+ error_type=ProxyErrorTypes.auth_error,+ route="/v1/chat/completions"+ )++ # Assert that _handle_logging_proxy_only_error WAS called+ # because /v1/chat/completions is an LLM API route+ mock_handle_logging.assert_called_once()diff --git a/tests/test_litellm/proxy/test_proxy_utils.py b/tests/test_litellm/proxy/test_proxy_utils.pyindex b6e9f6f6ee6..eb29ed51a97 100644--- a/tests/test_litellm/proxy/test_proxy_utils.py+++ b/tests/test_litellm/proxy/test_proxy_utils.py@@ -3,7 +3,11 @@ import osimport sysimport pytest-from fastapi.testclient import TestClient+from fastapi import HTTPException++from litellm.caching.caching import DualCache+from litellm.proxy._types import ProxyErrorTypes+from litellm.proxy.utils import ProxyLoggingsys.path.insert(0, os.path.abspath("../../..")@@ -19,3 +23,37 @@ def test_get_custom_url(monkeypatch):monkeypatch.setenv("SERVER_ROOT_PATH", "/litellm")custom_url = get_custom_url(request_base_url="http://0.0.0.0:4000", route="ui/")assert custom_url == "http://0.0.0.0:4000/litellm/ui/"++++def test_proxy_only_error_true_for_llm_route():+ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())+ assert proxy_logging_obj._is_proxy_only_llm_api_error(+ original_exception=Exception(),+ error_type=ProxyErrorTypes.auth_error,+ route="/v1/chat/completions",+ )+++def test_proxy_only_error_false_for_non_llm_route():+ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())+ assert (+ proxy_logging_obj._is_proxy_only_llm_api_error(+ original_exception=Exception(),+ error_type=ProxyErrorTypes.auth_error,+ route="/key/info",+ )+ is False+ )+++def test_proxy_only_error_false_for_other_error_type():+ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())+ assert (+ proxy_logging_obj._is_proxy_only_llm_api_error(+ original_exception=Exception(),+ error_type=None,+ route="/v1/chat/completions",+ )+ is False+ )