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
merge: bring litellm_internal_staging into the Bedrock files delete and list fix
mateo-berri942b647d42e6
diff --cc enterprise/litellm_enterprise/proxy/hooks/managed_files.pyindex 8b22bd936a8,c7e1b94a2ef..4899b87da7a--- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py+++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py@@@ -1781,19 -1802,31 +1803,22 @@@ class _PROXY_LiteLLMManagedFiles(Customfiltered_data = {k: v for k, v in data.items() if k not in ("model", "file_id")}for model_id, model_file_id in specific_model_file_id_mapping.items():credentials = llm_router.get_deployment_credentials_with_provider(model_id=model_id)- router_kwargs = (- {**filtered_data, "_litellm_internal_model_credentials": MappingProxyType(dict(credentials))}- if credentials is not None- else filtered_data- )- await llm_router.afile_delete(model=model_id, file_id=model_file_id, **router_kwargs)+ delete_data = {+ **{k: v for k, v in filtered_data.items() if k != "_litellm_internal_model_credentials"},+ **(+ {"_litellm_internal_model_credentials": MappingProxyType(dict(credentials))}+ if credentials is not None+ else {}+ ),+ }- delete_response = await llm_router.afile_delete(model=model_id, file_id=model_file_id, **delete_data)-- stored_file_object = await self.delete_unified_file_id(file_id, litellm_parent_otel_span)++ await llm_router.afile_delete(model=model_id, file_id=model_file_id, **delete_data)- # Record successful deletion metric only on actual success- if stored_file_object or delete_response:- prom_logger = self._get_prometheus_logger()- if prom_logger:- prom_logger.record_managed_file_deleted(result="success")+ await self.delete_unified_file_id(file_id, litellm_parent_otel_span)- if stored_file_object:- return OpenAIFileObject.model_validate(stored_file_object).model_copy(update={"id": file_id})- elif delete_response:- delete_response.id = file_id- return delete_response- else:- raise Exception(f"LiteLLM Managed File object with id={file_id} not found")+ prom_logger = self._get_prometheus_logger()+ if prom_logger:+ prom_logger.record_managed_file_deleted(result="success")+ return FileDeleted(id=file_id, object="file", deleted=True)async def afile_content(self,diff --cc litellm/constants.pyindex 63035cfa567,f9389d22dea..5cf2dce0242--- a/litellm/constants.py+++ b/litellm/constants.py@@@ -53,9 -53,9 +53,10 @@@ S3_BOUNDED_OBJECT_KEY_HEAD_BYTES: FinaS3_PREFIX_DIGEST_CHARS: Final = 16# s3 allows 2048 bytes of combined metadata headers, which Content-Disposition counts againstMAX_S3_OBJECT_DOWNLOAD_FILENAME_BYTES: Final = 1024+MAX_FILE_LIST_LIMIT: Final = 10000DEFAULT_SQS_FLUSH_INTERVAL_SECONDS: Final = int(os.getenv("DEFAULT_SQS_FLUSH_INTERVAL_SECONDS", 10))DEFAULT_NUM_WORKERS_LITELLM_PROXY: Final = int(os.getenv("DEFAULT_NUM_WORKERS_LITELLM_PROXY", 1))+ budget_reservation_disabled_info_emitted = FalseDYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTE = int(os.getenv("DYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTE", 1))DEFAULT_SQS_BATCH_SIZE: Final = int(os.getenv("DEFAULT_SQS_BATCH_SIZE", 512))SQS_SEND_MESSAGE_ACTION: Final = "SendMessage"diff --cc litellm/llms/bedrock/files/transformation.pyindex 201911737b6,9875ac2b9c3..29732f8afe2--- a/litellm/llms/bedrock/files/transformation.py+++ b/litellm/llms/bedrock/files/transformation.py@@@ -11,8 -7,8 +11,8 @@@ from datetime import datetimfrom functools import cachefrom itertools import chainfrom types import MappingProxyType- from typing import Any, Final, TypeAlias, TypedDict+ from typing import Any, Final, Literal, TypeAlias, TypedDict-from urllib.parse import unquote+from urllib.parse import quote, unquote, urlencodeimport httpxfrom httpx import Headers, Response@@@ -65,16 -60,13 +65,15 @@@ from litellm.utils import get_llm_provifrom ..base_aws_llm import BaseAWSLLMfrom ..common_utils import BedrockError, merge_bedrock_aws_request_params, resolve_s3_encryption_key_id- # litellm_params key used to hand SigV4-signed request headers from the- # content, delete, and list request transforms to `validate_environment` (the- # only hook the shared files HTTP handler exposes for setting request headers).- # Same pattern as the `upload_url` handoff in `transform_create_file_request`.S3_SIGNED_REQUEST_HEADERS_PARAM: Final = "_s3_signed_request_headers"- DELETED_FILE_ID_PARAM: Final = "_s3_deleted_file_id"-+LIST_FILES_PURPOSE_PARAM: Final = "_s3_list_files_purpose"+++ class _S3DeleteContext(BaseModel):+ file_id: str = Field(min_length=1)++# litellm_params key carrying the size of the body uploaded to S3, handed from# `transform_create_file_request` to `transform_create_file_response`.UPLOAD_CONTENT_LENGTH_PARAM: Final = "_s3_upload_content_length"@@@ -1350,52 -1213,10 +1338,52 @@@ class BedrockFilesConfig(BaseAWSLLM, Badef transform_list_files_request(self,purpose: str | None,- optional_params: dict,- litellm_params: dict,- ) -> tuple[str, dict]:- raise NotImplementedError("BedrockFilesConfig does not support file listing")+ optional_params: Mapping[str, object],+ litellm_params: MutableMapping[str, object],+ ) -> tuple[str, dict[str, str]]:+ litellm_params[LIST_FILES_PURPOSE_PARAM] = purpose # rebind-ok: handed to the response transform+ return self._signed_listing_request(purpose, optional_params, litellm_params, continuation_token=None)++ def transform_list_files_next_request(+ self,+ raw_response: httpx.Response,+ optional_params: Mapping[str, object],+ litellm_params: MutableMapping[str, object],+ ) -> tuple[str, dict[str, str]] | None:+ if raw_response.status_code >= 400:+ return None+ continuation_token: Final = ET.fromstring(raw_response.content).findtext("{*}NextContinuationToken")+ if not continuation_token:+ return None+ return self._signed_listing_request(+ _requested_listing_purpose(litellm_params), optional_params, litellm_params, continuation_token+ )++ def _signed_listing_request(+ self,+ purpose: str | None,+ optional_params: Mapping[str, object],+ litellm_params: MutableMapping[str, object],+ continuation_token: str | None,+ ) -> tuple[str, dict[str, str]]:+ bucket_name, configured_prefix = split_configured_cloud_bucket_name(+ _listing_bucket_name(litellm_params, purpose)+ )+ target: Final = self._s3_request_target(optional_params=optional_params, litellm_params=litellm_params)+ url: Final = f"{target.endpoint_url}/{bucket_name}/"+ listing_query: Final = _listing_query(configured_prefix, purpose)+ continuation_query: Final = (("continuation-token", continuation_token),) if continuation_token else ()+ query: Final[dict[str, str]] = dict( # mutable-ok: the base files contract returns the query as a dict+ listing_query + continuation_query+ )- signed_headers: Final = self._sign_s3_empty_body_request(++ signed_headers: Final = self._sign_s3_request_without_body(+ method="GET",+ api_base=f"{url}?{urlencode(query, quote_via=quote, safe='')}",+ aws_region_name=target.aws_region_name,+ request_params=target.request_params,+ )+ litellm_params[S3_SIGNED_REQUEST_HEADERS_PARAM] = signed_headers # rebind-ok: handed to validate_environment+ return url, querydef transform_list_files_response(self,@@@ -1444,47 -1243,46 +1432,58 @@@if not file_id:raise ValueError("file_id is required for Bedrock file content retrieval")+ return self._transform_s3_file_request(+ file_id=file_id, method="GET", optional_params=optional_params, litellm_params=litellm_params+ )++ def _transform_s3_file_request(+ self,+ *,+ file_id: str,+ method: Literal["GET", "DELETE"],+ optional_params: Mapping[str, object],+ litellm_params: MutableMapping[str, object],+ ) -> tuple[str, dict[str, str]]:- s3_uri: Final = extract_s3_uri_from_file_id(file_id)- bucket_name, object_key = _validate_file_id_against_configured_buckets(- s3_uri=s3_uri,- configured_bucket_names=get_configured_s3_bucket_names(litellm_params),- allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids(litellm_params),+ bucket_name, object_key = _resolve_managed_s3_object(file_id=file_id, litellm_params=litellm_params)+ target: Final = self._s3_request_target(optional_params=optional_params, litellm_params=litellm_params)+ url: Final = f"{target.endpoint_url}/{bucket_name}/{encode_s3_object_key_for_url(object_key)}"-- signed_headers: Final = self._sign_s3_empty_body_request(- method="GET",++ signed_headers: Final = self._sign_s3_request_without_body(++ method=method,+ api_base=url,+ aws_region_name=target.aws_region_name,+ request_params=target.request_params,)+ litellm_params[S3_SIGNED_REQUEST_HEADERS_PARAM] = signed_headers # rebind-ok: handed to validate_environment- return url, {}++ return url, {} # mutable-ok: the base files contract returns the query as a dict- request_params: Final = _BedrockS3RequestParams.model_validate({**litellm_params, **optional_params})-+ def _s3_request_target(+ self,+ optional_params: Mapping[str, object],+ litellm_params: Mapping[str, object],+ ) -> _S3RequestTarget:+ """+ The shared files handler passes optional_params={}, so AWS credentials and+ region arrive via litellm_params here (unlike the upload path).+ s3_region_name wins over aws_region_name, same priority as get_complete_file_url.+ """+ request_params: Final = _BedrockS3RequestParams.model_validate(+ MappingProxyType({**litellm_params, **optional_params})+ )region_preference: Final = request_params.s3_region_name or request_params.aws_region_name- region_params: Final[dict[str, str | None]] = {"aws_region_name": region_preference}- aws_region_name: Final = self._get_aws_region_name(optional_params=region_params, model="")-- s3_endpoint_url: Final = (+ aws_region_name: Final = self._get_aws_region_name(+ optional_params={"aws_region_name": region_preference}, # mutable-ok: BaseAWSLLM takes a dict+ model="",+ )+ endpoint_url: Final = (request_params.s3_endpoint_url or f"https://s3.{aws_region_name}.{get_aws_dns_suffix(aws_region_name)}").rstrip("/")- url: Final = f"{s3_endpoint_url}/{bucket_name}/{encode_s3_object_key_for_url(object_key)}"-- litellm_params[S3_SIGNED_REQUEST_HEADERS_PARAM] = self._sign_s3_request_without_body(- api_base=url,- aws_region_name=aws_region_name,- request_params=request_params,- method=method,+ return _S3RequestTarget(+ endpoint_url=endpoint_url, aws_region_name=aws_region_name, request_params=request_params)- return url, {}- def _sign_s3_empty_body_request(+ def _sign_s3_request_without_body(self,- method: str,++ method: Literal["GET", "DELETE"],api_base: str,aws_region_name: str,request_params: _BedrockS3RequestParams,diff --cc tests/test_litellm/enterprise/proxy/test_managed_files_hook.pyindex da4853294ad,48fceb50403..cb08e00ff65--- a/tests/test_litellm/enterprise/proxy/test_managed_files_hook.py+++ b/tests/test_litellm/enterprise/proxy/test_managed_files_hook.py@@@ -1095,6 -1095,110 +1095,110 @@@ async def test_afile_content_passes_truassert trusted_credentials["s3_bucket_name"] == "my-bucket"+ def _managed_deletion_file_id(provider_file_id):+ from litellm.types.utils import SpecialEnums++ value = SpecialEnums.LITELLM_MANAGED_FILE_COMPLETE_STR.value.format(+ "application/json", "test-file", "batch-model", provider_file_id, "model-123"+ )+ return base64.urlsafe_b64encode(value.encode()).decode().rstrip("=")+++ def _managed_files_with_deletion_row(unified_file_id, provider_file_id, file_object):+ from litellm.caching import DualCache+ from litellm.models.managed_files import LiteLLM_ManagedFileTable+ from litellm_enterprise.proxy.hooks.managed_files import _PROXY_LiteLLMManagedFiles++ row = LiteLLM_ManagedFileTable(+ unified_file_id=unified_file_id,+ model_mappings={"model-123": provider_file_id},+ flat_model_file_ids=[provider_file_id],+ file_object=file_object,+ )+ table = MagicMock(+ find_first=AsyncMock(return_value=row),+ delete=AsyncMock(),+ )+ return _PROXY_LiteLLMManagedFiles(+ internal_usage_cache=DualCache(),+ prisma_client=MagicMock(db=MagicMock(litellm_managedfiletable=table)),+ ), table+++ @pytest.mark.asyncio+ async def test_afile_delete_bedrock_uses_deployment_bucket_and_signed_s3_delete(monkeypatch):+ import httpx+ import respx++ from litellm import Router++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)+ monkeypatch.delenv("AWS_S3_OUTPUT_BUCKET_NAME", raising=False)+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ router = Router(+ model_list=[+ {+ "model_name": "bedrock-batch",+ "litellm_params": {+ "model": "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",+ "aws_access_key_id": "AKIAEXAMPLE",+ "aws_secret_access_key": "secret",+ "aws_region_name": "us-west-2",+ "s3_bucket_name": "my-bucket",+ },+ "model_info": {"id": "model-123"},+ }+ ],+ num_retries=0,+ )+ s3_uri = "s3://my-bucket/litellm-bedrock-files/input.jsonl"+ unified_file_id = _managed_deletion_file_id(s3_uri)+ managed_files, table = _managed_files_with_deletion_row(unified_file_id, s3_uri, None)+ with respx.mock:+ route = respx.delete(+ "https://s3.us-west-2.amazonaws.com/my-bucket/litellm-bedrock-files/input.jsonl"+ ).mock(return_value=httpx.Response(204))+ response = await managed_files.afile_delete(+ file_id=unified_file_id,+ litellm_parent_otel_span=None,+ llm_router=router,+ _litellm_internal_model_credentials={"s3_bucket_name": "request-bucket"},+ )++ assert len(route.calls) == 1+ assert route.calls[0].request.headers["Authorization"].startswith("AWS4-HMAC-SHA256")+ assert response.id == unified_file_id+ assert response.deleted is True+ table.delete.assert_awaited_once_with(where={"unified_file_id": unified_file_id})+++ @pytest.mark.asyncio+ async def test_afile_delete_returns_managed_id_for_stored_provider_output():+ from openai.types import FileDeleted++ provider_file_id = "file-error-output"+ unified_file_id = _managed_deletion_file_id(provider_file_id)+ stored_file = _make_file_object(provider_file_id)+ managed_files, table = _managed_files_with_deletion_row(unified_file_id, provider_file_id, stored_file)+ router = MagicMock(+ get_deployment_credentials_with_provider=MagicMock(return_value=None),+ afile_delete=AsyncMock(return_value=FileDeleted(id=provider_file_id, object="file", deleted=True)),+ )+ response = await managed_files.afile_delete(+ file_id=unified_file_id,+ litellm_parent_otel_span=None,+ llm_router=router,+ _litellm_internal_model_credentials={"s3_bucket_name": "request-bucket"},+ )++ assert response.id == unified_file_id+ assert response.object == "file"- assert response.filename == stored_file.filename++ assert response.deleted is True+ assert stored_file.id == provider_file_id+ router.afile_delete.assert_awaited_once_with(model="model-123", file_id=provider_file_id)+ table.delete.assert_awaited_once_with(where={"unified_file_id": unified_file_id})++@pytest.mark.asyncioasync def test_afile_content_bedrock_unified_id_end_to_end(monkeypatch):"""diff --cc tests/test_litellm/llms/bedrock/files/test_bedrock_files_transformation.pyindex 55f4b75ba02,3b01a4f2054..84433ea79a9--- a/tests/test_litellm/llms/bedrock/files/test_bedrock_files_transformation.py+++ b/tests/test_litellm/llms/bedrock/files/test_bedrock_files_transformation.py@@@ -1855,6 -1857,104 +1857,106 @@@ class TestBedrockBatchNonChatEndpointRe]+ class TestBedrockFileDeletion:+ S3_URI: Final = "s3://my-bucket/litellm-bedrock-files-model-abc.jsonl"+ URL: Final = "https://s3.us-west-2.amazonaws.com/my-bucket/litellm-bedrock-files-model-abc.jsonl"++ def test_interleaved_deletions_keep_their_own_file_ids(self, monkeypatch: pytest.MonkeyPatch) -> None:+ import httpx++ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ config: Final = BedrockFilesConfig()+ params: Final = {+ "aws_access_key_id": "AKIAEXAMPLE",+ "aws_secret_access_key": "test-secret",+ "aws_region_name": "us-west-2",+ }+ file_ids: Final = (self.S3_URI, "s3://my-bucket/litellm-bedrock-files-model-second.jsonl")+ for file_id in file_ids:+ config.transform_delete_file_request(file_id=file_id, optional_params={}, litellm_params=params)++ deleted: Final = tuple(+ config.transform_delete_file_response(+ raw_response=httpx.Response(204),+ logging_obj=MagicMock(model_call_details={"additional_args": {"file_id": file_id}}),+ litellm_params=params,+ ).id+ for file_id in file_ids+ )++ assert deleted == file_ids++ def test_delete_file_sends_signed_delete_and_returns_matching_id(self, monkeypatch: pytest.MonkeyPatch) -> None:+ import httpx+ import respx++ import litellm+ from litellm.llms.custom_httpx.http_handler import HTTPHandler++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ with respx.mock, closing(HTTPHandler()) as client:+ route: Final = respx.delete(self.URL).mock(return_value=httpx.Response(204))+ deleted: Final = litellm.file_delete(+ file_id=self.S3_URI, custom_llm_provider="bedrock", client=client,+ aws_access_key_id="AKIAEXAMPLE", aws_secret_access_key="test-secret", aws_region_name="us-west-2",+ )+ assert route.call_count == 1+ request: Final = route.calls[0].request+ assert request.content == b""+ signed: Final = AWSRequest(method="DELETE", url=self.URL, headers={+ "X-Amz-Date": request.headers["X-Amz-Date"],+ "X-Amz-Content-SHA256": request.headers["X-Amz-Content-SHA256"],+ })+ signed.context["timestamp"] = request.headers["X-Amz-Date"]+ auth: Final = S3SigV4Auth(Credentials("AKIAEXAMPLE", "test-secret"), "s3", "us-west-2")+ signature: Final = auth.signature(auth.string_to_sign(signed, auth.canonical_request(signed)), signed)+ assert request.headers["Authorization"].endswith(f"Signature={signature}")+ assert deleted.id == self.S3_URI and deleted.deleted is True++ @pytest.mark.asyncio+ async def test_adelete_file_propagates_s3_errors(self, monkeypatch: pytest.MonkeyPatch) -> None:+ import httpx+ import respx++ import litellm+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ async with AsyncExitStack() as stack:+ client: Final = AsyncHTTPHandler()+ stack.push_async_callback(client.close)+ with respx.mock:+ route: Final = respx.delete(self.URL).mock(+ return_value=httpx.Response(403, content=b"<Error><Code>AccessDenied</Code></Error>")+ )+ from litellm.llms.bedrock.common_utils import BedrockError++ with pytest.raises(BedrockError, match="AccessDenied"):+ await litellm.afile_delete(+ file_id=self.S3_URI, custom_llm_provider="bedrock", client=client,+ aws_access_key_id="AKIAEXAMPLE", aws_secret_access_key="test-secret", aws_region_name="us-west-2",+ )+ assert route.call_count == 1++ @pytest.mark.parametrize("file_id, message", [+ ("s3://other-bucket/litellm-bedrock-files-model-abc.jsonl", "configured storage bucket"),+ ("s3://my-bucket/private/data.jsonl", "LiteLLM-managed"),+ ])+ def test_delete_rejects_untrusted_objects_before_signing(+ self, file_id: str, message: str, monkeypatch: pytest.MonkeyPatch+ ) -> None:++ from litellm.llms.bedrock.common_utils import BedrockError+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")- with pytest.raises(ValueError, match=message):++ with pytest.raises(BedrockError, match=message) as rejection:+ BedrockFilesConfig().transform_delete_file_request(file_id=file_id, optional_params={}, litellm_params={})++ assert rejection.value.status_code == 400++class TestBedrockFileContentTransformation:"""SigV4-signed S3 GetObject retrieval of Bedrock batch output files."""@@@ -2516,8 -2604,7 +2618,8 @@@ def test_sign_s3_request_without_body_aassert request_params.aws_external_id == "external-id-files-get"with patch.object(boto3, "client", return_value=FakeSTSClient()):- signed_headers = BedrockFilesConfig()._sign_s3_empty_body_request(+ signed_headers = BedrockFilesConfig()._sign_s3_request_without_body(+ method="GET",api_base="https://s3.us-east-1.amazonaws.com/safe-bucket/litellm-bedrock-files-model-id-abc.jsonl",aws_region_name="us-east-1",request_params=request_params,@@@ -2525,940 -2612,3 +2627,931 @@@authorization = {key.lower(): value for key, value in signed_headers.items()}["authorization"]assert "ASIAFILESGETROLE" in authorization+++def _s3_signature_for(method: str, url: str, headers: Mapping[str, str]) -> str:+ sent = {name.lower(): value for name, value in headers.items()}+ signed_names = sent["authorization"].split("SignedHeaders=")[1].split(",")[0].split(";")+ request = AWSRequest(+ method=method,+ url=url,+ headers={name: sent[name] for name in signed_names if name in sent},+ )+ request.context["timestamp"] = sent["x-amz-date"]+ signer = S3SigV4Auth(Credentials("AKIAEXAMPLE", "secret"), "s3", "us-west-2")+ return signer.signature(signer.string_to_sign(request, signer.canonical_request(request)), request)+++def _sent_signature(headers: Mapping[str, str]) -> str:+ authorization = {name.lower(): value for name, value in headers.items()}["authorization"]+ return authorization.split("Signature=")[1].strip()+++def _bedrock_s3_params() -> dict:+ return {+ "aws_access_key_id": "AKIAEXAMPLE",+ "aws_secret_access_key": "secret",+ "aws_region_name": "us-west-2",+ }+++def _trusted_bucket_snapshot(**deployment_litellm_params) -> dict:+ from types import MappingProxyType++ from litellm.types.router import CredentialLiteLLMParams++ snapshot = CredentialLiteLLMParams(**deployment_litellm_params).model_dump(exclude_none=True)+ return {**_bedrock_s3_params(), "_litellm_internal_model_credentials": MappingProxyType(snapshot)}+++class TestBedrockFileDeletionTransformation:+ """SigV4-signed S3 DeleteObject for LiteLLM-managed Bedrock batch files."""++ S3_URI = "s3://my-bucket/litellm-bedrock-files/job-123/input.jsonl"+ EXPECTED_URL = "https://s3.us-west-2.amazonaws.com/my-bucket/litellm-bedrock-files/job-123/input.jsonl"++ def test_transform_delete_file_request_signs_s3_delete(self, monkeypatch):+ import hashlib++ from litellm.llms.bedrock.files.transformation import (- DELETED_FILE_ID_PARAM,+ S3_SIGNED_REQUEST_HEADERS_PARAM,+ BedrockFilesConfig,+ )++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ litellm_params = _bedrock_s3_params()++ url, params = BedrockFilesConfig().transform_delete_file_request(+ file_id=self.S3_URI,+ optional_params={},+ litellm_params=litellm_params,+ )++ assert url == self.EXPECTED_URL+ assert params == {}+ signed_headers = litellm_params[S3_SIGNED_REQUEST_HEADERS_PARAM]+ lowered = {name.lower(): value for name, value in signed_headers.items()}+ assert lowered["x-amz-content-sha256"] == hashlib.sha256(b"").hexdigest()+ assert "/us-west-2/s3/aws4_request" in lowered["authorization"]+ assert _sent_signature(signed_headers) == _s3_signature_for("DELETE", url, signed_headers)- assert litellm_params[DELETED_FILE_ID_PARAM] == self.S3_URI++ def test_transform_delete_file_request_decodes_unified_file_id(self, monkeypatch):+ import base64+- from litellm.llms.bedrock.files.transformation import (- DELETED_FILE_ID_PARAM,- BedrockFilesConfig,- )++ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig+ from litellm.types.utils import SpecialEnums++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ unified_file_id = SpecialEnums.LITELLM_MANAGED_FILE_COMPLETE_STR.value.format(+ "application/json", "unified-id", "", self.S3_URI, "model-id"+ )+ encoded_file_id = base64.urlsafe_b64encode(unified_file_id.encode()).decode().rstrip("=")+ litellm_params = _bedrock_s3_params()++ url, _ = BedrockFilesConfig().transform_delete_file_request(+ file_id=encoded_file_id,+ optional_params={},+ litellm_params=litellm_params,+ )++ assert url == self.EXPECTED_URL- assert litellm_params[DELETED_FILE_ID_PARAM] == encoded_file_id++ def test_transform_delete_file_request_uses_trusted_snapshot_bucket(self, monkeypatch):+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)++ url, _ = BedrockFilesConfig().transform_delete_file_request(+ file_id=self.S3_URI,+ optional_params={},+ litellm_params=_trusted_bucket_snapshot(s3_bucket_name="my-bucket"),+ )++ assert url == self.EXPECTED_URL++ def test_transform_delete_file_request_rejects_foreign_bucket(self, monkeypatch):+ from litellm.llms.bedrock.common_utils import BedrockError+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ with pytest.raises(BedrockError, match="configured storage bucket") as rejection:+ BedrockFilesConfig().transform_delete_file_request(+ file_id="s3://other-bucket/litellm-bedrock-files/job-123/input.jsonl",+ optional_params={},+ litellm_params=_bedrock_s3_params(),+ )++ assert rejection.value.status_code == 400+++ def test_transform_delete_file_request_rejects_unmanaged_key(self, monkeypatch):+ from litellm.llms.bedrock.common_utils import BedrockError+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ with pytest.raises(BedrockError, match="LiteLLM-managed") as rejection:+ BedrockFilesConfig().transform_delete_file_request(+ file_id="s3://my-bucket/private/x.jsonl",+ optional_params={},+ litellm_params=_bedrock_s3_params(),+ )++ assert rejection.value.status_code == 400+++ def test_transform_delete_file_response_echoes_the_deleted_id(self):+ import httpx+- from litellm.llms.bedrock.files.transformation import (- DELETED_FILE_ID_PARAM,- BedrockFilesConfig,- )++ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ deleted = BedrockFilesConfig().transform_delete_file_response(+ raw_response=httpx.Response(204),- logging_obj=MagicMock(),- litellm_params={DELETED_FILE_ID_PARAM: self.S3_URI},++ logging_obj=MagicMock(model_call_details={"additional_args": {"file_id": self.S3_URI}}),++ litellm_params={},+ )++ assert deleted.id == self.S3_URI+ assert deleted.deleted is True+ assert deleted.object == "file"++ def test_transform_delete_file_response_raises_on_s3_error(self):+ import httpx++ from litellm.llms.bedrock.common_utils import BedrockError+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ with pytest.raises(BedrockError) as excinfo:+ BedrockFilesConfig().transform_delete_file_response(+ raw_response=httpx.Response(403, text="<Error><Code>AccessDenied</Code></Error>"),+ logging_obj=MagicMock(),+ litellm_params={},+ )++ assert excinfo.value.status_code == 403++ def test_file_delete_end_to_end_sends_signed_delete(self, monkeypatch):+ import httpx+ import respx++ import litellm++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ with respx.mock:+ route = respx.delete(self.EXPECTED_URL).mock(return_value=httpx.Response(204))++ response = litellm.file_delete(+ file_id=self.S3_URI,+ custom_llm_provider="bedrock",+ **_bedrock_s3_params(),+ )++ assert route.called+ request = route.calls[0].request+ assert request.headers["Authorization"].startswith("AWS4-HMAC-SHA256")+ assert _sent_signature(request.headers) == _s3_signature_for("DELETE", str(request.url), request.headers)+ assert response.id == self.S3_URI+ assert response.deleted is True++ @pytest.mark.asyncio+ async def test_afile_delete_end_to_end_sends_signed_delete(self, monkeypatch):+ import httpx+ import respx++ import litellm++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ litellm.in_memory_llm_clients_cache.flush_cache()++ with respx.mock:+ route = respx.delete(self.EXPECTED_URL).mock(return_value=httpx.Response(204))++ response = await litellm.afile_delete(+ file_id=self.S3_URI,+ custom_llm_provider="bedrock",+ **_bedrock_s3_params(),+ )++ assert route.called+ request = route.calls[0].request+ assert _sent_signature(request.headers) == _s3_signature_for("DELETE", str(request.url), request.headers)+ assert response.id == self.S3_URI+ assert response.deleted is True++ def test_file_delete_end_to_end_answers_400_for_a_foreign_bucket(self, monkeypatch):+ import respx++ import litellm+ from litellm.llms.bedrock.common_utils import BedrockError++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ with respx.mock, pytest.raises(BedrockError) as rejection:+ litellm.file_delete(+ file_id="s3://other-bucket/litellm-bedrock-files/job-123/input.jsonl",+ custom_llm_provider="bedrock",+ **_bedrock_s3_params(),+ )++ assert rejection.value.status_code == 400+ assert "configured storage bucket" in rejection.value.message++ def test_file_delete_end_to_end_answers_400_for_a_non_managed_id(self, monkeypatch):+ import respx++ import litellm+ from litellm.llms.bedrock.common_utils import BedrockError++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ with respx.mock, pytest.raises(BedrockError) as rejection:+ litellm.file_delete(file_id="file-1234567890", custom_llm_provider="bedrock", **_bedrock_s3_params())++ assert rejection.value.status_code == 400+ assert "managed LiteLLM S3 file id" in rejection.value.message++ def test_file_delete_end_to_end_surfaces_the_s3_error_body(self, monkeypatch):+ import httpx+ import respx++ import litellm+ from litellm.llms.bedrock.common_utils import BedrockError++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ with respx.mock:+ respx.delete(self.EXPECTED_URL).mock(+ return_value=httpx.Response(403, text="<Error><Code>AccessDenied</Code></Error>")+ )+ with pytest.raises(BedrockError) as denied:+ litellm.file_delete(file_id=self.S3_URI, custom_llm_provider="bedrock", **_bedrock_s3_params())++ assert denied.value.status_code == 403+ assert "AccessDenied" in denied.value.message+++class TestBedrockFileListTransformation:+ """SigV4-signed S3 ListObjectsV2 over the LiteLLM-managed key prefixes."""++ BUCKET_URL = "https://s3.us-west-2.amazonaws.com/my-bucket/"+ MANAGED_QUERY = {"list-type": "2", "prefix": "litellm-b"}+ BATCH_QUERY = {"list-type": "2", "prefix": "litellm-bedrock-files"}+ OUTPUT_QUERY = {"list-type": "2", "prefix": "litellm-batch-outputs/"}+ OUTPUT_BUCKET_URL = "https://s3.us-west-2.amazonaws.com/my-output-bucket/"+ OUTPUT_BUCKET_LISTING = b"""<?xml version="1.0" encoding="UTF-8"?>+<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <Name>my-output-bucket</Name>+ <Prefix>litellm-batch-outputs/</Prefix>+ <Contents>+ <Key>litellm-batch-outputs/job-9/input.jsonl.out</Key>+ <LastModified>2026-09-04T08:00:00.000Z</LastModified>+ <Size>70</Size>+ </Contents>+</ListBucketResult>"""+ OUTPUT_BUCKET_ID = "s3://my-output-bucket/litellm-batch-outputs/job-9/input.jsonl.out"+ LISTING = b"""<?xml version="1.0" encoding="UTF-8"?>+<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <Name>my-bucket</Name>+ <Prefix>litellm-b</Prefix>+ <KeyCount>4</KeyCount>+ <IsTruncated>false</IsTruncated>+ <Contents>+ <Key>litellm-bedrock-files-model-abc.jsonl</Key>+ <LastModified>2026-09-01T10:00:00.000Z</LastModified>+ <Size>120</Size>+ </Contents>+ <Contents>+ <Key>litellm-bedrock-files/job-123/input.jsonl</Key>+ <LastModified>2026-09-02T11:30:00.000Z</LastModified>+ <Size>340</Size>+ </Contents>+ <Contents>+ <Key>litellm-batch-outputs/job-123/input.jsonl.out</Key>+ <LastModified>2026-09-03T12:45:00.000Z</LastModified>+ <Size>560</Size>+ </Contents>+ <Contents>+ <Key>litellm-bogus/other.jsonl</Key>+ <LastModified>2026-09-03T12:45:00.000Z</LastModified>+ <Size>1</Size>+ </Contents>+</ListBucketResult>"""+ BATCH_IDS = (+ "s3://my-bucket/litellm-bedrock-files-model-abc.jsonl",+ "s3://my-bucket/litellm-bedrock-files/job-123/input.jsonl",+ )+ OUTPUT_ID = "s3://my-bucket/litellm-batch-outputs/job-123/input.jsonl.out"+ CONTINUATION_TOKEN = "1ueGcxLPRx1Tr/XYExHnhbYLgveDs2J/wm36Hy4vbOwM="+ FIRST_PAGE = b"""<?xml version="1.0" encoding="UTF-8"?>+<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <Name>my-bucket</Name>+ <Prefix>litellm-bedrock-files</Prefix>+ <KeyCount>1</KeyCount>+ <MaxKeys>1</MaxKeys>+ <IsTruncated>true</IsTruncated>+ <NextContinuationToken>1ueGcxLPRx1Tr/XYExHnhbYLgveDs2J/wm36Hy4vbOwM=</NextContinuationToken>+ <Contents>+ <Key>litellm-bedrock-files/job-1/input.jsonl</Key>+ <LastModified>2026-09-01T10:00:00.000Z</LastModified>+ <Size>10</Size>+ </Contents>+</ListBucketResult>"""+ LAST_PAGE = b"""<?xml version="1.0" encoding="UTF-8"?>+<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <Name>my-bucket</Name>+ <Prefix>litellm-bedrock-files</Prefix>+ <KeyCount>1</KeyCount>+ <MaxKeys>1</MaxKeys>+ <IsTruncated>false</IsTruncated>+ <ContinuationToken>1ueGcxLPRx1Tr/XYExHnhbYLgveDs2J/wm36Hy4vbOwM=</ContinuationToken>+ <Contents>+ <Key>litellm-bedrock-files/job-2/input.jsonl</Key>+ <LastModified>2026-09-02T10:00:00.000Z</LastModified>+ <Size>20</Size>+ </Contents>+</ListBucketResult>"""+ PAGED_IDS = (+ "s3://my-bucket/litellm-bedrock-files/job-1/input.jsonl",+ "s3://my-bucket/litellm-bedrock-files/job-2/input.jsonl",+ )++ def test_transform_list_files_request_signs_managed_prefix_listing(self, monkeypatch):+ from litellm.llms.bedrock.files.transformation import (+ LIST_FILES_PURPOSE_PARAM,+ S3_SIGNED_REQUEST_HEADERS_PARAM,+ BedrockFilesConfig,+ )++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ litellm_params = _bedrock_s3_params()++ url, params = BedrockFilesConfig().transform_list_files_request(+ purpose="batch",+ optional_params={},+ litellm_params=litellm_params,+ )++ assert url == self.BUCKET_URL+ assert params == self.BATCH_QUERY+ signed_headers = litellm_params[S3_SIGNED_REQUEST_HEADERS_PARAM]+ assert _sent_signature(signed_headers) == _s3_signature_for(+ "GET", f"{url}?list-type=2&prefix=litellm-bedrock-files", signed_headers+ )+ assert litellm_params[LIST_FILES_PURPOSE_PARAM] == "batch"++ def test_transform_list_files_request_scopes_to_configured_prefix(self, monkeypatch):+ from litellm.llms.bedrock.files.transformation import (+ S3_SIGNED_REQUEST_HEADERS_PARAM,+ BedrockFilesConfig,+ )++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket/LLM AI Projects")+ litellm_params = _bedrock_s3_params()++ url, params = BedrockFilesConfig().transform_list_files_request(+ purpose=None,+ optional_params={},+ litellm_params=litellm_params,+ )++ assert url == self.BUCKET_URL+ assert params == {"list-type": "2", "prefix": "LLM AI Projects/litellm-b"}+ signed_headers = litellm_params[S3_SIGNED_REQUEST_HEADERS_PARAM]+ assert _sent_signature(signed_headers) == _s3_signature_for(+ "GET", f"{url}?list-type=2&prefix=LLM%20AI%20Projects%2Flitellm-b", signed_headers+ )++ def test_transform_list_files_request_uses_trusted_snapshot_bucket(self, monkeypatch):+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)++ url, params = BedrockFilesConfig().transform_list_files_request(+ purpose=None,+ optional_params={},+ litellm_params=_trusted_bucket_snapshot(s3_bucket_name="my-bucket"),+ )++ assert url == self.BUCKET_URL+ assert params == self.MANAGED_QUERY++ def _list_response(self, purpose: str | None, listing: bytes | None = None, status_code: int = 200):+ import httpx++ from litellm.llms.bedrock.files.transformation import (+ LIST_FILES_PURPOSE_PARAM,+ BedrockFilesConfig,+ )++ return BedrockFilesConfig().transform_list_files_response(+ raw_response=httpx.Response(status_code, content=listing if listing is not None else self.LISTING),+ logging_obj=MagicMock(),+ litellm_params={**_bedrock_s3_params(), LIST_FILES_PURPOSE_PARAM: purpose},+ )++ def test_transform_list_files_response_maps_managed_objects(self, monkeypatch):+ from datetime import datetime, timezone++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ files = self._list_response(purpose=None)++ assert [file.id for file in files] == [*self.BATCH_IDS, self.OUTPUT_ID]+ assert [file.purpose for file in files] == ["batch", "batch", "batch_output"]+ assert [file.bytes for file in files] == [120, 340, 560]+ assert [file.filename for file in files] == [+ "litellm-bedrock-files-model-abc.jsonl",+ "input.jsonl",+ "input.jsonl.out",+ ]+ assert files[1].created_at == int(datetime(2026, 9, 2, 11, 30, tzinfo=timezone.utc).timestamp())+ assert {file.object for file in files} == {"file"}+ assert {file.status for file in files} == {"uploaded"}++ def test_transform_list_files_response_filters_by_purpose(self, monkeypatch):+ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ assert [file.id for file in self._list_response(purpose="batch")] == list(self.BATCH_IDS)+ assert [file.id for file in self._list_response(purpose="batch_output")] == [self.OUTPUT_ID]++ def test_transform_list_files_response_scopes_to_configured_prefix(self, monkeypatch):+ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket/team-a")+ listing = b"""<?xml version="1.0" encoding="UTF-8"?>+<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <Name>my-bucket</Name>+ <Contents><Key>team-a/litellm-bedrock-files/job-1/input.jsonl</Key><Size>10</Size></Contents>+ <Contents><Key>team-a/litellm-batch-outputs/job-1/input.jsonl.out</Key><Size>20</Size></Contents>+ <Contents><Key>litellm-bedrock-files/job-2/input.jsonl</Key><Size>30</Size></Contents>+</ListBucketResult>"""++ files = self._list_response(purpose=None, listing=listing)++ assert [(file.id, file.purpose) for file in files] == [+ ("s3://my-bucket/team-a/litellm-bedrock-files/job-1/input.jsonl", "batch"),+ ("s3://my-bucket/team-a/litellm-batch-outputs/job-1/input.jsonl.out", "batch_output"),+ ]++ def test_transform_list_files_response_raises_on_s3_error(self, monkeypatch):+ from litellm.llms.bedrock.common_utils import BedrockError++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ with pytest.raises(BedrockError) as excinfo:+ self._list_response(purpose=None, listing=b"<Error><Code>AccessDenied</Code></Error>", status_code=403)++ assert excinfo.value.status_code == 403++ def test_file_list_end_to_end_sends_signed_listing(self, monkeypatch):+ import httpx+ import respx++ import litellm++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ with respx.mock:+ route = respx.get(self.BUCKET_URL, params__contains=self.BATCH_QUERY).mock(+ return_value=httpx.Response(200, content=self.LISTING)+ )++ files = litellm.file_list(custom_llm_provider="bedrock", purpose="batch", **_bedrock_s3_params())++ assert route.called+ request = route.calls[0].request+ assert request.headers["Authorization"].startswith("AWS4-HMAC-SHA256")+ assert _sent_signature(request.headers) == _s3_signature_for("GET", str(request.url), request.headers)+ assert [file.id for file in files] == list(self.BATCH_IDS)++ def test_file_list_uses_trusted_snapshot_bucket_without_env(self, monkeypatch):+ import httpx+ import respx++ import litellm++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)++ with respx.mock:+ route = respx.get(self.BUCKET_URL, params__contains=self.MANAGED_QUERY).mock(+ return_value=httpx.Response(200, content=self.LISTING)+ )++ files = litellm.file_list(+ custom_llm_provider="bedrock",+ **_trusted_bucket_snapshot(s3_bucket_name="my-bucket"),+ )++ assert route.called+ assert [file.id for file in files] == [*self.BATCH_IDS, self.OUTPUT_ID]++ @pytest.mark.asyncio+ async def test_afile_list_end_to_end_sends_signed_listing(self, monkeypatch):+ import httpx+ import respx++ import litellm++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ litellm.in_memory_llm_clients_cache.flush_cache()++ with respx.mock:+ route = respx.get(self.BUCKET_URL, params__contains=self.OUTPUT_QUERY).mock(+ return_value=httpx.Response(200, content=self.LISTING)+ )++ files = await litellm.afile_list(+ custom_llm_provider="bedrock", purpose="batch_output", **_bedrock_s3_params()+ )++ assert route.called+ request = route.calls[0].request+ assert _sent_signature(request.headers) == _s3_signature_for("GET", str(request.url), request.headers)+ assert [file.id for file in files] == [self.OUTPUT_ID]++ def test_transform_list_files_request_narrows_prefix_to_requested_purpose(self, monkeypatch):+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ monkeypatch.delenv("AWS_S3_OUTPUT_BUCKET_NAME", raising=False)++ batch_url, batch_params = BedrockFilesConfig().transform_list_files_request(+ purpose="batch", optional_params={}, litellm_params=_bedrock_s3_params()+ )+ output_url, output_params = BedrockFilesConfig().transform_list_files_request(+ purpose="batch_output", optional_params={}, litellm_params=_bedrock_s3_params()+ )++ assert (batch_url, batch_params) == (self.BUCKET_URL, self.BATCH_QUERY)+ assert (output_url, output_params) == (self.BUCKET_URL, self.OUTPUT_QUERY)++ def test_transform_list_files_request_lists_configured_output_bucket_for_batch_output(self, monkeypatch):+ from litellm.llms.bedrock.files.transformation import (+ S3_SIGNED_REQUEST_HEADERS_PARAM,+ BedrockFilesConfig,+ )++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)+ monkeypatch.delenv("AWS_S3_OUTPUT_BUCKET_NAME", raising=False)+ litellm_params = _trusted_bucket_snapshot(+ s3_bucket_name="my-bucket", s3_output_bucket_name="my-output-bucket/team-a"+ )++ url, params = BedrockFilesConfig().transform_list_files_request(+ purpose="batch_output", optional_params={}, litellm_params=litellm_params+ )+ signed_headers = litellm_params[S3_SIGNED_REQUEST_HEADERS_PARAM]+ input_url, input_params = BedrockFilesConfig().transform_list_files_request(+ purpose="batch", optional_params={}, litellm_params=dict(litellm_params)+ )++ assert url == self.OUTPUT_BUCKET_URL+ assert params == {"list-type": "2", "prefix": "team-a/litellm-batch-outputs/"}+ assert _sent_signature(signed_headers) == _s3_signature_for(+ "GET", f"{url}?list-type=2&prefix=team-a%2Flitellm-batch-outputs%2F", signed_headers+ )+ assert (input_url, input_params) == (self.BUCKET_URL, self.BATCH_QUERY)++ def test_transform_list_files_request_reads_output_bucket_from_env(self, monkeypatch):+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ monkeypatch.setenv("AWS_S3_OUTPUT_BUCKET_NAME", "my-output-bucket")++ url, params = BedrockFilesConfig().transform_list_files_request(+ purpose="batch_output", optional_params={}, litellm_params=_bedrock_s3_params()+ )++ assert (url, params) == (self.OUTPUT_BUCKET_URL, self.OUTPUT_QUERY)++ EMPTY_LISTING = b"""<?xml version="1.0" encoding="UTF-8"?>+<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <Name>my-bucket</Name>+ <Prefix></Prefix>+ <KeyCount>0</KeyCount>+ <MaxKeys>0</MaxKeys>+ <IsTruncated>false</IsTruncated>+</ListBucketResult>"""+ NO_KEYS_QUERY = {"list-type": "2", "max-keys": "0"}++ def test_transform_list_files_request_asks_for_no_keys_when_bedrock_never_stores_the_purpose(self, monkeypatch):+ import httpx++ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ litellm_params = _bedrock_s3_params()+ config = BedrockFilesConfig()++ url, params = config.transform_list_files_request(+ purpose="user_data", optional_params={}, litellm_params=litellm_params+ )+ next_request = config.transform_list_files_next_request(+ raw_response=httpx.Response(200, content=self.EMPTY_LISTING),+ optional_params={},+ litellm_params=litellm_params,+ )++ assert (url, params) == (self.BUCKET_URL, self.NO_KEYS_QUERY)+ assert next_request is None++ def test_file_list_never_walks_the_bucket_for_a_purpose_bedrock_never_stores(self, monkeypatch):+ import httpx+ import respx++ import litellm++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ with respx.mock:+ route = respx.get(self.BUCKET_URL, params__contains=self.NO_KEYS_QUERY).mock(+ return_value=httpx.Response(200, content=self.EMPTY_LISTING)+ )++ files = litellm.file_list(custom_llm_provider="bedrock", purpose="user_data", **_bedrock_s3_params())++ assert route.call_count == 1+ assert "prefix" not in route.calls[0].request.url.params+ assert files == []++ def test_transform_list_files_request_lists_the_output_bucket_without_an_input_bucket(self, monkeypatch):+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)+ monkeypatch.delenv("AWS_S3_OUTPUT_BUCKET_NAME", raising=False)+ litellm_params = _trusted_bucket_snapshot(s3_output_bucket_name="my-output-bucket")++ url, params = BedrockFilesConfig().transform_list_files_request(+ purpose="batch_output", optional_params={}, litellm_params=litellm_params+ )++ assert (url, params) == (self.OUTPUT_BUCKET_URL, self.OUTPUT_QUERY)+ with pytest.raises(ValueError, match="s3_bucket_name"):+ BedrockFilesConfig().transform_list_files_request(+ purpose="batch", optional_params={}, litellm_params=dict(litellm_params)+ )++ def test_transform_list_files_response_accepts_output_bucket_objects(self, monkeypatch):+ import httpx++ from litellm.llms.bedrock.files.transformation import (+ LIST_FILES_PURPOSE_PARAM,+ BedrockFilesConfig,+ )++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)+ monkeypatch.delenv("AWS_S3_OUTPUT_BUCKET_NAME", raising=False)++ files = BedrockFilesConfig().transform_list_files_response(+ raw_response=httpx.Response(200, content=self.OUTPUT_BUCKET_LISTING),+ logging_obj=MagicMock(),+ litellm_params={+ **_trusted_bucket_snapshot(s3_bucket_name="my-bucket", s3_output_bucket_name="my-output-bucket"),+ LIST_FILES_PURPOSE_PARAM: "batch_output",+ },+ )++ assert [(file.id, file.purpose, file.bytes) for file in files] == [(self.OUTPUT_BUCKET_ID, "batch_output", 70)]++ def test_file_list_batch_output_end_to_end_lists_output_bucket(self, monkeypatch):+ import httpx+ import respx++ import litellm++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)+ monkeypatch.delenv("AWS_S3_OUTPUT_BUCKET_NAME", raising=False)++ with respx.mock:+ route = respx.get(self.OUTPUT_BUCKET_URL, params__contains=self.OUTPUT_QUERY).mock(+ return_value=httpx.Response(200, content=self.OUTPUT_BUCKET_LISTING)+ )++ files = litellm.file_list(+ custom_llm_provider="bedrock",+ purpose="batch_output",+ **_trusted_bucket_snapshot(s3_bucket_name="my-bucket", s3_output_bucket_name="my-output-bucket"),+ )++ assert route.called+ request = route.calls[0].request+ assert _sent_signature(request.headers) == _s3_signature_for("GET", str(request.url), request.headers)+ assert [file.id for file in files] == [self.OUTPUT_BUCKET_ID]++ def test_transform_list_files_next_request_signs_the_continuation_page(self, monkeypatch):+ import httpx++ from litellm.llms.bedrock.files.transformation import (+ S3_SIGNED_REQUEST_HEADERS_PARAM,+ BedrockFilesConfig,+ )++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ litellm_params = _bedrock_s3_params()+ config = BedrockFilesConfig()+ config.transform_list_files_request(purpose="batch", optional_params={}, litellm_params=litellm_params)+ first_signature = _sent_signature(litellm_params.pop(S3_SIGNED_REQUEST_HEADERS_PARAM))++ next_request = config.transform_list_files_next_request(+ raw_response=httpx.Response(200, content=self.FIRST_PAGE),+ optional_params={},+ litellm_params=litellm_params,+ )++ assert next_request == (self.BUCKET_URL, {**self.BATCH_QUERY, "continuation-token": self.CONTINUATION_TOKEN})+ signed_headers = litellm_params[S3_SIGNED_REQUEST_HEADERS_PARAM]+ signed_url = (+ f"{self.BUCKET_URL}?list-type=2&prefix=litellm-bedrock-files"+ "&continuation-token=1ueGcxLPRx1Tr%2FXYExHnhbYLgveDs2J%2Fwm36Hy4vbOwM%3D"+ )+ assert _sent_signature(signed_headers) == _s3_signature_for("GET", signed_url, signed_headers)+ assert _sent_signature(signed_headers) != first_signature++ @pytest.mark.parametrize(+ ("status_code", "content"),+ [+ pytest.param(200, LAST_PAGE, id="last-page"),+ pytest.param(403, b"<Error><Code>AccessDenied</Code></Error>", id="error-page"),+ ],+ )+ def test_transform_list_files_next_request_stops_after_the_last_page(self, monkeypatch, status_code, content):+ import httpx++ from litellm.llms.bedrock.files.transformation import (+ S3_SIGNED_REQUEST_HEADERS_PARAM,+ BedrockFilesConfig,+ )++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")+ litellm_params = _bedrock_s3_params()++ next_request = BedrockFilesConfig().transform_list_files_next_request(+ raw_response=httpx.Response(status_code, content=content),+ optional_params={},+ litellm_params=litellm_params,+ )++ assert next_request is None+ assert S3_SIGNED_REQUEST_HEADERS_PARAM not in litellm_params++ def _mock_paged_listing(self, respx_module):+ import httpx++ last_page = respx_module.get(+ self.BUCKET_URL, params__contains={"continuation-token": self.CONTINUATION_TOKEN}+ ).mock(return_value=httpx.Response(200, content=self.LAST_PAGE))+ first_page = respx_module.get(self.BUCKET_URL, params__contains=self.BATCH_QUERY).mock(+ return_value=httpx.Response(200, content=self.FIRST_PAGE)+ )+ return first_page, last_page++ def _assert_paged_listing(self, first_page, last_page, files):+ assert (first_page.call_count, last_page.call_count) == (1, 1)+ read_timeouts = [call.request.extensions["timeout"]["read"] for call in (*first_page.calls, *last_page.calls)]+ assert read_timeouts == [12.0, 12.0]+ assert "continuation-token" not in str(first_page.calls[0].request.url)+ last_request = last_page.calls[0].request+ assert _sent_signature(last_request.headers) == _s3_signature_for(+ "GET", str(last_request.url), last_request.headers+ )+ assert [file.id for file in files] == list(self.PAGED_IDS)++ def test_file_list_follows_continuation_tokens_across_pages(self, monkeypatch):+ import respx++ import litellm++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)+ monkeypatch.delenv("AWS_S3_OUTPUT_BUCKET_NAME", raising=False)++ with respx.mock:+ first_page, last_page = self._mock_paged_listing(respx)+ files = litellm.file_list(+ custom_llm_provider="bedrock",+ purpose="batch",+ timeout=12,+ **_trusted_bucket_snapshot(s3_bucket_name="my-bucket"),+ )++ self._assert_paged_listing(first_page, last_page, files)++ @pytest.mark.asyncio+ async def test_afile_list_follows_continuation_tokens_across_pages(self, monkeypatch):+ import respx++ import litellm++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)+ monkeypatch.delenv("AWS_S3_OUTPUT_BUCKET_NAME", raising=False)+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ litellm.in_memory_llm_clients_cache.flush_cache()++ with respx.mock:+ first_page, last_page = self._mock_paged_listing(respx)+ files = await litellm.afile_list(+ custom_llm_provider="bedrock",+ purpose="batch",+ timeout=12,+ **_trusted_bucket_snapshot(s3_bucket_name="my-bucket"),+ )++ self._assert_paged_listing(first_page, last_page, files)++ OVERSIZED_PAGE_SIZE = 3000+ OVERSIZED_PAGE_COUNT = 6++ def _oversized_listing_page(self, page_index: int) -> bytes:+ contents = "".join(+ f"<Contents><Key>litellm-bedrock-files/page-{page_index}/obj-{index}.jsonl</Key>"+ "<LastModified>2026-09-01T10:00:00.000Z</LastModified><Size>1</Size></Contents>"+ for index in range(self.OVERSIZED_PAGE_SIZE)+ )+ continuation = (+ f"<IsTruncated>true</IsTruncated><NextContinuationToken>page-{page_index + 1}</NextContinuationToken>"+ if page_index < self.OVERSIZED_PAGE_COUNT - 1+ else "<IsTruncated>false</IsTruncated>"+ )+ return (+ '<?xml version="1.0" encoding="UTF-8"?>'+ '<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'+ f"{continuation}{contents}</ListBucketResult>"+ ).encode()++ def _mock_oversized_listing(self, respx_module):+ import httpx++ def page_for(request):+ token = request.url.params.get("continuation-token", "page-0")+ return httpx.Response(200, content=self._oversized_listing_page(int(token.removeprefix("page-"))))++ return respx_module.get(self.BUCKET_URL, params__contains=self.BATCH_QUERY).mock(side_effect=page_for)++ def _assert_capped_listing(self, route, files):+ from litellm.constants import MAX_FILE_LIST_LIMIT++ pages_needed = -(-MAX_FILE_LIST_LIMIT // self.OVERSIZED_PAGE_SIZE)+ last_index = MAX_FILE_LIST_LIMIT - (pages_needed - 1) * self.OVERSIZED_PAGE_SIZE - 1+ assert pages_needed < self.OVERSIZED_PAGE_COUNT+ assert route.call_count == pages_needed+ assert len(files) == MAX_FILE_LIST_LIMIT+ assert files[-1].id == f"s3://my-bucket/litellm-bedrock-files/page-{pages_needed - 1}/obj-{last_index}.jsonl"++ def test_file_list_stops_at_the_openai_listing_ceiling(self, monkeypatch):+ import respx++ import litellm++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)+ monkeypatch.delenv("AWS_S3_OUTPUT_BUCKET_NAME", raising=False)++ with respx.mock:+ route = self._mock_oversized_listing(respx)+ files = litellm.file_list(+ custom_llm_provider="bedrock",+ purpose="batch",+ **_trusted_bucket_snapshot(s3_bucket_name="my-bucket"),+ )++ self._assert_capped_listing(route, files)++ @pytest.mark.asyncio+ async def test_afile_list_stops_at_the_openai_listing_ceiling(self, monkeypatch):+ import respx++ import litellm++ monkeypatch.delenv("AWS_S3_BUCKET_NAME", raising=False)+ monkeypatch.delenv("AWS_S3_OUTPUT_BUCKET_NAME", raising=False)+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ litellm.in_memory_llm_clients_cache.flush_cache()++ with respx.mock:+ route = self._mock_oversized_listing(respx)+ files = await litellm.afile_list(+ custom_llm_provider="bedrock",+ purpose="batch",+ **_trusted_bucket_snapshot(s3_bucket_name="my-bucket"),+ )++ self._assert_capped_listing(route, files)++ def test_file_list_end_to_end_surfaces_the_s3_error_body(self, monkeypatch):+ import httpx+ import respx++ import litellm+ from litellm.llms.bedrock.common_utils import BedrockError++ monkeypatch.setenv("AWS_S3_BUCKET_NAME", "my-bucket")++ with respx.mock:+ respx.get(self.BUCKET_URL, params__contains=self.BATCH_QUERY).mock(+ return_value=httpx.Response(403, text="<Error><Code>AccessDenied</Code></Error>")+ )+ with pytest.raises(BedrockError) as denied:+ litellm.file_list(custom_llm_provider="bedrock", purpose="batch", **_bedrock_s3_params())++ assert denied.value.status_code == 403+ assert "AccessDenied" in denied.value.messagediff --cc tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.pyindex c8a705a729a,5f1e7e1fe0c..b696d9ebe5f--- a/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py+++ b/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py@@@ -4725,244 -4668,154 +4725,397 @@@ def test_create_file_path_traversal_filassert forwarded_calls == []+def test_list_files_target_model_names_passes_trusted_bedrock_credentials(+ mocker: MockerFixture, monkeypatch+):+ """+ GET /v1/files?target_model_names=<bedrock model> must hand the deployment's+ immutable credential snapshot to litellm.afile_list, since Bedrock resolves+ the S3 bucket to list from that snapshot rather than from request params.+ """+ from types import MappingProxyType++ import litellm.proxy.proxy_server as ps+ from litellm.proxy._types import LitellmUserRoles++ bedrock_router = Router(+ model_list=[+ {+ "model_name": "bedrock-claude",+ "litellm_params": {+ "model": "bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0",+ "aws_access_key_id": "AKIAEXAMPLE",+ "aws_secret_access_key": "secret",+ "aws_region_name": "us-west-2",+ "s3_bucket_name": "my-bucket",+ },+ },+ ]+ )++ proxy_logging_obj = setup_proxy_logging_object(monkeypatch, bedrock_router)+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", bedrock_router)+ proxy_logging_obj.update_request_status = mocker.AsyncMock()+ proxy_logging_obj.post_call_success_hook = mocker.AsyncMock(return_value=[])+ proxy_logging_obj.post_call_failure_hook = mocker.AsyncMock()++ captured_kwargs: dict = {}++ async def _mock_afile_list(**kwargs):+ captured_kwargs.update(kwargs)+ return []++ monkeypatch.setattr(litellm, "afile_list", _mock_afile_list)++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ api_key="test-key",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ user_id="test-user",+ )++ try:+ response = client.get(+ "/v1/files?target_model_names=bedrock-claude&purpose=batch",+ headers={"Authorization": "Bearer test-key"},+ )+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++ assert response.status_code == 200, response.text+ assert captured_kwargs["custom_llm_provider"] == "bedrock"+ assert captured_kwargs["purpose"] == "batch"+ trusted_credentials = captured_kwargs["_litellm_internal_model_credentials"]+ assert isinstance(trusted_credentials, MappingProxyType)+ assert trusted_credentials["s3_bucket_name"] == "my-bucket"+ proxy_logging_obj.post_call_failure_hook.assert_not_called()+++def test_delete_file_answers_400_for_an_id_outside_the_configured_bucket(mocker: MockerFixture, monkeypatch):+ from urllib.parse import quote++ import litellm.proxy.proxy_server as ps+ from litellm.proxy._types import LitellmUserRoles++ bedrock_router = Router(+ model_list=[+ {+ "model_name": "bedrock-claude",+ "litellm_params": {+ "model": "bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0",+ "aws_access_key_id": "AKIAEXAMPLE",+ "aws_secret_access_key": "secret",+ "aws_region_name": "us-west-2",+ "s3_bucket_name": "my-bucket",+ },+ },+ ]+ )++ proxy_logging_obj = setup_proxy_logging_object(monkeypatch, bedrock_router)+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", bedrock_router)+ proxy_logging_obj.update_request_status = mocker.AsyncMock()+ proxy_logging_obj.post_call_success_hook = mocker.AsyncMock(return_value=[])+ proxy_logging_obj.post_call_failure_hook = mocker.AsyncMock()++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ api_key="test-key",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ user_id="test-user",+ )+ foreign_file_id: Final = quote("s3://other-bucket/litellm-bedrock-files/job-123/input.jsonl", safe="")++ try:+ with respx.mock:+ response = client.delete(+ f"/v1/files/{foreign_file_id}?model=bedrock-claude",+ headers={"Authorization": "Bearer test-key"},+ )+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++ assert response.status_code == 400, response.text+ assert "configured storage bucket" in response.json()["error"]["message"]+++def _cloud_files_router() -> Router:+ return Router(+ model_list=[+ {+ "model_name": "bedrock-claude",+ "litellm_params": {+ "model": "bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0",+ "aws_access_key_id": "AKIAEXAMPLE",+ "aws_secret_access_key": "secret",+ "aws_region_name": "us-west-2",+ "s3_bucket_name": "my-bucket",+ },+ },+ {+ "model_name": "vertex-gemini",+ "litellm_params": {+ "model": "vertex_ai/gemini-3.8-flash",+ "vertex_project": "my-project",+ "vertex_location": "us-central1",+ "gcs_bucket_name": "my-gcs-bucket",+ },+ },+ ]+ )+++RAW_S3_FILE_ID: Final = "s3://my-bucket/litellm-batch-outputs/job-123/abc/input.jsonl.out"+RAW_GCS_FILE_ID: Final = "gs://my-gcs-bucket/litellm-vertex-files/publishers/google/models/gemini-3.8-flash/abc123"+++ ("route_prefix", "raw_file_id", "model_name"),+ (+ ("/bedrock/v1/files", RAW_S3_FILE_ID, "bedrock-claude"),+ ("/v1/files", RAW_S3_FILE_ID, "bedrock-claude"),+ ("/files", RAW_S3_FILE_ID, "bedrock-claude"),+ ("/vertex_ai/v1/files", RAW_GCS_FILE_ID, "vertex-gemini"),+ ),+)+def test_delete_file_answers_403_for_a_raw_cloud_id_from_a_non_admin_key(+ mocker: MockerFixture, monkeypatch, route_prefix: str, raw_file_id: str, model_name: str+):+ from urllib.parse import quote++ import litellm.proxy.proxy_server as ps+ from litellm.proxy._types import LitellmUserRoles++ bedrock_router = _cloud_files_router()+ proxy_logging_obj = setup_proxy_logging_object(monkeypatch, bedrock_router)+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", bedrock_router)+ proxy_logging_obj.update_request_status = mocker.AsyncMock()+ proxy_logging_obj.post_call_failure_hook = mocker.AsyncMock()+ afile_delete = mocker.AsyncMock()+ monkeypatch.setattr(litellm, "afile_delete", afile_delete)++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ api_key="test-key",+ user_role=LitellmUserRoles.INTERNAL_USER,+ user_id="test-user",+ models=["bedrock-claude", "vertex-gemini"],+ )++ try:+ response = client.delete(+ f"{route_prefix}/{quote(raw_file_id, safe='')}?model={model_name}",+ headers={"Authorization": "Bearer test-key"},+ )+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++ assert response.status_code == 403, response.text+ assert "proxy admin" in response.json()["error"]["message"]+ afile_delete.assert_not_called()+++def test_delete_file_forwards_a_raw_cloud_id_from_a_proxy_admin_key(mocker: MockerFixture, monkeypatch):+ from urllib.parse import quote++ import litellm.proxy.proxy_server as ps+ from litellm.proxy._types import LitellmUserRoles++ bedrock_router = _cloud_files_router()+ proxy_logging_obj = setup_proxy_logging_object(monkeypatch, bedrock_router)+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", bedrock_router)+ proxy_logging_obj.update_request_status = mocker.AsyncMock()+ proxy_logging_obj.post_call_failure_hook = mocker.AsyncMock()++ captured_kwargs: dict = {}++ async def _mock_afile_delete(**kwargs):+ captured_kwargs.update(kwargs)+ return OpenAIFileObject(+ id=RAW_S3_FILE_ID,+ object="file",+ bytes=2,+ created_at=1234567890,+ filename="input.jsonl.out",+ purpose="batch_output",+ status="processed",+ )++ monkeypatch.setattr(litellm, "afile_delete", _mock_afile_delete)++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ api_key="test-key",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ user_id="test-user",+ )++ try:+ response = client.delete(+ f"/bedrock/v1/files/{quote(RAW_S3_FILE_ID, safe='')}?model=bedrock-claude",+ headers={"Authorization": "Bearer test-key"},+ )+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++ assert response.status_code == 200, response.text+ assert captured_kwargs.get("file_id") == RAW_S3_FILE_ID+ assert captured_kwargs.get("custom_llm_provider") == "bedrock"+ proxy_logging_obj.post_call_failure_hook.assert_not_called()+++++ def _setup_managed_file_route_answering_404(+ mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch, llm_router: Router+ ) -> None:+ """Wire the single-file routes to a managed file store that knows no file, the way the+ managed files hook answers once a file has been deleted or was never the caller's."""+ import litellm.proxy.proxy_server as ps+ from fastapi import HTTPException+ from litellm.llms.base_llm.files.transformation import BaseFileEndpoints+ from litellm.proxy._types import LitellmUserRoles++ async def _file_not_found(file_id: str, **kwargs: object) -> None:+ raise HTTPException(status_code=404, detail=f"File not found: {file_id}")++ proxy_logging_obj = setup_proxy_logging_object(monkeypatch, llm_router)+ managed_files = mocker.MagicMock(spec=BaseFileEndpoints)+ managed_files.afile_retrieve = mocker.AsyncMock(side_effect=_file_not_found)+ managed_files.afile_delete = mocker.AsyncMock(side_effect=_file_not_found)+ managed_files.afile_content = mocker.AsyncMock(side_effect=_file_not_found)+ proxy_logging_obj.proxy_hook_mapping["managed_files"] = managed_files+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", llm_router)++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ api_key="test-key",+ user_role=LitellmUserRoles.INTERNAL_USER,+ user_id="test-user",+ )+++ def _call_managed_file_route(method: str, path: str) -> httpx.Response:+ try:+ return client.request(method, path, headers={"Authorization": "Bearer test-key"})+ finally:+ import litellm.proxy.proxy_server as ps++ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++ def _missing_managed_file_error(file_id: str) -> dict[str, dict[str, str | None]]:+ return {+ "error": {+ "message": f"File not found: {file_id}",+ "type": "invalid_request_error",+ "param": None,+ "code": "404",+ }+ }+++ def test_create_file_reports_a_half_specified_expires_after_as_a_400(+ monkeypatch: pytest.MonkeyPatch, llm_router: Router+ ):+ """A 400 raised inside the route answers with the type a 400 stands for and a JSON null+ param, not the literal string "None" in both fields, so a client can classify it."""+ setup_proxy_logging_object(monkeypatch, llm_router)+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", llm_router)++ response = client.post(+ "/v1/files",+ files={"file": ("mydata.jsonl", VALID_BATCH_LINE, "application/jsonl")},+ data={"purpose": "batch", "target_model_names": "gpt-3.5-turbo", "expires_after[anchor]": "created_at"},+ headers={"Authorization": "Bearer test-key"},+ )++ assert response.status_code == 400, response.text+ error = response.json()["error"]+ assert "expires_after[seconds]" in error["message"]+ assert error["type"] == "invalid_request_error"+ assert error["param"] is None+ assert error["code"] == "400"+++ def test_get_file_reports_a_missing_managed_file_as_a_404(+ mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch, llm_router: Router+ ):+ _setup_managed_file_route_answering_404(mocker, monkeypatch, llm_router)+ file_id = _unified_managed_file_id()++ response = _call_managed_file_route("GET", f"/v1/files/{file_id}")++ assert response.status_code == 404, response.text+ assert response.json() == _missing_managed_file_error(file_id)+++ def test_delete_file_reports_a_missing_managed_file_as_a_404(+ mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch, llm_router: Router+ ):+ _setup_managed_file_route_answering_404(mocker, monkeypatch, llm_router)+ file_id = _unified_managed_file_id()++ response = _call_managed_file_route("DELETE", f"/v1/files/{file_id}")++ assert response.status_code == 404, response.text+ assert response.json() == _missing_managed_file_error(file_id)+++ def test_get_file_content_reports_a_missing_managed_file_as_a_404(+ mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch, llm_router: Router+ ):+ _setup_managed_file_route_answering_404(mocker, monkeypatch, llm_router)+ file_id = _unified_managed_file_id()++ response = _call_managed_file_route("GET", f"/v1/files/{file_id}/content")++ assert response.status_code == 404, response.text+ assert response.json() == _missing_managed_file_error(file_id)+++ def _setup_managed_file_stored_in_an_unknown_storage_backend(+ mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch, llm_router: Router+ ) -> None:+ """Wire the content route to a managed file whose row names a storage backend the+ factory does not know, which is the one in-route ProxyException on these routes."""+ from types import SimpleNamespace++ import litellm.proxy.proxy_server as ps+ from litellm.llms.base_llm.files.transformation import BaseFileEndpoints+ from litellm.proxy._types import LitellmUserRoles++ proxy_logging_obj = setup_proxy_logging_object(monkeypatch, llm_router)+ managed_files = mocker.MagicMock(spec=BaseFileEndpoints)+ managed_files.prisma_client = mocker.MagicMock()+ proxy_logging_obj.proxy_hook_mapping["managed_files"] = managed_files+ repository = mocker.MagicMock()+ repository.table.find_first = mocker.AsyncMock(+ return_value=SimpleNamespace(storage_backend="ftp", storage_url="ftp://bucket/file")+ )+ monkeypatch.setattr(+ "litellm.proxy.openai_files_endpoints.files_endpoints.ManagedFileRepository", lambda _prisma: repository+ )+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", llm_router)++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ api_key="test-key",+ user_role=LitellmUserRoles.INTERNAL_USER,+ user_id="test-user",+ )+++ def test_get_file_content_keeps_the_status_of_a_rejection_raised_inside_the_route(+ mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch, llm_router: Router+ ):+ """A ProxyException raised inside the route carries its status as the string ``code``,+ and the tail used to rebuild it as a 500 because it only read ``status_code``."""+ _setup_managed_file_stored_in_an_unknown_storage_backend(mocker, monkeypatch, llm_router)++ response = _call_managed_file_route("GET", f"/v1/files/{_unified_managed_file_id()}/content")++ assert response.status_code == 400, response.text+ error = response.json()["error"]+ assert error["message"].startswith("Storage backend error")+ assert (error["type"], error["param"], error["code"]) == ("invalid_request_error", "file_id", "400")