Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions litellm/passthrough/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ def forward_headers_from_request(
request_headers.pop("content-length", None)
request_headers.pop("host", None)

custom_header_names = {header_name.lower() for header_name in headers}
for header_name in list(request_headers.keys()):
if header_name.lower() in custom_header_names:
request_headers.pop(header_name, None)

# Combine request headers with custom headers
headers = {**request_headers, **headers}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
)
from litellm.types.passthrough_endpoints.pass_through_endpoints import (
LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY,
LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY,
)
from litellm.proxy.utils import is_known_model
from litellm.proxy.vector_store_endpoints.utils import (
Expand Down Expand Up @@ -1123,6 +1124,9 @@ async def bedrock_proxy_route(
_forward_headers=True,
) # dynamically construct pass-through endpoint based on incoming path
setattr(request.state, LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY, data)
# SigV4 signs an exact payload; pass-through must send prepped.body, not json.dumps
# of a dict that hooks may mutate (logging_obj, metadata, etc.).
setattr(request.state, LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY, prepped.body)
received_value = await endpoint_func(
request,
fastapi_response,
Expand Down
57 changes: 44 additions & 13 deletions litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import traceback
from base64 import b64encode
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Union, cast
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union, cast
from urllib.parse import urlencode, urlparse

import httpx
Expand Down Expand Up @@ -62,6 +62,7 @@
from litellm.types.passthrough_endpoints.pass_through_endpoints import (
EndpointType,
LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY,
LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY,
PassthroughStandardLoggingPayload,
)

Expand Down Expand Up @@ -735,6 +736,13 @@ async def pass_through_request( # noqa: PLR0915
str(url)
)

# SigV4-signed callers (e.g. Bedrock) attach the exact bytes that were
# signed via request.state; we must send those instead of re-encoding the
# parsed dict (hooks mutate it, breaking the signature / Content-Length).
state_raw_body: Optional[Union[str, bytes]] = getattr(
request.state, LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY, None
)

# Skip body parsing for multipart requests - make_multipart_http_request will handle it
# But if custom_body is provided (e.g., JSON parsed despite multipart content-type), use it
is_multipart = (
Expand Down Expand Up @@ -883,12 +891,19 @@ async def pass_through_request( # noqa: PLR0915
)
)
else:
# SigV4-signed callers (Bedrock) supply the exact pre-signed bytes;
# otherwise httpx encodes the parsed JSON dict as before.
body_kwargs: Dict[str, Any] = (
{"content": state_raw_body}
if state_raw_body is not None
else {"json": _parsed_body}
)
req = async_client.build_request(
"POST",
url,
json=_parsed_body,
params=requested_query_params,
headers=headers,
**body_kwargs,
)

response = await async_client.send(req, stream=stream)
Expand Down Expand Up @@ -917,17 +932,28 @@ async def pass_through_request( # noqa: PLR0915
status_code=response.status_code,
)

response = (
await HttpPassThroughEndpointHelpers.non_streaming_http_request_handler(
request=request,
async_client=async_client,
if state_raw_body is not None:
# SigV4-signed callers (Bedrock) require the exact pre-signed bytes
# to be forwarded so the signature/Content-Length stay valid.
response = await async_client.request(
method=request.method,
url=url,
headers=headers,
requested_query_params=requested_query_params,
_parsed_body=_parsed_body,
forward_multipart=is_multipart,
params=requested_query_params,
content=state_raw_body,
Comment thread
milan-berri marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium: Request-body rewrite bypass

state_raw_body is captured before proxy_logging_obj.pre_call_hook(...) runs, then this branch forwards those original bytes instead of the possibly modified _parsed_body. An authenticated caller can send a Bedrock pass-through request containing content that a configured pre-call hook or passthrough guardrail masks/rewrites, and LiteLLM will still forward the original signed body upstream; recompute the SigV4 body and headers after pre-call mutations, or restrict this raw-body path so it cannot bypass mutating hooks.

)
Comment thread
milan-berri marked this conversation as resolved.
Resolved
else:
response = (
await HttpPassThroughEndpointHelpers.non_streaming_http_request_handler(
request=request,
async_client=async_client,
url=url,
headers=headers,
requested_query_params=requested_query_params,
_parsed_body=_parsed_body,
forward_multipart=is_multipart,
)
)
)
verbose_proxy_logger.debug("response.headers= %s", response.headers)

if _is_streaming_response(response) is True:
Expand Down Expand Up @@ -1225,7 +1251,7 @@ async def _parse_request_data_by_content_type(
def create_pass_through_route(
endpoint,
target: str,
custom_headers: Optional[dict] = None,
custom_headers: Optional[Mapping[str, Any]] = None,
_forward_headers: Optional[bool] = False,
_merge_query_params: Optional[bool] = False,
dependencies: Optional[List] = None,
Expand Down Expand Up @@ -1334,9 +1360,12 @@ async def endpoint_func( # type: ignore
)
)

# Ensure custom_headers is a dict
# Ensure custom_headers is a dict. Botocore returns a HeadersDict
# for SigV4-prepared requests, which is a Mapping but not a dict.
headers_dict = (
param_custom_headers if isinstance(param_custom_headers, dict) else {}
dict(param_custom_headers)
if isinstance(param_custom_headers, Mapping)
else {}
)

# Ensure query_params and custom_body are dicts or None
Expand Down Expand Up @@ -1379,6 +1408,8 @@ async def endpoint_func( # type: ignore
finally:
if hasattr(request.state, LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY):
delattr(request.state, LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY)
if hasattr(request.state, LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY):
delattr(request.state, LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY)

return endpoint_func

Expand Down
4 changes: 4 additions & 0 deletions litellm/types/passthrough_endpoints/pass_through_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
# JSON without a FastAPI `custom_body` parameter (which would consume the HTTP body).
LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY = "litellm_pass_through_custom_body"

# Request.state key for programmatic pass-through callers that must preserve an
# exact byte/string body, such as AWS SigV4-signed requests.
LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY = "litellm_pass_through_raw_body"


class EndpointType(str, Enum):
VERTEX_AI = "vertex-ai"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2153,7 +2153,12 @@ async def test_create_pass_through_route_custom_body_url_target():
endpoint_func = create_pass_through_route(
endpoint=unique_path,
target="https://bedrock-agent-runtime.us-east-1.amazonaws.com",
custom_headers={"Content-Type": "application/json"},
custom_headers=Headers(
{
"Authorization": "AWS4-HMAC-SHA256 signed",
"Content-Type": "application/json",
}
),
_forward_headers=True,
)

Expand Down Expand Up @@ -2213,6 +2218,12 @@ async def test_create_pass_through_route_custom_body_url_target():
# The critical assertion: custom_body takes precedence over
# the body parsed from the raw request
assert call_kwargs["custom_body"] == bedrock_body
# HeadersDict-like custom_headers (e.g. botocore SigV4) must be coerced
# to a plain dict so signed headers actually reach the upstream.
assert call_kwargs["custom_headers"] == {
"authorization": "AWS4-HMAC-SHA256 signed",
"content-type": "application/json",
}


@pytest.mark.asyncio
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,36 @@ def test_forward_headers_from_request_protected_headers_not_overwritten():
assert "Anthropic-Beta" not in result


def test_forward_headers_custom_wins_case_insensitive_over_request_authorization():
"""
When forwarding request headers, provider-signed/custom headers must win
even if the incoming request uses a different case for the same header name.
"""
from litellm.passthrough.utils import BasePassthroughUtils

request_headers = {
"authorization": "Bearer sk-litellm-key",
"content-type": "application/json",
"x-request-id": "req-123",
}
signed_headers = {
"Authorization": "AWS4-HMAC-SHA256 signed",
"Content-Type": "application/json",
}

result = BasePassthroughUtils.forward_headers_from_request(
request_headers=request_headers,
headers=signed_headers.copy(),
forward_headers=True,
)

assert result["Authorization"] == "AWS4-HMAC-SHA256 signed"
assert "authorization" not in result
assert result["Content-Type"] == "application/json"
assert "content-type" not in result
assert result["x-request-id"] == "req-123"


@pytest.mark.asyncio
async def test_vertex_passthrough_custom_model_name_replaced_in_url():
"""
Expand Down
Loading