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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Merge branch 'main' into litellm_budget_tier_enforcement_for_keys
Shivam Rawat7f655be1915b
diff --cc tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.pyindex 65575167940,efa7d27ec47..a783e15809c--- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py@@@ -5608,137 -5608,123 +5608,253 @@@ async def test_validate_key_list_check_assert "Key Hash not found" in exc_info.value.message+async def test_key_with_budget_id_does_not_store_budget_duration():+ """+ Test that when a key is created with budget_id but without explicit+ budget_duration, the key does NOT get budget_duration stored on it.++ Keys with budget_id follow their linked budget tier's reset schedule;+ reset_budget_for_keys_linked_to_budgets() resets them when the tier resets.+ This avoids duplicating budget_duration on keys so tier updates apply+ automatically to all linked keys.+ """+ from unittest.mock import AsyncMock, MagicMock, patch++ mock_prisma = MagicMock()++ mock_generate_key = AsyncMock(+ return_value={+ "key": "sk-test-key",+ "expires": None,+ "user_id": "test-user",+ "team_id": None,+ }+ )++ with patch(+ "litellm.proxy.proxy_server.prisma_client", mock_prisma+ ), patch(+ "litellm.proxy.proxy_server.llm_router", None+ ), patch(+ "litellm.proxy.proxy_server.premium_user", False+ ), patch(+ "litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"+ ), patch(+ "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",+ mock_generate_key,+ ):+ await _common_key_generation_helper(+ data=GenerateKeyRequest(+ budget_id="7d-budget-tier",+ max_budget=10.0,+ # NOTE: budget_duration is intentionally NOT set here+ ),+ user_api_key_dict=UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN,+ api_key="sk-1234",+ user_id="admin-user",+ ),+ litellm_changed_by=None,+ team_table=None,+ )++ mock_generate_key.assert_awaited_once()+ call_kwargs = mock_generate_key.call_args.kwargs++ # Key should NOT have key_budget_duration - it follows the budget tier's schedule+ assert call_kwargs.get("key_budget_duration") is None, (+ "key_budget_duration should be None for budget-linked keys without explicit "+ f"budget_duration; got: {call_kwargs.get('key_budget_duration')}"+ )++ # No budget tier lookup - we don't copy budget_duration onto the key+ mock_prisma.db.litellm_budgettable.find_unique.assert_not_called()+++async def test_key_does_not_override_explicit_budget_duration():+ """+ Test that when a key is created with both budget_id and an explicit+ budget_duration, the explicit budget_duration takes precedence over+ the budget tier's budget_duration.+ """+ from unittest.mock import AsyncMock, MagicMock, patch++ mock_prisma = MagicMock()+ # The budget tier has budget_duration="7d"+ mock_budget_row = MagicMock()+ mock_budget_row.budget_duration = "7d"+ mock_prisma.db.litellm_budgettable.find_unique = AsyncMock(+ return_value=mock_budget_row+ )++ mock_generate_key = AsyncMock(+ return_value={+ "key": "sk-test-key",+ "expires": None,+ "user_id": "test-user",+ "team_id": None,+ }+ )++ with patch(+ "litellm.proxy.proxy_server.prisma_client", mock_prisma+ ), patch(+ "litellm.proxy.proxy_server.llm_router", None+ ), patch(+ "litellm.proxy.proxy_server.premium_user", False+ ), patch(+ "litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"+ ), patch(+ "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",+ mock_generate_key,+ ):+ await _common_key_generation_helper(+ data=GenerateKeyRequest(+ budget_id="7d-budget-tier",+ max_budget=10.0,+ budget_duration="30d", # explicit budget_duration should take precedence+ ),+ user_api_key_dict=UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN,+ api_key="sk-1234",+ user_id="admin-user",+ ),+ litellm_changed_by=None,+ team_table=None,+ )++ mock_generate_key.assert_awaited_once()+ call_kwargs = mock_generate_key.call_args.kwargs++ # The explicit budget_duration should take precedence+ assert call_kwargs.get("key_budget_duration") == "30d", (+ "Explicit budget_duration should take precedence over the budget tier's value "+ f"but got: {call_kwargs.get('key_budget_duration')}"+ )++ # The budget tier should NOT have been looked up since budget_duration was explicit+ mock_prisma.db.litellm_budgettable.find_unique.assert_not_called()++@pytest.mark.asyncio+ @patch(+ "litellm.proxy.management_endpoints.key_management_endpoints.rotate_mcp_server_credentials_master_key"+ )+ async def test_rotate_master_key_model_data_valid_for_prisma(+ mock_rotate_mcp,+ ):+ """+ Test that _rotate_master_key produces valid data for Prisma create_many().++ Regression test for: master key rotation fails with Prisma validation error+ because created_at/updated_at are None (non-nullable DateTime) and+ litellm_params/model_info are JSON strings (create_many expects dicts).+ """+ from unittest.mock import AsyncMock, MagicMock+ from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+ from litellm.proxy.management_endpoints.key_management_endpoints import (+ _rotate_master_key,+ )++ # Setup mock prisma client+ mock_prisma_client = AsyncMock()+ mock_prisma_client.db = MagicMock()++ # Mock model table — return one model+ mock_model = MagicMock()+ mock_model.model_id = "model-1"+ mock_model.model_name = "test-model"+ mock_model.litellm_params = '{"model": "openai/gpt-4", "api_key": "sk-encrypted-old"}'+ mock_model.model_info = '{"id": "model-1"}'+ mock_model.created_by = "admin"+ mock_model.updated_by = "admin"+ mock_prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(+ return_value=[mock_model]+ )++ # Mock transaction context manager+ mock_tx = AsyncMock()+ mock_tx.litellm_proxymodeltable = MagicMock()+ mock_tx.litellm_proxymodeltable.delete_many = AsyncMock()+ mock_tx.litellm_proxymodeltable.create_many = AsyncMock()+ mock_prisma_client.db.tx = MagicMock(return_value=AsyncMock(+ __aenter__=AsyncMock(return_value=mock_tx),+ __aexit__=AsyncMock(return_value=False),+ ))++ # Mock config table — no env vars+ mock_prisma_client.db.litellm_config.find_many = AsyncMock(return_value=[])++ # Mock credentials table — no credentials+ mock_prisma_client.db.litellm_credentialstable.find_many = AsyncMock(+ return_value=[]+ )++ # Mock MCP rotation+ mock_rotate_mcp.return_value = None++ # Mock proxy_config+ mock_proxy_config = MagicMock()+ mock_proxy_config.decrypt_model_list_from_db.return_value = [+ {+ "model_name": "test-model",+ "litellm_params": {+ "model": "openai/gpt-4",+ "api_key": "sk-decrypted-key",+ },+ "model_info": {"id": "model-1"},+ }+ ]++ user_api_key_dict = UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN,+ api_key="sk-1234",+ user_id="test-user",+ )++ with patch(+ "litellm.proxy.proxy_server.proxy_config",+ mock_proxy_config,+ ):+ await _rotate_master_key(+ prisma_client=mock_prisma_client,+ user_api_key_dict=user_api_key_dict,+ current_master_key="sk-old-master-key",+ new_master_key="sk-new-master-key",+ )++ # Verify create_many was called+ mock_tx.litellm_proxymodeltable.create_many.assert_called_once()++ # Get the data passed to create_many+ call_args = mock_tx.litellm_proxymodeltable.create_many.call_args+ created_models = call_args.kwargs.get("data") or call_args[1].get("data")++ assert len(created_models) == 1+ model_data = created_models[0]++ # Verify timestamps are NOT present (Prisma @default(now()) should apply)+ assert "created_at" not in model_data, (+ "created_at should be excluded so Prisma @default(now()) applies"+ )+ assert "updated_at" not in model_data, (+ "updated_at should be excluded so Prisma @default(now()) applies"+ )++ # Verify litellm_params and model_info are prisma.Json wrappers, NOT JSON strings+ import prisma++ assert isinstance(model_data["litellm_params"], prisma.Json), (+ f"litellm_params should be prisma.Json for create_many(), got {type(model_data['litellm_params'])}"+ )+ assert isinstance(model_data["model_info"], prisma.Json), (+ f"model_info should be prisma.Json for create_many(), got {type(model_data['model_info'])}"+ )++ # Verify delete_many was called inside the transaction (before create_many)+ mock_tx.litellm_proxymodeltable.delete_many.assert_called_once()async def test_default_key_generate_params_duration(monkeypatch):"""Test that default_key_generate_params with 'duration' is applied