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(proxy): authenticate managed ids before routing

mateo-berri8c0556abf696
diff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.py
index c9f66c5a48b..aef1c5ac17e 100644
--- a/litellm/proxy/batches_endpoints/endpoints.py
+++ b/litellm/proxy/batches_endpoints/endpoints.py
@@ -177,7 +177,12 @@ async def create_batch(
}
input_file_id: Final = _create_batch_data.get("input_file_id", None)
- validate_managed_id_requirement(resource_id=input_file_id, resource_kind="file")
+ await validate_managed_id_requirement(
+ resource_id=input_file_id,
+ resource_kind="file",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ )
unified_file_id: str | Literal[False] = False
model_from_file_id = None
@@ -394,7 +399,12 @@ async def retrieve_batch(
data: dict = {}
try:
- validate_managed_id_requirement(resource_id=batch_id, resource_kind="batch")
+ await validate_managed_id_requirement(
+ resource_id=batch_id,
+ resource_kind="batch",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ )
model_from_id: Final = decode_model_from_file_id(batch_id)
_retrieve_batch_request: Final = RetrieveBatchRequest(
batch_id=batch_id,
@@ -843,7 +853,12 @@ async def cancel_batch(
data: dict = {}
try:
- validate_managed_id_requirement(resource_id=batch_id, resource_kind="batch")
+ await validate_managed_id_requirement(
+ resource_id=batch_id,
+ resource_kind="batch",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ )
# Check for encoded batch ID with model info
model_from_id: Final = decode_model_from_file_id(batch_id)
diff --git a/litellm/proxy/fine_tuning_endpoints/endpoints.py b/litellm/proxy/fine_tuning_endpoints/endpoints.py
index 87e9895eed0..a13ad00713d 100644
--- a/litellm/proxy/fine_tuning_endpoints/endpoints.py
+++ b/litellm/proxy/fine_tuning_endpoints/endpoints.py
@@ -135,10 +135,17 @@ async def create_fine_tuning_job(
## CHECK IF MANAGED FILE ID
unified_file_id: str | Literal[False] = False
training_file: Final = fine_tuning_request.training_file
- validate_managed_id_requirement(resource_id=training_file, resource_kind="file")
- validate_managed_id_requirement(
+ await validate_managed_id_requirement(
+ resource_id=training_file,
+ resource_kind="file",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ )
+ await validate_managed_id_requirement(
resource_id=fine_tuning_request.validation_file,
resource_kind="file",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
)
response: LiteLLMFineTuningJob | None = None
if training_file:
@@ -252,7 +259,12 @@ async def retrieve_fine_tuning_job(
try:
if premium_user is not True:
raise ValueError(f"Only premium users can use this endpoint + {CommonProxyErrors.not_premium_user.value}")
- validate_managed_id_requirement(resource_id=fine_tuning_job_id, resource_kind="fine-tuning job")
+ await validate_managed_id_requirement(
+ resource_id=fine_tuning_job_id,
+ resource_kind="fine-tuning job",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ )
# Include original request and headers in the data
base_llm_response_processor: Final = ProxyBaseLLMRequestProcessing(data=data)
(
@@ -520,7 +532,12 @@ async def cancel_fine_tuning_job(
try:
if premium_user is not True:
raise ValueError(f"Only premium users can use this endpoint + {CommonProxyErrors.not_premium_user.value}")
- validate_managed_id_requirement(resource_id=fine_tuning_job_id, resource_kind="fine-tuning job")
+ await validate_managed_id_requirement(
+ resource_id=fine_tuning_job_id,
+ resource_kind="fine-tuning job",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ )
# Include original request and headers in the data
base_llm_response_processor: Final = ProxyBaseLLMRequestProcessing(data=data)
(
diff --git a/litellm/proxy/openai_files_endpoints/common_utils.py b/litellm/proxy/openai_files_endpoints/common_utils.py
index 143bd5bc6b5..56e986c89cf 100644
--- a/litellm/proxy/openai_files_endpoints/common_utils.py
+++ b/litellm/proxy/openai_files_endpoints/common_utils.py
@@ -4,7 +4,7 @@ import re
from collections.abc import Mapping
from dataclasses import dataclass, field
from types import MappingProxyType
-from typing import TYPE_CHECKING, Final, Literal, Optional
+from typing import TYPE_CHECKING, Final, Literal, Optional, Protocol, runtime_checkable
from litellm.repositories.table_repositories import (
ManagedFileRepository,
@@ -22,6 +22,21 @@ if TYPE_CHECKING:
from litellm.types.utils import LiteLLMBatch
+@runtime_checkable
+class ManagedResourceAccessChecker(Protocol):
+ async def can_user_call_unified_file_id(
+ self,
+ unified_file_id: str,
+ user_api_key_dict: "UserAPIKeyAuth",
+ ) -> bool: ...
+
+ async def can_user_call_unified_object_id(
+ self,
+ unified_object_id: str,
+ user_api_key_dict: "UserAPIKeyAuth",
+ ) -> bool: ...
+
+
def _is_base64_encoded_unified_file_id(b64_uid: str) -> str | Literal[False]:
# Ensure b64_uid is a string and not a mock object
if not isinstance(b64_uid, str):
@@ -881,20 +896,24 @@ def validate_managed_files_requirement(
)
-def validate_managed_id_requirement(
+async def validate_managed_id_requirement(
resource_id: str | None,
resource_kind: Literal["file", "batch", "fine-tuning job"],
+ user_api_key_dict: "UserAPIKeyAuth",
+ managed_files_obj: object | None,
) -> None:
"""
Enforce proxy-level managed resources on every route that accepts a provider-issued id
- when ``litellm.require_managed_files`` is enabled.
+ when ``litellm.require_managed_files`` is enabled, and authenticate managed ids against
+ the caller's stored ownership record.
Ownership is only recorded for LiteLLM managed ids, so a raw provider id is forwarded to the
provider under shared credentials without any tenant check; knowing another tenant's provider
id would be enough to read, reuse, or destroy the object behind it.
Raises:
- HTTPException: 400 if ``resource_id`` is set and is not a LiteLLM managed id.
+ HTTPException: 400 for a raw id, 403 for an inaccessible managed id, or 500 when
+ ownership validation is unavailable.
"""
from fastapi import HTTPException
@@ -906,16 +925,33 @@ def validate_managed_id_requirement(
if not resource_id:
return
- if _is_base64_encoded_unified_file_id(resource_id):
+ if not _is_base64_encoded_unified_file_id(resource_id):
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"Raw provider {resource_kind} ids cannot be used when require_managed_files is enabled in "
+ f"litellm_settings. Use the LiteLLM managed {resource_kind} id returned when the "
+ f"{resource_kind} was created."
+ ),
+ )
+
+ if not isinstance(managed_files_obj, ManagedResourceAccessChecker):
+ raise HTTPException(
+ status_code=500,
+ detail="Managed resource ownership validation is unavailable.",
+ )
+
+ can_access: Final = (
+ await managed_files_obj.can_user_call_unified_file_id(resource_id, user_api_key_dict)
+ if resource_kind == "file"
+ else await managed_files_obj.can_user_call_unified_object_id(resource_id, user_api_key_dict)
+ )
+ if can_access:
return
raise HTTPException(
- status_code=400,
- detail=(
- f"Raw provider {resource_kind} ids cannot be used when require_managed_files is enabled in "
- f"litellm_settings. Use the LiteLLM managed {resource_kind} id returned when the "
- f"{resource_kind} was created."
- ),
+ status_code=403,
+ detail=f"The caller does not have access to this managed {resource_kind} id.",
)
diff --git a/litellm/proxy/openai_files_endpoints/files_endpoints.py b/litellm/proxy/openai_files_endpoints/files_endpoints.py
index b5950c4f852..0acaac3bf5d 100644
--- a/litellm/proxy/openai_files_endpoints/files_endpoints.py
+++ b/litellm/proxy/openai_files_endpoints/files_endpoints.py
@@ -613,7 +613,12 @@ async def get_file_content(
data: dict = {"file_id": file_id}
try:
- validate_managed_id_requirement(resource_id=file_id, resource_kind="file")
+ await validate_managed_id_requirement(
+ resource_id=file_id,
+ resource_kind="file",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ )
# Include original request and headers in the data
base_llm_response_processor: Final = ProxyBaseLLMRequestProcessing(data=data)
@@ -911,7 +916,12 @@ async def get_file(
data: dict = {"file_id": file_id}
try:
- validate_managed_id_requirement(resource_id=file_id, resource_kind="file")
+ await validate_managed_id_requirement(
+ resource_id=file_id,
+ resource_kind="file",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ )
custom_llm_provider: Final = (
provider
@@ -1103,7 +1113,12 @@ async def delete_file(
data: dict = {"file_id": file_id}
try:
- validate_managed_id_requirement(resource_id=file_id, resource_kind="file")
+ await validate_managed_id_requirement(
+ resource_id=file_id,
+ resource_kind="file",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ )
custom_llm_provider: Final = (
provider
diff --git a/litellm/proxy/vector_store_files_endpoints/endpoints.py b/litellm/proxy/vector_store_files_endpoints/endpoints.py
index f8fdf607292..c9b89bcd390 100644
--- a/litellm/proxy/vector_store_files_endpoints/endpoints.py
+++ b/litellm/proxy/vector_store_files_endpoints/endpoints.py
@@ -30,10 +30,12 @@ if TYPE_CHECKING:
router: Final = APIRouter()
-def _update_request_data_with_managed_file_id(
+async def _update_request_data_with_managed_file_id(
data: dict,
file_id: str,
request: Request,
+ user_api_key_dict: UserAPIKeyAuth,
+ managed_files_obj: object | None,
llm_router: Optional["Router"] = None,
) -> tuple[dict, str | None]:
"""
@@ -69,7 +71,12 @@ def _update_request_data_with_managed_file_id(
validate_managed_id_requirement,
)
- validate_managed_id_requirement(resource_id=file_id, resource_kind="file")
+ await validate_managed_id_requirement(
+ resource_id=file_id,
+ resource_kind="file",
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=managed_files_obj,
+ )
# First, check if this is a unified managed file ID (base64 encoded)
decoded_id: Final = is_base64_encoded_unified_id(file_id)
@@ -514,8 +521,13 @@ async def vector_store_file_create(
# Handle managed file IDs if present in request body
original_managed_file_id = None
if "file_id" in data:
- data, original_managed_file_id = _update_request_data_with_managed_file_id(
- data=data, file_id=data["file_id"], request=request, llm_router=llm_router
+ data, original_managed_file_id = await _update_request_data_with_managed_file_id(
+ data=data,
+ file_id=data["file_id"],
+ request=request,
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ llm_router=llm_router,
)
# Then handle managed vector store IDs
@@ -712,8 +724,13 @@ async def vector_store_file_retrieve(
)
# Handle managed file IDs first
- data, original_managed_file_id = _update_request_data_with_managed_file_id(
- data=data, file_id=file_id, request=request, llm_router=llm_router
+ data, original_managed_file_id = await _update_request_data_with_managed_file_id(
+ data=data,
+ file_id=file_id,
+ request=request,
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ llm_router=llm_router,
)
# Then handle managed vector store IDs
@@ -814,8 +831,13 @@ async def vector_store_file_content(
)
# Handle managed file IDs first
- data, original_managed_file_id = _update_request_data_with_managed_file_id(
- data=data, file_id=file_id, request=request, llm_router=llm_router
+ data, original_managed_file_id = await _update_request_data_with_managed_file_id(
+ data=data,
+ file_id=file_id,
+ request=request,
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ llm_router=llm_router,
)
# Then handle managed vector store IDs
@@ -916,8 +938,13 @@ async def vector_store_file_update(
)
# Handle managed file IDs first
- data, original_managed_file_id = _update_request_data_with_managed_file_id(
- data=data, file_id=file_id, request=request, llm_router=llm_router
+ data, original_managed_file_id = await _update_request_data_with_managed_file_id(
+ data=data,
+ file_id=file_id,
+ request=request,
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ llm_router=llm_router,
)
# Then handle managed vector store IDs
@@ -1018,8 +1045,13 @@ async def vector_store_file_delete(
)
# Handle managed file IDs first
- data, original_managed_file_id = _update_request_data_with_managed_file_id(
- data=data, file_id=file_id, request=request, llm_router=llm_router
+ data, original_managed_file_id = await _update_request_data_with_managed_file_id(
+ data=data,
+ file_id=file_id,
+ request=request,
+ user_api_key_dict=user_api_key_dict,
+ managed_files_obj=proxy_logging_obj.get_proxy_hook("managed_files"),
+ llm_router=llm_router,
)
# Then handle managed vector store IDs
diff --git a/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py b/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py
index 18ca604f88d..f9193db143e 100644
--- a/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py
+++ b/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py
@@ -2275,6 +2275,37 @@ def _unified_batch_id(model_id: str = "azure/gpt-4o", batch_id: str = "batch-pro
return base64.urlsafe_b64encode(unified.encode()).decode().rstrip("=")
+def _unified_file_id() -> str:
+ import base64
+
+ from litellm.types.utils import SpecialEnums
+
+ unified = SpecialEnums.LITELLM_MANAGED_FILE_COMPLETE_STR.value.format(
+ "application/json", "managed-id", "gpt-4o-mini", "file-provider-id", "gpt-4o-mini-id"
+ )
+ return base64.urlsafe_b64encode(unified.encode()).decode().rstrip("=")
+
+
+@dataclass(frozen=True)
+class ManagedResourceAccessCheckerStub:
+ file_access: bool = True
+ object_access: bool = True
+
+ async def can_user_call_unified_file_id(
+ self,
+ unified_file_id: str,
+ user_api_key_dict: UserAPIKeyAuth,
+ ) -> bool:
+ return self.file_access
+
+ async def can_user_call_unified_object_id(
+ self,
+ unified_object_id: str,
+ user_api_key_dict: UserAPIKeyAuth,
+ ) -> bool:
+ return self.object_access
+
+
@pytest.mark.asyncio
async def test_create__raw_input_file_id_rejected_when_managed_files_required(harness):
set_body(
@@ -2334,6 +2365,27 @@ async def test_create__raw_input_file_id_allowed_when_managed_files_not_required
assert harness.acreate_kwargs()["input_file_id"] == "file-victim-abc123"
+async def test_create__other_teams_unified_input_file_id_rejected(harness):
+ set_body(
+ harness,
+ {
+ "input_file_id": _unified_file_id(),
+ "endpoint": "/v1/chat/completions",
+ "completion_window": "24h",
+ },
+ )
+ harness.logging.get_proxy_hook.return_value = ManagedResourceAccessCheckerStub(file_access=False)
+
+ with patch.object(litellm, "require_managed_files", True):
+ with pytest.raises(ProxyException) as exc:
+ await call_create(harness)
+
+ assert exc.value.code == "403"
+ harness.litellm_acreate.assert_not_called()
+ harness.router_acreate.assert_not_called()
+
+
@pytest.mark.asyncio
async def test_retrieve__raw_batch_id_rejected_when_managed_files_required(retrieve_harness):
with patch.object(litellm, "require_managed_files", True):
@@ -2347,6 +2399,8 @@ async def test_retrieve__raw_batch_id_rejected_when_managed_files_required(retri
@pytest.mark.asyncio
async def test_retrieve__unified_batch_id_allowed_when_managed_files_required(retrieve_harness):
+ retrieve_harness.logging.get_proxy_hook.return_value = ManagedResourceAccessCheckerStub()
+
with patch.object(litellm, "require_managed_files", True):
await call_retrieve(retrieve_harness, _unified_batch_id())
@@ -2366,6 +2420,8 @@ async def test_cancel__raw_batch_id_rejected_when_managed_files_required(cancel_
@pytest.mark.asyncio
async def test_cancel__unified_batch_id_allowed_when_managed_files_required(cancel_harness):
+ cancel_harness.logging.get_proxy_hook.return_value = ManagedResourceAccessCheckerStub()
+
with patch.object(litellm, "require_managed_files", True):
await call_cancel(cancel_harness, _unified_batch_id())
diff --git a/tests/test_litellm/proxy/fine_tuning_endpoints/test_endpoints.py b/tests/test_litellm/proxy/fine_tuning_endpoints/test_endpoints.py
index 35c202057e7..b54787bf428 100644
--- a/tests/test_litellm/proxy/fine_tuning_endpoints/test_endpoints.py
+++ b/tests/test_litellm/proxy/fine_tuning_endpoints/test_endpoints.py
@@ -14,6 +14,7 @@ import base64
import os
import sys
from contextlib import ExitStack
+from dataclasses import dataclass
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -78,10 +79,31 @@ class FakeRequest:
return {}
+@dataclass(frozen=True)
+class ManagedResourceAccessCheckerStub:
+ file_access: bool = True
+ object_access: bool = True
+
+ async def can_user_call_unified_file_id(
+ self,
+ unified_file_id: str,
+ user_api_key_dict: UserAPIKeyAuth,
+ ) -> bool:
+ return self.file_access
+
+ async def can_user_call_unified_object_id(
+ self,
+ unified_object_id: str,
+ user_api_key_dict: UserAPIKeyAuth,
+ ) -> bool:
+ return self.object_access
+
+
class Seams:
- def __init__(self, router: MagicMock, litellm_calls: dict[str, AsyncMock]):
+ def __init__(self, router: MagicMock, litellm_calls: dict[str, AsyncMock], logging: MagicMock):
self.router = router
self.litellm_calls = litellm_calls
+ self.logging = logging
def assert_no_provider_call(self) -> None:
for name, mock in self.litellm_calls.items():
@@ -126,7 +148,7 @@ def seams():
stack.enter_context(patch.object(proxy_server, "proxy_config", MagicMock()))
stack.enter_context(patch.object(proxy_server, "version", "test-version"))
stack.enter_context(patch.object(endpoints, "fine_tuning_config", [{"custom_llm_provider": "openai"}]))
- yield Seams(router=router, litellm_calls=litellm_calls)
+ yield Seams(router=router, litellm_calls=litellm_calls, logging=logging)
async def _create(training_file: str, validation_file: str | None = None):
@@ -176,6 +198,8 @@ async def test_create__raw_training_file_rejected_when_managed_files_required(se
async def test_create__raw_validation_file_rejected_when_managed_files_required(seams):
"""The validation file is uploaded and readable exactly like the training file,
so a managed training_file must not smuggle a raw validation_file past the guard."""
+ seams.logging.get_proxy_hook.return_value = ManagedResourceAccessCheckerStub()
+
with patch.object(litellm, "require_managed_files", True):
with pytest.raises(ProxyException) as exc:
await _create(_unified_file_id(), validation_file=RAW_FILE_ID)
@@ -186,12 +210,26 @@ async def test_create__raw_validation_file_rejected_when_managed_files_required(
@pytest.mark.asyncio
async def test_create__unified_training_file_allowed_when_managed_files_required(seams):
+ seams.logging.get_proxy_hook.return_value = ManagedResourceAccessCheckerStub()
+
with patch.object(litellm, "require_managed_files", True):
await _create(_unified_file_id())
assert seams.router.acreate_fine_tuning_job.call_count == 1
+async def test_create__other_teams_unified_training_file_rejected(seams):
+ seams.logging.get_proxy_hook.return_value = ManagedResourceAccessCheckerStub(file_access=False)
+
+ with patch.object(litellm, "require_managed_files", True):
+ with pytest.raises(ProxyException) as exc:
+ await _create(_unified_file_id())
+
+ assert exc.value.code == "403"
+ seams.assert_no_provider_call()
+
+
@pytest.mark.asyncio
async def test_create__raw_training_file_allowed_when_managed_files_not_required(seams):
with patch.object(litellm, "require_managed_files", False):
@@ -212,6 +250,8 @@ async def test_retrieve__raw_job_id_rejected_when_managed_files_required(seams):
@pytest.mark.asyncio
async def test_retrieve__unified_job_id_allowed_when_managed_files_required(seams):
+ seams.logging.get_proxy_hook.return_value = ManagedResourceAccessCheckerStub()
+
with patch.object(litellm, "require_managed_files", True):
await _retrieve(_unified_job_id())
@@ -230,6 +270,8 @@ async def test_cancel__raw_job_id_rejected_when_managed_files_required(seams):
@pytest.mark.asyncio
async def test_cancel__unified_job_id_allowed_when_managed_files_required(seams):
+ seams.logging.get_proxy_hook.return_value = ManagedResourceAccessCheckerStub()
+
with patch.object(litellm, "require_managed_files", True):
await _cancel(_unified_job_id())
diff --git a/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py b/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py
index 2e15da7590a..e68e7102fce 100644
--- a/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py
+++ b/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py
@@ -3107,24 +3107,52 @@ def _unified_managed_file_id() -> str:
return base64.urlsafe_b64encode(unified_id.encode()).decode().rstrip("=")
-def test_require_managed_files_allows_unified_managed_file_id(monkeypatch):
+class _ManagedResourceAccessCheckerStub:
+ async def can_user_call_unified_file_id(
+ self,
+ unified_file_id: str,
+ user_api_key_dict: UserAPIKeyAuth,
+ ) -> bool:
+ return True
+
+ async def can_user_call_unified_object_id(
+ self,
+ unified_object_id: str,
+ user_api_key_dict: UserAPIKeyAuth,
+ ) -> bool:
+ return True
+
+
+async def test_require_managed_files_allows_owned_unified_managed_file_id(monkeypatch):
from litellm.proxy.openai_files_endpoints.common_utils import (
validate_managed_id_requirement,
)
monkeypatch.setattr("litellm.require_managed_files", True)
- validate_managed_id_requirement(resource_id=_unified_managed_file_id(), resource_kind="file")
+ await validate_managed_id_requirement(
+ resource_id=_unified_managed_file_id(),
+ resource_kind="file",
+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-test", user_id="owner-user"),
+ managed_files_obj=_ManagedResourceAccessCheckerStub(),
+ )
-def test_managed_file_id_requirement_is_opt_in(monkeypatch):
+async def test_managed_file_id_requirement_is_opt_in(monkeypatch):
from litellm.proxy.openai_files_endpoints.common_utils import (
validate_managed_id_requirement,
)
monkeypatch.setattr("litellm.require_managed_files", False)
- validate_managed_id_requirement(resource_id="file-victim-abc123", resource_kind="file")
+ await validate_managed_id_requirement(
+ resource_id="file-victim-abc123",
+ resource_kind="file",
+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-test"),
+ managed_files_obj=None,
+ )
def test_raw_provider_file_id_retrieve_allowed_when_managed_files_not_required(
diff --git a/tests/test_litellm/proxy/vector_store_files_endpoints/test_endpoints.py b/tests/test_litellm/proxy/vector_store_files_endpoints/test_endpoints.py
index c2bdb1d80f2..da5dd1934e4 100644
--- a/tests/test_litellm/proxy/vector_store_files_endpoints/test_endpoints.py
+++ b/tests/test_litellm/proxy/vector_store_files_endpoints/test_endpoints.py
@@ -5,13 +5,15 @@ Every vector-store file route (create, retrieve, content, update, delete) resolv
caller-supplied file id through _update_request_data_with_managed_file_id before the
provider call, so the guard lives there once and covers all five.
-A raw provider file id has no ownership row, so without the guard it is attached to a
-vector store or read back under the shared provider credentials with no tenant check.
+A raw or forged managed-looking file id has no ownership row, so without the guard it
+is attached to a vector store or read back under shared provider credentials.
"""
import base64
import os
import sys
+from dataclasses import dataclass
+from typing import Literal
from unittest.mock import MagicMock, patch
import pytest
@@ -21,12 +23,35 @@ sys.path.insert(0, os.path.abspath("../../../.."))
from fastapi import HTTPException
import litellm
+from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.vector_store_files_endpoints.endpoints import (
_update_request_data_with_managed_file_id,
)
from litellm.types.utils import SpecialEnums
RAW_FILE_ID = "file-victim-abc123"
+CALLER = UserAPIKeyAuth(api_key="sk-test", user_id="attacker-user", team_id="team-b")
+
+
+@dataclass(frozen=True)
+class ManagedResourceAccessCheckerStub:
+ file_access: Literal["allow", "deny", "missing"]
+
+ async def can_user_call_unified_file_id(
+ self,
+ unified_file_id: str,
+ user_api_key_dict: UserAPIKeyAuth,
+ ) -> bool:
+ if self.file_access == "missing":
+ raise HTTPException(status_code=404, detail=f"File not found: {unified_file_id}")
+ return self.file_access == "allow"
+
+ async def can_user_call_unified_object_id(
+ self,
+ unified_object_id: str,
+ user_api_key_dict: UserAPIKeyAuth,
+ ) -> bool:
+ return False
def _unified_file_id() -> str:
@@ -36,24 +61,31 @@ def _unified_file_id() -> str:
return base64.urlsafe_b64encode(unified.encode()).decode().rstrip("=")
-def _resolve(file_id: str):
- return _update_request_data_with_managed_file_id(
+async def _resolve(
+ file_id: str,
+ file_access: Literal["allow", "deny", "missing"] = "allow",
+):
+ return await _update_request_data_with_managed_file_id(
data={"vector_store_id": "vs-test", "file_id": file_id},
file_id=file_id,
request=MagicMock(headers={}, query_params={}),
+ user_api_key_dict=CALLER,
+ managed_files_obj=ManagedResourceAccessCheckerStub(file_access=file_access),
llm_router=None,
)
-def test_raw_file_id_rejected_when_managed_files_required():
+async def test_raw_file_id_rejected_when_managed_files_required():
with patch.object(litellm, "require_managed_files", True):
with pytest.raises(HTTPException) as exc:
- _resolve(RAW_FILE_ID)
+ await _resolve(RAW_FILE_ID)
assert exc.value.status_code == 400
-def test_model_encoded_file_id_rejected_when_managed_files_required():
+async def test_model_encoded_file_id_rejected_when_managed_files_required():
"""encode_file_id_with_model output is client-forgeable and carries no ownership
row, so it is not a managed file id."""
from litellm.proxy.openai_files_endpoints.common_utils import encode_file_id_with_model
@@ -62,22 +94,53 @@ def test_model_encoded_file_id_rejected_when_managed_files_required():
with patch.object(litellm, "require_managed_files", True):
with pytest.raises(HTTPException) as exc:
- _resolve(encoded)
+ await _resolve(encoded)
assert exc.value.status_code == 400
-def test_unified_file_id_allowed_when_managed_files_required():
+async def test_forged_unified_file_id_rejected_without_ownership_record():
+ forged_id = _unified_file_id()
+ data = {"vector_store_id": "vs-test", "file_id": forged_id}
+
+ with patch.object(litellm, "require_managed_files", True):
+ with pytest.raises(HTTPException) as exc:
+ await _update_request_data_with_managed_file_id(
+ data=data,
+ file_id=forged_id,
+ request=MagicMock(headers={}, query_params={}),
+ user_api_key_dict=CALLER,
+ managed_files_obj=ManagedResourceAccessCheckerStub(file_access="missing"),
+ llm_router=None,
+ )
+
+ assert exc.value.status_code == 404
+ assert data["file_id"] == forged_id
+
+
+async def test_other_teams_unified_file_id_rejected():
+ with patch.object(litellm, "require_managed_files", True):
+ with pytest.raises(HTTPException) as exc:
+ await _resolve(_unified_file_id(), file_access="deny")
+
+ assert exc.value.status_code == 403
+
+
+async def test_owned_unified_file_id_allowed_when_managed_files_required():
with patch.object(litellm, "require_managed_files", True):
- data, original = _resolve(_unified_file_id())
+ data, original = await _resolve(_unified_file_id())
assert original == _unified_file_id()
assert data["file_id"] == RAW_FILE_ID
-def test_raw_file_id_allowed_when_managed_files_not_required():
+async def test_raw_file_id_allowed_when_managed_files_not_required():
with patch.object(litellm, "require_managed_files", False):
- data, original = _resolve(RAW_FILE_ID)
+ data, original = await _resolve(RAW_FILE_ID)
assert original is None
assert data["file_id"] == RAW_FILE_ID