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): restrict batch_enqueued_token_limit metadata writes to proxy admins

hiraku-miyoshi6b17b8a8f248
diff --git a/litellm/constants.py b/litellm/constants.py
index d7ddacf5fac..facfc6f7c19 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1772,6 +1772,11 @@ PTU_PRUNE_SKEW_GRACE_SECONDS: Final[int] = 300
# was never observed (e.g. proxy restart); expiry returns the tokens to the caller.
BATCH_ENQUEUED_TOKEN_TTL_SECONDS: Final[int] = 8 * 24 * 60 * 60
+# Key/team metadata field that opts batches into enqueued-token limiting. Only proxy
+# admins may write it: when present it replaces the standard RPM/TPM checks for
+# batch submissions.
+BATCH_ENQUEUED_TOKEN_LIMIT_METADATA_KEY: Final = "batch_enqueued_token_limit"
+
# Shared read-only empty mapping, for defaulting optional Mapping parameters without
# constructing a fresh mutable dict at each call site.
EMPTY_MAPPING: Final = MappingProxyType({})
diff --git a/litellm/proxy/auth/auth_utils.py b/litellm/proxy/auth/auth_utils.py
index a105bf19458..883f986f6fd 100644
--- a/litellm/proxy/auth/auth_utils.py
+++ b/litellm/proxy/auth/auth_utils.py
@@ -12,7 +12,12 @@ from pydantic import PositiveInt, TypeAdapter, ValidationError
import litellm
from litellm import Router, provider_list
from litellm._logging import verbose_proxy_logger
-from litellm.constants import MINIMUM_CUSTOM_KEY_LENGTH, STANDARD_CUSTOMER_ID_HEADERS
+from litellm.constants import (
+ BATCH_ENQUEUED_TOKEN_LIMIT_METADATA_KEY,
+ EMPTY_MAPPING,
+ MINIMUM_CUSTOM_KEY_LENGTH,
+ STANDARD_CUSTOMER_ID_HEADERS,
+)
from litellm.litellm_core_utils.safe_json_loads import safe_json_loads
from litellm.litellm_core_utils.url_utils import (
SSRFError,
@@ -1169,6 +1174,46 @@ def enforce_output_token_estimates_are_admin_only(
)
+class BatchEnqueuedTokenLimitRequest(Protocol):
+ """The shape of any management request that can carry a batch enqueued-token limit."""
+
+ @property
+ def metadata(self) -> Mapping[str, object] | None: ...
+
+ @property
+ def model_fields_set(self) -> Collection[str]: ...
+
+
+def enforce_batch_enqueued_token_limit_is_admin_only(
+ data: BatchEnqueuedTokenLimitRequest,
+ existing_metadata: Mapping[str, object] | None,
+ user_api_key_dict: UserAPIKeyAuth,
+ entity: Literal["key", "team"],
+) -> None:
+ """Only a proxy admin may change a key or team's batch enqueued-token limit.
+
+ When set, ``batch_enqueued_token_limit`` replaces the standard RPM/TPM checks
+ for batch submissions, so a holder-writable copy would let a caller lift their
+ own batch quota. Gated on the resulting value rather than on presence, so a
+ form resending the stored value stays a no-op.
+ """
+ if user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN.value:
+ return
+ stored: Final[Mapping[str, object]] = existing_metadata or EMPTY_MAPPING
+ requested: Final[Mapping[str, object]] = (
+ (data.metadata or EMPTY_MAPPING) if "metadata" in data.model_fields_set else stored
+ )
+ if requested.get(BATCH_ENQUEUED_TOKEN_LIMIT_METADATA_KEY) == stored.get(BATCH_ENQUEUED_TOKEN_LIMIT_METADATA_KEY):
+ return
+ raise HTTPException(
+ status_code=403,
+ detail={ # mutable-ok: HTTPException.detail has no immutable form
+ "error": f"Only proxy admins can set {BATCH_ENQUEUED_TOKEN_LIMIT_METADATA_KEY} on a {entity}. "
+ "It replaces the standard rate limit checks for batch submissions."
+ },
+ )
+
+
def get_model_rate_limit_from_metadata(
user_api_key_dict: UserAPIKeyAuth,
metadata_accessor_key: Literal["team_metadata", "organization_metadata", "project_metadata"],
diff --git a/litellm/proxy/hooks/batch_enqueued_tokens.py b/litellm/proxy/hooks/batch_enqueued_tokens.py
index 9d6a599af4a..54b0111682d 100644
--- a/litellm/proxy/hooks/batch_enqueued_tokens.py
+++ b/litellm/proxy/hooks/batch_enqueued_tokens.py
@@ -1,7 +1,7 @@
"""
Enqueued-token accounting for batch submissions.
-Opt-in via ``batch_enqueued_token_limit`` in key or team metadata: batch
+Opt-in via admin-set ``batch_enqueued_token_limit`` in key or team metadata: batch
submissions reserve their estimated token count against a long-lived
enqueued-token allowance instead of the per-minute rate-limit windows, and
the reservation is refunded when the batch reaches a terminal state
@@ -17,7 +17,7 @@ from typing import TYPE_CHECKING, Annotated, Final, Literal, Protocol, TypeAlias
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError
from litellm._logging import verbose_proxy_logger
-from litellm.constants import BATCH_ENQUEUED_TOKEN_TTL_SECONDS
+from litellm.constants import BATCH_ENQUEUED_TOKEN_LIMIT_METADATA_KEY, BATCH_ENQUEUED_TOKEN_TTL_SECONDS
from litellm.proxy._types import UserAPIKeyAuth
if TYPE_CHECKING:
@@ -28,8 +28,6 @@ if TYPE_CHECKING:
Span = _Span
InternalUsageCache = _InternalUsageCache
-BATCH_ENQUEUED_TOKEN_LIMIT_METADATA_KEY: Final = "batch_enqueued_token_limit"
-
BATCH_ENQUEUED_REFUND_STATUSES: Final[frozenset[str]] = frozenset(
{"completed", "complete", "failed", "expired", "cancelled", "cancelling"}
)
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index 67a836b8c92..ade568ad07f 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -57,6 +57,7 @@ from litellm.proxy.auth.auth_checks import (
)
from litellm.proxy.auth.auth_utils import (
abbreviate_api_key,
+ enforce_batch_enqueued_token_limit_is_admin_only,
enforce_output_token_estimates_are_admin_only,
)
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
@@ -901,6 +902,12 @@ async def _common_key_generation_helper(
user_api_key_dict=user_api_key_dict,
entity="key",
)
+ enforce_batch_enqueued_token_limit_is_admin_only(
+ data=data,
+ existing_metadata=None,
+ user_api_key_dict=user_api_key_dict,
+ entity="key",
+ )
if data.metadata is not None and data.metadata.get("service_account_id") is not None and data.team_id is None:
await validate_team_id_used_in_service_account_request(
@@ -2296,6 +2303,14 @@ async def _process_single_key_update(
prisma_client=prisma_client,
)
+ _existing_row_metadata: Final = getattr(existing_key_row, "metadata", None)
+ enforce_batch_enqueued_token_limit_is_admin_only(
+ data=update_key_request,
+ existing_metadata=_existing_row_metadata if isinstance(_existing_row_metadata, dict) else None,
+ user_api_key_dict=user_api_key_dict,
+ entity="key",
+ )
+
# Check team member permissions
if prisma_client is not None:
await TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint(
@@ -2558,6 +2573,12 @@ async def _validate_update_key_data(
user_api_key_dict=user_api_key_dict,
entity="key",
)
+ enforce_batch_enqueued_token_limit_is_admin_only(
+ data=data,
+ existing_metadata=_existing_metadata if isinstance(_existing_metadata, dict) else None,
+ user_api_key_dict=user_api_key_dict,
+ entity="key",
+ )
# Personal-key bypass: the caller both created the key AND still owns it
# (user_id == caller). Checking only created_by would let a demoted admin
@@ -4754,6 +4775,12 @@ async def _execute_virtual_key_regeneration(
user_api_key_dict=user_api_key_dict,
entity="key",
)
+ enforce_batch_enqueued_token_limit_is_admin_only(
+ data=data,
+ existing_metadata=_existing_key_metadata if isinstance(_existing_key_metadata, dict) else None,
+ user_api_key_dict=user_api_key_dict,
+ entity="key",
+ )
new_token: Final = await get_new_token(data=data)
new_token_hash: Final = hash_token(new_token)
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
index 95632d7cb35..31006958ba1 100644
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -85,7 +85,10 @@ from litellm.proxy.auth.auth_checks import (
get_team_object,
get_user_object,
)
-from litellm.proxy.auth.auth_utils import enforce_output_token_estimates_are_admin_only
+from litellm.proxy.auth.auth_utils import (
+ enforce_batch_enqueued_token_limit_is_admin_only,
+ enforce_output_token_estimates_are_admin_only,
+)
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.common_utils.callback_utils import encrypt_callback_vars
from litellm.proxy.common_utils.json_merge_patch import apply_json_merge_patch
@@ -1303,6 +1306,12 @@ async def new_team(
user_api_key_dict=user_api_key_dict,
entity="team",
)
+ enforce_batch_enqueued_token_limit_is_admin_only(
+ data=data,
+ existing_metadata=None,
+ user_api_key_dict=user_api_key_dict,
+ entity="team",
+ )
# Check if license is over limit
total_teams: Final = await _team_db(prisma_client).count()
@@ -2007,6 +2016,12 @@ async def update_team(
user_api_key_dict=user_api_key_dict,
entity="team",
)
+ enforce_batch_enqueued_token_limit_is_admin_only(
+ data=data,
+ existing_metadata=_existing_team_metadata if isinstance(_existing_team_metadata, dict) else None,
+ user_api_key_dict=user_api_key_dict,
+ entity="team",
+ )
_check_passthrough_routes_caller_permission(data, user_api_key_dict, entity="team")
diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
index bdf09a95e4b..93a4788caf8 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
@@ -15515,6 +15515,207 @@ async def test_regenerate_key_output_token_estimate_lowered_rejected_for_non_adm
assert "Only proxy admins can set" in str(exc.value.detail)
+_BATCH_LIMIT = "batch_enqueued_token_limit"
+
+
+ "label, request_body, existing_metadata, allowed",
+ [
+ ("set on a key with none stored", {"metadata": {_BATCH_LIMIT: 50000}}, None, False),
+ ("raised above the stored limit", {"metadata": {_BATCH_LIMIT: 200000}}, {_BATCH_LIMIT: 100000}, False),
+ ("cleared by replacing the blob", {"metadata": {}}, {_BATCH_LIMIT: 100000}, False),
+ ("resent unchanged", {"metadata": {_BATCH_LIMIT: 100000}}, {_BATCH_LIMIT: 100000}, True),
+ ("left untouched", {}, {_BATCH_LIMIT: 100000}, True),
+ ],
+)
+def test_batch_enqueued_token_limit_admin_gate_matrix(label, request_body, existing_metadata, allowed):
+ """A non-admin may only leave a key's stored batch enqueued-token limit as it is.
+
+ When set, the limit replaces the standard RPM/TPM checks for batch
+ submissions, so a key holder writing it would pick their own batch quota.
+ Resending the stored value is what the edit form produces on every save
+ and has to stay allowed.
+ """
+ from litellm.proxy.auth.auth_utils import (
+ enforce_batch_enqueued_token_limit_is_admin_only,
+ )
+
+ def _call(caller):
+ enforce_batch_enqueued_token_limit_is_admin_only(
+ data=UpdateKeyRequest(key="sk-1", **request_body),
+ existing_metadata=existing_metadata,
+ user_api_key_dict=caller,
+ entity="key",
+ )
+
+ non_admin = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-non-admin",
+ user_id="alice",
+ )
+ if allowed:
+ _call(non_admin)
+ else:
+ with pytest.raises(HTTPException) as exc:
+ _call(non_admin)
+ assert exc.value.status_code == 403
+ assert "Only proxy admins can set" in str(exc.value.detail)
+
+ _call(
+ UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-admin",
+ user_id="admin",
+ )
+ )
+
+
+async def test_generate_key_batch_enqueued_token_limit_rejected_for_non_admin():
+ """A non-admin self-minting a key with the limit would replace the standard
+ batch RPM/TPM checks with a cap of their own choosing."""
+ with patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()):
+ with pytest.raises(HTTPException) as exc:
+ await _common_key_generation_helper(
+ data=GenerateKeyRequest(metadata={_BATCH_LIMIT: 100000}, rpm_limit=2),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-alice",
+ user_id="alice",
+ ),
+ litellm_changed_by=None,
+ team_table=None,
+ )
+ assert int(getattr(exc.value, "status_code", 0)) == 403
+ assert "Only proxy admins can set" in str(exc.value.detail)
+
+
+async def test_update_key_batch_enqueued_token_limit_raised_rejected_for_non_admin(monkeypatch):
+ """/key/update is reachable by the key's own holder, so the gate has to
+ fire inside the update path itself rather than only at generation."""
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ update_key_fn,
+ )
+
+ token = "d1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
+ _wire_update_key_fn(monkeypatch, _estimate_key_row(token, {_BATCH_LIMIT: 100000}))
+
+ mock_request = MagicMock()
+ mock_request.query_params = {}
+
+ with pytest.raises(ProxyException) as exc:
+ await update_key_fn(
+ request=mock_request,
+ data=UpdateKeyRequest(key=token, metadata={_BATCH_LIMIT: 10**12}),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-internal",
+ user_id="internal_user",
+ ),
+ litellm_changed_by=None,
+ )
+
+ assert str(exc.value.code) == "403"
+ assert "Only proxy admins can set" in str(exc.value.message)
+
+
+async def test_update_key_batch_enqueued_token_limit_unchanged_allows_non_admin_edit(monkeypatch):
+ """The edit form resends every field it renders, so gating on presence
+ would 403 a key owner renaming a key that carries an admin-set limit."""
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ update_key_fn,
+ )
+
+ token = "e1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
+ _wire_update_key_fn(monkeypatch, _estimate_key_row(token, {_BATCH_LIMIT: 100000}))
+
+ mock_request = MagicMock()
+ mock_request.query_params = {}
+
+ result = await update_key_fn(
+ request=mock_request,
+ data=UpdateKeyRequest(key=token, key_alias="my-alias", metadata={_BATCH_LIMIT: 100000}),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-internal",
+ user_id="internal_user",
+ ),
+ litellm_changed_by=None,
+ )
+
+ assert result is not None
+
+
+async def test_regenerate_key_batch_enqueued_token_limit_rejected_for_non_admin():
+ """/key/regenerate runs the request body through prepare_key_update_data
+ exactly as an update does, so it is a third write path into the field."""
+ from litellm.proxy._types import RegenerateKeyRequest
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ _execute_virtual_key_regeneration,
+ )
+
+ token = "f1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
+ key_in_db = LiteLLM_VerificationToken(
+ token=token,
+ user_id="internal_user",
+ metadata={_BATCH_LIMIT: 100000},
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await _execute_virtual_key_regeneration(
+ prisma_client=AsyncMock(),
+ key_in_db=key_in_db,
+ hashed_api_key=token,
+ key="sk-original",
+ data=RegenerateKeyRequest(key="sk-original", metadata={_BATCH_LIMIT: 10**12}),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-internal",
+ user_id="internal_user",
+ ),
+ litellm_changed_by=None,
+ user_api_key_cache=MagicMock(),
+ proxy_logging_obj=MagicMock(),
+ )
+
+ assert exc.value.status_code == 403
+ assert "Only proxy admins can set" in str(exc.value.detail)
+
+
+async def test_bulk_key_update_batch_enqueued_token_limit_rejected_for_non_admin():
+ """Bulk team-key updates run through _process_single_key_update, not
+ /key/update's validator, so the gate must also live on that path."""
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ _process_single_key_update,
+ )
+
+ token = "a2b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
+ existing = _estimate_key_row(token, {_BATCH_LIMIT: 100000})
+
+ with pytest.raises(HTTPException) as exc:
+ await _process_single_key_update(
+ update_key_request=UpdateKeyRequest(key=token, metadata={_BATCH_LIMIT: 10**12}),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-internal",
+ user_id="internal_user",
+ ),
+ litellm_changed_by=None,
+ prisma_client=None,
+ user_api_key_cache=MagicMock(),
+ proxy_logging_obj=MagicMock(),
+ llm_router=None,
+ existing_key_row=existing,
+ )
+
+ assert exc.value.status_code == 403
+ assert "Only proxy admins can set" in str(exc.value.detail)
+
+
@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_stamps_settings_updated_at():
"""Regenerate rewrites the key's config, so it must move settings_updated_at."""
diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
index db39fcd3799..05072a0a6d7 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
@@ -11649,6 +11649,63 @@ async def test_new_team_output_token_estimate_rejected_for_non_admin():
assert "on a team" in str(exc.value.message)
+_TEAM_BATCH_LIMIT = "batch_enqueued_token_limit"
+
+
+async def test_update_team_batch_enqueued_token_limit_raised_rejected_for_team_admin():
+ """_verify_team_access admits a team admin, so the gate has to fire inside
+ update_team itself to keep the team's batch quota admin-owned."""
+ import contextlib
+ from unittest.mock import Mock
+
+ from fastapi import Request
+
+ from litellm.proxy._types import UpdateTeamRequest
+ from litellm.proxy.management_endpoints.team_endpoints import update_team
+
+ with contextlib.ExitStack() as stack:
+ _wire_update_team(stack, {_TEAM_BATCH_LIMIT: 100000})
+ with pytest.raises(ProxyException) as exc:
+ await update_team(
+ data=UpdateTeamRequest(team_id="test_team_id", metadata={_TEAM_BATCH_LIMIT: 10**12}),
+ http_request=Mock(spec=Request),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-team-admin",
+ user_id="team-admin",
+ ),
+ )
+
+ assert str(exc.value.code) == "403"
+ assert "on a team" in str(exc.value.message)
+
+
+async def test_new_team_batch_enqueued_token_limit_rejected_for_non_admin():
+ """/team/new is the other write path into the same stored metadata."""
+ from unittest.mock import Mock
+
+ from fastapi import Request
+
+ from litellm.proxy._types import NewTeamRequest
+ from litellm.proxy.management_endpoints.team_endpoints import new_team
+
+ with pytest.raises(ProxyException) as exc:
+ await new_team(
+ data=NewTeamRequest(team_alias="t", metadata={_TEAM_BATCH_LIMIT: 100000}),
+ http_request=Mock(spec=Request),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-alice",
+ user_id="alice",
+ ),
+ )
+
+ assert str(exc.value.code) == "403"
+ assert "on a team" in str(exc.value.message)
+
+
@pytest.mark.asyncio
async def test_get_team_daily_activity_aggregated_scopes_and_flags(mock_db_client):
"""The aggregated endpoint must apply the same non-admin key scoping as the