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]

test(proxy): phase-4 payload behavior pinning for tier-2/3 key + team management endpoints (#28681)

yuneng-jiang5e16f2096203
diff --git a/tests/proxy_behavior/management/conftest.py b/tests/proxy_behavior/management/conftest.py
index fa0bef86280..5b33ee6fd89 100644
--- a/tests/proxy_behavior/management/conftest.py
+++ b/tests/proxy_behavior/management/conftest.py
@@ -142,6 +142,10 @@ async def create_scratch_team(
member_user_ids: Optional[list] = None,
team_member_permissions: Optional[list] = None,
models: Optional[list] = None,
+ max_budget: Optional[float] = None,
+ tpm_limit: Optional[int] = None,
+ rpm_limit: Optional[int] = None,
+ metadata: Optional[dict] = None,
) -> str:
"""Raw-seed a scratch-tagged team row; returns its team_id.
@@ -155,6 +159,10 @@ async def create_scratch_team(
team_member_permissions / models seed the matching raw columns — needed
by the team-key-permission and team-model matrices.
+
+ max_budget / tpm_limit / rpm_limit / metadata seed the team's own limit
+ columns (Phase 4 F1+F3) — they live directly on LiteLLM_TeamTable, no
+ budget-table relation needed.
"""
admin_user_ids = list(admin_user_ids or [])
member_user_ids = list(member_user_ids or [])
@@ -174,10 +182,73 @@ async def create_scratch_team(
data["team_member_permissions"] = team_member_permissions
if models is not None:
data["models"] = models
+ if max_budget is not None:
+ data["max_budget"] = max_budget
+ if tpm_limit is not None:
+ data["tpm_limit"] = tpm_limit
+ if rpm_limit is not None:
+ data["rpm_limit"] = rpm_limit
+ if metadata is not None:
+ data["metadata"] = Json(metadata)
await prisma.db.litellm_teamtable.create(data=data)
return team_id
+async def create_scratch_org(
+ prisma,
+ scratch_prefix: str,
+ *,
+ max_budget: Optional[float] = None,
+ tpm_limit: Optional[int] = None,
+ rpm_limit: Optional[int] = None,
+ models: Optional[list] = None,
+ metadata: Optional[dict] = None,
+ suffix: str = "org",
+) -> str:
+ """Seed a scratch-tagged org + its own budget row; returns organization_id.
+
+ The org's `budget_id` points at a fresh `litellm_budgettable` row that
+ carries the per-org limits (`_check_org_key_limits` and the team budget
+ helpers read `org_table.litellm_budget_table.<limit>`, not columns on the
+ org row itself). Both rows share the scratch prefix so the teardown
+ reclaims them — budget by `budget_id` prefix (already swept), org by
+ `organization_id` prefix (added in this PR to the `scratch` fixture).
+
+ models / metadata seed the matching org columns; `_check_org_team_limits`
+ (F3) reads `org_table.models`, and the org metadata mirror of
+ model_rpm_limit / model_tpm_limit is what F1's model-specific org guard
+ consults.
+ """
+ org_id = f"{scratch_prefix}-{suffix}"
+ budget_id = f"{scratch_prefix}-{suffix}-budget"
+ budget_data: Dict[str, Any] = {
+ "budget_id": budget_id,
+ "created_by": "phase4-scratch",
+ "updated_by": "phase4-scratch",
+ }
+ if max_budget is not None:
+ budget_data["max_budget"] = max_budget
+ if tpm_limit is not None:
+ budget_data["tpm_limit"] = tpm_limit
+ if rpm_limit is not None:
+ budget_data["rpm_limit"] = rpm_limit
+ await prisma.db.litellm_budgettable.create(data=budget_data)
+
+ org_data: Dict[str, Any] = {
+ "organization_id": org_id,
+ "organization_alias": org_id,
+ "budget_id": budget_id,
+ "created_by": "phase4-scratch",
+ "updated_by": "phase4-scratch",
+ }
+ if models is not None:
+ org_data["models"] = models
+ if metadata is not None:
+ org_data["metadata"] = Json(metadata)
+ await prisma.db.litellm_organizationtable.create(data=org_data)
+ return org_id
+
+
@dataclass(frozen=True)
class SeededActor:
user_id: str
@@ -263,6 +334,15 @@ async def scratch(prisma):
await prisma.db.litellm_usertable.delete_many(
where={"user_id": {"startswith": handle.prefix}}
)
+ # F1+F3 seed scratch orgs via create_scratch_org; the world seeder is
+ # the only other writer of LiteLLM_OrganizationTable and uses the
+ # behavior-pin- prefix, so a scratch-prefixed sweep here cannot
+ # collide with the read-world. Org must be reclaimed BEFORE its
+ # budget — org.budget_id → budget.budget_id, so deleting the parent
+ # first would FK-violate on any still-attached scratch org.
+ await prisma.db.litellm_organizationtable.delete_many(
+ where={"organization_id": {"startswith": handle.prefix}}
+ )
await prisma.db.litellm_budgettable.delete_many(
where={"budget_id": {"startswith": handle.prefix}}
)
diff --git a/tests/proxy_behavior/management/test_f7_coverage_closeout.py b/tests/proxy_behavior/management/test_f7_coverage_closeout.py
new file mode 100644
index 00000000000..c78adbbb79d
--- /dev/null
+++ b/tests/proxy_behavior/management/test_f7_coverage_closeout.py
@@ -0,0 +1,346 @@
+"""Phase 4 F7 — coverage gap-closer scenarios picked from the un-covered
+ranges left after F1–F6 landed.
+
+Each scenario cites the file:line range it pins (PR4.M3 requirement).
+Scenarios that would only pad the count without pinning observable
+behavior are excluded — see `phase4-plan.md` §4-F7 anti-patterns.
+
+Ranges addressed here:
+ * team_endpoints.py 455–521 (_check_team_model_specific_limits body)
+ * team_endpoints.py 538–566 (_check_team_rpm_tpm_limits body)
+ * team_endpoints.py 696–731 (_check_org_team_limits guaranteed-throughput
+ branch — currently dead because the call
+ site doesn't include_budget_table=True,
+ but the inner `find_many` + helper-loop
+ runs regardless, covering the lines)
+ * key_management_endpoints.py 1147–1156 (_check_project_key_limits
+ project-not-found 404)
+ * key_management_endpoints.py 3007–3018 (validate_key_team_change
+ team-admin-accepts branch)
+"""
+
+import uuid
+from typing import Any, Dict, Optional
+
+import pytest
+from prisma import Json
+
+from litellm.proxy.utils import hash_token
+
+from .actors import TEAM_ALPHA, Actor
+from .conftest import create_scratch_org, create_scratch_team
+
+pytestmark = pytest.mark.asyncio(loop_scope="session")
+
+
+# ---------------------------------------------------------------------------
+# /team/new — guaranteed_throughput route into _check_org_team_limits's
+# throughput branch (lines 696–731), which then calls
+# check_org_team_model_specific_limits → _check_team_model_specific_limits
+# (lines 442–525). The org metadata supplies the per-model cap; sibling
+# teams are loaded from DB to drive the allocation sum.
+# ---------------------------------------------------------------------------
+
+
+async def test_org_team_guaranteed_throughput_model_over_bound_rejected(
+ proxy_client, prisma, scratch, world
+):
+ org_id = await create_scratch_org(
+ prisma,
+ scratch.prefix,
+ models=["gpt-4"],
+ metadata={"model_rpm_limit": {"gpt-4": 30}},
+ )
+ # A sibling team in the same org already burning 20 rpm on gpt-4 —
+ # forces _check_team_model_specific_limits's `model_specific_rpm_limit`
+ # accumulator to actually accumulate (covers lines 468–478).
+ await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("sibling"),
+ organization_id=org_id,
+ metadata={"model_rpm_limit": {"gpt-4": 20}},
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ team_id = scratch.tag("new")
+ body = {
+ "team_id": team_id,
+ "team_alias": team_id,
+ "organization_id": org_id,
+ "models": ["gpt-4"],
+ "model_rpm_limit": {"gpt-4": 100},
+ "rpm_limit_type": "guaranteed_throughput",
+ }
+ resp = await proxy_client.post(
+ "/team/new",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json=body,
+ )
+ # 20 (sibling) + 100 (new) > 30 (org cap) → guard fires.
+ assert resp.status_code == 400, resp.text
+ assert "RPM" in resp.text, resp.text
+ rows = await prisma.db.litellm_teamtable.find_many(where={"team_id": team_id})
+ assert rows == []
+
+
+async def test_org_team_guaranteed_throughput_model_tpm_over_bound_rejected(
+ proxy_client, prisma, scratch, world
+):
+ """Mirror of the rpm scenario but for the model_tpm side — pins
+ _check_team_model_specific_limits's tpm branch (lines 503–521) which
+ the rpm scenario doesn't exercise."""
+ org_id = await create_scratch_org(
+ prisma,
+ scratch.prefix,
+ models=["gpt-4"],
+ metadata={"model_tpm_limit": {"gpt-4": 500}},
+ )
+ await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("sibling"),
+ organization_id=org_id,
+ metadata={"model_tpm_limit": {"gpt-4": 200}},
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ team_id = scratch.tag("new")
+ body = {
+ "team_id": team_id,
+ "team_alias": team_id,
+ "organization_id": org_id,
+ "models": ["gpt-4"],
+ "model_tpm_limit": {"gpt-4": 5000},
+ "tpm_limit_type": "guaranteed_throughput",
+ }
+ resp = await proxy_client.post(
+ "/team/new",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json=body,
+ )
+ assert resp.status_code == 400, resp.text
+ assert "TPM" in resp.text, resp.text
+ rows = await prisma.db.litellm_teamtable.find_many(where={"team_id": team_id})
+ assert rows == []
+
+
+async def test_org_team_guaranteed_throughput_aggregate_runs(
+ proxy_client, prisma, scratch, world
+):
+ """Aggregate guard's no-op path (line 549-566 — entity_rpm_limit is None
+ because include_budget_table=False at the call site). The helper still
+ executes its `allocated_tpm = sum(...)` and `allocated_rpm = sum(...)`
+ lines, which is the coverage target."""
+ org_id = await create_scratch_org(prisma, scratch.prefix, models=["m"])
+ await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("sibling"),
+ organization_id=org_id,
+ tpm_limit=100,
+ rpm_limit=10,
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ team_id = scratch.tag("new")
+ body = {
+ "team_id": team_id,
+ "team_alias": team_id,
+ "organization_id": org_id,
+ "models": ["m"],
+ "tpm_limit": 50,
+ "rpm_limit": 5,
+ "tpm_limit_type": "guaranteed_throughput",
+ }
+ resp = await proxy_client.post(
+ "/team/new",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json=body,
+ )
+ # No org budget table loaded → check is no-op → 200.
+ assert resp.status_code == 200, resp.text
+
+
+# ---------------------------------------------------------------------------
+# /key/generate — _check_project_key_limits project-not-found branch
+# (lines 1147–1156). Hitting it requires a project_id that doesn't resolve;
+# get_project_object returns None, the handler raises 404.
+# ---------------------------------------------------------------------------
+
+
+async def test_key_generate_with_unknown_project_id_rejected(
+ proxy_client, prisma, scratch, world
+):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ body = {
+ "key_alias": scratch.prefix,
+ "project_id": f"{scratch.prefix}-ghost-project",
+ }
+ resp = await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json=body,
+ )
+ # The unknown-project guard inside _check_project_key_limits raises 404.
+ # The route's exception handler may wrap it; pin both shapes.
+ assert resp.status_code in (400, 404), resp.text
+ assert "project" in resp.text.lower() or "not found" in resp.text.lower(), resp.text
+ rows = await prisma.db.litellm_verificationtoken.find_many(
+ where={"key_alias": scratch.prefix}
+ )
+ assert rows == [], "rejected key leaked a row"
+
+
+# ---------------------------------------------------------------------------
+# /key/update — validate_key_team_change team-admin-accepts branch
+# (line 3011). PROXY_ADMIN covers line 3006; a non-admin team admin of the
+# target team covers 3007–3011. Owner stays a member of the destination
+# team to clear the membership guard first.
+# ---------------------------------------------------------------------------
+
+
+async def _seed_key_for_relocation(
+ prisma, scratch_prefix: str, *, user_id: str, team_id: str
+) -> str:
+ cleartext = "sk-" + uuid.uuid4().hex
+ await prisma.db.litellm_verificationtoken.create(
+ data={
+ "token": hash_token(cleartext),
+ "key_alias": f"{scratch_prefix}-key",
+ "key_name": f"{scratch_prefix}-key",
+ "user_id": user_id,
+ "team_id": team_id,
+ "models": [],
+ }
+ )
+ return cleartext
+
+
+async def test_team_new_with_team_member_budget_creates_budget_row(
+ proxy_client, prisma, scratch, world
+):
+ """/team/new with `team_member_budget` routes through
+ TeamMemberBudgetHandler.create_team_member_budget_table (lines 196–248).
+ Observable end-state: a litellm_budgettable row is created and the
+ team's metadata.team_member_budget_id points at it."""
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ team_id = scratch.tag("team-with-mbudget")
+ resp = await proxy_client.post(
+ "/team/new",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_id": team_id,
+ "team_alias": scratch.tag("alias"),
+ "team_member_budget": 10.0,
+ "team_member_rpm_limit": 100,
+ "team_member_tpm_limit": 1000,
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ team_row = await prisma.db.litellm_teamtable.find_unique(where={"team_id": team_id})
+ assert team_row is not None
+ budget_id = (team_row.metadata or {}).get("team_member_budget_id")
+ assert (
+ budget_id is not None
+ ), f"team_member_budget_id not stamped on team metadata: {team_row.metadata!r}"
+
+ # The handler writes the per-member budget row under a non-scratch id
+ # pattern (`team-<alias>-budget-<uuid>`), so the prefix sweep can't
+ # reclaim it. Cleanup must run even when a downstream assertion fires;
+ # otherwise orphan rows accumulate across CI re-runs.
+ try:
+ budget_row = await prisma.db.litellm_budgettable.find_unique(
+ where={"budget_id": budget_id}
+ )
+ assert budget_row is not None, "team_member_budget row was not created"
+ assert budget_row.max_budget == 10.0
+ assert budget_row.rpm_limit == 100
+ assert budget_row.tpm_limit == 1000
+ finally:
+ await prisma.db.litellm_teamtable.update(
+ where={"team_id": team_id},
+ data={"metadata": Json({})},
+ )
+ await prisma.db.litellm_budgettable.delete(where={"budget_id": budget_id})
+
+
+async def test_team_update_team_member_budget_upserts(
+ proxy_client, prisma, scratch, world
+):
+ """/team/update with `team_member_budget` against a team that has no
+ pre-existing team_member_budget_id routes through
+ TeamMemberBudgetHandler.upsert_team_member_budget_table's else-branch
+ (lines 294–303), which in turn calls create_team_member_budget_table."""
+ team_id = await create_scratch_team(prisma, team_id=scratch.tag("team"))
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_id": team_id,
+ "team_member_budget": 5.0,
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ team_row = await prisma.db.litellm_teamtable.find_unique(where={"team_id": team_id})
+ assert team_row is not None
+ budget_id = (team_row.metadata or {}).get("team_member_budget_id")
+ assert budget_id is not None, "team_member_budget_id not upserted"
+
+ # See comment on the sibling test — non-prefixed budget row, cleanup
+ # must survive an assertion failure to avoid orphan accumulation.
+ try:
+ # (No further assertions today, but the try/finally keeps the
+ # cleanup contract uniform with the sibling test and is robust to
+ # future asserts being added here.)
+ pass
+ finally:
+ await prisma.db.litellm_teamtable.update(
+ where={"team_id": team_id},
+ data={"metadata": Json({})},
+ )
+ await prisma.db.litellm_budgettable.delete(where={"budget_id": budget_id})
+
+
+async def test_key_team_change_accepted_by_target_team_admin(
+ proxy_client, prisma, scratch, world
+):
+ """Caller is admin of the destination team AND the key's owner — the
+ common_key_access_checks gate requires user_id-match for non-proxy-admin
+ callers, so the team-admin-accepts branch of validate_key_team_change
+ can only be reached when the team admin is also the key holder.
+ Hits validate_key_team_change line 3007–3011."""
+ actor_user_id = f"{scratch.prefix}-self-admin"
+ actor_cleartext = "sk-" + uuid.uuid4().hex
+ await prisma.db.litellm_usertable.create(
+ data={"user_id": actor_user_id, "user_role": "internal_user"}
+ )
+ await prisma.db.litellm_verificationtoken.create(
+ data={
+ "token": hash_token(actor_cleartext),
+ "key_alias": f"{scratch.prefix}-actor-key",
+ "key_name": f"{scratch.prefix}-actor-key",
+ "user_id": actor_user_id,
+ "models": [],
+ "allowed_routes": ["/key/update"],
+ }
+ )
+ source_team = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("source"),
+ admin_user_ids=[actor_user_id],
+ )
+ target_team = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("target"),
+ admin_user_ids=[actor_user_id],
+ )
+ key_cleartext = await _seed_key_for_relocation(
+ prisma, scratch.prefix, user_id=actor_user_id, team_id=source_team
+ )
+ resp = await proxy_client.post(
+ "/key/update",
+ headers={"Authorization": f"Bearer {actor_cleartext}"},
+ json={"key": key_cleartext, "team_id": target_team},
+ )
+ assert resp.status_code == 200, resp.text
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(key_cleartext)}
+ )
+ assert row is not None
+ assert row.team_id == target_team, "key did not move under team-admin initiator"
diff --git a/tests/proxy_behavior/management/test_f7_key_coverage_push.py b/tests/proxy_behavior/management/test_f7_key_coverage_push.py
new file mode 100644
index 00000000000..1bf3d1d394e
--- /dev/null
+++ b/tests/proxy_behavior/management/test_f7_key_coverage_push.py
@@ -0,0 +1,916 @@
+"""Phase 4 F7-extension — additional payload pins pushing
+`key_management_endpoints.py` past the 70 % stretch.
+
+Same pattern as `test_f7_coverage_closeout.py`: each scenario cites the
+file:line range it pins and asserts observable end-state, not response-body
+snapshots. Targets the largest non-deferred un-covered ranges left after
+the first F7 pass:
+
+ * 5942–6063 /key/health logging-metadata path (test_key_logging body)
+ * 4630–4692 /key/reset_spend happy path + 404 + admin gate
+ * 4565–4596 _validate_reset_spend_value branches
+ * 4421–4476 /key/regenerate ghost-key 404 + premium gate
+ * 6118–6133 _enforce_unique_key_alias duplicate-alias rejection
+ * 6148–6169 validate_model_max_budget malformed payload rejection
+ * 4708–4789 validate_key_list_check user/team/org/key_hash branches
+
+Excluded: `_rotate_master_key` (lines 3997–4123) — deferred per plan §6.
+"""
+
+import uuid
+from typing import Any, Dict, Optional
+
+import pytest
+from prisma import Json
+
+from litellm.proxy.utils import hash_token
+
+from .actors import TEAM_ALPHA, TEAM_BETA, Actor
+from .conftest import create_scratch_team
+
+pytestmark = pytest.mark.asyncio(loop_scope="session")
+
+
+async def _seed_token(
+ prisma,
+ scratch_prefix: str,
+ *,
+ suffix: str = "tok",
+ user_id: str,
+ spend: float = 0.0,
+ max_budget: Optional[float] = None,
+ metadata: Optional[dict] = None,
+ team_id: Optional[str] = None,
+) -> str:
+ cleartext = "sk-" + uuid.uuid4().hex
+ data: Dict[str, Any] = {
+ "token": hash_token(cleartext),
+ "key_alias": f"{scratch_prefix}-{suffix}",
+ "key_name": f"{scratch_prefix}-{suffix}",
+ "user_id": user_id,
+ "models": [],
+ "spend": spend,
+ }
+ if max_budget is not None:
+ data["max_budget"] = max_budget
+ if metadata is not None:
+ data["metadata"] = Json(metadata)
+ if team_id is not None:
+ data["team_id"] = team_id
+ await prisma.db.litellm_verificationtoken.create(data=data)
+ return cleartext
+
+
+# ---------------------------------------------------------------------------
+# /key/health — `metadata.logging` flips the handler into test_key_logging,
+# which lives at lines 5990–6067. The healthy-no-logging path is already
+# covered by the existing test_key_health.py; this adds the logging-set
+# path. The mock_response inside test_key_logging means no real LLM call
+# fires — only the callback-name validation and the post-call sweep.
+# ---------------------------------------------------------------------------
+
+
+async def test_key_health_with_logging_metadata_runs_test_logging(
+ proxy_client, prisma, scratch, world
+):
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ metadata={
+ "logging": [
+ {"callback_name": "noop-scratch-callback"},
+ ]
+ },
+ )
+ resp = await proxy_client.post(
+ "/key/health",
+ headers={"Authorization": f"Bearer {cleartext}"},
+ )
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ # Either healthy or unhealthy — both pin the logging branch.
+ assert body["key"] in ("healthy", "unhealthy")
+ assert "logging_callbacks" in body
+ assert body["logging_callbacks"]["callbacks"] == ["noop-scratch-callback"]
+
+
+async def test_key_health_with_missing_callback_name_rejected(
+ proxy_client, prisma, scratch, world
+):
+ """test_key_logging raises ValueError if a callback dict lacks
+ callback_name — wrapped by the outer try/except into a 500."""
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ metadata={"logging": [{"not_callback_name": "x"}]},
+ )
+ resp = await proxy_client.post(
+ "/key/health",
+ headers={"Authorization": f"Bearer {cleartext}"},
+ )
+ # The outer handler currently wraps the inner ValueError as a 500;
+ # accept any rejection envelope so a future 400/422 conversion doesn't
+ # trip this test. The named-guard substring is the real pin.
+ assert resp.status_code in (400, 422, 500), resp.text
+ assert "callback_name" in resp.text
+
+
+# ---------------------------------------------------------------------------
+# /key/reset_spend — 404 + happy path + non-admin reject. Pins
+# _validate_reset_spend_value (lines 4565–4596) and
+# _check_proxy_or_team_admin_for_key (lines 4536–4562).
+# ---------------------------------------------------------------------------
+
+
+async def test_reset_spend_ghost_key_404(proxy_client, scratch, world):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ f"/key/sk-{scratch.prefix}-ghost/reset_spend",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"reset_to": 0.0},
+ )
+ assert resp.status_code == 404, resp.text
+
+
+async def test_reset_spend_happy_path(proxy_client, prisma, scratch, world):
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ spend=5.0,
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ f"/key/{cleartext}/reset_spend",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"reset_to": 1.0},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["spend"] == 1.0
+ assert resp.json()["previous_spend"] == 5.0
+
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(cleartext)}
+ )
+ assert row is not None
+ assert row.spend == 1.0
+
+
+# Pydantic catches non-float at the request layer (422), so the inner
+# `isinstance(reset_to, (int, float))` guard at line 4568 is unreachable
+# from the HTTP boundary. Only the negative + above-current-spend branches
+# fire as the handler's own 400.
+ "reset_to,expected_detail",
+ [
+ (-1.0, "must be >= 0"),
+ (100.0, "must be <= current spend"), # current spend = 5.0
+ ],
+ ids=["negative", "above_current_spend"],
+)
+async def test_reset_spend_validate_value_branches(
+ reset_to, expected_detail: str, proxy_client, prisma, scratch, world
+):
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ spend=5.0,
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ f"/key/{cleartext}/reset_spend",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"reset_to": reset_to},
+ )
+ assert resp.status_code == 400, resp.text
+ assert expected_detail in resp.text, resp.text
+ # Row spend must be unchanged.
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(cleartext)}
+ )
+ assert row.spend == 5.0, "spend mutated despite validation rejection"
+
+
+async def test_reset_spend_non_numeric_caught_by_pydantic(
+ proxy_client, prisma, scratch, world
+):
+ """Pin: non-float reset_to is rejected at the Pydantic layer with 422
+ before reaching _validate_reset_spend_value. This documents that the
+ helper's `isinstance(reset_to, (int, float))` guard at line 4568 is
+ structurally unreachable via HTTP."""
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ spend=5.0,
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ f"/key/{cleartext}/reset_spend",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"reset_to": "not-a-number"},
+ )
+ assert resp.status_code == 422, resp.text
+
+
+async def test_reset_spend_non_admin_caller_rejected(
+ proxy_client, prisma, scratch, world
+):
+ """_check_proxy_or_team_admin_for_key raises 403 when caller is neither
+ proxy admin nor admin of the key's team."""
+ # Seed a key against TEAM_BETA (no actor in our world is admin of beta).
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.CROSS_ORG_USER].user_id,
+ spend=5.0,
+ team_id=TEAM_BETA,
+ )
+ # Caller is a member of TEAM_ALPHA but not admin of TEAM_BETA.
+ initiator = world.keys[Actor.INTERNAL_USER].cleartext
+ resp = await proxy_client.post(
+ f"/key/{cleartext}/reset_spend",
+ headers={"Authorization": f"Bearer {initiator}"},
+ json={"reset_to": 1.0},
+ )
+ # Route-level admin gate may fire first (401) or the helper's own 403 —
+ # both prove the path is guarded; pin either as rejection.
+ assert resp.status_code in (401, 403), resp.text
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(cleartext)}
+ )
+ assert row.spend == 5.0, "spend mutated despite rejection"
+
+
+# ---------------------------------------------------------------------------
+# /key/regenerate — ghost key 404 + happy path + new_key override. Pins
+# the route handler body lines 4382–4533 and _execute_virtual_key_regeneration
+# entry-point lines around 4220–4240.
+# ---------------------------------------------------------------------------
+
+
+async def test_regenerate_ghost_key_404(proxy_client, scratch, world):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ f"/key/sk-{scratch.prefix}-ghost/regenerate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={},
+ )
+ assert resp.status_code == 404, resp.text
+
+
+async def test_regenerate_no_key_supplied_400(proxy_client, world):
+ """POST /key/regenerate with no key in path AND no key in body."""
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/key/regenerate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={},
+ )
+ assert resp.status_code == 400, resp.text
+ assert "No key passed in" in resp.text or "key" in resp.text.lower()
+
+
+async def test_regenerate_happy_path(proxy_client, prisma, scratch, world):
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ )
+ old_hash = hash_token(cleartext)
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ f"/key/{cleartext}/regenerate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={},
+ )
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["key"].startswith("sk-")
+ new_hash = hash_token(body["key"])
+ assert new_hash != old_hash
+
+ # Old token should no longer be in active tokens (deleted by regenerate).
+ old_row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": old_hash}
+ )
+ assert old_row is None, "old token still present after regenerate"
+
+ # New token should be active.
+ new_row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": new_hash}
+ )
+ assert new_row is not None, "new token not written after regenerate"
+
+
+async def test_regenerate_with_explicit_new_key(proxy_client, prisma, scratch, world):
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ suffix="explicit",
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ new_key = "sk-" + uuid.uuid4().hex
+ resp = await proxy_client.post(
+ f"/key/{cleartext}/regenerate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"new_key": new_key},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["key"] == new_key
+ new_row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(new_key)}
+ )
+ assert new_row is not None
+
+
+# ---------------------------------------------------------------------------
+# /key/generate duplicate-alias rejection — pins _enforce_unique_key_alias
+# (lines 6118–6133). Two keys cannot share an alias.
+# ---------------------------------------------------------------------------
+
+
+async def test_generate_duplicate_alias_rejected(proxy_client, prisma, scratch, world):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ alias = scratch.prefix + "-shared-alias"
+ first = await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"key_alias": alias},
+ )
+ assert first.status_code == 200, first.text
+ second = await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"key_alias": alias},
+ )
+ assert second.status_code == 400, second.text
+ assert "already exists" in second.text, second.text
+
+
+# ---------------------------------------------------------------------------
+# /key/generate with malformed model_max_budget → 400 from
+# validate_model_max_budget (lines 6148–6169).
+# ---------------------------------------------------------------------------
+
+
+async def test_generate_with_invalid_model_max_budget_rejected(
+ proxy_client, scratch, world
+):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "key_alias": scratch.prefix,
+ # Wrong shape — budget_limit should be numeric; passing a dict
+ # for the model value bypasses the BudgetConfig parse and trips
+ # the validator's exception wrap.
+ "model_max_budget": {"gpt-4": {"budget_limit": "not-a-number"}},
+ },
+ )
+ # validate_model_max_budget raises ValueError, which the outer handler
+ # currently wraps as a 500. Pin only the named-guard substring; accept
+ # 400/422/500 so a future error-envelope improvement doesn't trip this.
+ assert resp.status_code in (400, 422, 500), resp.text
+ assert "Invalid model_max_budget" in resp.text, resp.text
+
+
+# ---------------------------------------------------------------------------
+# /key/list — pins validate_key_list_check (lines 4695–4790). The handler
+# already runs via Phase 1–3's test_key_list.py for the PROXY_ADMIN bypass;
+# this adds the non-admin user_id-mismatch + team_id-mismatch +
+# organization_id-mismatch branches.
+# ---------------------------------------------------------------------------
+
+
+ "filter_kwarg,expected_substring",
+ [
+ ({"user_id": "behavior-pin-proxy_admin"}, "check another user"),
+ ({"team_id": "behavior-pin-team-beta"}, "check this team"),
+ (
+ {"organization_id": "behavior-pin-org-b"},
+ "check this organization",
+ ),
+ ],
+ ids=["user_mismatch", "team_mismatch", "org_mismatch"],
+)
+async def test_key_list_non_admin_authz_branches(
+ filter_kwarg, expected_substring: str, proxy_client, world
+):
+ """Non-admin caller hits validate_key_list_check's three rejection
+ branches. INTERNAL_USER (Org A, TEAM_ALPHA member) is the caller; each
+ filter targets a foreign user/team/org and trips the matching guard."""
+ caller = world.keys[Actor.INTERNAL_USER].cleartext
+ qs = "&".join(f"{k}={v}" for k, v in filter_kwarg.items())
+ resp = await proxy_client.get(
+ f"/key/list?{qs}",
+ headers={"Authorization": f"Bearer {caller}"},
+ )
+ assert resp.status_code == 403, resp.text
+ assert expected_substring in resp.text, resp.text
+
+
+# ---------------------------------------------------------------------------
+# /key/bulk_update — pins the whole admin-only handler body (lines 2622–2733)
+# including the per-key try/except branch (2688–2727) via a mixed batch
+# of one existing key + one ghost.
+# ---------------------------------------------------------------------------
+
+
+async def test_key_bulk_update_mixed_success_and_failure(
+ proxy_client, prisma, scratch, world
+):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ existing = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ suffix="bulk1",
+ )
+ resp = await proxy_client.post(
+ "/key/bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "keys": [
+ {"key": existing, "max_budget": 5.0},
+ {"key": "sk-ghost-" + scratch.prefix, "max_budget": 5.0},
+ ]
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["total_requested"] == 2
+ assert len(body["successful_updates"]) == 1
+ assert len(body["failed_updates"]) == 1
+ # Re-read confirms the successful key was actually updated.
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(existing)}
+ )
+ assert row.max_budget == 5.0
+
+
+async def test_key_bulk_update_non_admin_rejected(proxy_client, world):
+ """Lines 2631–2635 — admin-only role gate."""
+ caller = world.keys[Actor.INTERNAL_USER].cleartext
+ resp = await proxy_client.post(
+ "/key/bulk_update",
+ headers={"Authorization": f"Bearer {caller}"},
+ json={"keys": [{"key": "sk-x", "max_budget": 1.0}]},
+ )
+ assert resp.status_code in (401, 403), resp.text
+
+
+async def test_key_bulk_update_empty_keys_rejected(proxy_client, world):
+ """Line 2643–2647 — empty keys list rejected."""
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/key/bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"keys": []},
+ )
+ assert resp.status_code == 400, resp.text
+ assert "No keys" in resp.text
+
+
+async def test_key_bulk_update_exceeds_max_batch_rejected(proxy_client, world):
+ """Lines 2649–2656 — over-batch-size rejection. 501 ghost keys are fine
+ here because validation fires before any update runs."""
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ over_batch = [{"key": f"sk-{i}", "max_budget": 1.0} for i in range(501)]
+ resp = await proxy_client.post(
+ "/key/bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"keys": over_batch},
+ )
+ assert resp.status_code == 400, resp.text
+ assert "500" in resp.text or "Maximum" in resp.text
+
+
+# ---------------------------------------------------------------------------
+# /key/update with extended fields — pins prepare_key_update_data
+# branches: duration (1794–1802), budget_duration (1804–1815),
+# model_max_budget validation (1838–1840), and the reserved-metadata
+# immutability check (1718–1731).
+# ---------------------------------------------------------------------------
+
+
+async def test_key_update_with_duration_and_budget_duration(
+ proxy_client, prisma, scratch, world
+):
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/key/update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "key": cleartext,
+ "duration": "1h",
+ "budget_duration": "30d",
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(cleartext)}
+ )
+ assert row.expires is not None, "expires not stamped from duration"
+ assert row.budget_reset_at is not None, "budget_reset_at not stamped"
+
+
+async def test_key_update_with_clear_duration(proxy_client, prisma, scratch, world):
+ """`duration: -1` clears expires (line 1796–1798)."""
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ # First set an expiry
+ await proxy_client.post(
+ "/key/update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"key": cleartext, "duration": "1h"},
+ )
+ # Then clear it
+ resp = await proxy_client.post(
+ "/key/update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"key": cleartext, "duration": "-1"},
+ )
+ assert resp.status_code == 200, resp.text
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(cleartext)}
+ )
+ assert row.expires is None, "expires not cleared by duration=-1"
+
+
+# ---------------------------------------------------------------------------
+# /team/key/bulk_update — pins handler body lines 2797–2950 including:
+# - missing team_id 400 (2803–2807)
+# - over-batch-size 400 (2810–2816)
+# - all_keys_in_team scan (2818–2841)
+# - explicit key_ids dedupe (2842–2863)
+# - non-admin permission gate (2866–2882)
+# - per-key loop with mixed success/404 (2902–2944)
+# ---------------------------------------------------------------------------
+
+
+async def test_team_key_bulk_update_missing_team_id_rejected(proxy_client, world):
+ """Pydantic catches missing team_id at the request layer → 422 before
+ the handler's own `if not data.team_id` guard at line 2803."""
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/key/bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"update_fields": {"max_budget": 5.0}},
+ )
+ assert resp.status_code == 422, resp.text
+
+
+async def test_team_key_bulk_update_no_selector_rejected(proxy_client, world):
+ """Pydantic root-validator catches missing key_ids/all_keys_in_team
+ at the request layer → 422."""
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/key/bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_id": TEAM_ALPHA,
+ "update_fields": {"max_budget": 5.0},
+ },
+ )
+ assert resp.status_code == 422, resp.text
+ assert "key_ids" in resp.text or "all_keys_in_team" in resp.text
+
+
+async def test_team_key_bulk_update_all_keys_in_team(
+ proxy_client, prisma, scratch, world
+):
+ """Pin the all_keys_in_team branch (lines 2818–2841) plus the
+ per-key success path. Seed two scratch keys against the scratch team."""
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ team_id = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("team"),
+ admin_user_ids=[world.keys[Actor.PROXY_ADMIN].user_id],
+ )
+ k1 = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ suffix="t1",
+ team_id=team_id,
+ )
+ k2 = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ suffix="t2",
+ team_id=team_id,
+ )
+ resp = await proxy_client.post(
+ "/team/key/bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_id": team_id,
+ "all_keys_in_team": True,
+ "update_fields": {"max_budget": 7.0},
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["total_requested"] == 2
+ # Re-read both keys; max_budget should be set.
+ for k in (k1, k2):
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(k)}
+ )
+ assert row.max_budget == 7.0
+
+
+async def test_team_key_bulk_update_explicit_key_ids_mixed(
+ proxy_client, prisma, scratch, world
+):
+ """Pin the explicit-key_ids dedupe + per-key 404 path (lines 2842–2944).
+ Send a real key + a ghost key under the same team_id."""
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ team_id = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("team"),
+ admin_user_ids=[world.keys[Actor.PROXY_ADMIN].user_id],
+ )
+ real_key = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ suffix="real",
+ team_id=team_id,
+ )
+ resp = await proxy_client.post(
+ "/team/key/bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_id": team_id,
+ "key_ids": [real_key, real_key, "sk-ghost-" + scratch.prefix],
+ "update_fields": {"max_budget": 9.0},
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ # Dedupe collapses the two real_key entries → 2 unique tokens.
+ assert body["total_requested"] == 2
+ assert len(body["successful_updates"]) == 1
+ assert len(body["failed_updates"]) == 1
+
+
+# ---------------------------------------------------------------------------
+# /key/aliases — pins the handler body lines 5108–5207. PROXY_ADMIN hits
+# the broad-scope path; a non-admin caller hits the scoped path through
+# _apply_non_admin_alias_scope.
+# ---------------------------------------------------------------------------
+
+
+# ---------------------------------------------------------------------------
+# /key/info — pins the handler body (lines 3253–3303). PROXY_ADMIN with an
+# explicit ghost key 404s; with a real key 200s. Phase 1–3 covered the
+# auth matrix; this adds the explicit-key path the matrix doesn't hit.
+# ---------------------------------------------------------------------------
+
+
+async def test_key_info_ghost_key_404(proxy_client, scratch, world):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.get(
+ f"/key/info?key=sk-{scratch.prefix}-ghost",
+ headers={"Authorization": f"Bearer {seeder}"},
+ )
+ assert resp.status_code == 404, resp.text
+
+
+async def test_key_info_explicit_existing_key(proxy_client, prisma, scratch, world):
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ suffix="info-test",
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.get(
+ f"/key/info?key={cleartext}",
+ headers={"Authorization": f"Bearer {seeder}"},
+ )
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["key"] == cleartext
+ assert "info" in body
+ # Token hash is stripped from the response (line 3296).
+ assert "token" not in body["info"]
+
+
+async def test_key_info_no_key_uses_auth_header(proxy_client, world):
+ """Pin line 3260: `key = key or user_api_key_dict.api_key` — caller's
+ own key info is returned when no `?key=` is supplied."""
+ caller = world.keys[Actor.INTERNAL_USER].cleartext
+ resp = await proxy_client.get(
+ "/key/info",
+ headers={"Authorization": f"Bearer {caller}"},
+ )
+ assert resp.status_code == 200, resp.text
+
+
+# ---------------------------------------------------------------------------
+# /key/generate with budget_limits — pins budget_limits initialization
+# inside generate_key_helper_fn (lines 3427–3436).
+# ---------------------------------------------------------------------------
+
+
+async def test_key_generate_with_budget_limits(proxy_client, prisma, scratch, world):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "key_alias": scratch.prefix,
+ "budget_limits": [
+ {"max_budget": 5.0, "budget_duration": "1d"},
+ {"max_budget": 20.0, "budget_duration": "30d"},
+ ],
+ },
+ )
+ assert resp.status_code == 200, resp.text
+
+
+async def test_key_aliases_proxy_admin_unscoped(proxy_client, prisma, scratch, world):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ alias = scratch.prefix + "-aliases-test"
+ await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"key_alias": alias},
+ )
+ resp = await proxy_client.get(
+ "/key/aliases?size=10",
+ headers={"Authorization": f"Bearer {seeder}"},
+ )
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert "aliases" in body
+ assert "total_count" in body
+ assert body["current_page"] == 1
+ assert body["size"] == 10
+ assert (
+ alias in body["aliases"]
+ ), f"newly created alias not in list: {body['aliases']}"
+
+
+async def test_key_aliases_with_search_filter(proxy_client, prisma, scratch, world):
+ """Pin the `search` ILIKE branch (lines 5166–5168)."""
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ unique_alias = scratch.prefix + "-search-unique-tag"
+ await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"key_alias": unique_alias},
+ )
+ resp = await proxy_client.get(
+ f"/key/aliases?search={scratch.prefix}-search",
+ headers={"Authorization": f"Bearer {seeder}"},
+ )
+ assert resp.status_code == 200, resp.text
+ assert unique_alias in resp.json()["aliases"]
+
+
+async def test_key_aliases_non_admin_scoped(proxy_client, world):
+ """Non-admin caller routes through _apply_non_admin_alias_scope (line
+ 5161–5164). The exact alias visibility depends on team membership; the
+ pin is that the call succeeds with a scoped result."""
+ caller = world.keys[Actor.INTERNAL_USER].cleartext
+ resp = await proxy_client.get(
+ "/key/aliases?size=10",
+ headers={"Authorization": f"Bearer {caller}"},
+ )
+ assert resp.status_code == 200, resp.text
+ assert "aliases" in resp.json()
+
+
+# ---------------------------------------------------------------------------
+# /key/list with extended filters — pins _build_filter_conditions branches
+# at lines 5280–5388. Each scenario varies one filter so a different
+# branch fires.
+# ---------------------------------------------------------------------------
+
+
+ "query",
+ [
+ "include_created_by_keys=true",
+ "include_team_keys=true",
+ "return_full_object=true",
+ "sort_by=created_at&sort_order=asc",
+ "key_alias=behavior",
+ ],
+ ids=["created_by", "team_keys", "full_object", "sort", "alias_substring"],
+)
+async def test_key_list_filter_branches(query: str, proxy_client, world):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.get(
+ f"/key/list?{query}",
+ headers={"Authorization": f"Bearer {seeder}"},
+ )
+ assert resp.status_code == 200, resp.text
+
+
+# ---------------------------------------------------------------------------
+# /key/regenerate with grace_period — pins _insert_deprecated_key body
+# (lines 4168–4202). The old token gets retained in
+# LiteLLM_DeprecatedVerificationToken; assert it lands there.
+# ---------------------------------------------------------------------------
+
+
+async def test_regenerate_with_grace_period_inserts_deprecated_row(
+ proxy_client, prisma, scratch, world
+):
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ suffix="grace",
+ )
+ old_hash = hash_token(cleartext)
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ f"/key/{cleartext}/regenerate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"grace_period": "1h"},
+ )
+ assert resp.status_code == 200, resp.text
+ new_key = resp.json()["key"]
+ # Old token should now be in the deprecated table.
+ deprecated_row = await prisma.db.litellm_deprecatedverificationtoken.find_unique(
+ where={"token": old_hash}
+ )
+ assert deprecated_row is not None, "old token not retained in deprecated table"
+ assert deprecated_row.active_token_id == hash_token(new_key)
+ assert deprecated_row.revoke_at is not None
+ # Manual cleanup — scratch prefix sweep doesn't cover this table.
+ await prisma.db.litellm_deprecatedverificationtoken.delete(
+ where={"token": old_hash}
+ )
+
+
+async def test_regenerate_with_invalid_grace_period_format(
+ proxy_client, prisma, scratch, world
+):
+ """Invalid grace_period format falls through silently (line 4170–4175);
+ regenerate still succeeds but no deprecated row is inserted."""
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.PROXY_ADMIN].user_id,
+ suffix="grace-bad",
+ )
+ old_hash = hash_token(cleartext)
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ f"/key/{cleartext}/regenerate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"grace_period": "totally-not-a-duration"},
+ )
+ assert resp.status_code == 200, resp.text
+ deprecated_row = await prisma.db.litellm_deprecatedverificationtoken.find_unique(
+ where={"token": old_hash}
+ )
+ assert deprecated_row is None, "deprecated row created despite invalid grace_period"
+
+
+async def test_key_list_key_hash_filter_unauthorized(
+ proxy_client, prisma, scratch, world
+):
+ """validate_key_list_check's key_hash branch (lines 4766–4789): a
+ cross-tenant non-admin caller asks for a key_hash they don't own → 403.
+
+ `user_belongs_to_keys_team` returns True for any team member, so a
+ same-team caller is allowed to query peer keys by hash (intentional
+ per the helper's policy). The 403 path requires a caller who is neither
+ the key owner, team member, nor admin — i.e. CROSS_ORG_USER.
+ """
+ cleartext = await _seed_token(
+ prisma,
+ scratch.prefix,
+ user_id=world.keys[Actor.OWNER].user_id,
+ team_id=TEAM_ALPHA,
+ )
+ caller = world.keys[Actor.CROSS_ORG_USER].cleartext
+ resp = await proxy_client.get(
+ f"/key/list?key_hash={hash_token(cleartext)}",
+ headers={"Authorization": f"Bearer {caller}"},
+ )
+ assert resp.status_code == 403, resp.text
diff --git a/tests/proxy_behavior/management/test_key_budget_limits.py b/tests/proxy_behavior/management/test_key_budget_limits.py
new file mode 100644
index 00000000000..f5066d60a34
--- /dev/null
+++ b/tests/proxy_behavior/management/test_key_budget_limits.py
@@ -0,0 +1,383 @@
+"""Phase 4 F1 — payload-level pins for key budget & rate-limit enforcement.
+
+Pins the five helpers
+ * _check_key_model_specific_limits (key_management_endpoints.py:931)
+ * _check_key_rpm_tpm_limits (key_management_endpoints.py:1016)
+ * _check_team_key_limits (key_management_endpoints.py:1096)
+ * _check_org_key_limits (key_management_endpoints.py:1284)
+ * _check_project_key_limits (key_management_endpoints.py:1135)
+
+Driven through /key/generate. PROXY_ADMIN is the caller so authz never
+short-circuits the payload check — Phase 1–3 already pinned authz cleanly.
+
+`guaranteed_throughput` on either tpm_limit_type or rpm_limit_type is the
+trigger that arms `_check_team_key_limits` / `_check_org_key_limits`; without
+it both helpers early-return before reading any limit. The project sub-family
+covers `_check_project_key_limits`, which has no such gate.
+
+Each scenario asserts BOTH:
+ - HTTP status, and
+ - the DB row state on re-read (created when accepted; absent when rejected).
+A response-body check is deliberately avoided per parent plan's anti-snapshot
+rule.
+"""
+
+from typing import Any, Dict
+
+import pytest
+
+from .actors import Actor
+from .conftest import create_scratch_org, create_scratch_team
+
+pytestmark = pytest.mark.asyncio(loop_scope="session")
+
+
+# ---------------------------------------------------------------------------
+# _check_team_key_limits — aggregate tpm/rpm guard
+# ---------------------------------------------------------------------------
+
+# (id, team_tpm, team_rpm, body_extras, expected_status, detail_substring)
+_TEAM_RATE_LIMIT_SCENARIOS = [
+ (
+ "aggregate/tpm_within_bound",
+ 1000,
+ None,
+ {"tpm_limit": 400, "tpm_limit_type": "guaranteed_throughput"},
+ 200,
+ None,
+ ),
+ (
+ "aggregate/tpm_over_bound",
+ 1000,
+ None,
+ {"tpm_limit": 2000, "tpm_limit_type": "guaranteed_throughput"},
+ 400,
+ "TPM limit",
+ ),
+ (
+ "aggregate/rpm_within_bound",
+ None,
+ 100,
+ {"rpm_limit": 40, "rpm_limit_type": "guaranteed_throughput"},
+ 200,
+ None,
+ ),
+ (
+ "aggregate/rpm_over_bound",
+ None,
+ 100,
+ {"rpm_limit": 250, "rpm_limit_type": "guaranteed_throughput"},
+ 400,
+ "RPM limit",
+ ),
+ (
+ "aggregate/no_guaranteed_throughput_skips_check",
+ None,
+ 10,
+ # No *_limit_type → helper early-returns even though rpm exceeds team's.
+ {"rpm_limit": 50},
+ 200,
+ None,
+ ),
+]
+
+
+ "team_tpm,team_rpm,body_extras,expected_status,detail_substring",
+ [(a, b, c, d, e) for (_id, a, b, c, d, e) in _TEAM_RATE_LIMIT_SCENARIOS],
+ ids=[s[0] for s in _TEAM_RATE_LIMIT_SCENARIOS],
+)
+async def test_check_team_key_limits_aggregate(
+ team_tpm,
+ team_rpm,
+ body_extras: Dict[str, Any],
+ expected_status: int,
+ detail_substring,
+ proxy_client,
+ prisma,
+ scratch,
+ world,
+):
+ team_id = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("team"),
+ tpm_limit=team_tpm,
+ rpm_limit=team_rpm,
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ body: Dict[str, Any] = {
+ "key_alias": scratch.prefix,
+ "team_id": team_id,
+ **body_extras,
+ }
+ resp = await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json=body,
+ )
+ assert (
+ resp.status_code == expected_status
+ ), f"{body!r} → {resp.status_code}: {resp.text}"
+ if detail_substring is not None:
+ assert detail_substring in resp.text, resp.text
+
+ rows = await prisma.db.litellm_verificationtoken.find_many(
+ where={"key_alias": scratch.prefix}
+ )
+ if expected_status == 200:
+ assert len(rows) == 1
+ else:
+ assert rows == [], "rejected key leaked a row"
+
+
+# ---------------------------------------------------------------------------
+# _check_team_key_limits — model-specific guard (via team metadata)
+# ---------------------------------------------------------------------------
+
+# Body shape: {"model_rpm_limit": {"gpt-4": <n>}, "rpm_limit_type": "guaranteed_throughput"}
+# Team metadata supplies the matching per-model cap.
+_TEAM_MODEL_LIMIT_SCENARIOS = [
+ (
+ "model_rpm/within_bound",
+ {"model_rpm_limit": {"gpt-4": 30}},
+ {"model_rpm_limit": {"gpt-4": 20}, "rpm_limit_type": "guaranteed_throughput"},
+ 200,
+ None,
+ ),
+ (
+ "model_rpm/over_bound",
+ {"model_rpm_limit": {"gpt-4": 30}},
+ {"model_rpm_limit": {"gpt-4": 100}, "rpm_limit_type": "guaranteed_throughput"},
+ 400,
+ "RPM",
+ ),
+ (
+ "model_tpm/within_bound",
+ {"model_tpm_limit": {"gpt-4": 500}},
+ {"model_tpm_limit": {"gpt-4": 200}, "tpm_limit_type": "guaranteed_throughput"},
+ 200,
+ None,
+ ),
+ (
+ "model_tpm/over_bound",
+ {"model_tpm_limit": {"gpt-4": 500}},
+ {"model_tpm_limit": {"gpt-4": 5000}, "tpm_limit_type": "guaranteed_throughput"},
+ 400,
+ "TPM",
+ ),
+]
+
+
+ "team_metadata,body_extras,expected_status,detail_substring",
+ [(b, c, d, e) for (_id, b, c, d, e) in _TEAM_MODEL_LIMIT_SCENARIOS],
+ ids=[s[0] for s in _TEAM_MODEL_LIMIT_SCENARIOS],
+)
+async def test_check_team_key_limits_model_specific(
+ team_metadata,
+ body_extras: Dict[str, Any],
+ expected_status: int,
+ detail_substring,
+ proxy_client,
+ prisma,
+ scratch,
+ world,
+):
+ team_id = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("team"),
+ metadata=team_metadata,
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ body: Dict[str, Any] = {
+ "key_alias": scratch.prefix,
+ "team_id": team_id,
+ **body_extras,
+ }
+ resp = await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json=body,
+ )
+ assert (
+ resp.status_code == expected_status
+ ), f"{body!r} → {resp.status_code}: {resp.text}"
+ if detail_substring is not None:
+ assert detail_substring in resp.text, resp.text
+ rows = await prisma.db.litellm_verificationtoken.find_many(
+ where={"key_alias": scratch.prefix}
+ )
+ assert len(rows) == (1 if expected_status == 200 else 0)
+
+
+# ---------------------------------------------------------------------------
+# _check_org_key_limits — aggregate tpm/rpm guard via budget table
+#
+# Behavior pin, not a regression target: /key/generate (line 889) and
+# /key/update (line 2310) both call `get_org_object` WITHOUT
+# `include_budget_table=True`, so `org_table.litellm_budget_table` is None
+# at guard time and the aggregate path silently no-ops. Over-bound payloads
+# therefore land as 200, not 400. Documenting that here so a future change
+# that flips include_budget_table=True or moves the guard pre-load would
+# turn these into reds — exactly the regression-tripwire shape Phase 4 wants.
+# The model-specific guard below DOES fire because it reads org metadata,
+# which is loaded directly on the org row (no relation include needed).
+# ---------------------------------------------------------------------------
+
+_ORG_RATE_LIMIT_SCENARIOS = [
+ (
+ "org/tpm_within_bound",
+ {"max_budget": None, "tpm_limit": 1000, "rpm_limit": None},
+ {"tpm_limit": 400, "tpm_limit_type": "guaranteed_throughput"},
+ 200,
+ None,
+ ),
+ (
+ "org/tpm_over_bound_unenforced_no_include_budget_table",
+ {"max_budget": None, "tpm_limit": 1000, "rpm_limit": None},
+ {"tpm_limit": 2000, "tpm_limit_type": "guaranteed_throughput"},
+ 200,
+ None,
+ ),
+ (
+ "org/rpm_within_bound",
+ {"max_budget": None, "tpm_limit": None, "rpm_limit": 100},
+ {"rpm_limit": 40, "rpm_limit_type": "guaranteed_throughput"},
+ 200,
+ None,
+ ),
+ (
+ "org/rpm_over_bound_unenforced_no_include_budget_table",
+ {"max_budget": None, "tpm_limit": None, "rpm_limit": 100},
+ {"rpm_limit": 250, "rpm_limit_type": "guaranteed_throughput"},
+ 200,
+ None,
+ ),
+ (
+ "org/no_guaranteed_throughput_skips_check",
+ {"max_budget": None, "tpm_limit": None, "rpm_limit": 10},
+ {"rpm_limit": 50},
+ 200,
+ None,
+ ),
+]
+
+
+ "org_budget,body_extras,expected_status,detail_substring",
+ [(b, c, d, e) for (_id, b, c, d, e) in _ORG_RATE_LIMIT_SCENARIOS],
+ ids=[s[0] for s in _ORG_RATE_LIMIT_SCENARIOS],
+)
+async def test_check_org_key_limits_aggregate(
+ org_budget: Dict[str, Any],
+ body_extras: Dict[str, Any],
+ expected_status: int,
+ detail_substring,
+ proxy_client,
+ prisma,
+ scratch,
+ world,
+):
+ org_id = await create_scratch_org(prisma, scratch.prefix, **org_budget)
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ body: Dict[str, Any] = {
+ "key_alias": scratch.prefix,
+ "organization_id": org_id,
+ **body_extras,
+ }
+ resp = await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json=body,
+ )
+ assert (
+ resp.status_code == expected_status
+ ), f"{body!r} → {resp.status_code}: {resp.text}"
+ if detail_substring is not None:
+ assert detail_substring in resp.text, resp.text
+ rows = await prisma.db.litellm_verificationtoken.find_many(
+ where={"key_alias": scratch.prefix}
+ )
+ assert len(rows) == (1 if expected_status == 200 else 0)
+
+
+# ---------------------------------------------------------------------------
+# _check_org_key_limits — model-specific guard via org metadata
+# ---------------------------------------------------------------------------
+
+_ORG_MODEL_LIMIT_SCENARIOS = [
+ (
+ "org_model_rpm/within_bound",
+ {"model_rpm_limit": {"gpt-4": 30}},
+ {"model_rpm_limit": {"gpt-4": 20}, "rpm_limit_type": "guaranteed_throughput"},
+ 200,
+ None,
+ ),
+ (
+ "org_model_rpm/over_bound",
+ {"model_rpm_limit": {"gpt-4": 30}},
+ {"model_rpm_limit": {"gpt-4": 100}, "rpm_limit_type": "guaranteed_throughput"},
+ 400,
+ "RPM",
+ ),
+ (
+ "org_model_tpm/within_bound",
+ {"model_tpm_limit": {"gpt-4": 500}},
+ {"model_tpm_limit": {"gpt-4": 200}, "tpm_limit_type": "guaranteed_throughput"},
+ 200,
+ None,
+ ),
+ (
+ "org_model_tpm/over_bound",
+ {"model_tpm_limit": {"gpt-4": 500}},
+ {"model_tpm_limit": {"gpt-4": 5000}, "tpm_limit_type": "guaranteed_throughput"},
+ 400,
+ "TPM",
+ ),
+]
+
+
+ "org_metadata,body_extras,expected_status,detail_substring",
+ [(b, c, d, e) for (_id, b, c, d, e) in _ORG_MODEL_LIMIT_SCENARIOS],
+ ids=[s[0] for s in _ORG_MODEL_LIMIT_SCENARIOS],
+)
+async def test_check_org_key_limits_model_specific(
+ org_metadata,
+ body_extras: Dict[str, Any],
+ expected_status: int,
+ detail_substring,
+ proxy_client,
+ prisma,
+ scratch,
+ world,
+):
+ org_id = await create_scratch_org(prisma, scratch.prefix, metadata=org_metadata)
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ body: Dict[str, Any] = {
+ "key_alias": scratch.prefix,
+ "organization_id": org_id,
+ **body_extras,
+ }
+ resp = await proxy_client.post(
+ "/key/generate",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json=body,
+ )
+ assert (
+ resp.status_code == expected_status
+ ), f"{body!r} → {resp.status_code}: {resp.text}"
+ if detail_substring is not None:
+ assert detail_substring in resp.text, resp.text
+ rows = await prisma.db.litellm_verificationtoken.find_many(
+ where={"key_alias": scratch.prefix}
+ )
+ assert len(rows) == (1 if expected_status == 200 else 0)
+
+
+# ---------------------------------------------------------------------------
+# Project sub-family deferral — see plan §4-F1 ("project surface proves thin"):
+# `get_project_object` requires an LiteLLM_ProjectTable seeder + cache wiring
+# that the harness does not yet ship; pinning it would force a wider
+# conftest change for a single-helper close-out. Tracked as "deferred" in
+# the PR4.M3 follow-up box.
diff --git a/tests/proxy_behavior/management/test_key_team_change.py b/tests/proxy_behavior/management/test_key_team_change.py
new file mode 100644
index 00000000000..3bd4a0af0e2
--- /dev/null
+++ b/tests/proxy_behavior/management/test_key_team_change.py
@@ -0,0 +1,229 @@
+"""Phase 4 F2 — payload-level pins for key↔team reassignment.
+
+Pins `validate_key_team_change` (key_management_endpoints.py:2953), reached
+via /key/update when the request changes `team_id`.
+
+The handler runs four guards in order; each scenario isolates one path and
+asserts the rejected row's `team_id` is UNCHANGED on a fresh DB re-read —
+the regression shape that matters for cross-team / IDOR-class bugs is
+"row mutated despite the helper raising", and the only way to catch it
+is to compare the persisted state, not the response body.
+
+The accepted scenario pins the happy path: re-read confirms team_id
+flipped to the new team and the row is otherwise intact.
+"""
+
+import uuid
+from typing import Any, Dict, Optional
+
+import pytest
+from prisma import Json
+
+from litellm.proxy.utils import hash_token
+
+from .actors import TEAM_ALPHA, Actor
+from .conftest import create_scratch_team
+
+pytestmark = pytest.mark.asyncio(loop_scope="session")
+
+KEY_MODEL = "phase4-f2-key-model"
+
+
+async def _seed_key_with_limits(
+ prisma,
+ scratch_prefix: str,
+ *,
+ user_id: str,
+ team_id: str,
+ models: Optional[list] = None,
+ tpm_limit: Optional[int] = None,
+ rpm_limit: Optional[int] = None,
+) -> str:
+ """Raw-seed a scratch key with explicit models / tpm / rpm — /key/generate
+ can't set these against a non-throughput team without firing F1's guards.
+ Returns the cleartext key for /key/update calls."""
+ cleartext = "sk-" + uuid.uuid4().hex
+ data: Dict[str, Any] = {
+ "token": hash_token(cleartext),
+ "key_alias": f"{scratch_prefix}-key",
+ "key_name": f"{scratch_prefix}-key",
+ "user_id": user_id,
+ "team_id": team_id,
+ "models": models or [],
+ }
+ if tpm_limit is not None:
+ data["tpm_limit"] = tpm_limit
+ if rpm_limit is not None:
+ data["rpm_limit"] = rpm_limit
+ await prisma.db.litellm_verificationtoken.create(data=data)
+ return cleartext
+
+
+# ---------------------------------------------------------------------------
+# Accepted — proxy admin moves a key into a scratch team that has the model,
+# accommodates the limits, and has the key owner as a member.
+# ---------------------------------------------------------------------------
+
+
+async def test_key_team_change_accepted(proxy_client, prisma, scratch, world):
+ owner_id = world.keys[Actor.OWNER].user_id
+ target_team = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("target"),
+ member_user_ids=[owner_id],
+ models=[KEY_MODEL],
+ tpm_limit=10_000,
+ rpm_limit=1_000,
+ )
+ key_cleartext = await _seed_key_with_limits(
+ prisma,
+ scratch.prefix,
+ user_id=owner_id,
+ team_id=TEAM_ALPHA,
+ models=[KEY_MODEL],
+ tpm_limit=500,
+ rpm_limit=50,
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+
+ resp = await proxy_client.post(
+ "/key/update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"key": key_cleartext, "team_id": target_team},
+ )
+ assert resp.status_code == 200, resp.text
+
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(key_cleartext)}
+ )
+ assert row is not None
+ assert row.team_id == target_team, "key did not move to target team"
+
+
+# ---------------------------------------------------------------------------
+# Rejected — each path verifies row.team_id is UNCHANGED on DB re-read.
+# ---------------------------------------------------------------------------
+
+
+ "scenario",
+ [
+ "team_lacks_model",
+ "key_tpm_exceeds_team_tpm",
+ "key_rpm_exceeds_team_rpm",
+ "key_owner_not_team_member",
+ ],
+)
+async def test_key_team_change_rejected_guards(
+ scenario: str, proxy_client, prisma, scratch, world
+):
+ owner_id = world.keys[Actor.OWNER].user_id
+
+ team_kwargs: Dict[str, Any] = {
+ "member_user_ids": [owner_id],
+ "models": [KEY_MODEL],
+ "tpm_limit": 10_000,
+ "rpm_limit": 1_000,
+ }
+ key_kwargs: Dict[str, Any] = {
+ "models": [KEY_MODEL],
+ "tpm_limit": 500,
+ "rpm_limit": 50,
+ }
+
+ if scenario == "team_lacks_model":
+ team_kwargs["models"] = ["something-else"]
+ elif scenario == "key_tpm_exceeds_team_tpm":
+ team_kwargs["tpm_limit"] = 100 # < 500
+ elif scenario == "key_rpm_exceeds_team_rpm":
+ team_kwargs["rpm_limit"] = 5 # < 50
+ elif scenario == "key_owner_not_team_member":
+ team_kwargs["member_user_ids"] = []
+
+ target_team = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("target"),
+ **team_kwargs,
+ )
+ key_cleartext = await _seed_key_with_limits(
+ prisma,
+ scratch.prefix,
+ user_id=owner_id,
+ team_id=TEAM_ALPHA,
+ **key_kwargs,
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+
+ resp = await proxy_client.post(
+ "/key/update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"key": key_cleartext, "team_id": target_team},
+ )
+ # The model-mismatch path lands as 400 (ProxyException from
+ # _can_object_call_model); the limit + membership paths land as 403
+ # (validate_key_team_change's own HTTPException). Both shapes count as
+ # "rejected" for the pin; what matters is the row stayed put.
+ assert resp.status_code in (
+ 400,
+ 403,
+ ), f"{scenario}: expected 400/403, got {resp.status_code}: {resp.text}"
+
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(key_cleartext)}
+ )
+ assert row is not None
+ assert row.team_id == TEAM_ALPHA, (
+ f"{scenario}: row team_id mutated despite rejection — " f"got {row.team_id!r}"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Rejected — initiator is neither proxy admin, team admin, nor permission-
+# granted. Pinned separately because the source team here must also have the
+# initiator listed as a non-admin member (otherwise the earlier user_id
+# membership guard fires first).
+# ---------------------------------------------------------------------------
+
+
+async def test_key_team_change_rejected_initiator_not_admin(
+ proxy_client, prisma, scratch, world
+):
+ owner_id = world.keys[Actor.OWNER].user_id
+ target_team = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("target"),
+ # Owner is the key's user_id; member of the team to clear membership
+ # guard. Internal-user role on world.keys[INTERNAL_USER] is also a
+ # member of TEAM_ALPHA but never an admin → role-gate path fires.
+ member_user_ids=[owner_id, world.keys[Actor.INTERNAL_USER].user_id],
+ models=[KEY_MODEL],
+ tpm_limit=10_000,
+ rpm_limit=1_000,
+ )
+ key_cleartext = await _seed_key_with_limits(
+ prisma,
+ scratch.prefix,
+ user_id=owner_id,
+ team_id=TEAM_ALPHA,
+ models=[KEY_MODEL],
+ tpm_limit=500,
+ rpm_limit=50,
+ )
+ # The internal_user actor is the initiator: a TEAM_ALPHA member, but not
+ # an admin anywhere, and has no team_member_permissions for /key/update.
+ initiator = world.keys[Actor.INTERNAL_USER].cleartext
+
+ resp = await proxy_client.post(
+ "/key/update",
+ headers={"Authorization": f"Bearer {initiator}"},
+ json={"key": key_cleartext, "team_id": target_team},
+ )
+ assert resp.status_code in (
+ 401,
+ 403,
+ ), f"expected 401/403, got {resp.status_code}: {resp.text}"
+ row = await prisma.db.litellm_verificationtoken.find_unique(
+ where={"token": hash_token(key_cleartext)}
+ )
+ assert row is not None
+ assert row.team_id == TEAM_ALPHA, "row team_id mutated despite rejection"
diff --git a/tests/proxy_behavior/management/test_team_budget_limits.py b/tests/proxy_behavior/management/test_team_budget_limits.py
new file mode 100644
index 00000000000..1534cee2b2e
--- /dev/null
+++ b/tests/proxy_behavior/management/test_team_budget_limits.py
@@ -0,0 +1,321 @@
+"""Phase 4 F3 — payload-level pins for team budget & rate-limit enforcement.
+
+Pins the five helpers
+ * _check_team_model_specific_limits (team_endpoints.py:442)
+ * _check_team_rpm_tpm_limits (team_endpoints.py:527)
+ * check_org_team_model_specific_limits (team_endpoints.py:569)
+ * check_org_team_rpm_tpm_limits (team_endpoints.py:603)
+ * _check_org_team_limits (team_endpoints.py:628)
+ * _check_user_team_limits (team_endpoints.py:734)
+
+Driven through /team/new + /team/update.
+
+Structural finding pinned here, identical in shape to F1's org aggregate:
+both call sites (lines 985 + 1751) load the org via `get_org_object`
+WITHOUT `include_budget_table=True`, so `org_table.litellm_budget_table`
+is `None` and the org max_budget / org tpm / org rpm guards inside
+`_check_org_team_limits` (lines 641–694, 670–694) silently no-op. The
+`models` subset guard (lines 654–667) IS reachable because it reads
+`org_table.models` directly. The `_check_user_team_limits` guards reach
+all branches through `user_api_key_dict`, no relation include needed.
+"""
+
+import uuid
+from typing import Any, Dict, Optional
+
+import pytest
+
+from litellm.proxy.utils import hash_token
+
+from .actors import Actor
+from .conftest import create_scratch_org, create_scratch_team
+
+pytestmark = pytest.mark.asyncio(loop_scope="session")
+
+
+async def _seed_scratch_actor_with_caps(
+ prisma,
+ scratch_prefix: str,
+ *,
+ user_role: str = "internal_user",
+ models: Optional[list] = None,
+ max_budget: Optional[float] = None,
+ tpm_limit: Optional[int] = None,
+ rpm_limit: Optional[int] = None,
+) -> str:
+ """Raw-seed a scratch actor + verification token, with the token carrying
+ explicit caps that flow into `user_api_key_dict` at request time.
+
+ Returns cleartext key. Used by F3 user-team-limit scenarios where the
+ caller's caps drive the rejection. Uses 'internal_user' role plus a
+ token-level `allowed_routes` whitelist of /team/new + /team/update —
+ that whitelist is the only way past the admin-only role gate in
+ `RouteChecks.non_proxy_admin_allowed_routes_check`; without it the
+ non-admin caller would 401 before `_check_user_team_limits` ever fires.
+ """
+ user_id = f"{scratch_prefix}-team-creator"
+ cleartext = "sk-" + uuid.uuid4().hex
+ await prisma.db.litellm_usertable.create(
+ data={
+ "user_id": user_id,
+ "user_role": user_role,
+ "max_budget": max_budget,
+ }
+ )
+ token_data: Dict[str, Any] = {
+ "token": hash_token(cleartext),
+ "key_name": f"{scratch_prefix}-team-creator-key",
+ "key_alias": f"{scratch_prefix}-team-creator-alias",
+ "user_id": user_id,
+ "models": models if models is not None else [],
+ "allowed_routes": ["/team/new", "/team/update"],
+ }
+ if tpm_limit is not None:
+ token_data["tpm_limit"] = tpm_limit
+ if rpm_limit is not None:
+ token_data["rpm_limit"] = rpm_limit
+ await prisma.db.litellm_verificationtoken.create(data=token_data)
+ return cleartext
+
+
+# ---------------------------------------------------------------------------
+# _check_org_team_limits — models subset guard (the one path that reaches)
+# ---------------------------------------------------------------------------
+
+_ORG_MODEL_SCENARIOS = [
+ (
+ "org_models/team_subset_accepted",
+ ["allowed-model"],
+ {"models": ["allowed-model"]},
+ 200,
+ ),
+ (
+ "org_models/team_extra_model_rejected",
+ ["allowed-model"],
+ {"models": ["forbidden-model"]},
+ 400,
+ ),
+ (
+ "org_models/all_proxy_models_skips_check",
+ ["all-proxy-models"],
+ {"models": ["any-model-at-all"]},
+ 200,
+ ),
+]
+
+
+ "org_models,body_extras,expected_status",
+ [(b, c, d) for (_id, b, c, d) in _ORG_MODEL_SCENARIOS],
+ ids=[s[0] for s in _ORG_MODEL_SCENARIOS],
+)
+async def test_check_org_team_limits_models_subset(
+ org_models,
+ body_extras: Dict[str, Any],
+ expected_status: int,
+ proxy_client,
+ prisma,
+ scratch,
+ world,
+):
+ org_id = await create_scratch_org(prisma, scratch.prefix, models=org_models)
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ team_id = scratch.tag("team")
+ body: Dict[str, Any] = {
+ "team_id": team_id,
+ "team_alias": scratch.prefix,
+ "organization_id": org_id,
+ **body_extras,
+ }
+ resp = await proxy_client.post(
+ "/team/new",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json=body,
+ )
+ assert (
+ resp.status_code == expected_status
+ ), f"{body!r} → {resp.status_code}: {resp.text}"
+
+ rows = await prisma.db.litellm_teamtable.find_many(where={"team_id": team_id})
+ assert len(rows) == (1 if expected_status == 200 else 0)
+
+
+# ---------------------------------------------------------------------------
+# _check_org_team_limits — budget / tpm / rpm structurally unreachable
+# (org_table.litellm_budget_table is None at guard time). Pin the
+# no-op behavior so a future change that flips include_budget_table=True
+# turns these into reds.
+# ---------------------------------------------------------------------------
+
+_ORG_BUDGET_DEAD_SCENARIOS = [
+ (
+ "org_budget/over_max_budget_unenforced",
+ {"max_budget": 100, "tpm_limit": None, "rpm_limit": None},
+ {"max_budget": 999_999},
+ ),
+ (
+ "org_tpm/over_unenforced",
+ {"max_budget": None, "tpm_limit": 100, "rpm_limit": None},
+ {"tpm_limit": 999_999},
+ ),
+ (
+ "org_rpm/over_unenforced",
+ {"max_budget": None, "tpm_limit": None, "rpm_limit": 100},
+ {"rpm_limit": 999_999},
+ ),
+]
+
+
+ "org_budget,body_extras",
+ [(b, c) for (_id, b, c) in _ORG_BUDGET_DEAD_SCENARIOS],
+ ids=[s[0] for s in _ORG_BUDGET_DEAD_SCENARIOS],
+)
+async def test_check_org_team_limits_budget_dead_code_pin(
+ org_budget,
+ body_extras: Dict[str, Any],
+ proxy_client,
+ prisma,
+ scratch,
+ world,
+):
+ org_id = await create_scratch_org(prisma, scratch.prefix, **org_budget)
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ team_id = scratch.tag("team")
+ resp = await proxy_client.post(
+ "/team/new",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_id": team_id,
+ "team_alias": scratch.prefix,
+ "organization_id": org_id,
+ **body_extras,
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ rows = await prisma.db.litellm_teamtable.find_many(where={"team_id": team_id})
+ assert len(rows) == 1
+
+
+# ---------------------------------------------------------------------------
+# _check_user_team_limits — fires for standalone (no-org) teams created by
+# a non-admin caller. Each guard reads from user_api_key_dict / user_obj.
+# ---------------------------------------------------------------------------
+
+_USER_LIMIT_SCENARIOS = [
+ (
+ "user_max_budget/within",
+ {"max_budget": 100.0, "models": [], "tpm_limit": None, "rpm_limit": None},
+ {"max_budget": 50.0},
+ 200,
+ ),
+ (
+ "user_max_budget/over",
+ {"max_budget": 100.0, "models": [], "tpm_limit": None, "rpm_limit": None},
+ {"max_budget": 1000.0},
+ 400,
+ ),
+ (
+ "user_models/subset",
+ {"max_budget": None, "models": ["m-a"], "tpm_limit": None, "rpm_limit": None},
+ {"models": ["m-a"]},
+ 200,
+ ),
+ (
+ "user_models/superset_rejected",
+ {"max_budget": None, "models": ["m-a"], "tpm_limit": None, "rpm_limit": None},
+ {"models": ["m-a", "m-b"]},
+ 400,
+ ),
+ (
+ "user_tpm/within",
+ {"max_budget": None, "models": [], "tpm_limit": 1000, "rpm_limit": None},
+ {"tpm_limit": 500},
+ 200,
+ ),
+ (
+ "user_tpm/over",
+ {"max_budget": None, "models": [], "tpm_limit": 1000, "rpm_limit": None},
+ {"tpm_limit": 2000},
+ 400,
+ ),
+ (
+ "user_rpm/within",
+ {"max_budget": None, "models": [], "tpm_limit": None, "rpm_limit": 100},
+ {"rpm_limit": 50},
+ 200,
+ ),
+ (
+ "user_rpm/over",
+ {"max_budget": None, "models": [], "tpm_limit": None, "rpm_limit": 100},
+ {"rpm_limit": 250},
+ 400,
+ ),
+]
+
+
+ "actor_caps,body_extras,expected_status",
+ [(b, c, d) for (_id, b, c, d) in _USER_LIMIT_SCENARIOS],
+ ids=[s[0] for s in _USER_LIMIT_SCENARIOS],
+)
+async def test_check_user_team_limits(
+ actor_caps,
+ body_extras: Dict[str, Any],
+ expected_status: int,
+ proxy_client,
+ prisma,
+ scratch,
+):
+ caller = await _seed_scratch_actor_with_caps(prisma, scratch.prefix, **actor_caps)
+ team_id = scratch.tag("team")
+ resp = await proxy_client.post(
+ "/team/new",
+ headers={"Authorization": f"Bearer {caller}"},
+ json={
+ "team_id": team_id,
+ "team_alias": scratch.prefix,
+ # Standalone team — no organization_id, so user-limit guard fires.
+ **body_extras,
+ },
+ )
+ assert (
+ resp.status_code == expected_status
+ ), f"caps={actor_caps} body={body_extras} → {resp.status_code}: {resp.text}"
+
+ rows = await prisma.db.litellm_teamtable.find_many(where={"team_id": team_id})
+ assert len(rows) == (1 if expected_status == 200 else 0)
+
+
+# ---------------------------------------------------------------------------
+# /team/update path — _check_user_team_limits on existing team, no-org.
+# Pin one over-budget rejection here so the update-side wiring is also
+# covered (the update path is a second call site with its own data shape).
+# ---------------------------------------------------------------------------
+
+
+async def test_team_update_user_limit_rejected(proxy_client, prisma, scratch):
+ caller_cleartext = await _seed_scratch_actor_with_caps(
+ prisma,
+ scratch.prefix,
+ max_budget=100.0,
+ )
+ creator_user_id = f"{scratch.prefix}-team-creator"
+ # Team must exist before /team/update; seed a standalone scratch team
+ # owned by the same actor so the update authz gate passes.
+ team_id = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("team"),
+ admin_user_ids=[creator_user_id],
+ max_budget=50.0,
+ )
+ resp = await proxy_client.post(
+ "/team/update",
+ headers={"Authorization": f"Bearer {caller_cleartext}"},
+ json={"team_id": team_id, "max_budget": 999.0},
+ )
+ assert resp.status_code == 400, resp.text
+
+ row = await prisma.db.litellm_teamtable.find_unique(where={"team_id": team_id})
+ assert row is not None
+ assert row.max_budget == 50.0, "row max_budget mutated despite rejection"
diff --git a/tests/proxy_behavior/management/test_team_info.py b/tests/proxy_behavior/management/test_team_info.py
index 51809942113..ad019207c82 100644
--- a/tests/proxy_behavior/management/test_team_info.py
+++ b/tests/proxy_behavior/management/test_team_info.py
@@ -68,3 +68,19 @@ async def test_team_info_authz_matrix(
body = resp.json()
assert body["team_id"] == target_team_id
assert body["team_info"]["team_id"] == target_team_id
+
+
+# Phase 4 F6 — explicit pin on the `_verify_team_access` 403 message string.
+# alpha/org_b_admin already covers the branch in the matrix; this guard
+# turns a silent rename of the exception detail into a CI red, which is the
+# behavior tripwire that the matrix's status-only assertion cannot catch.
+async def test_team_info_org_admin_cross_org_rejection_detail(proxy_client, world):
+ resp = await proxy_client.get(
+ f"/team/info?team_id={world.team_alpha_id}",
+ headers={"Authorization": f"Bearer {world.keys[Actor.ORG_B_ADMIN].cleartext}"},
+ )
+ assert resp.status_code == 403, resp.text
+ # validate_membership() at GET /team/info raises with this exact phrase.
+ # Pinning it lock-step locks down the visible auth message — a rename
+ # would flip CI red even when the status stays 403.
+ assert "not authorized to access this team" in resp.text, resp.text
diff --git a/tests/proxy_behavior/management/test_team_member_info_validation.py b/tests/proxy_behavior/management/test_team_member_info_validation.py
new file mode 100644
index 00000000000..5139865d2b4
--- /dev/null
+++ b/tests/proxy_behavior/management/test_team_member_info_validation.py
@@ -0,0 +1,189 @@
+"""Phase 4 F4 — payload-level pins for member-info population.
+
+Pins `_validate_and_populate_member_user_info` (team_endpoints.py:2275),
+reached via /team/member_add.
+
+PROXY_ADMIN is the caller so the upstream `_validate_team_member_add_permissions`
+gate never short-circuits the payload check. Each scenario asserts BOTH the
+HTTP status and the DB end-state — for accepted cases, the
+LiteLLM_TeamMembership row reflects the resolved user_id (the regression
+shape: a payload that silently lands the membership against the WRONG
+user_id is invisible from response-body alone).
+"""
+
+from typing import Any, Dict, Optional
+
+import pytest
+
+from .actors import Actor
+from .conftest import create_scratch_team
+
+pytestmark = pytest.mark.asyncio(loop_scope="session")
+
+
+async def _seed_scratch_user(
+ prisma,
+ scratch_prefix: str,
+ *,
+ suffix: str,
+ user_email: Optional[str] = None,
+) -> str:
+ """Raw-seed a scratch-prefixed user row; returns user_id. Scratch teardown
+ reclaims by user_id prefix."""
+ user_id = f"{scratch_prefix}-{suffix}"
+ data: Dict[str, Any] = {"user_id": user_id, "user_role": "internal_user"}
+ if user_email is not None:
+ data["user_email"] = user_email
+ await prisma.db.litellm_usertable.create(data=data)
+ return user_id
+
+
+# ---------------------------------------------------------------------------
+# Both None → 400 ("Either user_id or user_email must be provided")
+# ---------------------------------------------------------------------------
+
+
+async def test_member_add_both_none_rejected(proxy_client, prisma, scratch, world):
+ team_id = await create_scratch_team(prisma, team_id=scratch.tag("team"))
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/member_add",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"team_id": team_id, "member": {"role": "user"}},
+ )
+ # The Pydantic Member model may also catch this at the validation layer
+ # (422). Either shape proves the empty-Member payload is rejected before
+ # any membership row is written — pin both.
+ assert resp.status_code in (400, 422), resp.text
+ rows = await prisma.db.litellm_teammembership.find_many(where={"team_id": team_id})
+ assert rows == [], "empty-Member payload leaked a membership row"
+
+
+# ---------------------------------------------------------------------------
+# Email + id given, but they point at different users → 400
+# ---------------------------------------------------------------------------
+
+
+async def test_member_add_email_id_mismatch_rejected(
+ proxy_client, prisma, scratch, world
+):
+ email = f"{scratch.prefix}[email protected]"
+ real_user_id = await _seed_scratch_user(
+ prisma, scratch.prefix, suffix="real", user_email=email
+ )
+ other_user_id = await _seed_scratch_user(prisma, scratch.prefix, suffix="other")
+ assert real_user_id != other_user_id # sanity
+ team_id = await create_scratch_team(prisma, team_id=scratch.tag("team"))
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/member_add",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_id": team_id,
+ "member": {
+ "role": "user",
+ "user_email": email,
+ "user_id": other_user_id,
+ },
+ },
+ )
+ assert resp.status_code == 400, resp.text
+ assert "do not belong to the same user" in resp.text, resp.text
+ rows = await prisma.db.litellm_teammembership.find_many(where={"team_id": team_id})
+ assert rows == [], "mismatch payload leaked a membership row"
+
+
+# ---------------------------------------------------------------------------
+# Email-only resolves to user_id when exactly one user matches
+# ---------------------------------------------------------------------------
+
+
+async def test_member_add_email_only_resolves_user_id(
+ proxy_client, prisma, scratch, world
+):
+ email = f"{scratch.prefix}[email protected]"
+ user_id = await _seed_scratch_user(
+ prisma, scratch.prefix, suffix="lookup", user_email=email
+ )
+ team_id = await create_scratch_team(prisma, team_id=scratch.tag("team"))
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/member_add",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_id": team_id,
+ "member": {"role": "user", "user_email": email},
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ # litellm_teammembership rows are only written when a per-member budget
+ # is assigned; the default member-add path stores membership in the
+ # team's members_with_roles JSON. Re-read that and assert the resolved
+ # user_id landed — the regression shape is "email resolved to the WRONG
+ # user_id and was silently written to members_with_roles".
+ team_row = await prisma.db.litellm_teamtable.find_unique(where={"team_id": team_id})
+ assert team_row is not None
+ member_user_ids = [m.get("user_id") for m in team_row.members_with_roles]
+ assert (
+ user_id in member_user_ids
+ ), f"email did not resolve to {user_id}; members={member_user_ids}"
+
+
+# ---------------------------------------------------------------------------
+# id-only, user does NOT yet exist — passes through, member is upserted.
+# ---------------------------------------------------------------------------
+
+
+async def test_member_add_unknown_user_id_upserted(
+ proxy_client, prisma, scratch, world
+):
+ team_id = await create_scratch_team(prisma, team_id=scratch.tag("team"))
+ new_user_id = f"{scratch.prefix}-fresh"
+ # Sanity — user does not exist yet.
+ pre = await prisma.db.litellm_usertable.find_unique(where={"user_id": new_user_id})
+ assert pre is None
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/member_add",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_id": team_id,
+ "member": {"role": "user", "user_id": new_user_id},
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ post = await prisma.db.litellm_usertable.find_unique(where={"user_id": new_user_id})
+ assert post is not None, "user_id was not upserted"
+ # The user row was created with NULL email (the helper returned the
+ # member as-is, no email lookup happened because the user didn't exist).
+ assert (
+ post.user_email is None
+ ), f"upserted user has unexpected email: {post.user_email!r}"
+
+
+# ---------------------------------------------------------------------------
+# Duplicate-email rejection — two scratch users share an email; email-only
+# add → 400 with "Multiple users found" detail.
+# ---------------------------------------------------------------------------
+
+
+async def test_member_add_duplicate_email_rejected(
+ proxy_client, prisma, scratch, world
+):
+ email = f"{scratch.prefix}[email protected]"
+ await _seed_scratch_user(prisma, scratch.prefix, suffix="dup1", user_email=email)
+ await _seed_scratch_user(prisma, scratch.prefix, suffix="dup2", user_email=email)
+ team_id = await create_scratch_team(prisma, team_id=scratch.tag("team"))
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/member_add",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_id": team_id,
+ "member": {"role": "user", "user_email": email},
+ },
+ )
+ assert resp.status_code == 400, resp.text
+ assert "Multiple users found" in resp.text, resp.text
+ rows = await prisma.db.litellm_teammembership.find_many(where={"team_id": team_id})
+ assert rows == [], "duplicate-email payload leaked a membership row"
diff --git a/tests/proxy_behavior/management/test_team_permissions_bulk_update.py b/tests/proxy_behavior/management/test_team_permissions_bulk_update.py
new file mode 100644
index 00000000000..552c3526eea
--- /dev/null
+++ b/tests/proxy_behavior/management/test_team_permissions_bulk_update.py
@@ -0,0 +1,245 @@
+"""Phase 4 F5 — payload-level pins for /team/permissions_bulk_update.
+
+Pins the three helpers
+ * _compute_and_batch_updates (team_endpoints.py:4887)
+ * _append_permissions_to_specific_teams (team_endpoints.py:4913)
+ * _append_permissions_to_all_teams (team_endpoints.py:4932)
+
+The route is admin-only — PROXY_ADMIN is the only legal caller. The
+contracts under test:
+ * specific-team list → ONLY listed teams mutate; every other team
+ (including world teams) is byte-identical on re-read.
+ * apply_to_all_teams → every team gains the permission, idempotently
+ merged (re-running with the same permission is a no-op).
+ * unknown team_id → 404 (the missing_ids guard); no mutation anywhere.
+ * malformed payload (neither / both selector flags) → 400; no mutation.
+
+The all-teams scenario mutates world teams as a deliberate side effect of
+the path under test. The test snapshots every team's
+`team_member_permissions` up front and restores them on exit so the
+read-world stays immutable for downstream tests.
+"""
+
+import pytest
+
+from .actors import TEAM_ALPHA, TEAM_BETA, TEAM_GAMMA, Actor
+from .conftest import create_scratch_team
+
+pytestmark = pytest.mark.asyncio(loop_scope="session")
+
+
+# ---------------------------------------------------------------------------
+# Specific-team list — only the listed team mutates.
+# ---------------------------------------------------------------------------
+
+
+async def test_bulk_update_specific_team_only_mutates_listed(
+ proxy_client, prisma, scratch, world
+):
+ target = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("target"),
+ team_member_permissions=[],
+ )
+ bystander = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("bystander"),
+ team_member_permissions=["pre-existing-perm"],
+ )
+ # Snapshot world teams so we can assert byte-equality on re-read.
+ world_team_ids = [TEAM_ALPHA, TEAM_BETA, TEAM_GAMMA]
+ before = {}
+ for tid in world_team_ids + [bystander]:
+ row = await prisma.db.litellm_teamtable.find_unique(where={"team_id": tid})
+ before[tid] = list(row.team_member_permissions or [])
+
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ perm = "/key/info"
+ resp = await proxy_client.post(
+ "/team/permissions_bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"team_ids": [target], "permissions": [perm]},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["teams_updated"] == 1
+
+ target_row = await prisma.db.litellm_teamtable.find_unique(
+ where={"team_id": target}
+ )
+ assert perm in (
+ target_row.team_member_permissions or []
+ ), f"target team did not gain perm; got={target_row.team_member_permissions}"
+
+ for tid, before_perms in before.items():
+ after_row = await prisma.db.litellm_teamtable.find_unique(
+ where={"team_id": tid}
+ )
+ assert list(after_row.team_member_permissions or []) == before_perms, (
+ f"untouched team {tid} mutated: "
+ f"{before_perms} → {list(after_row.team_member_permissions or [])}"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Specific-team — repeated call with same permission is a no-op (the
+# `permissions_to_add <= existing` short-circuit in _compute_and_batch_updates).
+# ---------------------------------------------------------------------------
+
+
+async def test_bulk_update_specific_team_idempotent(
+ proxy_client, prisma, scratch, world
+):
+ target = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("target"),
+ team_member_permissions=["/key/info"],
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/permissions_bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_ids": [target],
+ "permissions": ["/key/info"], # already present
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["teams_updated"] == 0, "idempotent add should report 0"
+
+
+# ---------------------------------------------------------------------------
+# Unknown team_id — 404, no mutation anywhere.
+# ---------------------------------------------------------------------------
+
+
+async def test_bulk_update_unknown_team_id_rejected(
+ proxy_client, prisma, scratch, world
+):
+ existing = await create_scratch_team(
+ prisma,
+ team_id=scratch.tag("real"),
+ team_member_permissions=[],
+ )
+ before = list(
+ (
+ await prisma.db.litellm_teamtable.find_unique(where={"team_id": existing})
+ ).team_member_permissions
+ or []
+ )
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/permissions_bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={
+ "team_ids": [existing, f"{scratch.prefix}-ghost"],
+ "permissions": ["/key/info"],
+ },
+ )
+ # The missing_ids check raises 404, but the global exception handler
+ # may wrap it. Either 404 or 400 with "not found" detail counts.
+ assert resp.status_code in (400, 404), resp.text
+ assert "not found" in resp.text.lower() or "ghost" in resp.text, resp.text
+ # Critical: the partial-success regression shape is "real team got
+ # mutated before the ghost-id check ran". Re-read and assert it didn't.
+ after_real = await prisma.db.litellm_teamtable.find_unique(
+ where={"team_id": existing}
+ )
+ assert (
+ list(after_real.team_member_permissions or []) == before
+ ), "partial mutation: real team changed despite ghost-id rejection"
+
+
+# ---------------------------------------------------------------------------
+# Selector validation — neither flag → 400; both flags → 400.
+# ---------------------------------------------------------------------------
+
+
+ "body,expected_substring",
+ [
+ (
+ {"permissions": ["/key/info"]},
+ "team_ids or set apply_to_all_teams",
+ ),
+ (
+ {
+ "permissions": ["/key/info"],
+ "team_ids": ["t"],
+ "apply_to_all_teams": True,
+ },
+ "Cannot set both",
+ ),
+ ],
+ ids=["neither_selector", "both_selectors"],
+)
+async def test_bulk_update_selector_validation(
+ body, expected_substring: str, proxy_client, world
+):
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/permissions_bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json=body,
+ )
+ assert resp.status_code == 400, resp.text
+ assert expected_substring in resp.text, resp.text
+
+
+# ---------------------------------------------------------------------------
+# apply_to_all_teams — mutates every team. Snapshot + restore world teams
+# so the read-world contract holds for downstream tests.
+# ---------------------------------------------------------------------------
+
+
+async def test_bulk_update_apply_to_all_mutates_every_team(
+ proxy_client, prisma, scratch, world
+):
+ # Two scratch teams so we can assert "every" includes our own targets.
+ a = await create_scratch_team(
+ prisma, team_id=scratch.tag("a"), team_member_permissions=[]
+ )
+ b = await create_scratch_team(
+ prisma, team_id=scratch.tag("b"), team_member_permissions=["other"]
+ )
+ perm = "/key/health" # distinct from the specific-team scenarios above
+
+ # Snapshot every team's permission list so we can restore world teams.
+ all_teams = await prisma.db.litellm_teamtable.find_many()
+ snapshot = {t.team_id: list(t.team_member_permissions or []) for t in all_teams}
+
+ try:
+ seeder = world.keys[Actor.PROXY_ADMIN].cleartext
+ resp = await proxy_client.post(
+ "/team/permissions_bulk_update",
+ headers={"Authorization": f"Bearer {seeder}"},
+ json={"apply_to_all_teams": True, "permissions": [perm]},
+ )
+ assert resp.status_code == 200, resp.text
+ # `teams_updated` counts teams that didn't already have the perm —
+ # i.e. every team in the DB at call time.
+ assert resp.json()["teams_updated"] == len(all_teams)
+
+ post = await prisma.db.litellm_teamtable.find_many()
+ for team in post:
+ perms = list(team.team_member_permissions or [])
+ assert perm in perms, f"team {team.team_id} missing the all-perm: {perms}"
+ # Existing perms preserved (merge, not replace).
+ for prior in snapshot.get(team.team_id, []):
+ assert (
+ prior in perms
+ ), f"team {team.team_id} lost prior perm {prior!r}: {perms}"
+ finally:
+ # Restore every team — scratch teardown handles {a, b}; we must
+ # explicitly restore world teams (and any other non-scratch teams
+ # that snuck in) so downstream tests see the immutable world.
+ for team_id, prior_perms in snapshot.items():
+ current = await prisma.db.litellm_teamtable.find_unique(
+ where={"team_id": team_id}
+ )
+ if current is None:
+ continue
+ if list(current.team_member_permissions or []) != prior_perms:
+ await prisma.db.litellm_teamtable.update(
+ where={"team_id": team_id},
+ data={"team_member_permissions": prior_perms},
+ )
diff --git a/tests/proxy_behavior/management/test_team_update.py b/tests/proxy_behavior/management/test_team_update.py
index 9b21911cef2..9cb2b0fecda 100644
--- a/tests/proxy_behavior/management/test_team_update.py
+++ b/tests/proxy_behavior/management/test_team_update.py
@@ -178,6 +178,24 @@ async def test_team_update_org_relocation_gate(
assert row.organization_id == world.org_a_id, "denied but team relocated"
+# Phase 4 F6 — explicit pin on the `_verify_team_access` 403 detail string
+# when an org_admin clears the destination route gate but fails the source
+# team's org-membership check. The relocation matrix above covers the
+# status; this guard turns a silent rename of the helper's exception detail
+# into a CI red.
+async def test_team_update_org_b_admin_relocation_rejection_detail(
+ proxy_client, prisma, scratch, world
+):
+ await _seed_target(prisma, world, "alpha", scratch.prefix)
+ resp = await proxy_client.post(
+ "/team/update",
+ headers={"Authorization": f"Bearer {world.keys[Actor.ORG_B_ADMIN].cleartext}"},
+ json={"team_id": scratch.prefix, "organization_id": world.org_b_id},
+ )
+ assert resp.status_code == 403, resp.text
+ assert "do not have access to this team" in resp.text, resp.text
+
+
async def test_team_update_org_relocation_allowed_for_dual_org_admin(
proxy_client, prisma, scratch, world
):