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
test: add coverage for credential leak prevention changes
userb16d0b1d5ea5
diff --git a/litellm/llms/vertex_ai/vertex_llm_base.py b/litellm/llms/vertex_ai/vertex_llm_base.pyindex 430cc27adc8..46f4a807cd7 100644--- a/litellm/llms/vertex_ai/vertex_llm_base.py+++ b/litellm/llms/vertex_ai/vertex_llm_base.py@@ -412,7 +412,7 @@ class VertexBase:url = "{}/models/{}:{}".format(api_base, model, endpoint)if gemini_api_key is None:raise ValueError(- "Missing gemini_api_key, please set `GEMINI_API_KEY`"+ "Missing Gemini API key. Set the GEMINI_API_KEY or GOOGLE_API_KEY environment variable.")if gemini_api_key is not None:auth_header = {"x-goog-api-key": gemini_api_key} # type: ignore[assignment]@@ -469,6 +469,10 @@ class VertexBase:"""version: Optional[Literal["v1beta1", "v1"]] = Noneif custom_llm_provider == "gemini":+ if not gemini_api_key:+ raise ValueError(+ "Missing Gemini API key. Set the GEMINI_API_KEY or GOOGLE_API_KEY environment variable."+ )url, endpoint = _get_gemini_url(mode=mode,model=model,diff --git a/tests/test_litellm/interactions/test_gemini_interactions_transformation.py b/tests/test_litellm/interactions/test_gemini_interactions_transformation.pynew file mode 100644index 00000000000..465334d26fe--- /dev/null+++ b/tests/test_litellm/interactions/test_gemini_interactions_transformation.py@@ -0,0 +1,148 @@+"""+Tests for Gemini Interactions API transformation.++Covers credential leak prevention changes:+- validate_environment sets x-goog-api-key header+- get_complete_url excludes API key from URL+- get/delete/cancel interaction request URLs exclude API key+"""++import os+import sys+from unittest.mock import patch++import pytest++sys.path.insert(0, os.path.abspath("../../.."))++from litellm.llms.gemini.interactions.transformation import (+ GoogleAIStudioInteractionsConfig,+)+from litellm.types.router import GenericLiteLLMParams++_PATCH_GET_API_KEY = "litellm.llms.gemini.common_utils.GeminiModelInfo.get_api_key"+++def config():+ return GoogleAIStudioInteractionsConfig()+++class TestValidateEnvironment:+ def test_sets_x_goog_api_key_header(self, config):+ litellm_params = GenericLiteLLMParams(api_key="test-api-key-123")++ headers = config.validate_environment(+ headers={},+ model="gemini-2.5-flash",+ litellm_params=litellm_params,+ )++ assert headers["x-goog-api-key"] == "test-api-key-123"+ assert headers["Content-Type"] == "application/json"++ def test_no_api_key_skips_header(self, config):+ litellm_params = GenericLiteLLMParams(api_key=None)++ with patch(_PATCH_GET_API_KEY, return_value=None):+ headers = config.validate_environment(+ headers={},+ model="gemini-2.5-flash",+ litellm_params=litellm_params,+ )++ assert "x-goog-api-key" not in headers+ assert headers["Content-Type"] == "application/json"++ def test_no_litellm_params_skips_header(self, config):+ headers = config.validate_environment(+ headers={},+ model="gemini-2.5-flash",+ litellm_params=None,+ )++ assert "x-goog-api-key" not in headers+ assert headers["Content-Type"] == "application/json"++ def test_preserves_existing_headers(self, config):+ litellm_params = GenericLiteLLMParams(api_key="test-key")++ headers = config.validate_environment(+ headers={"X-Custom": "value"},+ model="gemini-2.5-flash",+ litellm_params=litellm_params,+ )++ assert headers["X-Custom"] == "value"+ assert headers["x-goog-api-key"] == "test-key"+++class TestGetCompleteUrl:+ def test_url_excludes_api_key(self, config):+ with patch(_PATCH_GET_API_KEY, return_value="secret-key"):+ url = config.get_complete_url(+ api_base=None,+ model="gemini-2.5-flash",+ litellm_params={"api_key": "secret-key"},+ )++ assert "key=" not in url+ assert "secret-key" not in url+ assert url.endswith("/interactions")++ def test_stream_url_has_alt_sse_only(self, config):+ with patch(_PATCH_GET_API_KEY, return_value="secret-key"):+ url = config.get_complete_url(+ api_base=None,+ model="gemini-2.5-flash",+ litellm_params={"api_key": "secret-key"},+ stream=True,+ )++ assert "key=" not in url+ assert "secret-key" not in url+ assert "alt=sse" in url++ def test_raises_without_api_key(self, config):+ with patch(_PATCH_GET_API_KEY, return_value=None):+ with pytest.raises(ValueError, match="Google API key is required"):+ config.get_complete_url(+ api_base=None,+ model="gemini-2.5-flash",+ litellm_params={"api_key": None},+ )+++class TestInteractionOperationUrls:+ """Test that get/delete/cancel interaction URLs exclude API key."""++ @pytest.mark.parametrize(+ "method_name,interaction_id,expected_suffix",+ [+ ("transform_get_interaction_request", "interaction-123", "interaction-123"),+ ("transform_delete_interaction_request", "interaction-456", "interaction-456"),+ ("transform_cancel_interaction_request", "interaction-789", "interaction-789:cancel"),+ ],+ )+ def test_url_excludes_key(self, config, method_name, interaction_id, expected_suffix):+ with patch(_PATCH_GET_API_KEY, return_value="secret-key"):+ url, params = getattr(config, method_name)(+ interaction_id=interaction_id,+ api_base="https://generativelanguage.googleapis.com",+ litellm_params=GenericLiteLLMParams(api_key="secret-key"),+ headers={},+ )++ assert "key=" not in url+ assert "secret-key" not in url+ assert expected_suffix in url++ def test_get_interaction_raises_without_key(self, config):+ with patch(_PATCH_GET_API_KEY, return_value=None):+ with pytest.raises(ValueError, match="Google API key is required"):+ config.transform_get_interaction_request(+ interaction_id="interaction-123",+ api_base="https://generativelanguage.googleapis.com",+ litellm_params=GenericLiteLLMParams(api_key=None),+ headers={},+ )diff --git a/tests/test_litellm/llms/custom_httpx/test_credential_leak_prevention.py b/tests/test_litellm/llms/custom_httpx/test_credential_leak_prevention.pynew file mode 100644index 00000000000..543559422b0--- /dev/null+++ b/tests/test_litellm/llms/custom_httpx/test_credential_leak_prevention.py@@ -0,0 +1,234 @@+"""+Tests for credential leak prevention in HTTP handlers.++Covers:+- MaskedHTTPStatusError construction and masking behavior+- _safe_get_response_text, _safe_aread_response, _safe_read_response helpers+- _raise_masked_sync_error and _raise_masked_async_error+"""++import os+import sys+from unittest.mock import AsyncMock, MagicMock, patch++import httpx+import pytest++sys.path.insert(0, os.path.abspath("../../../.."))++from litellm.llms.custom_httpx.http_handler import (+ AsyncHTTPHandler,+ HTTPHandler,+ MaskedHTTPStatusError,+ _raise_masked_async_error,+ _raise_masked_sync_error,+ _safe_aread_response,+ _safe_get_response_text,+ _safe_read_response,+)+++def _make_httpx_status_error(+ status_code: int = 400,+ url: str = "https://example.com/v1/models?key=SECRET_KEY_123",+ body: str = "Bad Request",+) -> httpx.HTTPStatusError:+ """Create a real httpx.HTTPStatusError for testing."""+ request = httpx.Request("POST", url)+ response = httpx.Response(status_code, request=request, content=body.encode())+ return httpx.HTTPStatusError(+ message=f"Client error '{status_code}' for url '{url}'",+ request=request,+ response=response,+ )+++class TestMaskedHTTPStatusError:+ def test_masks_url_in_request(self):+ orig = _make_httpx_status_error(url="https://api.example.com?key=MY_SECRET")+ masked = MaskedHTTPStatusError(orig)++ assert "MY_SECRET" not in str(masked.request.url)+ assert "[REDACTED_API_KEY]" in str(masked.request.url)++ def test_masks_original_message(self):+ orig = _make_httpx_status_error(url="https://api.example.com?key=SUPER_SECRET")+ masked = MaskedHTTPStatusError(orig)++ assert "SUPER_SECRET" not in str(masked)+ assert "[REDACTED_API_KEY]" in str(masked)++ def test_preserves_status_code(self):+ orig = _make_httpx_status_error(status_code=403)+ masked = MaskedHTTPStatusError(orig)++ assert masked.status_code == 403+ assert masked.response.status_code == 403++ def test_preserves_message_and_text_attrs(self):+ orig = _make_httpx_status_error()+ masked = MaskedHTTPStatusError(orig, message="custom msg", text="custom text")++ assert masked.message == "custom msg"+ assert masked.text == "custom text"++ def test_handles_response_content_decompression_failure(self):+ """If response.content raises (e.g. zlib error), should fall back to b''."""+ orig = _make_httpx_status_error()++ with patch.object(+ type(orig.response), "content",+ new_callable=lambda: property(lambda self: (_ for _ in ()).throw(Exception("zlib error"))),+ ):+ masked = MaskedHTTPStatusError(orig)++ assert masked.response.content == b""+ assert masked.status_code == 400+++class TestSafeResponseHelpers:+ def test_safe_get_response_text_normal(self):+ response = httpx.Response(200, content=b"hello world")+ assert _safe_get_response_text(response) == "hello world"++ def test_safe_get_response_text_error(self):+ response = MagicMock(spec=httpx.Response)+ type(response).text = property(lambda self: (_ for _ in ()).throw(UnicodeDecodeError("utf-8", b"", 0, 1, "bad")))+ assert _safe_get_response_text(response) == ""++ def test_safe_read_response_normal(self):+ response = httpx.Response(200, content=b"raw bytes")+ result = _safe_read_response(response)+ assert result == b"raw bytes"++ def test_safe_read_response_error(self):+ response = MagicMock(spec=httpx.Response)+ response.read.side_effect = Exception("read failure")+ assert _safe_read_response(response) == b""++ @pytest.mark.asyncio+ async def test_safe_aread_response_normal(self):+ response = MagicMock(spec=httpx.Response)+ response.aread = AsyncMock(return_value=b"async bytes")+ result = await _safe_aread_response(response)+ assert result == b"async bytes"++ @pytest.mark.asyncio+ async def test_safe_aread_response_error(self):+ response = MagicMock(spec=httpx.Response)+ response.aread = AsyncMock(side_effect=Exception("async read failure"))+ result = await _safe_aread_response(response)+ assert result == b""+++class TestRaiseMaskedError:+ def test_sync_non_stream(self):+ orig = _make_httpx_status_error(+ url="https://api.example.com?key=LEAKED_KEY", body="error body"+ )+ with pytest.raises(MaskedHTTPStatusError) as exc_info:+ _raise_masked_sync_error(orig, stream=False)++ err = exc_info.value+ assert "LEAKED_KEY" not in str(err.request.url)+ assert err.status_code == 400+ assert err.text == "error body"++ def test_sync_stream(self):+ orig = _make_httpx_status_error(+ url="https://api.example.com?key=LEAKED_KEY", body="stream body"+ )+ with pytest.raises(MaskedHTTPStatusError) as exc_info:+ _raise_masked_sync_error(orig, stream=True)++ err = exc_info.value+ assert "LEAKED_KEY" not in str(err.request.url)+ assert err.message is not None++ def test_sync_breaks_exception_chain(self):+ orig = _make_httpx_status_error()+ with pytest.raises(MaskedHTTPStatusError) as exc_info:+ _raise_masked_sync_error(orig, stream=False)++ assert exc_info.value.__cause__ is None++ @pytest.mark.asyncio+ async def test_async_non_stream(self):+ orig = _make_httpx_status_error(+ url="https://api.example.com?key=LEAKED_KEY", body="async error"+ )+ with pytest.raises(MaskedHTTPStatusError) as exc_info:+ await _raise_masked_async_error(orig, stream=False)++ err = exc_info.value+ assert "LEAKED_KEY" not in str(err.request.url)+ assert err.status_code == 400+ assert err.text == "async error"++ @pytest.mark.asyncio+ async def test_async_stream(self):+ orig = _make_httpx_status_error(+ url="https://api.example.com?key=LEAKED_KEY", body="async stream"+ )+ with pytest.raises(MaskedHTTPStatusError) as exc_info:+ await _raise_masked_async_error(orig, stream=True)++ err = exc_info.value+ assert "LEAKED_KEY" not in str(err.request.url)+ assert err.message is not None++ @pytest.mark.asyncio+ async def test_async_breaks_chain(self):+ orig = _make_httpx_status_error()+ with pytest.raises(MaskedHTTPStatusError) as exc_info:+ await _raise_masked_async_error(orig, stream=False)++ assert exc_info.value.__cause__ is None+++class TestHTTPHandlerErrorPaths:+ """Test that HTTP handler methods raise MaskedHTTPStatusError on HTTPStatusError."""++ @pytest.fixture+ def sync_handler(self):+ handler = HTTPHandler()+ yield handler+ handler.close()++ @pytest.fixture+ async def async_handler(self):+ handler = AsyncHTTPHandler()+ yield handler+ await handler.close()++ @pytest.mark.parametrize("method", ["post", "put", "patch", "delete"])+ def test_sync_raises_masked_error(self, sync_handler, method):+ with patch.object(+ sync_handler.client,+ "send",+ side_effect=_make_httpx_status_error(url="https://api.test.com?key=SECRET"),+ ):+ with pytest.raises(MaskedHTTPStatusError) as exc_info:+ kwargs = {"url": "https://api.test.com?key=SECRET"}+ if method != "delete":+ kwargs["data"] = {"test": 1}+ getattr(sync_handler, method)(**kwargs)++ assert "SECRET" not in str(exc_info.value.request.url)++ @pytest.mark.parametrize("method", ["post", "put", "patch", "delete"])+ @pytest.mark.asyncio+ async def test_async_raises_masked_error(self, async_handler, method):+ with patch.object(+ async_handler.client,+ "send",+ new_callable=AsyncMock,+ side_effect=_make_httpx_status_error(url="https://api.test.com?key=SECRET"),+ ):+ with pytest.raises(MaskedHTTPStatusError) as exc_info:+ kwargs = {"url": "https://api.test.com?key=SECRET"}+ if method != "delete":+ kwargs["data"] = {"test": 1}+ await getattr(async_handler, method)(**kwargs)++ assert "SECRET" not in str(exc_info.value.request.url)diff --git a/tests/test_litellm/test_redact_string_in_error_paths.py b/tests/test_litellm/test_redact_string_in_error_paths.pynew file mode 100644index 00000000000..7d402ee68f1--- /dev/null+++ b/tests/test_litellm/test_redact_string_in_error_paths.py@@ -0,0 +1,245 @@+"""+Tests for _redact_string usage in error/logging paths.++Covers actual execution of redaction in:+- WebSocket close reasons in realtime handlers (openai, azure, bedrock)+- Gemini RAG ingestion x-goog-api-key header usage+- Traceback redaction pattern used in proxy streaming+"""++import os+import sys+import traceback+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++sys.path.insert(0, os.path.abspath("../.."))++from litellm._logging import _ENABLE_SECRET_REDACTION, _redact_string+++class TestRedactStringFunction:+ def test_redacts_bearer_token(self):+ text = "Authorization: Bearer sk-1234567890abcdefghij"+ result = _redact_string(text)+ assert "sk-1234567890abcdefghij" not in result+ assert "REDACTED" in result++ def test_redacts_api_key_in_url(self):+ text = "Error at https://example.com?api_key=my-secret-key-value-here"+ result = _redact_string(text)+ assert "my-secret-key-value-here" not in result++ def test_redacts_google_api_key(self):+ text = "key=AIzaSyB1234567890abcdefghijklmnopqrstuvwx"+ result = _redact_string(text)+ assert "AIzaSyB1234567890abcdefghijklmnopqrstuvwx" not in result++ def test_passes_clean_text_through(self):+ text = "This is a normal error message with no secrets"+ assert _redact_string(text) == text++ @pytest.mark.skipif(+ not _ENABLE_SECRET_REDACTION, reason="redaction disabled via env var"+ )+ def test_redaction_enabled_by_default(self):+ text = "Bearer sk-1234567890abcdefghij"+ result = _redact_string(text)+ assert "sk-1234567890abcdefghij" not in result+++class TestOpenAIRealtimeRedaction:+ """Test that OpenAI realtime handler redacts secrets in websocket close reasons."""++ def _make_patches(self, handler):+ """Shared patches for OpenAI realtime handler tests."""+ return (+ patch.object(handler, "_construct_url", return_value="wss://api.openai.com/v1/realtime?model=gpt-4"),+ patch.object(handler, "_get_ssl_config", return_value=None),+ patch.object(handler, "_get_additional_headers", return_value={}),+ )++ def _call_kwargs(self):+ return dict(+ model="gpt-4",+ websocket=AsyncMock(),+ logging_obj=MagicMock(),+ api_base="https://api.openai.com/",+ api_key="test-key",+ )++ @pytest.mark.asyncio+ async def test_invalid_status_code_redacts_reason(self):+ import websockets.exceptions++ from litellm.llms.openai.realtime.handler import OpenAIRealtime++ handler = OpenAIRealtime()+ exc = websockets.exceptions.InvalidStatusCode(403, None)+ exc.status_code = 403++ kwargs = self._call_kwargs()+ mock_ws = kwargs["websocket"]+ p1, p2, p3 = self._make_patches(handler)+ with p1, p2, p3, patch("websockets.connect", side_effect=exc):+ await handler.async_realtime(**kwargs)++ mock_ws.close.assert_called_once()+ assert mock_ws.close.call_args[1]["code"] == 403++ @pytest.mark.asyncio+ async def test_generic_exception_redacts_reason(self):+ from litellm.llms.openai.realtime.handler import OpenAIRealtime++ handler = OpenAIRealtime()+ secret_error = RuntimeError("Connection failed for api_key=sk-1234567890abcdefghij")++ kwargs = self._call_kwargs()+ mock_ws = kwargs["websocket"]+ p1, p2, p3 = self._make_patches(handler)+ with p1, p2, p3, patch("websockets.connect", side_effect=secret_error):+ await handler.async_realtime(**kwargs)++ mock_ws.close.assert_called_once()+ assert mock_ws.close.call_args[1]["code"] == 1011+ assert "sk-1234567890abcdefghij" not in mock_ws.close.call_args[1]["reason"]+++class TestAzureRealtimeRedaction:+ """Test that Azure realtime handler redacts secrets in websocket close reasons."""++ @pytest.mark.asyncio+ async def test_invalid_status_code_redacts_reason(self):+ import websockets.exceptions++ from litellm.llms.azure.realtime.handler import AzureOpenAIRealtime++ handler = AzureOpenAIRealtime()+ mock_ws = AsyncMock()+ exc = websockets.exceptions.InvalidStatusCode(403, None)+ exc.status_code = 403++ with patch.object(handler, "_construct_url", return_value="wss://test.openai.azure.com/openai/realtime"), \+ patch("websockets.connect", side_effect=exc):+ await handler.async_realtime(+ model="gpt-4",+ websocket=mock_ws,+ logging_obj=MagicMock(),+ api_base="https://test.openai.azure.com/",+ api_key="test-key",+ api_version="2024-10-01-preview",+ )++ mock_ws.close.assert_called_once()+ assert mock_ws.close.call_args[1]["code"] == 403+++class TestBedrockRealtimeRedaction:+ """Test that _redact_string produces safe close reasons for Bedrock-style errors."""++ def test_internal_error_message_redacted(self):+ secret_error = RuntimeError("Failed with aws_secret_access_key=AKIAIOSFODNN7EXAMPLE123456")+ reason = _redact_string(f"Internal error: {str(secret_error)}")+ assert "AKIAIOSFODNN7EXAMPLE123456" not in reason+++class TestLLMHTTPHandlerRealtimeRedaction:+ """Test _redact_string on the exact patterns used in llm_http_handler WS close."""++ def test_invalid_status_pattern(self):+ error_msg = "InvalidStatusCode: 403 for wss://api.example.com?api_key=sk-leaked-key-here"+ assert "sk-leaked-key-here" not in _redact_string(str(error_msg))++ def test_internal_server_error_pattern(self):+ error_msg = "Connection failed for api_key=sk-secret-key-12345678"+ assert "sk-secret-key-12345678" not in _redact_string(f"Internal server error: {error_msg}")+++class TestProxyStreamingDataGeneratorRedaction:+ """Test _redact_string on traceback.format_exc() — the pattern at common_request_processing.py:1733."""++ def test_redact_traceback_format_exc(self):+ try:+ raise RuntimeError(+ "Failed connecting to api_key=sk-1234567890abcdefghij at https://api.example.com"+ )+ except RuntimeError:+ raw_tb = traceback.format_exc()++ redacted_tb = _redact_string(raw_tb)++ assert "sk-1234567890abcdefghij" not in redacted_tb+ assert "Traceback" in redacted_tb+ assert "RuntimeError" in redacted_tb+++def _make_mock_ingest_options():+ mock = MagicMock()+ mock.vector_store_config = {}+ mock.ingest_name = "test"+ mock.chunking_strategy = None+ mock.embedding_model = None+ mock.vector_db_type = "gemini"+ return mock+++class TestGeminiIngestionHeaders:+ """Test that Gemini RAG ingestion uses x-goog-api-key header."""++ @pytest.mark.asyncio+ async def test_create_file_search_store_sends_header(self):+ from litellm.rag.ingestion.gemini_ingestion import GeminiRAGIngestion++ ingestion = GeminiRAGIngestion(ingest_options=_make_mock_ingest_options())++ mock_client = AsyncMock()+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"name": "fileSearchStores/abc123"}+ mock_client.post.return_value = mock_response++ with patch(+ "litellm.rag.ingestion.gemini_ingestion.get_async_httpx_client",+ return_value=mock_client,+ ):+ result = await ingestion._create_file_search_store(+ api_key="test-gemini-key",+ base_url="https://generativelanguage.googleapis.com/v1beta",+ display_name="test-store",+ )++ assert result == "fileSearchStores/abc123"+ call_kwargs = mock_client.post.call_args+ assert call_kwargs[1]["headers"]["x-goog-api-key"] == "test-gemini-key"+ assert "key=" not in call_kwargs[0][0]++ @pytest.mark.asyncio+ async def test_initiate_resumable_upload_sends_header(self):+ from litellm.rag.ingestion.gemini_ingestion import GeminiRAGIngestion++ ingestion = GeminiRAGIngestion(ingest_options=_make_mock_ingest_options())++ mock_client = AsyncMock()+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.headers = {"x-goog-upload-url": "https://upload.example.com/upload123"}+ mock_client.post.return_value = mock_response++ with patch(+ "litellm.rag.ingestion.gemini_ingestion.get_async_httpx_client",+ return_value=mock_client,+ ):+ result = await ingestion._initiate_resumable_upload(+ api_key="test-gemini-key",+ base_url="https://generativelanguage.googleapis.com/v1beta",+ vector_store_id="fileSearchStores/abc123",+ filename="test.txt",+ file_size=1024,+ content_type="text/plain",+ )++ assert result == "https://upload.example.com/upload123"+ call_kwargs = mock_client.post.call_args+ assert call_kwargs[1]["headers"]["x-goog-api-key"] == "test-gemini-key"+ assert "key=" not in call_kwargs[0][0]