Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(spend-logs): authorize request_id lookups over distinct owners, build call id index concurrently

mateo-berric0adca7c9420
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260831120000_add_litellm_call_id_spend_logs/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260831120000_add_litellm_call_id_spend_logs/migration.sql
index b3bcad738ee..3bf6b819715 100644
--- a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260831120000_add_litellm_call_id_spend_logs/migration.sql
+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260831120000_add_litellm_call_id_spend_logs/migration.sql
@@ -1,5 +1,2 @@
-- AlterTable
ALTER TABLE "LiteLLM_SpendLogs" ADD COLUMN IF NOT EXISTS "litellm_call_id" TEXT;
-
--- CreateIndex
-CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_litellm_call_id_idx" ON "LiteLLM_SpendLogs"("litellm_call_id");
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260831120001_spend_logs_litellm_call_id_index/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260831120001_spend_logs_litellm_call_id_index/migration.sql
new file mode 100644
index 00000000000..62ad5c42ba7
--- /dev/null
+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260831120001_spend_logs_litellm_call_id_index/migration.sql
@@ -0,0 +1,12 @@
+-- CreateIndex (CONCURRENTLY)
+--
+-- Disclaimer:
+-- - CREATE INDEX CONCURRENTLY cannot run inside a transaction. This migration must stay a
+-- single statement so Prisma Migrate on PostgreSQL can apply it outside a transaction.
+-- - Builds are slower and use more I/O than a blocking CREATE INDEX; if the build is
+-- interrupted, Postgres may leave an INVALID index that must be dropped and recreated.
+-- - Do not edit this file after it has been applied to any database: Prisma checksums
+-- migrations; add a new migration instead.
+-- - Requires PostgreSQL that supports CONCURRENTLY with IF NOT EXISTS (use a new migration
+-- without IF NOT EXISTS if you must support older versions).
+CREATE INDEX CONCURRENTLY IF NOT EXISTS "LiteLLM_SpendLogs_litellm_call_id_idx" ON "LiteLLM_SpendLogs"("litellm_call_id");
diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.py
index e6ca23ca065..f3017cf12bf 100644
--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py
+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py
@@ -67,9 +67,9 @@ class _SupportsModelDump(Protocol):
def model_dump(self) -> Mapping[str, object]: ...
-class _SpendLogOwnershipRow(Protocol):
- user: str | None
- team_id: str | None
+class _SpendLogOwnerRow(TypedDict):
+ user: ReadOnly[str | None]
+ team_id: ReadOnly[str | None]
class _ActivityRow(TypedDict):
@@ -243,20 +243,23 @@ def _request_id_or_call_id_clause(request_id: str) -> tuple[_RequestIdEquals, _L
return (request_id_clause, call_id_clause)
-_SPEND_LOG_ID_LOOKUP_ROW_CAP: Final = 100
-
-
-async def _find_spend_log_rows(prisma_client: PrismaClient, request_id: str) -> Sequence[_SpendLogOwnershipRow]:
- """Read every spend log row identified by ``request_id`` or ``litellm_call_id``.
+async def _find_spend_log_owners(prisma_client: PrismaClient, request_id: str) -> Sequence[_SpendLogOwnerRow]:
+ """Read the distinct ``(user, team_id)`` owner pairs across every spend log row
+ identified by ``request_id`` or ``litellm_call_id``.
``litellm_call_id`` is populated from the client-settable ``x-litellm-call-id``
- request header, so it is not guaranteed unique to one tenant: more than one row
- can match. Callers must authorize every returned row, not just one of them.
+ request header, so it is not guaranteed unique to one tenant: any number of rows
+ can match one id. Authorization must consider the owner of every match, uncapped,
+ because a flood of matching rows could otherwise push a foreign owner past a
+ row-sample cap while the data queries still return that foreign row.
"""
- return await _spend_logs_table(prisma_client).find_many(
- where={"OR": _request_id_or_call_id_clause(request_id)},
- take=_SPEND_LOG_ID_LOOKUP_ROW_CAP,
- )
+ sql_query: Final = """
+ SELECT DISTINCT "user", team_id
+ FROM "LiteLLM_SpendLogs"
+ WHERE request_id = $1 OR litellm_call_id = $1
+ """
+ owners: Final[Sequence[_SpendLogOwnerRow] | None] = await _query_raw_or_none(prisma_client, sql_query, request_id)
+ return owners if owners is not None else ()
async def _count_spend_logs(prisma_client: PrismaClient, where: Mapping[str, object]) -> int:
@@ -4303,18 +4306,18 @@ def _can_user_view_spend_log(user_api_key_dict: UserAPIKeyAuth) -> bool:
)
-async def _user_can_view_spend_log_row(
+async def _user_can_view_spend_log_owner(
prisma_client: PrismaClient,
user_api_key_dict: UserAPIKeyAuth,
- row: _SpendLogOwnershipRow,
+ owner: _SpendLogOwnerRow,
) -> bool:
- if row.user is not None and row.user == user_api_key_dict.user_id:
+ if owner["user"] is not None and owner["user"] == user_api_key_dict.user_id:
return True
- if row.team_id:
+ if owner["team_id"]:
return await _can_team_member_view_log(
prisma_client=prisma_client,
user_api_key_dict=user_api_key_dict,
- team_id=row.team_id,
+ team_id=owner["team_id"],
)
return False
@@ -4331,9 +4334,9 @@ async def _assert_user_can_view_request_id(
granted only when the user owns all of them directly or via a permitted team.
Raises HTTP 403 if any matching row is not the user's to view.
"""
- rows: Final = await _find_spend_log_rows(prisma_client, request_id)
- for row in rows:
- if not await _user_can_view_spend_log_row(prisma_client, user_api_key_dict, row):
+ owners: Final = await _find_spend_log_owners(prisma_client, request_id)
+ for owner in owners:
+ if not await _user_can_view_spend_log_owner(prisma_client, user_api_key_dict, owner):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={"error": f"Not authorized to view spend log for request_id={request_id}"},
diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
index 9d1911d9613..34e403b93b9 100644
--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
@@ -190,6 +190,8 @@ def make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn, team_lookup_fn=No
query_observer(sql_query, params)
if "mcp_tool_call_count" in sql_query:
return []
+ if 'SELECT DISTINCT "user", team_id' in sql_query:
+ return _emulate_spend_log_owner_lookup(mock_spend_logs, sql_query, params)
filtered = filter_fn(_reconstruct_ui_where_from_sql(sql_query, params))
total = len(filtered)
if "COUNT(*)" in sql_query:
@@ -401,33 +403,54 @@ def test_can_user_view_spend_log_false_for_other_roles():
assert spend_management_endpoints._can_user_view_spend_log(auth) is False
+def _emulate_spend_log_owner_lookup(rows, sql_query, params):
+ """Emulate the ownership lookup SQL over an in-memory spend-log corpus,
+ honoring DISTINCT and any literal LIMIT the query carries so a capped or
+ non-distinct query produces the truncated result it would in Postgres."""
+ lookup_id = params[0]
+ matches = [
+ {"user": row.get("user"), "team_id": row.get("team_id")}
+ for row in rows
+ if lookup_id in (row.get("request_id"), row.get("litellm_call_id"))
+ ]
+ if "DISTINCT" in sql_query:
+ deduped = []
+ for match in matches:
+ if match not in deduped:
+ deduped.append(match)
+ matches = deduped
+ limit = re.search(r"LIMIT\s+(\d+)", sql_query, re.IGNORECASE)
+ if limit is not None:
+ matches = matches[: int(limit.group(1))]
+ return matches
+
+
+def _make_owner_lookup_prisma(rows):
+ class MockDB:
+ async def query_raw(self, sql_query, *params):
+ return _emulate_spend_log_owner_lookup(rows, sql_query, params)
+
+ class MockPrisma:
+ def __init__(self):
+ self.db = MockDB()
+
+ return MockPrisma()
+
+
@pytest.mark.asyncio
async def test_assert_user_can_view_request_id_rejects_both_users_none():
"""
API keys with user_id=None must not be treated as owning a log whose user
field is None (avoid None == None bypass).
"""
-
- class MockRow:
- user = None
- team_id = None
-
- class MockSpendLogs:
- async def find_many(self, where=None, take=None):
- return [MockRow()]
-
- class MockDB:
- def __init__(self):
- self.litellm_spendlogs = MockSpendLogs()
-
- class MockPrisma:
- def __init__(self):
- self.db = MockDB()
+ prisma = _make_owner_lookup_prisma(
+ [{"request_id": "req-none-user", "litellm_call_id": None, "user": None, "team_id": None}]
+ )
auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id=None)
with pytest.raises(HTTPException) as exc_info:
await spend_management_endpoints._assert_user_can_view_request_id(
- MockPrisma(), auth, "req-none-user"
+ prisma, auth, "req-none-user"
)
assert exc_info.value.status_code == 403
@@ -442,31 +465,64 @@ async def test_assert_user_can_view_request_id_rejects_spoofed_call_id_collision
belong to the caller, or the whole lookup is rejected. Regression for the
cross-tenant spend-log read this OR clause introduced.
"""
+ prisma = _make_owner_lookup_prisma(
+ [
+ {
+ "request_id": "caller-own-request",
+ "litellm_call_id": "victim-request-id",
+ "user": "caller",
+ "team_id": None,
+ },
+ {
+ "request_id": "victim-request-id",
+ "litellm_call_id": "victim-call-id",
+ "user": "victim",
+ "team_id": None,
+ },
+ ]
+ )
- class _OwnRow:
- user = "caller"
- team_id = None
-
- class _VictimRow:
- user = "victim"
- team_id = None
-
- class MockSpendLogs:
- async def find_many(self, where=None, take=None):
- return [_OwnRow(), _VictimRow()]
+ auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="caller")
+ with pytest.raises(HTTPException) as exc_info:
+ await spend_management_endpoints._assert_user_can_view_request_id(
+ prisma, auth, "victim-request-id"
+ )
+ assert exc_info.value.status_code == 403
- class MockDB:
- def __init__(self):
- self.litellm_spendlogs = MockSpendLogs()
- class MockPrisma:
- def __init__(self):
- self.db = MockDB()
+async def test_assert_user_can_view_request_id_rejects_foreign_match_past_any_row_cap():
+ """
+ An attacker can mint hundreds of their own rows carrying the victim's
+ request_id as their litellm_call_id, so a capped or sampled ownership read
+ can exhaust its cap on attacker-owned rows and never see the one foreign
+ row the data queries would still return. The ownership check must consider
+ every matching row's owner no matter how many rows match. Regression for
+ the find_many(take=100) sample the first fix used.
+ """
+ rows = [
+ {
+ "request_id": f"attacker-request-{i}",
+ "litellm_call_id": "victim-request-id",
+ "user": "attacker",
+ "team_id": None,
+ }
+ for i in range(150)
+ ]
+ rows.append(
+ {
+ "request_id": "victim-request-id",
+ "litellm_call_id": "victim-call-id",
+ "user": "victim",
+ "team_id": None,
+ }
+ )
+ prisma = _make_owner_lookup_prisma(rows)
- auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="caller")
+ auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="attacker")
with pytest.raises(HTTPException) as exc_info:
await spend_management_endpoints._assert_user_can_view_request_id(
- MockPrisma(), auth, "victim-request-id"
+ prisma, auth, "victim-request-id"
)
assert exc_info.value.status_code == 403
@@ -476,30 +532,26 @@ async def test_assert_user_can_view_request_id_allows_when_every_match_is_owned(
"""The same ambiguous id matching more than one row is fine when every match
belongs to the caller (e.g. two of the caller's own requests happen to share
a request_id/litellm_call_id pairing); only a foreign match should block it."""
-
- class _OwnRowA:
- user = "caller"
- team_id = None
-
- class _OwnRowB:
- user = "caller"
- team_id = None
-
- class MockSpendLogs:
- async def find_many(self, where=None, take=None):
- return [_OwnRowA(), _OwnRowB()]
-
- class MockDB:
- def __init__(self):
- self.litellm_spendlogs = MockSpendLogs()
-
- class MockPrisma:
- def __init__(self):
- self.db = MockDB()
+ prisma = _make_owner_lookup_prisma(
+ [
+ {
+ "request_id": "shared-request-id",
+ "litellm_call_id": "caller-call-a",
+ "user": "caller",
+ "team_id": None,
+ },
+ {
+ "request_id": "caller-request-b",
+ "litellm_call_id": "shared-request-id",
+ "user": "caller",
+ "team_id": None,
+ },
+ ]
+ )
auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="caller")
result = await spend_management_endpoints._assert_user_can_view_request_id(
- MockPrisma(), auth, "shared-request-id"
+ prisma, auth, "shared-request-id"
)
assert result is None
@@ -2402,23 +2454,18 @@ async def test_ui_view_spend_logs_request_id_blocks_non_owner(client, monkeypatc
"""A non-admin looking up a request_id they do not own is rejected (403), so
the relaxed date window cannot read another tenant's log by id."""
- class _ForeignRow:
- user = "other_user"
- team_id = None
-
- class _SpendLogs:
- async def find_many(self, where=None, take=None):
- return [_ForeignRow()]
-
- class _DB:
- def __init__(self):
- self.litellm_spendlogs = _SpendLogs()
-
- class _Prisma:
- def __init__(self):
- self.db = _DB()
+ prisma = _make_owner_lookup_prisma(
+ [
+ {
+ "request_id": "foreign-req",
+ "litellm_call_id": None,
+ "user": "other_user",
+ "team_id": None,
+ }
+ ]
+ )
- monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", _Prisma())
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", prisma)
app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1"
)
@@ -2468,15 +2515,6 @@ async def test_ui_view_spend_logs_request_id_owner_scoped_by_id_only(
return rows
mock_prisma = make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn)
-
- class _OwnedRow:
- user = "user_1"
- team_id = "team1"
-
- async def _find_many(where=None, take=None):
- return [_OwnedRow()]
-
- mock_prisma.db.find_many = _find_many
monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
# A 5-day window that EXCLUDES the 90-day-old log, as the dashboard sends.