The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(proxy): enforce batch list limit bounds on managed passthrough listings
mateo-berri6e55a21ebbf8
diff --git a/litellm/proxy/batches_endpoints/common_utils.py b/litellm/proxy/batches_endpoints/common_utils.pynew file mode 100644index 00000000000..3ce2ebd27bd--- /dev/null+++ b/litellm/proxy/batches_endpoints/common_utils.py@@ -0,0 +1,18 @@+from litellm.proxy._types import ProxyException+++def validate_batch_list_limit(limit: int | None) -> None:+ if limit is None or 0 <= limit <= 100:+ return+ bound, expected, openai_code = (+ ("below minimum", ">= 0", "integer_below_min_value")+ if limit < 0+ else ("above maximum", "<= 100", "integer_above_max_value")+ )+ raise ProxyException(+ message=f"Invalid 'limit': integer {bound} value. Expected a value {expected}, but got {limit} instead.",+ type="invalid_request_error",+ param="limit",+ code=400,+ openai_code=openai_code,+ )diff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.pyindex 1cd46fd6dcb..9863808adee 100644--- a/litellm/proxy/batches_endpoints/endpoints.py+++ b/litellm/proxy/batches_endpoints/endpoints.py@@ -14,6 +14,7 @@ from litellm._logging import verbose_proxy_loggerfrom litellm.batches.main import CancelBatchRequest, RetrieveBatchRequestfrom litellm.proxy._types import *from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.batches_endpoints.common_utils import validate_batch_list_limitfrom litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessingfrom litellm.proxy.common_utils.callback_utils import sanitize_openai_provider_metadatafrom litellm.proxy.common_utils.http_parsing_utils import _read_request_body@@ -642,23 +643,6 @@ async def retrieve_batch(raise handle_exception_on_proxy(e)-def validate_batch_list_limit(limit: int | None) -> None:- if limit is None or 0 <= limit <= 100:- return- bound, expected, openai_code = (- ("below minimum", ">= 0", "integer_below_min_value")- if limit < 0- else ("above maximum", "<= 100", "integer_above_max_value")- )- raise ProxyException(- message=f"Invalid 'limit': integer {bound} value. Expected a value {expected}, but got {limit} instead.",- type="invalid_request_error",- param="limit",- code=400,- openai_code=openai_code,- )--@router.get("/{provider}/v1/batches",dependencies=[Depends(user_api_key_auth)],diff --git a/litellm/proxy/pass_through_endpoints/managed_id_rewriter.py b/litellm/proxy/pass_through_endpoints/managed_id_rewriter.pyindex 04f1390540e..e8b5fab626f 100644--- a/litellm/proxy/pass_through_endpoints/managed_id_rewriter.py+++ b/litellm/proxy/pass_through_endpoints/managed_id_rewriter.py@@ -45,6 +45,7 @@ from litellm.llms.base_llm.managed_resources.isolation import (can_access_resource,)from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.batches_endpoints.common_utils import validate_batch_list_limitfrom litellm.repositories.table_repositories import (ManagedFileRepository,ManagedObjectRepository,@@ -1029,12 +1030,16 @@ async def list_passthrough_ids_from_db(if resource_kind is None:return None+ raw_limit, fetch_limit = _parse_list_limit(query_params)+ if resource_kind == "batches":+ validate_batch_list_limit(raw_limit)+ if raw_limit == 0:+ return _empty_list_response()+owner_filter: Final = build_owner_filter(user_api_key_dict)if owner_filter is None:verbose_proxy_logger.warning("managed_id_rewriter: list denied — caller has no user_id or team_id")return _empty_list_response()-- raw_limit, fetch_limit = _parse_list_limit(query_params)where, fetch_order = await _build_list_where_with_cursor(prisma_client, resource_kind, provider, owner_filter, query_params)diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.pyindex 627df3a873d..211c3742343 100644--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py@@ -1538,6 +1538,8 @@ async def pass_through_request(#########################################################+ if isinstance(e, ProxyException):+ raiseif isinstance(e, HTTPException):raise ProxyException(message=getattr(e, "message", str(getattr(e, "detail", str(e)))),diff --git a/tests/pass_through_unit_tests/test_passthrough_managed_ids.py b/tests/pass_through_unit_tests/test_passthrough_managed_ids.pyindex cbbf9257118..3ecb1270dea 100644--- a/tests/pass_through_unit_tests/test_passthrough_managed_ids.py+++ b/tests/pass_through_unit_tests/test_passthrough_managed_ids.py@@ -31,7 +31,7 @@ import litellmfrom litellm.llms.base_llm.managed_resources.utils import (resolve_passthrough_managed_id_provider,)-from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy._types import ProxyException, UserAPIKeyAuthfrom litellm.proxy.pass_through_endpoints.managed_id_codec import (decode,encode,@@ -1796,6 +1796,84 @@ class TestListPassthroughIdsFromDb:assert result["data"][0]["id"] == managed_idassert result["data"][0]["object"] == "batch"+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "limit,expected_message,expected_openai_code",+ [+ (+ "-1",+ "Invalid 'limit': integer below minimum value. Expected a value >= 0, but got -1 instead.",+ "integer_below_min_value",+ ),+ (+ "101",+ "Invalid 'limit': integer above maximum value. Expected a value <= 100, but got 101 instead.",+ "integer_above_max_value",+ ),+ ],+ )+ async def test_list_batches_out_of_range_limit_raises_400(+ self, limit, expected_message, expected_openai_code+ ):+ pc = _prisma_with_list(+ batch_rows=[_fake_batch_row(new_managed_id("openai", "batch_abc"))]+ )++ with pytest.raises(ProxyException) as exc:+ await list_passthrough_ids_from_db(+ provider="openai",+ route="/openai/v1/batches",+ user_api_key_dict=_user(),+ prisma_client=pc,+ query_params={"limit": limit},+ )++ assert exc.value.code == "400"+ assert exc.value.param == "limit"+ assert exc.value.type == "invalid_request_error"+ assert exc.value.openai_code == expected_openai_code+ assert exc.value.message == expected_message+ pc.db.litellm_managedobjecttable.find_many.assert_not_called()++ @pytest.mark.asyncio+ async def test_list_batches_limit_zero_returns_empty_page_without_db_query(self):+ pc = _prisma_with_list(+ batch_rows=[_fake_batch_row(new_managed_id("openai", "batch_abc"))]+ )++ result = await list_passthrough_ids_from_db(+ provider="openai",+ route="/openai/v1/batches",+ user_api_key_dict=_user(),+ prisma_client=pc,+ query_params={"limit": "0"},+ )++ assert result == {+ "object": "list",+ "data": [],+ "first_id": None,+ "last_id": None,+ "has_more": False,+ }+ pc.db.litellm_managedobjecttable.find_many.assert_not_called()++ @pytest.mark.asyncio+ async def test_list_files_limit_above_batch_cap_still_served(self):+ managed_id = new_managed_id("openai", "file-abc")+ pc = _prisma_with_list(file_rows=[_fake_file_row(managed_id)])++ result = await list_passthrough_ids_from_db(+ provider="openai",+ route="/openai/v1/files",+ user_api_key_dict=_user(),+ prisma_client=pc,+ query_params={"limit": "101"},+ )++ assert result is not None+ assert [item["id"] for item in result["data"]] == [managed_id]+@pytest.mark.asyncioasync def test_list_files_admin_gets_all_rows(self):"""Admin should receive all rows; the where filter passed to DB is {}."""diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.pyindex 40b4dfa6d15..eefdefcee80 100644--- a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py@@ -33,7 +33,7 @@ from litellm.proxy.pass_through_endpoints.pass_through_endpoints import (websocket_passthrough_request,)from litellm.integrations.custom_logger import CustomLogger-from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy._types import ProxyException, UserAPIKeyAuthfrom litellm.types.passthrough_endpoints.pass_through_endpoints import (LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY,)@@ -366,6 +366,39 @@ async def test_pass_through_request_failure_handler():assert "traceback_str" in call_args+async def test_pass_through_request_preserves_proxy_exception_status():+ original = ProxyException(+ message="Invalid 'limit': integer above maximum value. Expected a value <= 100, but got 101 instead.",+ type="invalid_request_error",+ param="limit",+ code=400,+ openai_code="integer_above_max_value",+ )++ with patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy_logging:+ mock_proxy_logging.post_call_failure_hook = AsyncMock()+ mock_proxy_logging.pre_call_hook = AsyncMock(side_effect=original)++ mock_request = MagicMock(spec=Request)+ mock_request.method = "GET"+ mock_request.body = AsyncMock(return_value=b"")+ mock_request.headers = Headers({})+ mock_request.query_params = QueryParams({"limit": "101"})++ with pytest.raises(ProxyException) as exc:+ await pass_through_request(+ request=mock_request,+ target="http://test.com/v1/batches",+ custom_headers={},+ user_api_key_dict=MagicMock(),+ )++ assert exc.value is original+ assert exc.value.code == "400"+ assert exc.value.param == "limit"++def test_is_langfuse_route():"""Test that the is_langfuse_route method correctly identifies Langfuse routes