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(httpx): set response.request and strip content-encoding in MaskedHTTPStatusError

Yuneng Jiangc8cfc5de2168
diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py
index 859afcfe7e5..47b06990963 100644
--- a/litellm/llms/custom_httpx/http_handler.py
+++ b/litellm/llms/custom_httpx/http_handler.py
@@ -367,24 +367,39 @@ class MaskedHTTPStatusError(httpx.HTTPStatusError):
# Mask the original exception message too (it contains the full URL)
masked_original_message = mask_sensitive_info(str(original_error))
- # Safely access response content — decompression can fail (e.g. zlib error)
+ # Safely access response content — decompression can fail (e.g. zlib error).
+ # `.content` returns already-decoded bytes, so we must strip transport
+ # encoding headers before rebuilding the Response (otherwise httpx will
+ # try to decode the bytes a second time and raise DecodingError).
try:
response_content = original_error.response.content
except Exception:
response_content = b""
+ response_headers = {
+ k: v
+ for k, v in original_error.response.headers.items()
+ if k.lower() not in ("content-encoding", "content-length")
+ }
+
+ masked_request = httpx.Request(
+ method=original_error.request.method,
+ url=masked_url,
+ headers=original_error.request.headers,
+ content=original_error.request.content,
+ )
+
super().__init__(
message=masked_original_message,
- request=httpx.Request(
- method=original_error.request.method,
- url=masked_url,
- headers=original_error.request.headers,
- content=original_error.request.content,
- ),
+ request=masked_request,
+ # Attach the masked request so `response.request` is set — otherwise
+ # downstream code that inspects err.response.request (e.g.
+ # exception_mapping_utils) hits `RuntimeError: .request not set`.
response=httpx.Response(
status_code=original_error.response.status_code,
content=response_content,
- headers=original_error.response.headers,
+ headers=response_headers,
+ request=masked_request,
),
)
self.message = message
@@ -912,9 +927,9 @@ class AsyncHTTPHandler:
if AIOHTTP_CONNECTOR_LIMIT > 0:
transport_connector_kwargs["limit"] = AIOHTTP_CONNECTOR_LIMIT
if AIOHTTP_CONNECTOR_LIMIT_PER_HOST > 0:
- transport_connector_kwargs[
- "limit_per_host"
- ] = AIOHTTP_CONNECTOR_LIMIT_PER_HOST
+ transport_connector_kwargs["limit_per_host"] = (
+ AIOHTTP_CONNECTOR_LIMIT_PER_HOST
+ )
return LiteLLMAiohttpTransport(
client=lambda: ClientSession(
diff --git a/tests/local_testing/test_custom_callback_input.py b/tests/local_testing/test_custom_callback_input.py
index c6dab28e3c7..15a2975becc 100644
--- a/tests/local_testing/test_custom_callback_input.py
+++ b/tests/local_testing/test_custom_callback_input.py
@@ -1410,15 +1410,13 @@ def test_logging_key_masking_gemini():
mock_client.assert_called()
- print(f"mock_client.call_args.kwargs: {mock_client.call_args.kwargs}")
- assert (
- "LEAVE_ONLY_LAST_4_CHAR_UNMASKED_THIS_PART"
- not in mock_client.call_args.kwargs["kwargs"]["litellm_params"]["api_base"]
- )
- key = mock_client.call_args.kwargs["kwargs"]["litellm_params"]["api_base"]
- trimmed_key = key.split("key=")[1]
- trimmed_key = trimmed_key.replace("*", "")
- assert "PART" == trimmed_key
+ # Gemini API keys are now transmitted via the x-goog-api-key header
+ # instead of the legacy ?key=... URL query parameter (security commit
+ # 25f93bed91). Verify the key never appears in api_base.
+ api_base = mock_client.call_args.kwargs["kwargs"]["litellm_params"]["api_base"]
+ assert "LEAVE_ONLY_LAST_4_CHAR_UNMASKED_THIS_PART" not in api_base
+ assert "?key=" not in api_base
+ assert "&key=" not in api_base
@pytest.mark.parametrize("sync_mode", [True, False])
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.py
index 543559422b0..72b4da7b38b 100644
--- a/tests/test_litellm/llms/custom_httpx/test_credential_leak_prevention.py
+++ b/tests/test_litellm/llms/custom_httpx/test_credential_leak_prevention.py
@@ -77,14 +77,64 @@ class TestMaskedHTTPStatusError:
orig = _make_httpx_status_error()
with patch.object(
- type(orig.response), "content",
- new_callable=lambda: property(lambda self: (_ for _ in ()).throw(Exception("zlib error"))),
+ 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
+ def test_response_request_is_set(self):
+ """response.request must be set so downstream code can read it safely.
+
+ Regression: if the inner httpx.Response is constructed without
+ request=..., accessing masked.response.request raises
+ RuntimeError("The .request property has not been set.").
+ """
+ orig = _make_httpx_status_error(url="https://api.example.com?key=KEY_X")
+ masked = MaskedHTTPStatusError(orig)
+
+ # Must not raise RuntimeError.
+ req = masked.response.request
+ assert req is not None
+ # The attached request must be the masked one, not the original.
+ assert "KEY_X" not in str(req.url)
+
+ def test_strips_content_encoding_to_avoid_double_decode(self):
+ """If the upstream response declared Content-Encoding (e.g. gzip),
+ the rebuilt Response must not carry that header over — otherwise httpx
+ tries to decode the already-decoded bytes again and raises DecodingError.
+ """
+ # Build a gzipped upstream response so .content decodes once cleanly.
+ import gzip
+
+ body = b'{"error": "bad request"}'
+ gzipped = gzip.compress(body)
+ request = httpx.Request("POST", "https://api.example.com?key=KEY")
+ response = httpx.Response(
+ status_code=400,
+ content=gzipped,
+ headers={
+ "content-encoding": "gzip",
+ "content-length": str(len(gzipped)),
+ "content-type": "application/json",
+ },
+ request=request,
+ )
+ orig = httpx.HTTPStatusError("400", request=request, response=response)
+
+ # Previously this raised httpx.DecodingError; must now succeed.
+ masked = MaskedHTTPStatusError(orig)
+
+ # Content must be the once-decoded bytes, not a double-decode attempt.
+ assert masked.response.content == body
+ # Content-Encoding must have been stripped from the rebuilt headers.
+ assert "content-encoding" not in {k.lower() for k in masked.response.headers}
+
class TestSafeResponseHelpers:
def test_safe_get_response_text_normal(self):
@@ -93,7 +143,11 @@ class TestSafeResponseHelpers:
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")))
+ 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):