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]

merge: resolve conflicts with litellm_yj_march_18_2026 base branch

Cursor Agentf9e57c700a4e
diff --cc litellm/proxy/management_endpoints/key_management_endpoints.py
index 55def0008b7,e09d7607ebe..ff502a508e5
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@@ -4786,19 -4942,27 +4940,28 @@@ async def block_key
else:
hashed_token = data.key
+ # Admin-only: only proxy admins, team admins, or org admins can block keys
+ await _check_key_admin_access(
+ user_api_key_dict=user_api_key_dict,
+ hashed_token=hashed_token,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ route="/key/block",
+ )
+
- if litellm.store_audit_logs is True:
- # make an audit log for key update
- record = await prisma_client.db.litellm_verificationtoken.find_unique(
- where={"token": hashed_token}
+ # Check if the key exists before trying to block it
+ existing_record = await prisma_client.db.litellm_verificationtoken.find_unique(
+ where={"token": hashed_token}
+ )
+ if existing_record is None:
+ raise ProxyException(
+ message=f"Key not found. Passed key={data.key}",
+ type=ProxyErrorTypes.not_found_error,
+ param="key",
+ code=status.HTTP_404_NOT_FOUND,
)
- if record is None:
- raise ProxyException(
- message=f"Key {data.key} not found",
- type=ProxyErrorTypes.bad_request_error,
- param="key",
- code=status.HTTP_404_NOT_FOUND,
- )
+
+ if litellm.store_audit_logs is True:
asyncio.create_task(
create_audit_log_for_update(
request_data=LiteLLM_AuditLogs(
@@@ -4886,19 -5065,27 +5049,28 @@@ async def unblock_key
else:
hashed_token = data.key
+ # Admin-only: only proxy admins, team admins, or org admins can unblock keys
+ await _check_key_admin_access(
+ user_api_key_dict=user_api_key_dict,
+ hashed_token=hashed_token,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ route="/key/unblock",
+ )
+
- if litellm.store_audit_logs is True:
- # make an audit log for key update
- record = await prisma_client.db.litellm_verificationtoken.find_unique(
- where={"token": hashed_token}
+ # Check if the key exists before trying to unblock it
+ existing_record = await prisma_client.db.litellm_verificationtoken.find_unique(
+ where={"token": hashed_token}
+ )
+ if existing_record is None:
+ raise ProxyException(
+ message=f"Key not found. Passed key={data.key}",
+ type=ProxyErrorTypes.not_found_error,
+ param="key",
+ code=status.HTTP_404_NOT_FOUND,
)
- if record is None:
- raise ProxyException(
- message=f"Key {data.key} not found",
- type=ProxyErrorTypes.bad_request_error,
- param="key",
- code=status.HTTP_404_NOT_FOUND,
- )
+
+ if litellm.store_audit_logs is True:
asyncio.create_task(
create_audit_log_for_update(
request_data=LiteLLM_AuditLogs(
diff --cc tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
index 664a08989e9,a3bca77ae3a..3bff35fbd55
--- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
@@@ -7364,3 -7329,773 +7508,759 @@@ def test_update_key_request_has_organiz
# Also verify it defaults to None
data_no_org = UpdateKeyRequest(key="sk-test-key")
assert data_no_org.organization_id is None
+
+
+ # ============================================================================
+ # Tests for admin-only access on /key/block, /key/unblock, /key/update max_budget
+ # ============================================================================
+
+
+ def _setup_block_unblock_mocks(monkeypatch, mock_key_team_id=None):
+ """Helper to set up common mocks for block/unblock tests."""
+ mock_prisma_client = AsyncMock()
+ mock_user_api_key_cache = MagicMock()
+ mock_proxy_logging_obj = MagicMock()
+
+ test_hashed_token = (
+ "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
+ )
+
+ mock_key_record = MagicMock()
+ mock_key_record.token = test_hashed_token
+ mock_key_record.blocked = False
+ mock_key_record.team_id = mock_key_team_id
+ mock_key_record.model_dump_json.return_value = (
+ f'{{"token": "{test_hashed_token}", "blocked": false}}'
+ )
+
+ mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
+ return_value=mock_key_record
+ )
+ mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
+ return_value=mock_key_record
+ )
+
+ mock_key_object = MagicMock()
+ mock_key_object.blocked = True
+
+ def mock_hash_token(token):
+ if token.startswith("sk-"):
+ return test_hashed_token
+ return token
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
+ )
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
+ )
+ monkeypatch.setattr("litellm.proxy.proxy_server.hash_token", mock_hash_token)
+ monkeypatch.setattr("litellm.store_audit_logs", False)
+
- async def mock_get_key_object(**kwargs):
- return mock_key_object
-
- async def mock_cache_key_object(**kwargs):
++ async def mock_delete_cache_key_object(**kwargs):
+ pass
+
+ monkeypatch.setattr(
- "litellm.proxy.management_endpoints.key_management_endpoints.get_key_object",
- mock_get_key_object,
- )
- monkeypatch.setattr(
- "litellm.proxy.management_endpoints.key_management_endpoints._cache_key_object",
- mock_cache_key_object,
++ "litellm.proxy.management_endpoints.key_management_endpoints._delete_cache_key_object",
++ mock_delete_cache_key_object,
+ )
+
+ return mock_prisma_client, test_hashed_token
+
+
+ @pytest.mark.asyncio
+ async def test_block_key_rejected_for_internal_user(monkeypatch):
+ """Internal users should not be able to block keys."""
+ from litellm.proxy._types import BlockKeyRequest
+ from litellm.proxy.management_endpoints.key_management_endpoints import block_key
+
+ _setup_block_unblock_mocks(monkeypatch)
+
+ mock_request = MagicMock()
+ user_api_key_dict = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-internal",
+ user_id="internal_user",
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await block_key(
+ data=BlockKeyRequest(key="sk-test123456789"),
+ http_request=mock_request,
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+
+ assert exc.value.status_code == 403
+ assert "Only proxy admins, team admins, or org admins" in str(exc.value.detail)
+
+
+ @pytest.mark.asyncio
+ async def test_unblock_key_rejected_for_internal_user(monkeypatch):
+ """Internal users should not be able to unblock keys."""
+ from litellm.proxy._types import BlockKeyRequest
+ from litellm.proxy.management_endpoints.key_management_endpoints import unblock_key
+
+ _setup_block_unblock_mocks(monkeypatch)
+
+ mock_request = MagicMock()
+ user_api_key_dict = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-internal",
+ user_id="internal_user",
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await unblock_key(
+ data=BlockKeyRequest(key="sk-test123456789"),
+ http_request=mock_request,
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+
+ assert exc.value.status_code == 403
+ assert "Only proxy admins, team admins, or org admins" in str(exc.value.detail)
+
+
+ @pytest.mark.asyncio
+ async def test_block_key_allowed_for_proxy_admin(monkeypatch):
+ """Proxy admins should be able to block keys."""
+ from litellm.proxy._types import BlockKeyRequest
+ from litellm.proxy.management_endpoints.key_management_endpoints import block_key
+
+ _setup_block_unblock_mocks(monkeypatch)
+
+ mock_request = MagicMock()
+ user_api_key_dict = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-admin",
+ user_id="admin_user",
+ )
+
+ result = await block_key(
+ data=BlockKeyRequest(key="sk-test123456789"),
+ http_request=mock_request,
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+ assert result is not None
+
+
+ @pytest.mark.asyncio
+ async def test_block_key_allowed_for_team_admin(monkeypatch):
+ """Team admins should be able to block keys belonging to their team."""
+ from litellm.proxy._types import BlockKeyRequest
+ from litellm.proxy.management_endpoints.key_management_endpoints import block_key
+
+ team_id = "team-123"
+ _setup_block_unblock_mocks(monkeypatch, mock_key_team_id=team_id)
+
+ # Mock get_team_object to return a team where the user is admin
+ team_obj = LiteLLM_TeamTableCachedObj(
+ team_id=team_id,
+ members_with_roles=[
+ Member(user_id="team_admin_user", role="admin"),
+ ],
+ )
+
+ async def mock_get_team_object(**kwargs):
+ return team_obj
+
+ monkeypatch.setattr(
+ "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
+ mock_get_team_object,
+ )
+
+ mock_request = MagicMock()
+ user_api_key_dict = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-teamadmin",
+ user_id="team_admin_user",
+ )
+
+ result = await block_key(
+ data=BlockKeyRequest(key="sk-test123456789"),
+ http_request=mock_request,
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+ assert result is not None
+
+
+ @pytest.mark.asyncio
+ async def test_update_key_max_budget_rejected_for_internal_user(monkeypatch):
+ """Internal users should not be able to modify max_budget on keys."""
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ update_key_fn,
+ )
+
+ mock_prisma_client = AsyncMock()
+ mock_user_api_key_cache = AsyncMock()
+ mock_proxy_logging_obj = MagicMock()
+
+ test_hashed_token = (
+ "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
+ )
+
+ # Mock existing key row
+ mock_existing_key = MagicMock()
+ mock_existing_key.token = test_hashed_token
+ mock_existing_key.user_id = "internal_user"
+ mock_existing_key.team_id = None
+ mock_existing_key.project_id = None
+ mock_existing_key.max_budget = 10.0
+ mock_existing_key.models = []
+ mock_existing_key.model_dump.return_value = {
+ "token": test_hashed_token,
+ "user_id": "internal_user",
+ "team_id": None,
+ "max_budget": 10.0,
+ }
+
+ mock_prisma_client.get_data = AsyncMock(return_value=mock_existing_key)
+ mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
+ return_value=mock_existing_key
+ )
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
+ )
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
+ )
+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
+ monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
+
+ mock_request = MagicMock()
+ mock_request.query_params = {}
+ user_api_key_dict = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-internal",
+ user_id="internal_user",
+ )
+
+ with pytest.raises(ProxyException) as exc:
+ await update_key_fn(
+ request=mock_request,
+ data=UpdateKeyRequest(key=test_hashed_token, max_budget=999999),
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+
+ assert str(exc.value.code) == "403"
+ assert "Only proxy admins, team admins, or org admins" in str(exc.value.message)
+
+
+ @pytest.mark.asyncio
+ async def test_update_key_non_budget_fields_allowed_for_internal_user(monkeypatch):
+ """Internal users should still be able to update non-budget fields on their own keys."""
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ update_key_fn,
+ )
+
+ mock_prisma_client = AsyncMock()
+ mock_user_api_key_cache = AsyncMock()
+ mock_proxy_logging_obj = MagicMock()
+
+ test_hashed_token = (
+ "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
+ )
+
+ # Mock existing key row
+ mock_existing_key = MagicMock()
+ mock_existing_key.token = test_hashed_token
+ mock_existing_key.user_id = "internal_user"
+ mock_existing_key.team_id = None
+ mock_existing_key.project_id = None
+ mock_existing_key.max_budget = 10.0
+ mock_existing_key.key_alias = None
+ mock_existing_key.models = []
+ mock_existing_key.model_dump.return_value = {
+ "token": test_hashed_token,
+ "user_id": "internal_user",
+ "team_id": None,
+ "max_budget": 10.0,
+ }
+
+ mock_updated_key = MagicMock()
+ mock_updated_key.token = test_hashed_token
+ mock_updated_key.key_alias = "my-alias"
+
+ mock_prisma_client.get_data = AsyncMock(return_value=mock_existing_key)
+ mock_prisma_client.update_data = AsyncMock(return_value=mock_updated_key)
+ mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
+ return_value=mock_existing_key
+ )
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
+ )
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
+ )
+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
+ monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
+ monkeypatch.setattr("litellm.store_audit_logs", False)
+
+ def mock_hash_token(token):
+ return test_hashed_token
+
+ monkeypatch.setattr("litellm.proxy.proxy_server.hash_token", mock_hash_token)
+
- async def mock_cache_key_object(**kwargs):
- pass
-
+ async def mock_delete_cache_key_object(**kwargs):
+ pass
+
- monkeypatch.setattr(
- "litellm.proxy.management_endpoints.key_management_endpoints._cache_key_object",
- mock_cache_key_object,
- )
+ monkeypatch.setattr(
+ "litellm.proxy.management_endpoints.key_management_endpoints._delete_cache_key_object",
+ mock_delete_cache_key_object,
+ )
+
+ # Mock _enforce_unique_key_alias to avoid DB call
+ async def mock_enforce_unique_key_alias(**kwargs):
+ pass
+
+ monkeypatch.setattr(
+ "litellm.proxy.management_endpoints.key_management_endpoints._enforce_unique_key_alias",
+ mock_enforce_unique_key_alias,
+ )
+
+ mock_request = MagicMock()
+ mock_request.query_params = {}
+ user_api_key_dict = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ api_key="sk-internal",
+ user_id="internal_user",
+ )
+
+ # Updating key_alias (non-budget field) should succeed
+ result = await update_key_fn(
+ request=mock_request,
+ data=UpdateKeyRequest(key=test_hashed_token, key_alias="my-alias"),
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+
+ assert result is not None
+
+
+ # ============================================================================
+ # LIT-1884: Internal users cannot create invalid keys
+ # ============================================================================
+
+
+ class TestLIT1884KeyGenerateValidation:
+ """Tests for LIT-1884: internal users should not be able to generate invalid keys."""
+
+ @pytest.mark.asyncio
+ async def test_internal_user_generate_key_no_user_id_auto_assigns(self):
+ """
+ When an internal_user calls /key/generate without user_id,
+ the caller's user_id should be auto-assigned before reaching
+ _common_key_generation_helper.
+ """
+ mock_prisma_client = AsyncMock()
+
+ data = GenerateKeyRequest(key_alias="test-alias")
+ assert data.user_id is None
+
+ user_api_key_dict = UserAPIKeyAuth(
+ user_id="internal-user-123",
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ )
+
+ # Patch _common_key_generation_helper to avoid needing full DB mocks.
+ # We just want to verify user_id is set before we reach this point.
+ with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client), \
+ patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()), \
+ patch("litellm.proxy.proxy_server.user_custom_key_generate", None), \
+ patch(
+ "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
+ new_callable=AsyncMock,
+ return_value=MagicMock(),
+ ):
+ await generate_key_fn(
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+
+ # The data object should have been mutated to include the caller's user_id
+ assert data.user_id == "internal-user-123"
+
+ @pytest.mark.asyncio
+ async def test_internal_user_generate_key_invalid_team_id_rejected(self):
+ """
+ When an internal_user provides a non-existent team_id,
+ key/generate should raise ProxyException with status 400.
+ """
+ mock_prisma_client = AsyncMock()
+
+ data = GenerateKeyRequest(
+ key_alias="test-alias",
+ team_id="nonexistent-team-id",
+ )
+
+ user_api_key_dict = UserAPIKeyAuth(
+ user_id="internal-user-123",
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ )
+
+ with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client), \
+ patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()), \
+ patch("litellm.proxy.proxy_server.user_custom_key_generate", None), \
+ patch(
+ "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
+ AsyncMock(side_effect=Exception("Team not found")),
+ ):
+ with pytest.raises(ProxyException) as exc_info:
+ await generate_key_fn(
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+ assert str(exc_info.value.code) == "400"
+ assert "Team not found" in str(exc_info.value.message)
+
+ @pytest.mark.asyncio
+ async def test_admin_generate_key_invalid_team_id_allowed(self):
+ """
+ Admin callers should be allowed to create keys with any team_id,
+ even if the team doesn't exist (team_table=None is OK for admins).
+ """
+ data = GenerateKeyRequest(
+ key_alias="admin-key",
+ team_id="nonexistent-team-id",
+ user_id="admin-user",
+ )
+
+ user_api_key_dict = UserAPIKeyAuth(
+ user_id="admin-user",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ )
+
+ mock_prisma_client = AsyncMock()
+
+ with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client), \
+ patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()), \
+ patch("litellm.proxy.proxy_server.user_custom_key_generate", None), \
+ patch(
+ "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
+ AsyncMock(side_effect=Exception("Team not found")),
+ ), \
+ patch(
+ "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
+ new_callable=AsyncMock,
+ return_value=MagicMock(),
+ ):
+ # Should NOT raise — admin bypasses team validation
+ result = await generate_key_fn(
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+ assert result is not None
+
+ @pytest.mark.asyncio
+ async def test_admin_generate_key_no_user_id_not_auto_assigned(self):
+ """
+ Admin callers should NOT have user_id auto-assigned — they may
+ intentionally create keys without a user_id.
+ """
+ data = GenerateKeyRequest(key_alias="admin-unbound-key")
+ assert data.user_id is None
+
+ user_api_key_dict = UserAPIKeyAuth(
+ user_id="admin-user",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ )
+
+ mock_prisma_client = AsyncMock()
+
+ with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client), \
+ patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()), \
+ patch("litellm.proxy.proxy_server.user_custom_key_generate", None), \
+ patch(
+ "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
+ new_callable=AsyncMock,
+ return_value=MagicMock(),
+ ):
+ await generate_key_fn(
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ litellm_changed_by=None,
+ )
+
+ # user_id should remain None for admin
+ assert data.user_id is None
+
+ def test_key_generation_check_non_admin_no_team_table_raises(self):
+ """
+ key_generation_check should raise 400 for non-admin when team_table is None
+ and key_generation_settings is not set.
+ """
+ data = GenerateKeyRequest(team_id="some-team-id")
+ user_api_key_dict = UserAPIKeyAuth(
+ user_id="internal-user",
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ )
+
+ with patch.object(litellm, "key_generation_settings", None):
+ with pytest.raises(HTTPException) as exc_info:
+ key_generation_check(
+ team_table=None,
+ user_api_key_dict=user_api_key_dict,
+ data=data,
+ route="key_generate",
+ )
+ assert exc_info.value.status_code == 400
+ assert "Unable to find team object" in str(exc_info.value.detail)
+
+ def test_key_generation_check_admin_no_team_table_allowed(self):
+ """
+ key_generation_check should allow admin to proceed even when team_table is None.
+ """
+ data = GenerateKeyRequest(team_id="some-team-id")
+ user_api_key_dict = UserAPIKeyAuth(
+ user_id="admin-user",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ )
+
+ with patch.object(litellm, "key_generation_settings", None):
+ result = key_generation_check(
+ team_table=None,
+ user_api_key_dict=user_api_key_dict,
+ data=data,
+ route="key_generate",
+ )
+ assert result is True
+
+
+ class TestLIT1884KeyUpdateValidation:
+ """Tests for LIT-1884: internal users should not be able to update keys to remove user_id or set invalid team."""
+
+ @pytest.mark.asyncio
+ async def test_internal_user_cannot_remove_user_id(self):
+ """
+ Non-admin users should not be able to set user_id to empty string (remove it).
+ """
+ data = UpdateKeyRequest(key="sk-test-key", user_id="")
+ existing_key_row = MagicMock()
+ existing_key_row.user_id = "internal-user-123"
+ existing_key_row.token = "hashed_token"
+ existing_key_row.team_id = None
+
+ user_api_key_dict = UserAPIKeyAuth(
+ user_id="internal-user-123",
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await _validate_update_key_data(
+ data=data,
+ existing_key_row=existing_key_row,
+ user_api_key_dict=user_api_key_dict,
+ llm_router=None,
+ premium_user=False,
+ prisma_client=AsyncMock(),
+ user_api_key_cache=MagicMock(),
+ )
+ assert exc_info.value.status_code == 403
+ assert "cannot remove the user_id" in str(exc_info.value.detail)
+
+ @pytest.mark.asyncio
+ async def test_internal_user_cannot_set_invalid_team_id(self):
+ """
+ Non-admin users should not be able to update a key to a non-existent team.
+ get_team_object raises HTTPException(404) when team doesn't exist in DB.
+ """
+ data = UpdateKeyRequest(key="sk-test-key", team_id="nonexistent-team")
+ existing_key_row = MagicMock()
+ existing_key_row.user_id = "internal-user-123"
+ existing_key_row.token = "hashed_token"
+ existing_key_row.team_id = None
+ existing_key_row.organization_id = None
+ existing_key_row.project_id = None
+
+ user_api_key_dict = UserAPIKeyAuth(
+ user_id="internal-user-123",
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ )
+
+ with patch(
+ "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
+ AsyncMock(side_effect=HTTPException(
+ status_code=404,
+ detail="Team doesn't exist in db. Team=nonexistent-team.",
+ )),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await _validate_update_key_data(
+ data=data,
+ existing_key_row=existing_key_row,
+ user_api_key_dict=user_api_key_dict,
+ llm_router=None,
+ premium_user=False,
+ prisma_client=AsyncMock(),
+ user_api_key_cache=MagicMock(),
+ )
+ assert exc_info.value.status_code == 404
+ assert "Team doesn't exist" in str(exc_info.value.detail)
+
+ @pytest.mark.asyncio
+ async def test_admin_can_remove_user_id(self):
+ """
+ Admin users should be allowed to set user_id to empty string.
+ """
+ data = UpdateKeyRequest(key="sk-test-key", user_id="")
+ existing_key_row = MagicMock()
+ existing_key_row.user_id = "some-user"
+ existing_key_row.token = "hashed_token"
+ existing_key_row.team_id = None
+ existing_key_row.organization_id = None
+ existing_key_row.project_id = None
+
+ user_api_key_dict = UserAPIKeyAuth(
+ user_id="admin-user",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ )
+
+ mock_prisma_client = AsyncMock()
+
+ # Should NOT raise
+ await _validate_update_key_data(
+ data=data,
+ existing_key_row=existing_key_row,
+ user_api_key_dict=user_api_key_dict,
+ llm_router=None,
+ premium_user=False,
+ prisma_client=mock_prisma_client,
+ user_api_key_cache=MagicMock(),
+ )
+
+
+ class TestKeyAliasSkipValidationOnUnchanged:
+ """
+ Test that updating/regenerating a key without changing its key_alias
+ does NOT re-validate the alias. This prevents legacy aliases (created
+ before stricter validation rules) from blocking edits to other fields.
+ """
+
+ @pytest.fixture(autouse=True)
+ def enable_validation(self):
+ litellm.enable_key_alias_format_validation = True
+ yield
+ litellm.enable_key_alias_format_validation = False
+
+ @pytest.fixture
+ def mock_prisma(self):
+ prisma = MagicMock()
+ prisma.db = MagicMock()
+ prisma.db.litellm_verificationtoken = MagicMock()
+ prisma.get_data = AsyncMock(return_value=None) # no duplicate alias
+ prisma.update_data = AsyncMock(return_value=None)
+ prisma.jsonify_object = MagicMock(side_effect=lambda data: data)
+ return prisma
+
+ @pytest.fixture
+ def existing_key_with_legacy_alias(self):
+ """A key whose alias contains '@' — valid now, but simulates a legacy alias."""
+ return LiteLLM_VerificationToken(
+ token="hashed_token_123",
+ key_alias="[email protected]",
+ team_id="team-1",
+ models=[],
+ max_budget=100.0,
+ )
+
+ @pytest.mark.asyncio
+ async def test_update_key_unchanged_legacy_alias_passes(
+ self, mock_prisma, existing_key_with_legacy_alias
+ ):
+ """
+ Updating a key without changing its key_alias should skip format
+ validation — even if the alias wouldn't pass current rules.
+ """
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ _validate_key_alias_format,
+ )
+
+ # Temporarily make the regex reject '@' to simulate stricter rules
+ import re
+ from litellm.proxy.management_endpoints import key_management_endpoints as mod
+
+ original_pattern = mod._KEY_ALIAS_PATTERN
+ mod._KEY_ALIAS_PATTERN = re.compile(
+ r"^[a-zA-Z0-9][a-zA-Z0-9_\-/\.]{0,253}[a-zA-Z0-9]$"
+ )
+ try:
+ # Confirm the alias WOULD fail validation directly
+ with pytest.raises(ProxyException):
+ _validate_key_alias_format("[email protected]")
+
+ # But prepare_key_update_data + the skip logic should allow it
+ # Simulate what update_key_fn does: alias is in non_default_values
+ # but matches existing_key_row.key_alias => skip validation
+ existing_alias = existing_key_with_legacy_alias.key_alias
+ new_alias = "[email protected]" # same as existing
+ assert new_alias == existing_alias # unchanged
+
+ # This is the core logic from update_key_fn:
+ if new_alias != existing_alias:
+ _validate_key_alias_format(new_alias)
+ # No exception raised — test passes
+ finally:
+ mod._KEY_ALIAS_PATTERN = original_pattern
+
+ @pytest.mark.asyncio
+ async def test_update_key_changed_alias_still_validated(
+ self, mock_prisma, existing_key_with_legacy_alias
+ ):
+ """
+ When the alias IS being changed, validation should still run.
+ """
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ _validate_key_alias_format,
+ )
+
+ existing_alias = existing_key_with_legacy_alias.key_alias
+ new_alias = "!invalid!"
+
+ assert new_alias != existing_alias
+ with pytest.raises(ProxyException):
+ if new_alias != existing_alias:
+ _validate_key_alias_format(new_alias)
+
+ @pytest.mark.asyncio
+ async def test_update_key_changed_to_valid_alias_passes(
+ self, mock_prisma, existing_key_with_legacy_alias
+ ):
+ """
+ Changing the alias to a new valid value should pass validation.
+ """
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ _validate_key_alias_format,
+ )
+
+ existing_alias = existing_key_with_legacy_alias.key_alias
+ new_alias = "new-valid-alias"
+
+ assert new_alias != existing_alias
+ # Should not raise
+ if new_alias != existing_alias:
+ _validate_key_alias_format(new_alias)
+
+ @pytest.mark.asyncio
+ async def test_update_key_alias_none_skips_validation(self):
+ """
+ When key_alias is not in the update payload (None), validation
+ should be skipped regardless.
+ """
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ _validate_key_alias_format,
+ )
+
+ # None alias should always pass
+ _validate_key_alias_format(None)