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
chore(vector stores): tighten managed store access
userd3ab59e0595e
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 76c52f83ee4..e3ad714d45d 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -97,6 +97,55 @@ def _serialize_http_exception_detail(return str(detail), None+def _collect_response_file_search_vector_store_ids(data: Dict[str, Any]) -> set[str]:+ vector_store_ids: set[str] = set()+ tools = data.get("tools")+ if not isinstance(tools, list):+ return vector_store_ids++ for tool in tools:+ if not isinstance(tool, dict) or tool.get("type") != "file_search":+ continue+ ids = tool.get("vector_store_ids") or []+ if not isinstance(ids, list):+ raise HTTPException(+ status_code=400,+ detail={+ "error": "file_search.vector_store_ids must be a list of strings"+ },+ )+ for vector_store_id in ids:+ if not isinstance(vector_store_id, str) or not vector_store_id:+ raise HTTPException(+ status_code=400,+ detail={+ "error": "file_search.vector_store_ids must be a list of strings"+ },+ )+ vector_store_ids.add(vector_store_id)++ return vector_store_ids+++async def _authorize_response_file_search_vector_stores(+ data: Dict[str, Any],+ user_api_key_dict: UserAPIKeyAuth,+) -> None:+ vector_store_ids = _collect_response_file_search_vector_store_ids(data)+ if not vector_store_ids:+ return++ from litellm.proxy.vector_store_endpoints.utils import (+ assert_user_can_access_vector_store_id,+ )++ for vector_store_id in sorted(vector_store_ids):+ await assert_user_can_access_vector_store_id(+ vector_store_id=vector_store_id,+ user_api_key_dict=user_api_key_dict,+ )++async def _parse_event_data_for_error(event_line: Union[str, bytes]) -> Optional[int]:"""Parses an event line and returns an error code if present, else None."""event_line = (@@ -786,6 +835,11 @@ class ProxyBaseLLMRequestProcessing:version=version,proxy_config=proxy_config,)+ if route_type in {"aresponses", "_aresponses_websocket"}:+ await _authorize_response_file_search_vector_stores(+ data=self.data,+ user_api_key_dict=user_api_key_dict,+ )# Calculate request queue time after add_litellm_data_to_request# which sets arrival_time in proxy_server_requestdiff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.pyindex 6521abffb85..ddb6717cb2e 100644--- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py+++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py@@ -47,6 +47,7 @@ from litellm.types.passthrough_endpoints.pass_through_endpoints import ()from litellm.proxy.utils import is_known_modelfrom litellm.proxy.vector_store_endpoints.utils import (+ assert_user_can_access_vector_store,is_allowed_to_call_vector_store_endpoint,)from litellm.secret_managers.main import get_secret_str@@ -533,6 +534,10 @@ async def milvus_proxy_route()if vector_store is None:raise Exception(f"Vector store not found for {vector_store_name}")+ await assert_user_can_access_vector_store(+ vector_store=vector_store,+ user_api_key_dict=user_api_key_dict,+ )litellm_params = vector_store.get("litellm_params") or {}auth_credentials = provider_config.get_auth_credentials(litellm_params=litellm_params@@ -1438,6 +1443,10 @@ async def azure_proxy_route()if vector_store is None:raise Exception(f"Vector store not found for {vector_store_name}")+ await assert_user_can_access_vector_store(+ vector_store=vector_store,+ user_api_key_dict=user_api_key_dict,+ )litellm_params = vector_store.get("litellm_params") or {}auth_credentials = provider_config.get_auth_credentials(litellm_params=litellm_params@@ -1777,6 +1786,11 @@ async def _base_vertex_proxy_route(request=request,api_key=api_key_to_use,)+ if router_credentials is not None:+ await assert_user_can_access_vector_store(+ vector_store=router_credentials,+ user_api_key_dict=user_api_key_dict,+ )vertex_project: Optional[str] = get_vertex_project_id_from_url(endpoint)vertex_location: Optional[str] = get_vertex_location_from_url(endpoint)@@ -1929,6 +1943,10 @@ async def vertex_discovery_proxy_route("Vector store ID %s found in endpoint but no credentials found in registry",vector_store_id,)+ raise HTTPException(+ status_code=403,+ detail="Access denied: You do not have permission to access this vector store",+ )discovery_handler = get_vertex_pass_through_handler(call_type="discovery")return await _base_vertex_proxy_route(diff --git a/litellm/proxy/rag_endpoints/endpoints.py b/litellm/proxy/rag_endpoints/endpoints.pyindex 95ca51612fc..9e6093a47a1 100644--- a/litellm/proxy/rag_endpoints/endpoints.py+++ b/litellm/proxy/rag_endpoints/endpoints.py@@ -22,10 +22,45 @@ from litellm.proxy.common_utils.http_parsing_utils import (_safe_get_request_headers,get_form_data,)+from litellm.proxy.vector_store_endpoints.utils import (+ assert_user_can_access_vector_store_id,+)router = APIRouter()+def _collect_vector_store_ids_from_payload(payload: Any) -> set[str]:+ vector_store_ids: set[str] = set()++ if isinstance(payload, dict):+ for key, value in payload.items():+ if key == "vector_store_id":+ if not isinstance(value, str) or not value:+ raise HTTPException(+ status_code=400,+ detail={"error": "vector_store_id must be a non-empty string"},+ )+ vector_store_ids.add(value)+ continue+ vector_store_ids.update(_collect_vector_store_ids_from_payload(value))+ elif isinstance(payload, list):+ for item in payload:+ vector_store_ids.update(_collect_vector_store_ids_from_payload(item))++ return vector_store_ids+++async def _authorize_nested_vector_store_ids(+ payload: Any,+ user_api_key_dict: UserAPIKeyAuth,+) -> None:+ for vector_store_id in sorted(_collect_vector_store_ids_from_payload(payload)):+ await assert_user_can_access_vector_store_id(+ vector_store_id=vector_store_id,+ user_api_key_dict=user_api_key_dict,+ )++def _build_file_metadata_entry(response: Any,file_data: Optional[Tuple[str, bytes, str]] = None,@@ -385,6 +420,11 @@ async def rag_ingest(},)+ await _authorize_nested_vector_store_ids(+ payload=ingest_options,+ user_api_key_dict=user_api_key_dict,+ )+# Add litellm datarequest_data: Dict[str, Any] = {}request_data = await add_litellm_data_to_request(@@ -537,11 +577,20 @@ async def rag_query(status_code=400,detail={"error": "retrieval_config is required"},)+ if not isinstance(retrieval_config, dict):+ raise HTTPException(+ status_code=400,+ detail={"error": "retrieval_config must be an object"},+ )if "vector_store_id" not in retrieval_config:raise HTTPException(status_code=400,detail={"error": "retrieval_config must contain 'vector_store_id'"},)+ await _authorize_nested_vector_store_ids(+ payload=retrieval_config,+ user_api_key_dict=user_api_key_dict,+ )# Add litellm datarequest_data: Dict[str, Any] = {}diff --git a/litellm/proxy/vector_store_endpoints/endpoints.py b/litellm/proxy/vector_store_endpoints/endpoints.pyindex 1fdfad8c96c..05423d9843d 100644--- a/litellm/proxy/vector_store_endpoints/endpoints.py+++ b/litellm/proxy/vector_store_endpoints/endpoints.py@@ -1,8 +1,6 @@from typing import Any, Dict, Optionalfrom fastapi import APIRouter, Depends, HTTPException, Request, Response--import litellmfrom litellm.integrations.vector_store_integrations.vector_store_pre_call_hook import (LiteLLM_ManagedVectorStore,)@@ -10,7 +8,10 @@ from litellm.proxy._types import CommonProxyErrors, UserAPIKeyAuthfrom litellm.proxy.auth.user_api_key_auth import user_api_key_authfrom litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessingfrom litellm.proxy.utils import jsonify_object-from litellm.proxy.vector_store_endpoints.utils import can_user_access_vector_store+from litellm.proxy.vector_store_endpoints.utils import (+ assert_user_can_access_vector_store,+ get_litellm_managed_vector_store,+)from litellm.types.vector_stores import IndexCreateRequestrouter = APIRouter()@@ -32,9 +33,14 @@ async def _check_vector_store_access(- key-level and team-level ``object_permission.vector_stores`` allowlists- team_id match between key and store"""- return await can_user_access_vector_store(- vector_store=vector_store, user_api_key_dict=user_api_key_dict- )+ try:+ await assert_user_can_access_vector_store(+ vector_store=vector_store,+ user_api_key_dict=user_api_key_dict,+ )+ return True+ except HTTPException:+ return Falseasync def _update_request_data_with_litellm_managed_vector_store_registry(@@ -53,35 +59,27 @@ async def _update_request_data_with_litellm_managed_vector_store_registry(Raises:HTTPException: If user doesn't have access to the vector store"""- if litellm.vector_store_registry is not None:- vector_store_to_run: Optional[LiteLLM_ManagedVectorStore] = (- litellm.vector_store_registry.get_litellm_managed_vector_store_from_registry(- vector_store_id=vector_store_id+ vector_store_to_run: Optional[LiteLLM_ManagedVectorStore] = (+ await get_litellm_managed_vector_store(vector_store_id=vector_store_id)+ )+ if vector_store_to_run is not None:+ if user_api_key_dict is not None:+ await assert_user_can_access_vector_store(+ vector_store=vector_store_to_run,+ user_api_key_dict=user_api_key_dict,)- )- if vector_store_to_run is not None:- if user_api_key_dict is not None:- if not await _check_vector_store_access(- vector_store_to_run, user_api_key_dict- ):- raise HTTPException(- status_code=403,- detail="Access denied: You do not have permission to access this vector store",- )-- if "custom_llm_provider" in vector_store_to_run:- data["custom_llm_provider"] = vector_store_to_run.get(- "custom_llm_provider"- )-- if "litellm_credential_name" in vector_store_to_run:- data["litellm_credential_name"] = vector_store_to_run.get(- "litellm_credential_name"- )-- if "litellm_params" in vector_store_to_run:- litellm_params = vector_store_to_run.get("litellm_params", {}) or {}- data.update(litellm_params)++ if "custom_llm_provider" in vector_store_to_run:+ data["custom_llm_provider"] = vector_store_to_run.get("custom_llm_provider")++ if "litellm_credential_name" in vector_store_to_run:+ data["litellm_credential_name"] = vector_store_to_run.get(+ "litellm_credential_name"+ )++ if "litellm_params" in vector_store_to_run:+ litellm_params = vector_store_to_run.get("litellm_params", {}) or {}+ data.update(litellm_params)return data@@ -121,8 +119,7 @@ async def vector_store_search()data = await _read_request_body(request=request)- if "vector_store_id" not in data:- data["vector_store_id"] = vector_store_id+ data["vector_store_id"] = vector_store_id# Check for legacy vector store registry (non-managed vector stores)data = await _update_request_data_with_litellm_managed_vector_store_registry(diff --git a/litellm/proxy/vector_store_endpoints/utils.py b/litellm/proxy/vector_store_endpoints/utils.pyindex 061a8aaa240..827bbba630e 100644--- a/litellm/proxy/vector_store_endpoints/utils.py+++ b/litellm/proxy/vector_store_endpoints/utils.py@@ -1,7 +1,9 @@+import jsonfrom typing import Any, Dict, Literal, Optionalfrom fastapi import HTTPException, Request+import litellmfrom litellm._logging import verbose_proxy_loggerfrom litellm.proxy._types import (LiteLLM_ObjectPermissionTable,@@ -13,6 +15,21 @@ from litellm.types.vector_stores import LiteLLM_ManagedVectorStorefrom litellm.utils import ProviderConfigManager+def _normalize_litellm_params(+ vector_store: LiteLLM_ManagedVectorStore,+) -> LiteLLM_ManagedVectorStore:+ litellm_params = vector_store.get("litellm_params")+ if isinstance(litellm_params, str):+ normalized = LiteLLM_ManagedVectorStore(**dict(vector_store))+ try:+ parsed = json.loads(litellm_params)+ normalized["litellm_params"] = parsed if isinstance(parsed, dict) else {}+ except (TypeError, ValueError):+ normalized["litellm_params"] = {}+ return normalized+ return vector_store++def _is_proxy_admin(user_api_key_dict: UserAPIKeyAuth) -> bool:return (user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN@@ -120,6 +137,85 @@ async def can_user_access_vector_store(return False+async def get_litellm_managed_vector_store(+ vector_store_id: str,+) -> Optional[LiteLLM_ManagedVectorStore]:+ """+ Resolve a LiteLLM-managed vector store from the registry or database.++ Provider-native vector store IDs will not be present in either location and+ return None, preserving direct provider behavior while still protecting+ LiteLLM-managed multi-tenant stores.+ """+ if not vector_store_id:+ return None++ if litellm.vector_store_registry is not None:+ try:+ vector_store = litellm.vector_store_registry.get_litellm_managed_vector_store_from_registry(+ vector_store_id=vector_store_id+ )+ if vector_store is not None:+ return _normalize_litellm_params(vector_store)+ except Exception as e:+ verbose_proxy_logger.debug(+ "Failed to resolve vector store id=%s from registry: %s",+ vector_store_id,+ e,+ )++ try:+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ return None+ row = await prisma_client.db.litellm_managedvectorstorestable.find_unique(+ where={"vector_store_id": vector_store_id}+ )+ if row is None:+ return None+ return _normalize_litellm_params(LiteLLM_ManagedVectorStore(**row.model_dump()))+ except Exception as e:+ verbose_proxy_logger.debug(+ "Failed to resolve vector store id=%s from database: %s",+ vector_store_id,+ e,+ )+ return None+++async def assert_user_can_access_vector_store(+ vector_store: LiteLLM_ManagedVectorStore,+ user_api_key_dict: UserAPIKeyAuth,+ detail: str = "Access denied: You do not have permission to access this vector store",+) -> None:+ """Raise 403 unless the caller can access the resolved vector store."""+ if not await can_user_access_vector_store(vector_store, user_api_key_dict):+ raise HTTPException(status_code=403, detail=detail)+++async def assert_user_can_access_vector_store_id(+ vector_store_id: str,+ user_api_key_dict: UserAPIKeyAuth,+ detail: str = "Access denied: You do not have permission to access this vector store",+) -> Optional[LiteLLM_ManagedVectorStore]:+ """+ Resolve a managed vector store id and enforce ownership if it exists.++ Unknown ids are treated as provider-native ids and are not rejected here.+ """+ vector_store = await get_litellm_managed_vector_store(+ vector_store_id=vector_store_id+ )+ if vector_store is not None:+ await assert_user_can_access_vector_store(+ vector_store=vector_store,+ user_api_key_dict=user_api_key_dict,+ detail=detail,+ )+ return vector_store++def _does_endpoint_match(endpoint_path: str, request_path: str) -> bool:if endpoint_path in request_path:return Truediff --git a/litellm/proxy/vector_store_files_endpoints/endpoints.py b/litellm/proxy/vector_store_files_endpoints/endpoints.pyindex 7cdf865692b..ae8dc602e82 100644--- a/litellm/proxy/vector_store_files_endpoints/endpoints.py+++ b/litellm/proxy/vector_store_files_endpoints/endpoints.py@@ -17,6 +17,7 @@ from litellm.proxy.openai_files_endpoints.common_utils import (prepare_data_with_credentials,)from litellm.proxy.vector_store_endpoints.utils import (+ assert_user_can_access_vector_store_id,is_allowed_to_call_vector_store_files_endpoint,)from litellm.types.utils import LlmProviders@@ -363,8 +364,11 @@ async def vector_store_file_create()data = await _read_request_body(request=request)- if "vector_store_id" not in data:- data["vector_store_id"] = vector_store_id+ data["vector_store_id"] = vector_store_id+ await assert_user_can_access_vector_store_id(+ vector_store_id=vector_store_id,+ user_api_key_dict=user_api_key_dict,+ )# Handle managed file IDs if present in request bodyoriginal_managed_file_id = None@@ -459,6 +463,11 @@ async def vector_store_file_list(query_params = dict(request.query_params)data: Dict[str, Optional[str]] = {"vector_store_id": vector_store_id}data.update(query_params)+ data["vector_store_id"] = vector_store_id+ await assert_user_can_access_vector_store_id(+ vector_store_id=vector_store_id,+ user_api_key_dict=user_api_key_dict,+ )data = _update_request_data_with_litellm_managed_vector_store_registry(data=data, vector_store_id=vector_store_id, llm_router=llm_router@@ -541,6 +550,10 @@ async def vector_store_file_retrieve("vector_store_id": vector_store_id,"file_id": file_id,}+ await assert_user_can_access_vector_store_id(+ vector_store_id=vector_store_id,+ user_api_key_dict=user_api_key_dict,+ )# Handle managed file IDs firstdata, original_managed_file_id = _update_request_data_with_managed_file_id(@@ -635,6 +648,10 @@ async def vector_store_file_content("vector_store_id": vector_store_id,"file_id": file_id,}+ await assert_user_can_access_vector_store_id(+ vector_store_id=vector_store_id,+ user_api_key_dict=user_api_key_dict,+ )# Handle managed file IDs firstdata, original_managed_file_id = _update_request_data_with_managed_file_id(@@ -729,6 +746,10 @@ async def vector_store_file_update(data = await _read_request_body(request=request)data["vector_store_id"] = vector_store_iddata["file_id"] = file_id+ await assert_user_can_access_vector_store_id(+ vector_store_id=vector_store_id,+ user_api_key_dict=user_api_key_dict,+ )# Handle managed file IDs firstdata, original_managed_file_id = _update_request_data_with_managed_file_id(@@ -823,6 +844,10 @@ async def vector_store_file_delete("vector_store_id": vector_store_id,"file_id": file_id,}+ await assert_user_can_access_vector_store_id(+ vector_store_id=vector_store_id,+ user_api_key_dict=user_api_key_dict,+ )# Handle managed file IDs firstdata, original_managed_file_id = _update_request_data_with_managed_file_id(diff --git a/litellm/vector_stores/main.py b/litellm/vector_stores/main.pyindex 6d28d670979..13f2f27d3fa 100644--- a/litellm/vector_stores/main.py+++ b/litellm/vector_stores/main.py@@ -377,15 +377,11 @@ def search(_is_async = kwargs.pop("asearch", False) is True# pull credentials from registry if available- vector_store_id_for_credentials = kwargs.get("vector_store_id", vector_store_id)- if (- litellm.vector_store_registry is not None- and vector_store_id_for_credentials is not None- ):+ if litellm.vector_store_registry is not None and vector_store_id is not None:try:registry_credentials = (litellm.vector_store_registry.get_credentials_for_vector_store(- vector_store_id_for_credentials+ vector_store_id))kwargs.update(registry_credentials)diff --git a/tests/test_litellm/proxy/vector_store_endpoints/test_vector_store_tenant_guard.py b/tests/test_litellm/proxy/vector_store_endpoints/test_vector_store_tenant_guard.pynew file mode 100644index 00000000000..c160c5aceb3--- /dev/null+++ b/tests/test_litellm/proxy/vector_store_endpoints/test_vector_store_tenant_guard.py@@ -0,0 +1,362 @@+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from fastapi import HTTPException, Request, Response++import litellm+from litellm.proxy._types import UserAPIKeyAuth+++def _mock_request() -> MagicMock:+ request = MagicMock(spec=Request)+ request.headers = {}+ request.method = "POST"+ request.query_params = {}+ request.url.path = "/v1/vector_stores/vs_path/search"+ return request+++async def test_vector_store_search_forces_path_id_over_body_id():+ from litellm.proxy.vector_store_endpoints.endpoints import vector_store_search++ captured_data = {}++ async def fake_base_process(self, **kwargs):+ captured_data.update(self.data)+ return {"ok": True}++ request = _mock_request()+ with (+ patch(+ "litellm.proxy.proxy_server._read_request_body",+ new=AsyncMock(+ return_value={+ "vector_store_id": "vs_body_victim",+ "query": "test",+ }+ ),+ ),+ patch.object(litellm, "vector_store_registry", None),+ patch(+ "litellm.proxy.vector_store_endpoints.endpoints.ProxyBaseLLMRequestProcessing.base_process_llm_request",+ new=fake_base_process,+ ),+ ):+ response = await vector_store_search(+ request=request,+ vector_store_id="vs_path_allowed",+ fastapi_response=Response(),+ user_api_key_dict=UserAPIKeyAuth(team_id="team-a"),+ )++ assert response == {"ok": True}+ assert captured_data["vector_store_id"] == "vs_path_allowed"+++async def test_vector_store_file_create_forces_path_id_over_body_id():+ from litellm.proxy.vector_store_files_endpoints.endpoints import (+ vector_store_file_create,+ )++ captured_data = {}++ async def fake_base_process(self, **kwargs):+ captured_data.update(self.data)+ return {"ok": True}++ mock_registry = MagicMock()+ mock_registry.get_litellm_managed_vector_store_from_registry.return_value = {+ "vector_store_id": "vs_path_allowed",+ "custom_llm_provider": "openai",+ "team_id": "team-a",+ }++ request = _mock_request()+ with (+ patch(+ "litellm.proxy.proxy_server._read_request_body",+ new=AsyncMock(+ return_value={+ "vector_store_id": "vs_body_victim",+ "file_id": "file_123",+ }+ ),+ ),+ patch.object(litellm, "vector_store_registry", mock_registry),+ patch(+ "litellm.proxy.vector_store_files_endpoints.endpoints.ProxyBaseLLMRequestProcessing.base_process_llm_request",+ new=fake_base_process,+ ),+ ):+ response = await vector_store_file_create(+ vector_store_id="vs_path_allowed",+ request=request,+ fastapi_response=Response(),+ user_api_key_dict=UserAPIKeyAuth(team_id="team-a"),+ )++ assert response == {"ok": True}+ assert captured_data["vector_store_id"] == "vs_path_allowed"+ mock_registry.get_litellm_managed_vector_store_from_registry.assert_any_call(+ vector_store_id="vs_path_allowed"+ )+++async def test_vector_store_file_create_denies_other_team_path_store():+ from litellm.proxy.vector_store_files_endpoints.endpoints import (+ vector_store_file_create,+ )++ mock_registry = MagicMock()+ mock_registry.get_litellm_managed_vector_store_from_registry.return_value = {+ "vector_store_id": "vs_other_team",+ "custom_llm_provider": "openai",+ "team_id": "team-b",+ }++ request = _mock_request()+ with (+ patch(+ "litellm.proxy.proxy_server._read_request_body",+ new=AsyncMock(return_value={"file_id": "file_123"}),+ ),+ patch.object(litellm, "vector_store_registry", mock_registry),+ patch(+ "litellm.proxy.vector_store_files_endpoints.endpoints.ProxyBaseLLMRequestProcessing.base_process_llm_request",+ new=AsyncMock(),+ ) as mock_base_process,+ ):+ with pytest.raises(HTTPException) as exc_info:+ await vector_store_file_create(+ vector_store_id="vs_other_team",+ request=request,+ fastapi_response=Response(),+ user_api_key_dict=UserAPIKeyAuth(team_id="team-a"),+ )++ assert exc_info.value.status_code == 403+ mock_base_process.assert_not_called()+++async def test_rag_query_denies_nested_other_team_vector_store():+ from litellm.proxy.rag_endpoints.endpoints import rag_query++ mock_registry = MagicMock()+ mock_registry.get_litellm_managed_vector_store_from_registry.return_value = {+ "vector_store_id": "vs_other_team",+ "custom_llm_provider": "openai",+ "team_id": "team-b",+ }++ request = _mock_request()+ with (+ patch(+ "litellm.proxy.rag_endpoints.endpoints._read_request_body",+ new=AsyncMock(+ return_value={+ "model": "gpt-4o-mini",+ "messages": [{"role": "user", "content": "hello"}],+ "retrieval_config": {"vector_store_id": "vs_other_team"},+ }+ ),+ ),+ patch.object(litellm, "vector_store_registry", mock_registry),+ patch(+ "litellm.proxy.rag_endpoints.endpoints.litellm.aquery",+ new=AsyncMock(),+ ) as mock_aquery,+ ):+ with pytest.raises(HTTPException) as exc_info:+ await rag_query(+ request=request,+ fastapi_response=Response(),+ user_api_key_dict=UserAPIKeyAuth(team_id="team-a"),+ )++ assert exc_info.value.status_code == 403+ mock_aquery.assert_not_called()+++async def test_rag_ingest_denies_nested_other_team_vector_store():+ from litellm.proxy.rag_endpoints.endpoints import rag_ingest++ mock_registry = MagicMock()+ mock_registry.get_litellm_managed_vector_store_from_registry.return_value = {+ "vector_store_id": "vs_other_team",+ "custom_llm_provider": "openai",+ "team_id": "team-b",+ }++ request = _mock_request()+ with (+ patch(+ "litellm.proxy.rag_endpoints.endpoints.parse_rag_ingest_request",+ new=AsyncMock(+ return_value=(+ {+ "vector_store": {+ "custom_llm_provider": "openai",+ "vector_store_id": "vs_other_team",+ }+ },+ None,+ "https://example.com/file.txt",+ None,+ )+ ),+ ),+ patch.object(litellm, "vector_store_registry", mock_registry),+ patch(+ "litellm.proxy.rag_endpoints.endpoints.litellm.aingest",+ new=AsyncMock(),+ ) as mock_aingest,+ ):+ with pytest.raises(HTTPException) as exc_info:+ await rag_ingest(+ request=request,+ fastapi_response=Response(),+ user_api_key_dict=UserAPIKeyAuth(team_id="team-a"),+ )++ assert exc_info.value.status_code == 403+ mock_aingest.assert_not_called()+++async def test_responses_file_search_denies_other_team_vector_store():+ from litellm.proxy.common_request_processing import (+ _authorize_response_file_search_vector_stores,+ )++ mock_registry = MagicMock()+ mock_registry.get_litellm_managed_vector_store_from_registry.return_value = {+ "vector_store_id": "vs_other_team",+ "custom_llm_provider": "openai",+ "team_id": "team-b",+ }++ with patch.object(litellm, "vector_store_registry", mock_registry):+ with pytest.raises(HTTPException) as exc_info:+ await _authorize_response_file_search_vector_stores(+ data={+ "tools": [+ {+ "type": "file_search",+ "vector_store_ids": ["vs_other_team"],+ }+ ]+ },+ user_api_key_dict=UserAPIKeyAuth(team_id="team-a"),+ )++ assert exc_info.value.status_code == 403+++async def test_vertex_discovery_denies_other_team_vector_store_credentials():+ from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import (+ _base_vertex_proxy_route,+ )++ request = _mock_request()+ request.method = "GET"+ vector_store_credentials = {+ "vector_store_id": "vs_other_team",+ "custom_llm_provider": "vertex_ai",+ "team_id": "team-b",+ }++ with patch(+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.user_api_key_auth",+ new=AsyncMock(return_value=UserAPIKeyAuth(team_id="team-a")),+ ):+ with pytest.raises(HTTPException) as exc_info:+ await _base_vertex_proxy_route(+ endpoint="projects/p/locations/us-central1/dataStores/vs_other_team",+ request=request,+ fastapi_response=Response(),+ get_vertex_pass_through_handler=MagicMock(),+ router_credentials=vector_store_credentials,+ )++ assert exc_info.value.status_code == 403+++async def test_vertex_discovery_denies_unregistered_vector_store_id():+ from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import (+ vertex_discovery_proxy_route,+ )++ request = _mock_request()+ request.method = "GET"++ with patch(+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.passthrough_endpoint_router.get_vector_store_credentials",+ return_value=None,+ ):+ with pytest.raises(HTTPException) as exc_info:+ await vertex_discovery_proxy_route(+ endpoint="projects/p/locations/us-central1/dataStores/vs_unknown",+ request=request,+ fastapi_response=Response(),+ )++ assert exc_info.value.status_code == 403+++async def test_milvus_passthrough_denies_other_team_vector_store_index():+ from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import (+ milvus_proxy_route,+ )++ request = _mock_request()+ request.url.path = "/milvus/v2/vectordb/entities/search"++ index_object = MagicMock()+ index_object.litellm_params.vector_store_name = "tenant-b-store"+ index_object.litellm_params.vector_store_index = "tenant_b_collection"++ mock_index_registry = MagicMock()+ mock_index_registry.is_vector_store_index.return_value = True+ mock_index_registry.get_vector_store_index_by_name.return_value = index_object++ mock_vector_registry = MagicMock()+ mock_vector_registry.get_litellm_managed_vector_store_from_registry_by_name.return_value = {+ "vector_store_id": "vs_other_team",+ "custom_llm_provider": "milvus",+ "team_id": "team-b",+ "litellm_params": {"api_base": "https://milvus.example.com"},+ }++ with (+ patch(+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.ProviderConfigManager.get_provider_vector_stores_config",+ return_value=MagicMock(),+ ),+ patch(+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.get_request_body",+ new=AsyncMock(return_value={"collectionName": "managed_index"}),+ ),+ patch(+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.is_allowed_to_call_vector_store_endpoint",+ return_value=True,+ ),+ patch.object(litellm, "vector_store_index_registry", mock_index_registry),+ patch.object(litellm, "vector_store_registry", mock_vector_registry),+ ):+ with pytest.raises(HTTPException) as exc_info:+ await milvus_proxy_route(+ endpoint="v2/vectordb/entities/search",+ request=request,+ fastapi_response=Response(),+ user_api_key_dict=UserAPIKeyAuth(team_id="team-a"),+ )++ assert exc_info.value.status_code == 403