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
harden cloud file compatibility path
user2776e0162c69
diff --git a/litellm/files/main.py b/litellm/files/main.pyindex ceccba8d800..a516ab372d7 100644--- a/litellm/files/main.py+++ b/litellm/files/main.py@@ -10,6 +10,7 @@ import contextvarsimport timeimport uuid as uuid_modulefrom functools import partial+from types import MappingProxyTypefrom typing import Any, Coroutine, Dict, Literal, Optional, Union, castimport httpx@@ -846,6 +847,11 @@ def file_content(try:optional_params = GenericLiteLLMParams(**kwargs)litellm_params_dict = get_litellm_params(**kwargs)+ trusted_model_credentials = kwargs.get("_litellm_internal_model_credentials")+ if isinstance(trusted_model_credentials, type(MappingProxyType({}))):+ litellm_params_dict["_litellm_internal_model_credentials"] = (+ trusted_model_credentials+ )### TIMEOUT LOGIC ###timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600client = kwargs.get("client")diff --git a/litellm/litellm_core_utils/cloud_storage_security.py b/litellm/litellm_core_utils/cloud_storage_security.pyindex b47a07abb91..4766331fae1 100644--- a/litellm/litellm_core_utils/cloud_storage_security.py+++ b/litellm/litellm_core_utils/cloud_storage_security.py@@ -1,3 +1,4 @@+import osimport posixpathimport refrom typing import Optional, Sequence, Tuple@@ -109,11 +110,26 @@ def encode_s3_object_key_for_url(object_key: str) -> str:return quote(unquote(object_key), safe="/")+def should_allow_legacy_cloud_file_ids(litellm_params: Optional[dict] = None) -> bool:+ value = None+ if isinstance(litellm_params, dict):+ value = litellm_params.get("allow_legacy_cloud_file_ids")+ if value is None:+ value = os.getenv("LITELLM_ALLOW_LEGACY_CLOUD_FILE_IDS")++ if isinstance(value, bool):+ return value+ if isinstance(value, str):+ return value.strip().lower() in {"1", "true", "yes", "on"}+ return False++def validate_managed_cloud_file_id(file_id: str,scheme: str,configured_bucket_name: str,allowed_object_prefixes: Sequence[str],+ allow_legacy_cloud_file_ids: bool = False,) -> Tuple[str, str]:decoded_file_id = unquote(file_id)if not decoded_file_id.startswith(scheme):@@ -137,7 +153,16 @@ def validate_managed_cloud_file_id(f"{configured_prefix.rstrip('/')}/{prefix}" for prefix in allowed_prefixes)- if not object_name.startswith(allowed_prefixes):- raise ValueError("file_id must reference a LiteLLM-managed storage object")+ if object_name.startswith(allowed_prefixes):+ return bucket_name, object_name++ if allow_legacy_cloud_file_ids:+ if configured_prefix and not object_name.startswith(+ f"{configured_prefix.rstrip('/')}/"+ ):+ raise ValueError(+ "file_id object does not match the configured storage prefix"+ )+ return bucket_name, object_name- return bucket_name, object_name+ raise ValueError("file_id must reference a LiteLLM-managed storage object")diff --git a/litellm/llms/bedrock/files/handler.py b/litellm/llms/bedrock/files/handler.pyindex b3cd77cff72..faa34ac6ca7 100644--- a/litellm/llms/bedrock/files/handler.py+++ b/litellm/llms/bedrock/files/handler.py@@ -1,6 +1,7 @@import asyncioimport base64import os+from types import MappingProxyTypefrom typing import Any, Coroutine, Optional, Tuple, Unionimport httpx@@ -8,6 +9,7 @@ import httpxfrom litellm import LlmProvidersfrom litellm.litellm_core_utils.cloud_storage_security import (BEDROCK_MANAGED_S3_PREFIXES,+ should_allow_legacy_cloud_file_ids,validate_managed_cloud_file_id,)from litellm.llms.custom_httpx.http_handler import get_async_httpx_client@@ -71,7 +73,10 @@ class BedrockFilesHandler(BaseAWSLLM):raise ValueError("file_id must be a managed LiteLLM S3 file id")def _parse_s3_uri(- self, s3_uri: str, configured_bucket_name: str+ self,+ s3_uri: str,+ configured_bucket_name: str,+ allow_legacy_cloud_file_ids: bool = False,) -> Tuple[str, str]:"""Parse S3 URI to extract bucket name and object key.@@ -87,13 +92,20 @@ class BedrockFilesHandler(BaseAWSLLM):scheme="s3://",configured_bucket_name=configured_bucket_name,allowed_object_prefixes=BEDROCK_MANAGED_S3_PREFIXES,+ allow_legacy_cloud_file_ids=allow_legacy_cloud_file_ids,)- def _get_configured_s3_bucket_name(self, optional_params: dict) -> str:- bucket_name = os.getenv("AWS_S3_BUCKET_NAME")+ def _get_configured_s3_bucket_name(self, litellm_params: dict) -> str:+ trusted_model_credentials = litellm_params.get(+ "_litellm_internal_model_credentials"+ )+ bucket_name = None+ if isinstance(trusted_model_credentials, type(MappingProxyType({}))):+ bucket_name = trusted_model_credentials.get("s3_bucket_name")+ bucket_name = bucket_name or os.getenv("AWS_S3_BUCKET_NAME")if not bucket_name:raise ValueError(- "S3 bucket_name is required. Set AWS_S3_BUCKET_NAME for Bedrock file content retrieval."+ "S3 bucket_name is required. Set 's3_bucket_name' in proxy config or AWS_S3_BUCKET_NAME for Bedrock file content retrieval.")return bucket_name@@ -129,6 +141,9 @@ class BedrockFilesHandler(BaseAWSLLM):bucket_name, object_key = self._parse_s3_uri(s3_uri=s3_uri,configured_bucket_name=configured_bucket_name,+ allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids(+ optional_params+ ),)# Get AWS credentialsdiff --git a/litellm/llms/vertex_ai/files/handler.py b/litellm/llms/vertex_ai/files/handler.pyindex 48683ba41ae..402a21f56c4 100644--- a/litellm/llms/vertex_ai/files/handler.py+++ b/litellm/llms/vertex_ai/files/handler.py@@ -11,6 +11,7 @@ from litellm.integrations.gcs_bucket.gcs_bucket_base import ()from litellm.litellm_core_utils.cloud_storage_security import (VERTEX_AI_MANAGED_GCS_PREFIX,+ should_allow_legacy_cloud_file_ids,validate_managed_cloud_file_id,)from litellm.llms.custom_httpx.http_handler import get_async_httpx_client@@ -134,6 +135,7 @@ class VertexAIFilesHandler(GCSBucketBase):scheme="gs://",configured_bucket_name=configured_bucket_name,allowed_object_prefixes=(VERTEX_AI_MANAGED_GCS_PREFIX,),+ allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids(),)async def afile_content(diff --git a/litellm/llms/vertex_ai/files/transformation.py b/litellm/llms/vertex_ai/files/transformation.pyindex b864ad43136..85663bd551c 100644--- a/litellm/llms/vertex_ai/files/transformation.py+++ b/litellm/llms/vertex_ai/files/transformation.py@@ -12,6 +12,7 @@ from litellm.litellm_core_utils.cloud_storage_security import (build_managed_cloud_object_name,encode_gcs_object_name_for_url,sanitize_cloud_object_path,+ should_allow_legacy_cloud_file_ids,split_configured_cloud_bucket_name,validate_managed_cloud_file_id,)@@ -362,6 +363,9 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig):scheme="gs://",configured_bucket_name=configured_bucket_name,allowed_object_prefixes=(VERTEX_AI_MANAGED_GCS_PREFIX,),+ allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids(+ litellm_params+ ),)return bucket_name, encode_gcs_object_name_for_url(object_path)diff --git a/litellm/proxy/openai_files_endpoints/common_utils.py b/litellm/proxy/openai_files_endpoints/common_utils.pyindex 25ad1b25aad..30c78ed5ba7 100644--- a/litellm/proxy/openai_files_endpoints/common_utils.py+++ b/litellm/proxy/openai_files_endpoints/common_utils.py@@ -2,6 +2,7 @@ import base64import mimetypesimport refrom dataclasses import dataclass, field+from types import MappingProxyTypefrom typing import TYPE_CHECKING, List, Literal, Optional, Unionfrom litellm.types.utils import SpecialEnums@@ -298,6 +299,7 @@ def prepare_data_with_credentials(data: dict,credentials: dict,file_id: Optional[str] = None,+ include_internal_credentials: bool = False,) -> None:"""Update data dictionary with model credentials (in-place).@@ -306,8 +308,14 @@ def prepare_data_with_credentials(data: Data dictionary to updatecredentials: Credentials from routerfile_id: Optional original file_id to set (for decoded file IDs)+ include_internal_credentials: Preserve an immutable server-side snapshot+ for code paths that must distinguish proxy config from request params."""data.update(credentials)+ if include_internal_credentials:+ data["_litellm_internal_model_credentials"] = MappingProxyType(+ dict(credentials)+ )data.pop("custom_llm_provider", None)if file_id is not None:diff --git a/litellm/proxy/openai_files_endpoints/files_endpoints.py b/litellm/proxy/openai_files_endpoints/files_endpoints.pyindex c9be707af0c..c69898621e4 100644--- a/litellm/proxy/openai_files_endpoints/files_endpoints.py+++ b/litellm/proxy/openai_files_endpoints/files_endpoints.py@@ -774,6 +774,7 @@ async def get_file_content( # noqa: PLR0915data=data,credentials=credentials, # type: ignorefile_id=original_file_id, # Use decoded file ID if from encoded ID+ include_internal_credentials=True,)response = await litellm.afile_content(custom_llm_provider=credentials["custom_llm_provider"], # type: ignorediff --git a/tests/litellm/proxy/test_model_based_routing_files_batches.py b/tests/litellm/proxy/test_model_based_routing_files_batches.pyindex 94e2c4603bc..f9bc07212a2 100644--- a/tests/litellm/proxy/test_model_based_routing_files_batches.py+++ b/tests/litellm/proxy/test_model_based_routing_files_batches.py@@ -6,10 +6,13 @@ Tests the model-based routing ID encoding/decoding used by the batchand file proxy endpoints."""+from types import MappingProxyType+from litellm.proxy.openai_files_endpoints.common_utils import (decode_model_from_file_id,encode_file_id_with_model,get_original_file_id,+ prepare_data_with_credentials,)@@ -50,6 +53,42 @@ class TestEncodeFileIdWithModel:assert result.startswith("file-")+class TestPrepareDataWithCredentials:+ def test_preserves_trusted_internal_credentials_snapshot(self):+ data = {"file_id": "file-abc"}+ credentials = {+ "custom_llm_provider": "bedrock",+ "s3_bucket_name": "safe-bucket",+ }++ prepare_data_with_credentials(+ data=data,+ credentials=credentials,+ include_internal_credentials=True,+ )++ assert data["s3_bucket_name"] == "safe-bucket"+ assert "custom_llm_provider" not in data+ assert isinstance(+ data["_litellm_internal_model_credentials"], type(MappingProxyType({}))+ )+ assert (+ data["_litellm_internal_model_credentials"]["s3_bucket_name"]+ == "safe-bucket"+ )++ def test_does_not_add_internal_credentials_by_default(self):+ data = {"file_id": "file-abc"}+ credentials = {+ "custom_llm_provider": "bedrock",+ "s3_bucket_name": "safe-bucket",+ }++ prepare_data_with_credentials(data=data, credentials=credentials)++ assert "_litellm_internal_model_credentials" not in data++class TestRoundTrip:"""Tests for encode -> decode round-trip integrity."""diff --git a/tests/test_litellm/llms/bedrock/files/test_bedrock_files_handler.py b/tests/test_litellm/llms/bedrock/files/test_bedrock_files_handler.pyindex d1622008b0e..e73be764c66 100644--- a/tests/test_litellm/llms/bedrock/files/test_bedrock_files_handler.py+++ b/tests/test_litellm/llms/bedrock/files/test_bedrock_files_handler.py@@ -1,9 +1,11 @@import base64import os-from unittest.mock import patch+from types import MappingProxyType+from unittest.mock import MagicMock, patchimport pytest+import litellm.files.main as files_mainfrom litellm.llms.bedrock.files.handler import BedrockFilesHandlerfrom litellm.types.utils import SpecialEnums@@ -55,6 +57,34 @@ class TestBedrockFilesHandler:configured_bucket_name="safe-bucket",)+ def test_should_allow_legacy_same_bucket_key_when_server_flag_enabled(self):+ bucket, key = self.handler._parse_s3_uri(+ s3_uri="s3://safe-bucket/private/output.jsonl",+ configured_bucket_name="safe-bucket",+ allow_legacy_cloud_file_ids=True,+ )++ assert bucket == "safe-bucket"+ assert key == "private/output.jsonl"++ def test_should_keep_configured_prefix_for_legacy_keys(self):+ bucket, key = self.handler._parse_s3_uri(+ s3_uri="s3://safe-bucket/team-a/private/output.jsonl",+ configured_bucket_name="safe-bucket/team-a",+ allow_legacy_cloud_file_ids=True,+ )++ assert bucket == "safe-bucket"+ assert key == "team-a/private/output.jsonl"++ def test_should_reject_legacy_key_outside_configured_prefix(self):+ with pytest.raises(ValueError, match="configured storage prefix"):+ self.handler._parse_s3_uri(+ s3_uri="s3://safe-bucket/team-b/private/output.jsonl",+ configured_bucket_name="safe-bucket/team-a",+ allow_legacy_cloud_file_ids=True,+ )+def test_should_reject_dot_segment_key(self):with pytest.raises(ValueError, match="invalid path segment"):self.handler._parse_s3_uri(@@ -102,9 +132,55 @@ class TestBedrockFilesHandler:== "safe-bucket")+ def test_should_trust_proxy_config_s3_bucket_name_for_expected_bucket(self):+ trusted_credentials = MappingProxyType({"s3_bucket_name": "safe-bucket"})++ with patch.dict(os.environ, {}, clear=True):+ assert (+ self.handler._get_configured_s3_bucket_name(+ {+ "s3_bucket_name": "attacker-bucket",+ "_litellm_internal_model_credentials": trusted_credentials,+ }+ )+ == "safe-bucket"+ )++ def test_should_not_trust_user_supplied_internal_credentials_dict(self):+ with patch.dict(os.environ, {}, clear=True):+ with pytest.raises(ValueError, match="S3 bucket_name is required"):+ self.handler._get_configured_s3_bucket_name(+ {+ "_litellm_internal_model_credentials": {+ "s3_bucket_name": "attacker-bucket"+ }+ }+ )+def test_should_require_server_s3_bucket_name(self):with patch.dict(os.environ, {}, clear=True):- with pytest.raises(ValueError, match="AWS_S3_BUCKET_NAME"):+ with pytest.raises(ValueError, match="S3 bucket_name is required"):self.handler._get_configured_s3_bucket_name({"s3_bucket_name": "attacker-bucket"})+++def test_should_forward_trusted_model_credentials_to_bedrock_provider_config():+ trusted_credentials = MappingProxyType({"s3_bucket_name": "safe-bucket"})+ mock_response = MagicMock()++ with patch.object(+ files_main.base_llm_http_handler,+ "retrieve_file_content",+ return_value=mock_response,+ ) as mock_retrieve_file_content:+ response = files_main.file_content(+ file_id="s3://safe-bucket/litellm-bedrock-files/file.jsonl",+ custom_llm_provider="bedrock",+ _litellm_internal_model_credentials=trusted_credentials,+ )++ assert response is mock_response+ litellm_params = mock_retrieve_file_content.call_args.kwargs["litellm_params"]+ assert litellm_params["_litellm_internal_model_credentials"] is trusted_credentials+ assert "s3_bucket_name" not in litellm_paramsdiff --git a/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_handler.py b/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_handler.pyindex 2b71e6c18dc..6558cc2969f 100644--- a/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_handler.py+++ b/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_handler.py@@ -3,6 +3,7 @@ Test Vertex AI files handler functionality"""import asyncio+import osimport pytestfrom unittest.mock import AsyncMock, patch@@ -66,6 +67,22 @@ class TestVertexAIFilesHandler:configured_bucket_name="test-bucket",)+ def test_extract_bucket_and_object_from_file_id_allows_legacy_path_with_env_flag(+ self,+ ):+ file_id = "gs%3A%2F%2Ftest-bucket%2Ftest-file.txt"++ with patch.dict(os.environ, {"LITELLM_ALLOW_LEGACY_CLOUD_FILE_IDS": "true"}):+ bucket_name, object_path = (+ self.handler._extract_bucket_and_object_from_file_id(+ file_id=file_id,+ configured_bucket_name="test-bucket",+ )+ )++ assert bucket_name == "test-bucket"+ assert object_path == "test-file.txt"+def test_extract_bucket_and_object_from_file_id_rejects_no_gs_prefix(self):"""Test extraction when gs:// prefix is missing"""file_id = "test-bucket%2Flitellm-vertex-files%2Ftest-file.txt"diff --git a/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_transformation.py b/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_transformation.pyindex 4a7a8733ae9..5c018513b0d 100644--- a/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_transformation.py+++ b/tests/test_litellm/llms/vertex_ai/files/test_vertex_ai_files_transformation.py@@ -73,6 +73,40 @@ class TestParseGcsUri:litellm_params={"bucket_name": "my-bucket"},)+ def test_should_allow_legacy_object_path_when_server_flag_enabled(self, config):+ bucket, encoded = config._parse_gcs_uri(+ "gs://my-bucket/private/object.txt",+ litellm_params={+ "bucket_name": "my-bucket",+ "allow_legacy_cloud_file_ids": True,+ },+ )++ assert bucket == "my-bucket"+ assert encoded == urllib.parse.quote("private/object.txt", safe="")++ def test_should_keep_configured_prefix_for_legacy_object_path(self, config):+ bucket, encoded = config._parse_gcs_uri(+ "gs://my-bucket/team-a/private/object.txt",+ litellm_params={+ "bucket_name": "my-bucket/team-a",+ "allow_legacy_cloud_file_ids": True,+ },+ )++ assert bucket == "my-bucket"+ assert encoded == urllib.parse.quote("team-a/private/object.txt", safe="")++ def test_should_reject_legacy_object_outside_configured_prefix(self, config):+ with pytest.raises(ValueError, match="configured storage prefix"):+ config._parse_gcs_uri(+ "gs://my-bucket/team-b/private/object.txt",+ litellm_params={+ "bucket_name": "my-bucket/team-a",+ "allow_legacy_cloud_file_ids": True,+ },+ )+def test_should_reject_unconfigured_bucket(self, config):with pytest.raises(ValueError, match="configured storage bucket"):config._parse_gcs_uri(