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
fix(s3_v2): sign S3 object URLs with S3SigV4Auth so encoded paths verify (#35726)
devin-ai-integration[bot]a01cac2132a8
diff --git a/litellm/integrations/s3_v2.py b/litellm/integrations/s3_v2.pyindex 3c663ed31ce..d52bcda525f 100644--- a/litellm/integrations/s3_v2.py+++ b/litellm/integrations/s3_v2.py@@ -293,7 +293,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):import hashlibimport requests- from botocore.auth import SigV4Auth+ from botocore.auth import S3SigV4Authfrom botocore.awsrequest import AWSRequestexcept ImportError:raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.")@@ -359,7 +359,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):headers=prepped.headers,)aws_region_name: Final = self.get_aws_region_name_for_non_llm_api_calls(aws_region_name=self.s3_region_name)- SigV4Auth(credentials, "s3", aws_region_name).add_auth(aws_request)+ S3SigV4Auth(credentials, "s3", aws_region_name).add_auth(aws_request)# Prepare the signed headerssigned_headers: Final = dict(aws_request.headers.items())@@ -479,7 +479,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):import hashlibimport requests- from botocore.auth import SigV4Auth+ from botocore.auth import S3SigV4Authfrom botocore.awsrequest import AWSRequestfrom botocore.credentials import Credentialsexcept ImportError:@@ -536,7 +536,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):headers=prepped.headers,)aws_region_name: Final = self.get_aws_region_name_for_non_llm_api_calls(aws_region_name=self.s3_region_name)- SigV4Auth(credentials, "s3", aws_region_name).add_auth(aws_request)+ S3SigV4Auth(credentials, "s3", aws_region_name).add_auth(aws_request)# Prepare the signed headerssigned_headers: Final = dict(aws_request.headers.items())@@ -583,7 +583,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):import hashlibimport requests- from botocore.auth import SigV4Auth+ from botocore.auth import S3SigV4Authfrom botocore.awsrequest import AWSRequestexcept ImportError:raise ImportError("Missing boto3 to call S3. Run 'pip install boto3'.")@@ -635,7 +635,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):url=prepped.url,headers=prepped.headers,)- SigV4Auth(credentials, "s3", self.s3_region_name).add_auth(aws_request)+ S3SigV4Auth(credentials, "s3", self.s3_region_name).add_auth(aws_request)# Prepare the signed headerssigned_headers: Final = dict(aws_request.headers.items())diff --git a/tests/test_litellm/integrations/test_s3_v2.py b/tests/test_litellm/integrations/test_s3_v2.pyindex 3977daae92f..8cccfd937e7 100644--- a/tests/test_litellm/integrations/test_s3_v2.py+++ b/tests/test_litellm/integrations/test_s3_v2.py@@ -1638,3 +1638,125 @@ def test_non_string_key_id_is_dropped_and_valid_algorithm_is_kept():assert logger.s3_sse_kms_key_id is Nonefinally:litellm.s3_callback_params = original+++_ACCESS_KEY = "AKIAIOSFODNN7EXAMPLE"+_SECRET_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"+_KEY_WITH_SPACE = "LOGS/LLM AI Projects/2026-08-04/time-13-01-00-abc.json"+++def _signature_for(signer_cls, url: str, method: str, body: bytes | None, headers: dict[str, str]) -> str:+ from botocore.awsrequest import AWSRequest+ from botocore.credentials import Credentials++ sent = {name.lower(): value for name, value in headers.items()}+ signed_header_names = sent["authorization"].split("SignedHeaders=")[1].split(", ")[0].split(";")+ request = AWSRequest(+ method=method,+ url=url,+ data=body,+ headers={name: sent[name] for name in signed_header_names if name in sent},+ )+ request.context["timestamp"] = sent["x-amz-date"]+ signer = signer_cls(Credentials(_ACCESS_KEY, _SECRET_KEY), "s3", "us-east-1")+ canonical_request = signer.canonical_request(request)+ return signer.signature(signer.string_to_sign(request, canonical_request), request)+++def _assert_signed_for_s3_canonicalization(url: str, method: str, body: bytes | None, headers: dict[str, str]) -> None:+ """+ S3 rebuilds the canonical request from the wire path with single percent-encoding, which+ botocore models as S3SigV4Auth; plain SigV4Auth double-encodes it (%2520 for a space) and S3+ answers 403 SignatureDoesNotMatch. Assert we signed the path the way S3 reads it.+ """+ from botocore.auth import S3SigV4Auth, SigV4Auth++ assert "%20" in url+ sent_signature = headers["Authorization"].split("Signature=")[1].strip()+ assert sent_signature == _signature_for(S3SigV4Auth, url, method, body, headers)+ assert sent_signature != _signature_for(SigV4Auth, url, method, body, headers)+++def _logger_for_signing() -> S3Logger:+ return S3Logger(+ s3_bucket_name="logs-bucket",+ s3_aws_access_key_id=_ACCESS_KEY,+ s3_aws_secret_access_key=_SECRET_KEY,+ s3_region_name="us-east-1",+ )+++def _element_with_space():+ from litellm.types.integrations.s3_v2 import s3BatchLoggingElement++ return s3BatchLoggingElement(+ s3_object_key=_KEY_WITH_SPACE,+ payload={"test": "sigv4"},+ s3_object_download_filename="log.json",+ )+++async def test_async_upload_signs_object_key_with_space_the_way_s3_does():+ from unittest.mock import AsyncMock, MagicMock++ logger = _logger_for_signing()+ response = MagicMock()+ response.status_code = 200+ response.raise_for_status = MagicMock()+ logger.async_httpx_client = AsyncMock()+ logger.async_httpx_client.put.return_value = response++ await logger.async_upload_data_to_s3(_element_with_space())++ call = logger.async_httpx_client.put.call_args+ _assert_signed_for_s3_canonicalization(+ url=call[0][0],+ method="PUT",+ body=call.kwargs["data"].encode("utf-8"),+ headers=call.kwargs["headers"],+ )+++def test_sync_upload_signs_object_key_with_space_the_way_s3_does():+ from unittest.mock import MagicMock++ logger = _logger_for_signing()+ response = MagicMock()+ response.status_code = 200+ response.raise_for_status = MagicMock()+ mock_sync_client = MagicMock()+ mock_sync_client.put.return_value = response++ with patch("litellm.integrations.s3_v2._get_httpx_client", return_value=mock_sync_client):+ logger.upload_data_to_s3(_element_with_space())++ call = mock_sync_client.put.call_args+ _assert_signed_for_s3_canonicalization(+ url=call[0][0],+ method="PUT",+ body=call.kwargs["data"].encode("utf-8"),+ headers=call.kwargs["headers"],+ )+++async def test_download_signs_object_key_with_space_the_way_s3_does():+ from unittest.mock import AsyncMock, MagicMock++ logger = _logger_for_signing()+ response = MagicMock()+ response.status_code = 200+ response.json = MagicMock(return_value={"downloaded": "data"})+ logger.async_httpx_client = AsyncMock()+ logger.async_httpx_client.get.return_value = response++ assert await logger._download_object_from_s3(_KEY_WITH_SPACE) == {"downloaded": "data"}++ call = logger.async_httpx_client.get.call_args+ _assert_signed_for_s3_canonicalization(+ url=call[0][0],+ method="GET",+ body=None,+ headers=call.kwargs["headers"],+ )