Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from litellm._logging import verbose_proxy_logger
from litellm._uuid import uuid
from litellm.proxy._types import *
from litellm.proxy.auth.auth_checks import delete_cached_project_object
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.management_endpoints.common_utils import _set_object_metadata_field
from litellm.proxy.management_helpers.utils import (
Expand Down Expand Up @@ -514,6 +515,7 @@ async def update_project(
litellm_proxy_admin_name,
premium_user,
prisma_client,
user_api_key_cache,
)

try:
Expand Down Expand Up @@ -672,6 +674,11 @@ async def update_project(
include={"litellm_budget_table": True, "object_permission": True},
)

await delete_cached_project_object(
project_id=data.project_id,
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
user_api_key_cache=user_api_key_cache,
)

return updated_project
except Exception as e:
verbose_proxy_logger.exception(
Expand Down Expand Up @@ -710,7 +717,7 @@ async def delete_project(
}'
```
"""
from litellm.proxy.proxy_server import premium_user, prisma_client
from litellm.proxy.proxy_server import premium_user, prisma_client, user_api_key_cache

try:
if not premium_user:
Expand Down Expand Up @@ -773,6 +780,11 @@ async def delete_project(
prisma_models.LiteLLM_ProjectTable | None
) = await prisma_client.db.litellm_projecttable.delete(where={"project_id": project_id})

await delete_cached_project_object(
project_id=project_id,
user_api_key_cache=user_api_key_cache,
)

deleted_projects.append(deleted_project)

return deleted_projects
Expand Down
19 changes: 18 additions & 1 deletion litellm/proxy/auth/auth_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -4262,6 +4262,10 @@ async def _project_soft_budget_check(
)


def _project_cache_key(project_id: str) -> str:
return f"project_id:{project_id}"


async def get_project_object(
project_id: str,
prisma_client: PrismaClient | None,
Expand All @@ -4279,7 +4283,7 @@ async def get_project_object(
return None

# Check cache first
cache_key: Final = f"project_id:{project_id}"
cache_key: Final = _project_cache_key(project_id)
deserialized_project: Final = await user_api_key_cache.async_get_cache(
key=cache_key,
model_type=LiteLLM_ProjectTableCachedObj,
Expand Down Expand Up @@ -4310,6 +4314,19 @@ async def get_project_object(
return project_obj


async def delete_cached_project_object(
project_id: str,
user_api_key_cache: UserApiKeyCache,
) -> None:
"""
Every endpoint that mutates litellm_projecttable must call this: get_project_object
serves auth cache-first with no freshness check, so without invalidation a stale
project (e.g. a pre-update empty model allowlist) keeps being enforced until the
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
TTL expires (LIT-3803).
"""
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
await user_api_key_cache.async_delete_cache(key=_project_cache_key(project_id))


async def _organization_max_budget_check(
valid_token: UserAPIKeyAuth | None,
team_object: LiteLLM_TeamTable | None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -864,3 +864,115 @@ def test_litellm_project_table_has_timestamp_fields():
fields = LiteLLM_ProjectTable.model_fields
assert "created_at" in fields, "LiteLLM_ProjectTable must have created_at field"
assert "updated_at" in fields, "LiteLLM_ProjectTable must have updated_at field"


@pytest.mark.asyncio
async def test_update_project_invalidates_cached_project_object(monkeypatch):
"""
LIT-3803 regression: auth reads projects cache-first with no freshness check,
so /project/update must evict the cached project. Before the fix, a project
cached with models=[] kept bypassing the new allowlist until the TTL expired.
"""
from unittest.mock import AsyncMock, MagicMock

from litellm.proxy.auth.auth_checks import get_project_object
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache

project_id = f"project-{uuid.uuid4()}"
cache = UserApiKeyCache()

stale_row = MagicMock()
stale_row.model_dump = lambda: {"project_id": project_id, "team_id": None, "models": []}

mock_prisma = MagicMock()
mock_prisma.jsonify_object = lambda data: data
mock_prisma.db.litellm_projecttable.find_unique = AsyncMock(return_value=stale_row)

seeded = await get_project_object(
project_id=project_id, prisma_client=mock_prisma, user_api_key_cache=cache
)
assert seeded is not None and seeded.models == []

updated_models = ["gemini-2.5-flash-image", "gemini-3.1-flash-lite-preview"]
existing_row = MagicMock(team_id=None, budget_id=None, object_permission_id=None)
updated_row = MagicMock()
updated_row.model_dump = lambda: {
"project_id": project_id,
"team_id": None,
"models": updated_models,
}

mock_prisma.db.litellm_projecttable.find_unique = AsyncMock(return_value=existing_row)
mock_prisma.db.litellm_projecttable.update = AsyncMock(return_value=updated_row)

monkeypatch.setattr(litellm.proxy.proxy_server, "premium_user", True)
monkeypatch.setattr(litellm.proxy.proxy_server, "prisma_client", mock_prisma)
monkeypatch.setattr(litellm.proxy.proxy_server, "user_api_key_cache", cache)

await update_project(
data=UpdateProjectRequest(project_id=project_id, models=updated_models),
http_request=Request(scope={"type": "http"}),
user_api_key_dict=UserAPIKeyAuth(
user_role=LitellmUserRoles.PROXY_ADMIN,
api_key="sk-1234",
user_id="1234",
),
)

mock_prisma.db.litellm_projecttable.find_unique = AsyncMock(return_value=updated_row)
refreshed = await get_project_object(
project_id=project_id, prisma_client=mock_prisma, user_api_key_cache=cache
)
assert refreshed is not None
assert refreshed.models == updated_models


@pytest.mark.asyncio
async def test_delete_project_invalidates_cached_project_object(monkeypatch):
"""
LIT-3803 regression: /project/delete must evict the cached project so auth
stops enforcing (or trusting) a project that no longer exists.
"""
from unittest.mock import AsyncMock, MagicMock

from litellm.proxy.auth.auth_checks import get_project_object
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache

project_id = f"project-{uuid.uuid4()}"
cache = UserApiKeyCache()

row = MagicMock()
row.model_dump = lambda: {"project_id": project_id, "team_id": None, "models": ["gpt-5.5"]}

mock_prisma = MagicMock()
mock_prisma.db.litellm_projecttable.find_unique = AsyncMock(return_value=row)

seeded = await get_project_object(
project_id=project_id, prisma_client=mock_prisma, user_api_key_cache=cache
)
assert seeded is not None

mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
mock_prisma.db.litellm_projecttable.delete = AsyncMock(return_value=row)

monkeypatch.setattr(litellm.proxy.proxy_server, "premium_user", True)
monkeypatch.setattr(litellm.proxy.proxy_server, "prisma_client", mock_prisma)
monkeypatch.setattr(litellm.proxy.proxy_server, "user_api_key_cache", cache)

await delete_project(
data=DeleteProjectRequest(project_ids=[project_id]),
http_request=Request(scope={"type": "http"}),
user_api_key_dict=UserAPIKeyAuth(
user_role=LitellmUserRoles.PROXY_ADMIN,
api_key="sk-1234",
user_id="1234",
),
)

mock_prisma.db.litellm_projecttable.find_unique = AsyncMock(return_value=None)
assert (
await get_project_object(
project_id=project_id, prisma_client=mock_prisma, user_api_key_cache=cache
)
is None
)
57 changes: 57 additions & 0 deletions tests/test_litellm/proxy/auth/test_auth_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -5464,6 +5464,63 @@ async def test_get_project_object_db_fetch_returns_cached_obj():
assert result.project_alias == "proj"


@pytest.mark.asyncio
async def test_project_allowlist_enforced_when_key_models_empty():
"""
LIT-3803: a project-bound key with models=[] has no key-level restriction,
but the project allowlist must still 403 team models outside it.
"""
from litellm.proxy._types import (
LiteLLM_ProjectTableCachedObj,
ProxyErrorTypes,
ProxyException,
)
from litellm.proxy.auth.auth_checks import _run_project_checks, can_key_call_model

valid_token = UserAPIKeyAuth(
api_key="hashed-key",
project_id="p-1",
team_id="t-1",
models=[],
)
project = LiteLLM_ProjectTableCachedObj(
project_id="p-1",
team_id="t-1",
models=["gemini-2.5-flash-image", "gemini-3.1-flash-lite-preview"],
)

assert (
await can_key_call_model(
model="gemini-2.5-flash",
llm_model_list=None,
valid_token=valid_token,
llm_router=None,
)
is True
)

await _run_project_checks(
project_object=project,
_model="gemini-2.5-flash-image",
llm_router=None,
skip_budget_checks=True,
valid_token=valid_token,
proxy_logging_obj=MagicMock(),
)

with pytest.raises(ProxyException) as exc_info:
await _run_project_checks(
project_object=project,
_model="gemini-2.5-flash",
llm_router=None,
skip_budget_checks=True,
valid_token=valid_token,
proxy_logging_obj=MagicMock(),
)
assert exc_info.value.type == ProxyErrorTypes.project_model_access_denied
assert exc_info.value.code == "403"


def test_is_user_proxy_admin_rejects_view_only_admin():
"""This predicate skips `non_proxy_admin_allowed_routes_check` entirely, so an
Admin Viewer answering True here would gain every write route. Read parity for
Expand Down
Loading