Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 104 additions & 16 deletions enterprise/litellm_enterprise/proxy/hooks/managed_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,24 @@
PrismaClient = Any


def _parse_managed_file_object(
raw_file_object: object, unified_file_id: str
) -> Optional[OpenAIFileObject]:
if not raw_file_object:
return None
try:
return (
OpenAIFileObject.model_validate_json(raw_file_object)
if isinstance(raw_file_object, str)
else OpenAIFileObject.model_validate(raw_file_object)
)
except Exception as e:
verbose_logger.warning(
f"Failed to parse managed file object {unified_file_id}: {e}"
)
return None


class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
# Class variables or attributes
def __init__(
Expand Down Expand Up @@ -376,13 +394,43 @@ async def get_user_created_file_ids(
if owner_filter is None:
return []

file_ids = await self.prisma_client.db.litellm_managedfiletable.find_many(
rows = await self.prisma_client.db.litellm_managedfiletable.find_many(
where={
**owner_filter,
"flat_model_file_ids": {"hasSome": model_object_ids},
}
)
return [OpenAIFileObject.model_validate(file_object.file_object) for file_object in file_ids]
return [
parsed
for row in rows
if (
parsed := _parse_managed_file_object(
row.file_object, row.unified_file_id
)
)
is not None
]

async def _provider_file_ids_claimed_by_managed_rows(
self, model_object_ids: List[str]
) -> set[str]:
"""Provider file ids from ``model_object_ids`` that appear in any managed row.

Used by list filtering so untracked (non-managed) provider uploads stay
visible, while managed rows owned by other callers can still be hidden.
"""
if not model_object_ids:
return set()
page_ids = set(model_object_ids)
rows = await self.prisma_client.db.litellm_managedfiletable.find_many(
where={"flat_model_file_ids": {"hasSome": model_object_ids}},
)
Comment on lines +425 to +427

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 List hook adds direct DB queries

Every nonempty managed file-list response now performs this owner-agnostic query inline, followed by another direct query when claimed IDs exist, increasing database load and latency on GET /v1/files and violating the repository rule against direct request-path database access.

Rule Used: What: In critical path of request, there should be... (source)

Knowledge Base Used: Enterprise package (enterprise/)

claimed: set[str] = set()
for row in rows:
for provider_id in row.flat_model_file_ids or []:
if provider_id in page_ids:
claimed.add(provider_id)
return claimed

async def check_managed_file_id_access(
self, data: Dict, user_api_key_dict: UserAPIKeyAuth
Expand Down Expand Up @@ -1248,30 +1296,70 @@ async def async_post_call_success_hook(
)
elif isinstance(response, AsyncCursorPage):
"""
For listing files, filter for the ones created by the user
Filter a provider file list for multi-tenant isolation.

Managed rows on a shared provider account must only be visible to
their owner. Untracked (non-managed) provider uploads, including
provider-scoped /{provider}/v1/files creates that never entered the
managed table, must stay on the page; dropping them is LIT-4820.
"""
## check if file object
if hasattr(response, "data") and isinstance(response.data, list):
if all(
isinstance(file_object, FileObject) for file_object in response.data
):
## Get all file id's
## Check which file id's were created by the user
## Filter the response to only include the files created by the user
## Return the filtered response
file_ids = [
file_object.id
for file_object in cast(List[FileObject], response.data) # type: ignore
]
user_created_file_ids = await self.get_user_created_file_ids(
user_api_key_dict, file_ids
response.data = await self._filter_listed_provider_files( # type: ignore
provider_files=cast(List[FileObject], response.data), # type: ignore
user_api_key_dict=user_api_key_dict,
)
## Filter the response to only include the files created by the user
response.data = user_created_file_ids # type: ignore
return response
return response
return response

async def _filter_listed_provider_files(
self,
provider_files: List[FileObject],
user_api_key_dict: UserAPIKeyAuth,
) -> List[Union[FileObject, OpenAIFileObject]]:
file_ids = [file_object.id for file_object in provider_files]
if not file_ids:
return []

claimed_by_anyone = await self._provider_file_ids_claimed_by_managed_rows(
file_ids
)
owner_filter = build_owner_filter(user_api_key_dict)
user_owned_by_provider_id: Dict[str, OpenAIFileObject] = {}
if owner_filter is not None and claimed_by_anyone:
user_owned_rows = await self.prisma_client.db.litellm_managedfiletable.find_many(
where={
**owner_filter,
"flat_model_file_ids": {"hasSome": list(claimed_by_anyone)},
}
)
page_id_set = set(file_ids)
for row in user_owned_rows:
parsed = _parse_managed_file_object(row.file_object, row.unified_file_id)
if parsed is None:
continue
for provider_id in row.flat_model_file_ids or []:
if provider_id in page_id_set:
user_owned_by_provider_id[provider_id] = parsed

kept: List[Union[FileObject, OpenAIFileObject]] = []
emitted_managed_ids: set[str] = set()
for provider_file in provider_files:
if provider_file.id not in claimed_by_anyone:
kept.append(provider_file)
Comment on lines +1350 to +1352

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Untracked files bypass owner isolation

If multiple virtual keys share upstream provider credentials, an upload without a managed row is appended without applying build_owner_filter, causing its file metadata to appear in another caller's GET /v1/files results.

How this was verified: The untracked-ID branch returns the provider object directly, while ownership filtering is applied only when loading managed rows.

Rule Used: What: Fail any PR which may contains a security in... (source)

Knowledge Base Used: Enterprise package (enterprise/)

continue
managed_obj = user_owned_by_provider_id.get(provider_file.id)
if managed_obj is None:
continue
if managed_obj.id in emitted_managed_ids:
continue
kept.append(managed_obj)
emitted_managed_ids.add(managed_obj.id)
return kept

async def afile_retrieve(
self, file_id: str, litellm_parent_otel_span: Optional[Span], llm_router=None
) -> OpenAIFileObject:
Expand Down
7 changes: 7 additions & 0 deletions litellm/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -1376,6 +1376,13 @@
BATCH_STATUS_POLL_INTERVAL_SECONDS = int(os.getenv("BATCH_STATUS_POLL_INTERVAL_SECONDS", 3600)) # 1 hour
BATCH_STATUS_POLL_MAX_ATTEMPTS = int(os.getenv("BATCH_STATUS_POLL_MAX_ATTEMPTS", 24)) # for 24 hours

# Deadline for the batch rate limiter's input-file read. The read happens inline
# in POST /v1/batches, so it must resolve well within a client's read timeout;
# unbounded, the OpenAI SDK default (600s, max_retries=2) applies and a stalled
# Files API holds the request open indefinitely. Override with
# general_settings.batch_input_file_read_timeout.
DEFAULT_BATCH_INPUT_FILE_READ_TIMEOUT_SECONDS = 10.0

HEALTH_CHECK_TIMEOUT_SECONDS = int(os.getenv("HEALTH_CHECK_TIMEOUT_SECONDS", 60)) # 60 seconds
_background_health_check_max_tokens_env = os.getenv("BACKGROUND_HEALTH_CHECK_MAX_TOKENS")
try:
Expand Down
4 changes: 4 additions & 0 deletions litellm/proxy/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2417,6 +2417,10 @@ class ConfigGeneralSettings(LiteLLMPydanticObjectBase):
None,
description="By default, the user calling /team/new is automatically added to the new team as a team admin. If True, proxy admins are no longer auto-added; members explicitly listed in members_with_roles are unaffected. Default is False.",
)
batch_input_file_read_timeout: float | None = Field(
None,
description="Seconds the batch rate limiter may spend reading a batch input file to count tokens (default 10). The read runs inline in POST /v1/batches, so this must stay well inside client read timeouts. On timeout, keys whose model allowlist must be validated against the file are rejected; keys with unrestricted model access are admitted without rate limiting.",
)
maximum_spend_logs_retention_period: str | None = Field(
None,
description="Maximum retention period for spend logs (e.g., '7d' for 7 days). Logs older than this will be deleted.",
Expand Down
105 changes: 102 additions & 3 deletions litellm/proxy/hooks/batch_rate_limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
- async_log_success_event() fires on GET /v1/batches/{id} (batch completion)
"""

import asyncio
import json
from collections.abc import Iterable
from typing import (
Expand All @@ -32,6 +33,7 @@

import litellm
from litellm._logging import verbose_proxy_logger
from litellm.constants import DEFAULT_BATCH_INPUT_FILE_READ_TIMEOUT_SECONDS
from litellm.batches.batch_utils import (
_count_entry_tokens,
_estimate_batch_entry_tokens,
Expand Down Expand Up @@ -91,6 +93,24 @@ class BatchFileUsage(BaseModel):
request_count: int


class BatchInputFileReadTimeout(Exception):
"""The batch input-file read exceeded its deadline.

Distinct from a generic failure because the read serves two purposes and the
two have opposite safe defaults: it counts tokens for rate limiting (where
admitting the batch unmetered is tolerable) and it validates every
``body.model`` in the JSONL against the caller's allowlist (where admitting
the batch unchecked is a privilege escalation). Carrying its own type lets
``async_pre_call_hook`` fail closed only for keys that need the allowlist
check, instead of the blanket fail-open its generic handler applies.
"""

def __init__(self, file_id: str, timeout_seconds: float) -> None:
self.file_id = file_id
self.timeout_seconds = timeout_seconds
super().__init__(f"Timed out after {timeout_seconds}s reading batch input file {file_id}")


class _PROXY_BatchRateLimiter(CustomLogger):
"""
Rate limiter for batch API requests.
Expand Down Expand Up @@ -287,6 +307,28 @@ def _warn_if_unsupported_model_skip_configured(self, general_settings: dict) ->
"disable_batch_input_file_rate_limiting instead."
)

@staticmethod
def _batch_input_file_read_timeout() -> float:
"""Seconds the input-file read may take before it is abandoned.

Falls back to the default when the operator's value is missing or not a
positive number: a zero/negative deadline would make wait_for expire
immediately and reject every batch from a restricted key.
"""
from litellm.proxy.proxy_server import general_settings

configured = general_settings.get("batch_input_file_read_timeout")
if isinstance(configured, bool) or not isinstance(configured, (int, float)):
return DEFAULT_BATCH_INPUT_FILE_READ_TIMEOUT_SECONDS
if configured <= 0:
verbose_proxy_logger.warning(
"Ignoring general_settings.batch_input_file_read_timeout=%s: must be > 0. Using %ss.",
configured,
DEFAULT_BATCH_INPUT_FILE_READ_TIMEOUT_SECONDS,
)
return DEFAULT_BATCH_INPUT_FILE_READ_TIMEOUT_SECONDS
return float(configured)

@staticmethod
def _key_requires_batch_model_access_check(
user_api_key_dict: UserAPIKeyAuth,
Expand Down Expand Up @@ -513,8 +555,11 @@ async def count_input_file_usage(
# For managed files the unified file id encodes the proxy model
# alias(es) the file was uploaded for; auth validates against those.
target_model_names = get_models_from_unified_file_id(is_managed_file) if is_managed_file else []
# Resolved before the coroutine is built so a failure here can never
# leave an un-awaited coroutine behind.
timeout_seconds = self._batch_input_file_read_timeout()
if is_managed_file and user_api_key_dict is not None:
file_content = await self._fetch_managed_file_content(
fetch = self._fetch_managed_file_content(
file_id=file_id,
user_api_key_dict=user_api_key_dict,
)
Expand All @@ -524,13 +569,31 @@ async def count_input_file_usage(
custom_llm_provider=custom_llm_provider,
data=data or {},
)
# For non-managed files, use the standard litellm.afile_content
file_content = await litellm.afile_content(
# For non-managed files, use the standard litellm.afile_content.
# `timeout` reaches file_content's TIMEOUT LOGIC via
# GenericLiteLLMParams, capping the upstream HTTP request itself
# rather than only the await, so an abandoned read stops
# occupying its executor thread too.
fetch = litellm.afile_content(
file_id=provider_file_id,
user_api_key_dict=user_api_key_dict,
timeout=timeout_seconds,
**fetch_kwargs,
)

# Bound the read: it runs inline in POST /v1/batches, so unbounded the
# SDK default (600s x 3 attempts) outlives every client timeout and the
# request just hangs (LIT-5027).
#
# wait_for is what guarantees the handler stops waiting, and it is the
# only bound the managed-files path has (that hook takes no timeout
# argument), so an abandoned managed read may hold its executor thread
# until the SDK's own timeout fires.
try:
file_content = await asyncio.wait_for(fetch, timeout=timeout_seconds)
except asyncio.TimeoutError as exc:
raise BatchInputFileReadTimeout(file_id=file_id, timeout_seconds=timeout_seconds) from exc

file_content_bytes = getattr(file_content, "content", None)
if not isinstance(file_content_bytes, bytes):
raise ValueError(
Expand Down Expand Up @@ -599,6 +662,10 @@ async def count_input_file_usage(
"Batch input file rejected for %s: status=%s detail=%s", file_id, e.status_code, e.detail
)
raise
except BatchInputFileReadTimeout:
# The caller decides the policy (reject vs admit unmetered) and logs
# accordingly; a generic error line here would just duplicate it.
raise
except Exception as e:
verbose_proxy_logger.error("Error counting input file usage for %s: %s", file_id, e)
raise
Expand Down Expand Up @@ -845,6 +912,38 @@ async def async_pre_call_hook(
except HTTPException:
# Re-raise HTTP exceptions (rate limit exceeded)
raise
except BatchInputFileReadTimeout as e:
# The read is both the token count and the JSONL model-allowlist
# check, so the two cases diverge. A key restricted to a subset of
# models cannot be admitted without validating the file: doing so
# would grant exactly the bypass _should_skip_batch_input_file_processing
# refuses to allow via operator config. An unrestricted key has only
# rate-limit accuracy at stake, so it is admitted unmetered, matching
# the generic fail-open below.
if self._key_requires_batch_model_access_check(user_api_key_dict):
verbose_proxy_logger.error(
"Rejecting batch: could not read input file %s within %ss to validate "
"the models it references against the key's allowlist.",
e.file_id,
e.timeout_seconds,
)
raise ProxyException(
message=(
f"Could not read the batch input file within {e.timeout_seconds}s to "
"validate the models it references. Retry, or contact your proxy admin "
"if the files API is degraded."
),
type=ProxyErrorTypes.internal_server_error,
param="input_file_id",
code=504,
) from e
verbose_proxy_logger.warning(
"Batch admitted without rate limiting: reading input file %s timed out after %ss. "
"Its tokens and requests are not counted against this key's limits.",
e.file_id,
e.timeout_seconds,
)
return data
except Exception as e:
verbose_proxy_logger.error("Error in batch rate limiting: %s", e, exc_info=True)
# Don't block the request if rate limiting fails
Expand Down
5 changes: 4 additions & 1 deletion litellm/proxy/openai_files_endpoints/files_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
from litellm.router import Router
from litellm.types.llms.openai import (
CREATE_FILE_REQUESTS_PURPOSE,
AsyncCursorPage,
FileExpiresAfter,
OpenAIFileObject,
OpenAIFilesPurpose,
Expand Down Expand Up @@ -1397,7 +1398,9 @@ async def list_files(
_response = await proxy_logging_obj.post_call_success_hook(
data=data, user_api_key_dict=user_api_key_dict, response=response
)
if _response is not None and isinstance(_response, OpenAIFileObject):
if _response is not None and isinstance(
_response, (OpenAIFileObject, AsyncCursorPage)
):
response = _response

### ALERTING ###
Expand Down
2 changes: 0 additions & 2 deletions tests/e2e/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@ Every test under `tests/e2e/mcp/` must exercise the proxy against the real Datad
- Prefer calling real Datadog tools that prove the product path (e.g. `search_datadog_logs` for list/call and permission denials). Seed a unique marker (`e2e-datadog-mcp-*`) in a chat completion when you need a log the tool can find; dual-read with `dd_logs` from conftest when delivery matters
- Delete the MCP server (and any keys) through `resources.defer` the same way every other suite tears down
- If a new MCP behavior cannot be covered with Datadog's tool surface, say so in the PR and get agreement before inventing another upstream; the default is always Datadog
- The one standing exception is `test_mcp_chat_completion_oauth_e2e.py`. Datadog authenticates with the static `DD-API-KEY` / `DD-APPLICATION-KEY` headers and exposes no authorize/token dance at all, so it cannot exercise gateway-managed OAuth or per-user token seeding in any form. That test drives a real Linear MCP server instead; it is still a real remote upstream, so the no-mock, no-fixture rule above holds unchanged

## Lay the pattern down in a class

Keep the cases for one feature inside a class so the file reads as a spec for how that feature behaves in production. The class name says what is under test; each method is one behavior. Think of it as documenting the contract, with the rough intent being
Expand Down
Loading
Loading