Skip to content

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]

fix: cover provider path traversal variants

user94c13fe399e6
diff --git a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
index 76c247aea81..8535a3545cb 100644
--- a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
+++ b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
@@ -22,6 +22,7 @@ from litellm.constants import (
AZURE_DOCUMENT_INTELLIGENCE_DEFAULT_DPI,
AZURE_OPERATION_POLLING_TIMEOUT,
)
+from litellm.litellm_core_utils.url_utils import encode_url_path_segment
from litellm.llms.base_llm.ocr.transformation import (
BaseOCRConfig,
DocumentType,
@@ -217,11 +218,12 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig):
if "/" in model:
# Extract the last part after the last slash
model_id = model.split("/")[-1]
+ encoded_model_id = encode_url_path_segment(model_id, field_name="model_id")
# Azure Document Intelligence analyze endpoint
# Note: API version 2024-11-30+ uses /documentintelligence/ (not /formrecognizer/)
url = (
- f"{api_base}/documentintelligence/documentModels/{model_id}:analyze"
+ f"{api_base}/documentintelligence/documentModels/{encoded_model_id}:analyze"
f"?api-version={AZURE_DOCUMENT_INTELLIGENCE_API_VERSION}"
)
diff --git a/litellm/llms/bedrock/chat/invoke_agent/transformation.py b/litellm/llms/bedrock/chat/invoke_agent/transformation.py
index 2c7135f4d83..4c667b0ce39 100644
--- a/litellm/llms/bedrock/chat/invoke_agent/transformation.py
+++ b/litellm/llms/bedrock/chat/invoke_agent/transformation.py
@@ -12,6 +12,7 @@ import httpx
from litellm._logging import verbose_logger
from litellm._uuid import uuid
+from litellm.litellm_core_utils.url_utils import encode_url_path_segment
from litellm.litellm_core_utils.prompt_templates.common_utils import (
convert_content_list_to_str,
)
@@ -97,8 +98,15 @@ class AmazonInvokeAgentConfig(BaseConfig, BaseAWSLLM):
agent_id, agent_alias_id = self._get_agent_id_and_alias_id(model)
session_id = self._get_session_id(optional_params)
+ encoded_agent_id = encode_url_path_segment(agent_id, field_name="agent_id")
+ encoded_agent_alias_id = encode_url_path_segment(
+ agent_alias_id, field_name="agent_alias_id"
+ )
+ encoded_session_id = encode_url_path_segment(
+ session_id, field_name="session_id"
+ )
- endpoint_url = f"{endpoint_url}/agents/{agent_id}/agentAliases/{agent_alias_id}/sessions/{session_id}/text"
+ endpoint_url = f"{endpoint_url}/agents/{encoded_agent_id}/agentAliases/{encoded_agent_alias_id}/sessions/{encoded_session_id}/text"
return endpoint_url
diff --git a/litellm/llms/vertex_ai/batches/handler.py b/litellm/llms/vertex_ai/batches/handler.py
index 7436bfef58b..c627599da8d 100644
--- a/litellm/llms/vertex_ai/batches/handler.py
+++ b/litellm/llms/vertex_ai/batches/handler.py
@@ -4,7 +4,11 @@ from typing import Any, Coroutine, Dict, Optional, Union
import httpx
import litellm
-from litellm.litellm_core_utils.url_utils import async_safe_get, safe_get
+from litellm.litellm_core_utils.url_utils import (
+ async_safe_get,
+ encode_url_path_segment,
+ safe_get,
+)
from litellm.llms.custom_httpx.http_handler import (
_get_httpx_client,
get_async_httpx_client,
@@ -170,7 +174,8 @@ class VertexAIBatchPrediction(VertexLLM):
)
# Append batch_id to the URL
- default_api_base = f"{default_api_base}/{batch_id}"
+ encoded_batch_id = encode_url_path_segment(batch_id, field_name="batch_id")
+ default_api_base = f"{default_api_base}/{encoded_batch_id}"
if len(default_api_base.split(":")) > 1:
endpoint = default_api_base.split(":")[-1]
@@ -413,7 +418,8 @@ class VertexAIBatchPrediction(VertexLLM):
vertex_project=vertex_project or project_id,
)
- retrieve_api_base_default = f"{default_api_base}/{batch_id}"
+ encoded_batch_id = encode_url_path_segment(batch_id, field_name="batch_id")
+ retrieve_api_base_default = f"{default_api_base}/{encoded_batch_id}"
cancel_api_base_default = f"{retrieve_api_base_default}:cancel"
_, api_base = self._check_custom_proxy(
diff --git a/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py b/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py
index 6cb7a86bea2..61fb848b40a 100644
--- a/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py
+++ b/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py
@@ -3,6 +3,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
import httpx
from litellm import get_model_info
+from litellm.litellm_core_utils.url_utils import encode_url_path_segment
from litellm.llms.base_llm.vector_store.transformation import BaseVectorStoreConfig
from litellm.llms.vertex_ai.vertex_llm_base import VertexBase
from litellm.types.router import GenericLiteLLMParams
@@ -91,12 +92,18 @@ class VertexSearchAPIVectorStoreConfig(BaseVectorStoreConfig, VertexBase):
raise ValueError("vector_store_id is required")
if api_base:
return api_base.rstrip("/")
+ encoded_collection_id = encode_url_path_segment(
+ collection_id, field_name="vertex_collection_id"
+ )
+ encoded_datastore_id = encode_url_path_segment(
+ datastore_id, field_name="vector_store_id"
+ )
# Vertex AI Search API endpoint for search
return (
f"https://discoveryengine.googleapis.com/v1/"
f"projects/{vertex_project}/locations/{vertex_location}/"
- f"collections/{collection_id}/dataStores/{datastore_id}/servingConfigs/default_config"
+ f"collections/{encoded_collection_id}/dataStores/{encoded_datastore_id}/servingConfigs/default_config"
)
def transform_search_vector_store_request(
diff --git a/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py b/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py
new file mode 100644
index 00000000000..e638be68ec0
--- /dev/null
+++ b/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py
@@ -0,0 +1,33 @@
+import pytest
+
+from litellm.llms.azure_ai.ocr.document_intelligence.transformation import (
+ AzureDocumentIntelligenceOCRConfig,
+)
+
+
+def test_should_encode_azure_document_intelligence_model_id():
+ config = AzureDocumentIntelligenceOCRConfig()
+
+ url = config.get_complete_url(
+ api_base="https://example.cognitiveservices.azure.com",
+ model="prebuilt-layout?x=1#frag",
+ optional_params={},
+ litellm_params={},
+ )
+
+ assert (
+ url
+ == "https://example.cognitiveservices.azure.com/documentintelligence/documentModels/prebuilt-layout%3Fx%3D1%23frag:analyze?api-version=2024-11-30"
+ )
+
+
+def test_should_reject_dot_segment_azure_document_intelligence_model_id():
+ config = AzureDocumentIntelligenceOCRConfig()
+
+ with pytest.raises(ValueError, match="model_id cannot be a dot path segment"):
+ config.get_complete_url(
+ api_base="https://example.cognitiveservices.azure.com",
+ model="azure_ai/doc-intelligence/..",
+ optional_params={},
+ litellm_params={},
+ )
diff --git a/tests/test_litellm/llms/bedrock/invoke_agent/test_bedrock_agent_transformation.py b/tests/test_litellm/llms/bedrock/invoke_agent/test_bedrock_agent_transformation.py
index ffd3526698a..9e526e47784 100644
--- a/tests/test_litellm/llms/bedrock/invoke_agent/test_bedrock_agent_transformation.py
+++ b/tests/test_litellm/llms/bedrock/invoke_agent/test_bedrock_agent_transformation.py
@@ -1,12 +1,9 @@
import base64
-import json
import os
import sys
-from litellm._uuid import uuid
-from unittest.mock import MagicMock, Mock, patch
+from unittest.mock import patch
import pytest
-from fastapi.testclient import TestClient
sys.path.insert(
0, os.path.abspath("../../../..")
@@ -15,12 +12,7 @@ sys.path.insert(
from litellm.llms.bedrock.chat.invoke_agent.transformation import (
AmazonInvokeAgentConfig,
)
-from litellm.types.llms.bedrock_invoke_agents import (
- InvokeAgentEvent,
- InvokeAgentEventHeaders,
- InvokeAgentUsage,
-)
-from litellm.types.utils import Message, ModelResponse, Usage
+from litellm.types.utils import ModelResponse
class TestAmazonInvokeAgentConfig:
@@ -270,3 +262,28 @@ class TestAmazonInvokeAgentConfig:
"https://bedrock-runtime.us-east-1.amazonaws.com/agents/L1RT58GYRW/agentAliases/MFPSBCXYTW/sessions"
in result
)
+
+ @patch(
+ "litellm.llms.bedrock.chat.invoke_agent.transformation.convert_content_list_to_str"
+ )
+ @patch.object(AmazonInvokeAgentConfig, "get_runtime_endpoint")
+ @patch.object(AmazonInvokeAgentConfig, "_get_aws_region_name")
+ def test_get_complete_url_encodes_session_id(
+ self, mock_region, mock_endpoint, mock_convert, config
+ ):
+ """Test get_complete_url encodes session ID path segment."""
+ mock_endpoint.return_value = (
+ "https://bedrock-runtime.us-east-1.amazonaws.com",
+ None,
+ )
+ mock_region.return_value = "us-east-1"
+
+ result = config.get_complete_url(
+ api_base=None,
+ api_key=None,
+ model="agent/L1RT58GYRW/MFPSBCXYTW",
+ optional_params={"sessionID": "../../sessions/other?x=1#frag"},
+ litellm_params={},
+ )
+
+ assert "sessions/..%2F..%2Fsessions%2Fother%3Fx%3D1%23frag/text" in result
diff --git a/tests/test_litellm/llms/vertex_ai/test_vertex_ai_batch_transformation.py b/tests/test_litellm/llms/vertex_ai/test_vertex_ai_batch_transformation.py
index 33b3bfce44a..8a135dac3bb 100644
--- a/tests/test_litellm/llms/vertex_ai/test_vertex_ai_batch_transformation.py
+++ b/tests/test_litellm/llms/vertex_ai/test_vertex_ai_batch_transformation.py
@@ -93,6 +93,51 @@ def test_vertex_ai_cancel_batch():
assert ":cancel" in call_args.kwargs["url"]
+def test_vertex_ai_cancel_batch_encodes_batch_id():
+ """Test that vertex_ai cancel_batch encodes user-controlled batch IDs."""
+ handler = VertexAIBatchPrediction(gcs_bucket_name="test-bucket")
+
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "name": "projects/test-project/locations/us-central1/batchPredictionJobs/123456",
+ "state": "JOB_STATE_CANCELLING",
+ "createTime": "2024-03-17T10:00:00.000000Z",
+ "inputConfig": {"gcsSource": {"uris": ["gs://test-bucket/input.jsonl"]}},
+ "outputConfig": {
+ "gcsDestination": {"outputUriPrefix": "gs://test-bucket/output"}
+ },
+ }
+
+ with patch(
+ "litellm.llms.vertex_ai.batches.handler._get_httpx_client"
+ ) as mock_client:
+ mock_client.return_value.post.return_value = mock_response
+ mock_client.return_value.get.return_value = mock_response
+
+ with patch.object(handler, "_ensure_access_token") as mock_auth:
+ mock_auth.return_value = ("fake-token", "test-project")
+
+ handler.cancel_batch(
+ _is_async=False,
+ batch_id="../../batchPredictionJobs/other?x=1#frag",
+ api_base=None,
+ vertex_credentials=None,
+ vertex_project="test-project",
+ vertex_location="us-central1",
+ timeout=600.0,
+ max_retries=None,
+ )
+
+ post_url = mock_client.return_value.post.call_args.kwargs["url"]
+ get_url = mock_client.return_value.get.call_args.kwargs["url"]
+ assert (
+ "/..%2F..%2FbatchPredictionJobs%2Fother%3Fx%3D1%23frag:cancel"
+ in post_url
+ )
+ assert "/..%2F..%2FbatchPredictionJobs%2Fother%3Fx%3D1%23frag" in get_url
+
+
def test_vertex_ai_cancel_batch_forwards_timeout():
"""Test that timeout is forwarded to the POST (cancel) HTTP call.
diff --git a/tests/test_litellm/llms/vertex_ai/test_vertex_ai_search_vector_store_transformation.py b/tests/test_litellm/llms/vertex_ai/test_vertex_ai_search_vector_store_transformation.py
new file mode 100644
index 00000000000..b6329f33ae4
--- /dev/null
+++ b/tests/test_litellm/llms/vertex_ai/test_vertex_ai_search_vector_store_transformation.py
@@ -0,0 +1,40 @@
+import pytest
+
+from litellm.llms.vertex_ai.vector_stores.search_api.transformation import (
+ VertexSearchAPIVectorStoreConfig,
+)
+
+
+def test_should_encode_vertex_search_vector_store_id_in_complete_url():
+ config = VertexSearchAPIVectorStoreConfig()
+
+ url = config.get_complete_url(
+ api_base=None,
+ litellm_params={
+ "vertex_project": "test-project",
+ "vertex_location": "global",
+ "vertex_collection_id": "default/collection",
+ "vector_store_id": "../../dataStores/other?x=1#frag",
+ },
+ )
+
+ assert (
+ url
+ == "https://discoveryengine.googleapis.com/v1/projects/test-project/locations/global/collections/default%2Fcollection/dataStores/..%2F..%2FdataStores%2Fother%3Fx%3D1%23frag/servingConfigs/default_config"
+ )
+
+
+def test_should_reject_dot_segment_vertex_search_vector_store_id():
+ config = VertexSearchAPIVectorStoreConfig()
+
+ with pytest.raises(
+ ValueError, match="vector_store_id cannot be a dot path segment"
+ ):
+ config.get_complete_url(
+ api_base=None,
+ litellm_params={
+ "vertex_project": "test-project",
+ "vertex_location": "global",
+ "vector_store_id": "..",
+ },
+ )