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 remote-tracking branch 'origin/litellm_internal_staging' into HEAD
userc84ae978990f
diff --cc litellm/litellm_core_utils/url_utils.pyindex d1649452f79,224927e5acd..ff53b5808b3--- a/litellm/litellm_core_utils/url_utils.py+++ b/litellm/litellm_core_utils/url_utils.py@@@ -21,8 -21,8 +21,8 @@@ Admins can opt out via two ``litellm``import socketfrom ipaddress import ip_address, ip_network-from typing import Any, List, Set, Tuple+from typing import Any, List, Optional, Set, Tuple- from urllib.parse import urlparse, urlunparse+ from urllib.parse import quote, urlparse, urlunparseimport httpxdiff --cc litellm/llms/gemini/files/transformation.pyindex 3804145eb5b,63a383ebd3d..00822da43e1--- a/litellm/llms/gemini/files/transformation.py+++ b/litellm/llms/gemini/files/transformation.py@@@ -12,8 -12,8 +12,11 @@@ import httpfrom openai.types.file_deleted import FileDeletedfrom litellm._logging import verbose_logger-from litellm.litellm_core_utils.url_utils import encode_url_path_segmentfrom litellm.litellm_core_utils.prompt_templates.common_utils import extract_file_data- from litellm.litellm_core_utils.url_utils import is_url_destination_allowed_by_host++from litellm.litellm_core_utils.url_utils import (++ encode_url_path_segment,++ is_url_destination_allowed_by_host,++)from litellm.llms.base_llm.files.transformation import (BaseFilesConfig,LiteLLMLoggingObj,@@@ -268,46 -259,15 +271,29 @@@ class GoogleAIStudioFilesHandler(Gemininormalized_file_id = file_idnormalized_file_id = normalized_file_id.strip("/")- if not normalized_file_id.startswith("files/"):- normalized_file_id = f"files/{normalized_file_id}"- self._validate_gemini_file_name(normalized_file_id)+ if normalized_file_id.startswith("files/"):+ normalized_file_id = normalized_file_id.removeprefix("files/")++ encoded_file_id = encode_url_path_segment(+ normalized_file_id, field_name="file_id"+ )- return normalized_file_id+ return f"files/{encoded_file_id}"+ @staticmethod+ def _is_allowed_gemini_file_url(+ file_url: str, api_base: Optional[str] = None+ ) -> bool:+ import litellm++ allowed_hosts: List[str] = []+ if api_base:+ allowed_hosts.append(api_base)+ allowed_hosts.extend(+ getattr(litellm, "provider_url_destination_allowed_hosts", []) or []+ )+ return is_url_destination_allowed_by_host(file_url, allowed_hosts)+- @staticmethod- def _validate_gemini_file_name(file_name: str) -> None:- parts = file_name.split("/")- decoded_file_id = ""- if len(parts) == 2:- decoded_file_id = parts[1]- while True:- next_decoded_file_id = unquote(decoded_file_id)- if next_decoded_file_id == decoded_file_id:- break- decoded_file_id = next_decoded_file_id- if (- len(parts) != 2- or parts[0] != "files"- or not parts[1]- or decoded_file_id in {".", ".."}- or any(char in decoded_file_id for char in ("/", "\\", "?", "#"))- ):- raise ValueError("Invalid Gemini file name")-def transform_retrieve_file_response(self,raw_response: httpx.Response,diff --cc tests/test_litellm/litellm_core_utils/test_url_utils.pyindex efe3f2b67a4,e363418e774..cef09f3f2b0--- a/tests/test_litellm/litellm_core_utils/test_url_utils.py+++ b/tests/test_litellm/litellm_core_utils/test_url_utils.py@@@ -4,7 -4,13 +4,14 @@@ import pytesimport litellmfrom litellm.litellm_core_utils import url_utils- from litellm.litellm_core_utils.url_utils import SSRFError, _is_blocked_ip, validate_url+ from litellm.litellm_core_utils.url_utils import (+ SSRFError,+ _is_blocked_ip,++ assert_same_origin,+ encode_url_path_segment,+ encode_url_path_segments,+ validate_url,+ )@pytest.fixture@@@ -396,43 -424,74 +425,113 @@@ class TestHostAllowlistvalidate_url("http://internal.corp/")-# ── assert_same_origin ────────────────────────────────────────────────────────+class TestProviderUrlDestinationAllowlist:+ def test_host_entry_matches_any_scheme_and_port(self):+ assert url_utils.is_url_destination_allowed_by_host(+ "https://trusted.example/v1/chat/completions",+ ["trusted.example"],+ )+ assert url_utils.is_url_destination_allowed_by_host(+ "http://trusted.example:8080/v1/chat/completions",+ ["trusted.example"],+ )++ def test_origin_entry_matches_scheme_and_default_port(self):+ assert url_utils.is_url_destination_allowed_by_host(+ "https://trusted.example/v1/chat/completions",+ ["https://trusted.example"],+ )+ assert not url_utils.is_url_destination_allowed_by_host(+ "http://trusted.example/v1/chat/completions",+ ["https://trusted.example"],+ )++ def test_port_entry_only_matches_same_effective_port(self):+ assert url_utils.is_url_destination_allowed_by_host(+ "https://trusted.example/v1/chat/completions",+ ["trusted.example:443"],+ )+ assert not url_utils.is_url_destination_allowed_by_host(+ "https://trusted.example:8443/v1/chat/completions",+ ["trusted.example:443"],+ )++ def test_rejects_userinfo_and_invalid_port(self):+ assert not url_utils.is_url_destination_allowed_by_host(+ "https://user:[email protected]/v1/chat/completions",+ ["trusted.example"],+ )+ assert not url_utils.is_url_destination_allowed_by_host(+ "https://trusted.example:99999/v1/chat/completions",+ ["trusted.example"],+ )++-from litellm.litellm_core_utils.url_utils import assert_same_origin++# ── assert_same_origin ────────────────────────────────────────────────────────+++ def test_assert_same_origin_matches_scheme_host_port():+ """A polling URL on the same scheme + host + port as the api_base+ passes — the upstream is trusted; the URL it returned points back at+ the same upstream."""+ assert_same_origin(+ "https://api.example.com/v1/operations/abc",+ "https://api.example.com/v1/generate",+ )+++ def test_assert_same_origin_treats_default_ports_as_explicit():+ """``https://x/`` and ``https://x:443/`` are the same origin."""+ assert_same_origin("https://api.example.com/poll", "https://api.example.com:443/")+ assert_same_origin("https://api.example.com:443/poll", "https://api.example.com/")+ assert_same_origin("http://api.example.com/poll", "http://api.example.com:80/")+++ def test_assert_same_origin_rejects_different_host():+ with pytest.raises(SSRFError, match="host"):+ assert_same_origin(+ "https://attacker.example.com/poll",+ "https://api.example.com/generate",+ )+++ def test_assert_same_origin_rejects_different_scheme():+ with pytest.raises(SSRFError, match="scheme"):+ assert_same_origin(+ "http://api.example.com/poll", "https://api.example.com/generate"+ )+++ def test_assert_same_origin_rejects_different_port():+ with pytest.raises(SSRFError, match="port"):+ assert_same_origin(+ "https://api.example.com:8443/poll", "https://api.example.com/generate"+ )+++ def test_assert_same_origin_rejects_non_http_scheme():+ """``file://`` polling URLs are rejected outright — the upstream+ should never return a non-HTTP scheme."""+ with pytest.raises(SSRFError, match="scheme"):+ assert_same_origin("file:///etc/passwd", "https://api.example.com/")+++ def test_assert_same_origin_case_insensitive_host():+ assert_same_origin(+ "https://API.example.com/poll", "https://api.example.com/generate"+ )+++ def test_assert_same_origin_error_message_does_not_leak_hostnames():+ """Greptile P2: in the SSRF threat model the caller is the attacker.+ The error message must not echo the operator's expected host or the+ attacker-supplied candidate host back to the caller — only identify+ *which* component mismatched."""+ with pytest.raises(SSRFError) as exc:+ assert_same_origin(+ "https://attacker.example.com:1234/poll",+ "https://api.internal-corp.example/generate",+ )+ detail = str(exc.value)+ assert "attacker.example.com" not in detail+ assert "api.internal-corp.example" not in detaildiff --cc tests/test_litellm/llms/gemini/files/test_gemini_files_transformation.pyindex 9cadba972e4,a2f95724688..33fe5d24d77--- a/tests/test_litellm/llms/gemini/files/test_gemini_files_transformation.py+++ b/tests/test_litellm/llms/gemini/files/test_gemini_files_transformation.py@@@ -93,92 -92,28 +93,76 @@@ class TestGoogleAIStudioFilesTransformaassert "key=" not in urlassert params == {}+ def test_transform_retrieve_file_request_rejects_untrusted_full_url(self):+ file_id = "https://attacker.example/v1beta/files/test123"+ litellm_params = {"api_key": "test-api-key"}++ with pytest.raises(ValueError, match="Invalid Gemini file URL"):+ self.handler.transform_retrieve_file_request(+ file_id=file_id,+ optional_params={},+ litellm_params=litellm_params,+ )++ def test_transform_retrieve_file_request_allows_full_url_matching_api_base(self):+ file_id = "https://custom-gemini.example/v1beta/files/test123"+ litellm_params = {+ "api_key": "test-api-key",+ "api_base": "https://custom-gemini.example",+ }++ url, params = self.handler.transform_retrieve_file_request(+ file_id=file_id,+ optional_params={},+ litellm_params=litellm_params,+ )++ assert url == "https://custom-gemini.example/v1beta/files/test123"+ assert params == {}++ def test_transform_retrieve_file_request_allows_full_url_when_host_allowlisted(+ self,+ monkeypatch,+ ):+ monkeypatch.setattr(+ litellm,+ "provider_url_destination_allowed_hosts",+ ["trusted-gemini.example"],+ )+ file_id = "https://trusted-gemini.example/v1beta/files/test123"+ litellm_params = {"api_key": "test-api-key"}++ url, params = self.handler.transform_retrieve_file_request(+ file_id=file_id,+ optional_params={},+ litellm_params=litellm_params,+ )++ assert url == "https://generativelanguage.googleapis.com/v1beta/files/test123"+ assert params == {}+- def test_transform_retrieve_file_request_rejects_traversal_name(self):+ def test_transform_retrieve_file_request_encodes_file_id_path_segment(self):+ file_id = "files/../../models/gemini-pro?x=1#frag"litellm_params = {"api_key": "test-api-key"}- with pytest.raises(ValueError, match="Invalid Gemini file name"):- self.handler.transform_retrieve_file_request(- file_id="files/../secrets",- optional_params={},- litellm_params=litellm_params,- )-- def test_transform_retrieve_file_request_rejects_encoded_traversal_name(self):- litellm_params = {"api_key": "test-api-key"}-- with pytest.raises(ValueError, match="Invalid Gemini file name"):- self.handler.transform_retrieve_file_request(- file_id="files/..%2Fsecrets",- optional_params={},- litellm_params=litellm_params,- )-- def test_transform_retrieve_file_request_rejects_double_encoded_separator(self):- litellm_params = {"api_key": "test-api-key"}-- with pytest.raises(ValueError, match="Invalid Gemini file name"):- self.handler.transform_retrieve_file_request(- file_id="files/..%252Fsecrets",- optional_params={},- litellm_params=litellm_params,- )+ url, params = self.handler.transform_retrieve_file_request(+ file_id=file_id,+ optional_params={},+ litellm_params=litellm_params,+ )- def test_transform_retrieve_file_request_rejects_deeply_encoded_separator(self):- litellm_params = {"api_key": "test-api-key"}+ assert (+ url+ == "https://generativelanguage.googleapis.com/v1beta/files/..%2F..%2Fmodels%2Fgemini-pro%3Fx%3D1%23frag"+ )+ assert params == {}- with pytest.raises(ValueError, match="Invalid Gemini file name"):+ def test_transform_retrieve_file_request_rejects_dot_path_segment(self):+ with pytest.raises(ValueError, match="file_id cannot be a dot path segment"):self.handler.transform_retrieve_file_request(- file_id="files/..%2525252Fsecrets",+ file_id="files/..",optional_params={},- litellm_params=litellm_params,+ litellm_params={"api_key": "test-api-key"},)@patch.dict("os.environ", {}, clear=True)@@@ -411,35 -344,8 +393,36 @@@assert "generativelanguage.googleapis.com" in urlassert params == {}+ def test_transform_delete_file_request_rejects_untrusted_full_url(self):+ litellm_params = {+ "api_key": "test-api-key",+ "api_base": "https://generativelanguage.googleapis.com",+ }++ with pytest.raises(ValueError, match="Invalid Gemini file URL"):+ self.handler.transform_delete_file_request(+ file_id="https://attacker.example/v1beta/files/test123",+ optional_params={},+ litellm_params=litellm_params,+ )++ def test_transform_delete_file_request_allows_full_url_matching_api_base(self):+ litellm_params = {+ "api_key": "test-api-key",+ "api_base": "https://custom-gemini.example",+ }++ url, params = self.handler.transform_delete_file_request(+ file_id="https://custom-gemini.example/v1beta/files/test123",+ optional_params={},+ litellm_params=litellm_params,+ )++ assert url == "https://custom-gemini.example/v1beta/files/test123"+ assert params == {}+- def test_transform_delete_file_request_rejects_encoded_traversal_url(self):+ def test_transform_delete_file_request_encodes_file_id_path_segment(self):+ file_id = "files/../../models/gemini-pro?x=1#frag"litellm_params = {"api_key": "test-api-key","api_base": "https://generativelanguage.googleapis.com",