diff --git a/enterprise/litellm_enterprise/proxy/management_endpoints/key_management_endpoints.py b/enterprise/litellm_enterprise/proxy/management_endpoints/key_management_endpoints.py index 794568b210b7..5de46bc9e05f 100644 --- a/enterprise/litellm_enterprise/proxy/management_endpoints/key_management_endpoints.py +++ b/enterprise/litellm_enterprise/proxy/management_endpoints/key_management_endpoints.py @@ -17,7 +17,12 @@ def add_team_member_key_duration( team_table.metadata is not None and team_table.metadata.get("team_member_key_duration") is not None ): - data.duration = team_table.metadata["team_member_key_duration"] + team_max = team_table.metadata["team_member_key_duration"] + # Act as a ceiling: only apply team max when the user didn't provide a + # duration. If the user explicitly supplied a shorter duration (already + # validated against team max upstream), respect their value. + if "duration" not in data.model_fields_set: + data.duration = team_max return data diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 4d44006369b5..95ea8ad4187c 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -512,6 +512,14 @@ async def _common_key_generation_helper( # noqa: PLR0915 ) if upperbound_value is not None: if value is None: + if key == "duration" and key in data.model_fields_set: + # Explicitly null = never expires → exceeds any finite upperbound + raise HTTPException( + status_code=400, + detail={ + "error": f"{key} is over max limit set in config - user_value=null (never expires); max_value={upperbound_value}" + }, + ) # Use the upperbound value if user didn't provide a value setattr(data, key, upperbound_value) else: @@ -534,11 +542,14 @@ async def _common_key_generation_helper( # noqa: PLR0915 upperbound_duration = duration_in_seconds( duration=upperbound_value ) - # Handle special case where duration is "-1" (never expires) if value == "-1": - user_duration = float("inf") # Infinite duration - else: - user_duration = duration_in_seconds(duration=value) + raise HTTPException( + status_code=400, + detail={ + "error": "'-1' is no longer a valid duration value. Pass duration: null to set a key to never expire." + }, + ) + user_duration = duration_in_seconds(duration=value) if user_duration > upperbound_duration: raise HTTPException( status_code=400, @@ -547,6 +558,29 @@ async def _common_key_generation_helper( # noqa: PLR0915 }, ) + # Validate key duration against the team's max key duration. + # Only runs when the caller explicitly included "duration" in the request + # (distinguishes "omitted" from "null = never expires"). + if ( + team_table is not None + and team_table.metadata is not None + and team_table.metadata.get("team_member_key_duration") + and "duration" in data.model_fields_set + ): + team_max_duration = team_table.metadata["team_member_key_duration"] + team_max_seconds = duration_in_seconds(duration=team_max_duration) + if data.duration is None: + user_key_duration: float = float("inf") # null = never expires = infinite + else: + user_key_duration = duration_in_seconds(duration=data.duration) + if user_key_duration > team_max_seconds: + raise HTTPException( + status_code=400, + detail={ + "error": f"Key duration exceeds team maximum. Requested: {data.duration}; Team maximum: {team_max_duration}" + }, + ) + # APPLY ENTERPRISE KEY MANAGEMENT PARAMS try: from litellm_enterprise.proxy.management_endpoints.key_management_endpoints import ( @@ -1462,8 +1496,8 @@ async def prepare_key_update_data( if "duration" in non_default_values: duration = non_default_values.pop("duration") - if duration == "-1": - # Set expires to None to indicate the key never expires + if duration is None: + # null (never-expires checkbox) means no expiry non_default_values["expires"] = None elif duration and (isinstance(duration, str)) and len(duration) > 0: duration_s = duration_in_seconds(duration=duration) @@ -1786,7 +1820,7 @@ async def update_key_fn( - tpm_limit_type: Optional[str] - TPM rate limit type - "best_effort_throughput", "guaranteed_throughput", or "dynamic" - rpm_limit_type: Optional[str] - RPM rate limit type - "best_effort_throughput", "guaranteed_throughput", or "dynamic" - allowed_cache_controls: Optional[list] - List of allowed cache control values - - duration: Optional[str] - Key validity duration ("30d", "1h", etc.) or "-1" to never expire + - duration: Optional[str] - Key validity duration ("30d", "1h", etc.) or null to never expire - permissions: Optional[dict] - Key-specific permissions - send_invite_email: Optional[bool] - Send invite email to user_id - guardrails: Optional[List[str]] - List of active guardrails for the key @@ -3372,6 +3406,68 @@ async def _insert_deprecated_key( "Failed to insert deprecated key for grace period: %s", deprecated_err, ) +async def _validate_regenerate_key_duration_against_team( + data: Optional[RegenerateKeyRequest], + key_in_db: LiteLLM_VerificationToken, + prisma_client: PrismaClient, + user_api_key_cache: DualCache, +) -> None: + """Raise HTTP 400 if the requested duration exceeds the team's max key duration.""" + if data is None: + return + + # Service account keys are exempt from team member duration limits, + # mirroring the enterprise add_team_member_key_duration guard. + if getattr(key_in_db, "user_id", None) is None: + return + + # Determine the user's requested duration in seconds. + # Distinguish "duration not sent" (leave unchanged) from "duration: null" (never expires). + if data.duration is None: + if "duration" not in data.model_fields_set: + return # Not provided — leave the existing expiry unchanged + user_seconds: float = float("inf") # Explicitly null = never expires + else: + user_seconds = duration_in_seconds(duration=data.duration) + + team_id = getattr(key_in_db, "team_id", None) + if not team_id: + return + + try: + team_table = await get_team_object( + team_id=team_id, + prisma_client=prisma_client, + user_api_key_cache=user_api_key_cache, + parent_otel_span=None, + ) + except Exception as e: + verbose_proxy_logger.warning( + "Could not look up team %s for duration validation during key regeneration, skipping check: %s", + team_id, + str(e), + ) + return + + if ( + team_table is None + or team_table.metadata is None + or not team_table.metadata.get("team_member_key_duration") + ): + return + + team_max_duration = team_table.metadata["team_member_key_duration"] + team_max_seconds = duration_in_seconds(duration=team_max_duration) + + if user_seconds > team_max_seconds: + raise HTTPException( + status_code=400, + detail={ + "error": f"Key duration exceeds team maximum. Requested: {data.duration}; Team maximum: {team_max_duration}" + }, + ) + + async def _execute_virtual_key_regeneration( *, prisma_client: PrismaClient, @@ -3387,6 +3483,13 @@ async def _execute_virtual_key_regeneration( """Generate new token, update DB, invalidate cache, and return response.""" from litellm.proxy.proxy_server import hash_token + await _validate_regenerate_key_duration_against_team( + data=data, + key_in_db=key_in_db, + prisma_client=prisma_client, + user_api_key_cache=user_api_key_cache, + ) + new_token = get_new_token(data=data) new_token_hash = hash_token(new_token) new_token_key_name = f"sk-...{new_token[-4:]}" diff --git a/tests/proxy_unit_tests/test_proxy_utils.py b/tests/proxy_unit_tests/test_proxy_utils.py index f7101085f0f9..6cf0bb8da6c9 100644 --- a/tests/proxy_unit_tests/test_proxy_utils.py +++ b/tests/proxy_unit_tests/test_proxy_utils.py @@ -678,8 +678,8 @@ async def test_prepare_key_update_data(): updated_data = await prepare_key_update_data(data, existing_key_row) assert updated_data["metadata"] is None - # Test duration "-1" sets expires to None (never expires) - data = UpdateKeyRequest(key="test_key", duration="-1") + # Test duration=null sets expires to None (never expires) + data = UpdateKeyRequest(key="test_key", duration=None) updated_data = await prepare_key_update_data(data, existing_key_row) assert updated_data["expires"] is None diff --git a/tests/test_litellm/enterprise/proxy/test_key_duration_ceiling.py b/tests/test_litellm/enterprise/proxy/test_key_duration_ceiling.py new file mode 100644 index 000000000000..8be95e8cbdce --- /dev/null +++ b/tests/test_litellm/enterprise/proxy/test_key_duration_ceiling.py @@ -0,0 +1,126 @@ +""" +Tests for add_team_member_key_duration ceiling behavior. + +team_member_key_duration acts as a ceiling: +- Not provided by user → apply team max as default +- Provided and shorter than team max → respect user's value +- No team / no metadata / no team_member_key_duration → leave unchanged +- Service account (user_id=None) → leave unchanged +""" + +import importlib.util +import os +import sys + +import pytest +from unittest.mock import MagicMock + +from litellm.proxy._types import GenerateKeyRequest, LiteLLM_TeamTable + +_ENTERPRISE_SOURCE = os.path.normpath( + os.path.join( + os.path.dirname(__file__), + "..", "..", "..", "..", + "enterprise", "litellm_enterprise", "proxy", + "management_endpoints", "key_management_endpoints.py", + ) +) + +pytestmark = pytest.mark.skipif( + not os.path.exists(_ENTERPRISE_SOURCE), + reason=f"Enterprise source not available at {_ENTERPRISE_SOURCE}", +) + + +def _load_local_add_team_member_key_duration(): + """Load add_team_member_key_duration from the local enterprise source tree.""" + module_name = "_local_enterprise_key_management_endpoints" + # Remove cached version so we always reload from the local file + sys.modules.pop(module_name, None) + spec = importlib.util.spec_from_file_location(module_name, _ENTERPRISE_SOURCE) + module = importlib.util.module_from_spec(spec) # type: ignore[arg-type] + spec.loader.exec_module(module) # type: ignore[union-attr] + return module.add_team_member_key_duration + + +def _make_team(duration: str) -> LiteLLM_TeamTable: + team = MagicMock(spec=LiteLLM_TeamTable) + team.metadata = {"team_member_key_duration": duration} + return team + + +class TestAddTeamMemberKeyDuration: + def test_no_duration_provided_uses_team_max(self): + """User omits duration → team max is applied as the default.""" + fn = _load_local_add_team_member_key_duration() + + data = GenerateKeyRequest(user_id="user-1") + assert "duration" not in data.model_fields_set + + result = fn(_make_team("30d"), data) + + assert result.duration == "30d" + + def test_shorter_duration_respected(self): + """User provides a duration shorter than team max → their value is kept.""" + fn = _load_local_add_team_member_key_duration() + + data = GenerateKeyRequest(user_id="user-1", duration="5d") + assert "duration" in data.model_fields_set + + result = fn(_make_team("30d"), data) + + assert result.duration == "5d" + + def test_duration_equal_to_team_max_respected(self): + """User provides duration equal to team max → their value is kept.""" + fn = _load_local_add_team_member_key_duration() + + data = GenerateKeyRequest(user_id="user-1", duration="30d") + result = fn(_make_team("30d"), data) + + assert result.duration == "30d" + + def test_no_team_returns_unchanged(self): + """team_table=None → data is returned unchanged.""" + fn = _load_local_add_team_member_key_duration() + + data = GenerateKeyRequest(user_id="user-1") + result = fn(None, data) + + assert result.duration is None + + def test_no_metadata_returns_unchanged(self): + """Team has no metadata → data is returned unchanged.""" + fn = _load_local_add_team_member_key_duration() + + team = MagicMock(spec=LiteLLM_TeamTable) + team.metadata = None + + data = GenerateKeyRequest(user_id="user-1") + result = fn(team, data) + + assert result.duration is None + + def test_no_team_member_key_duration_returns_unchanged(self): + """team_member_key_duration absent from metadata → data is returned unchanged.""" + fn = _load_local_add_team_member_key_duration() + + team = MagicMock(spec=LiteLLM_TeamTable) + team.metadata = {} + + data = GenerateKeyRequest(user_id="user-1") + result = fn(team, data) + + assert result.duration is None + + def test_service_account_returns_unchanged(self): + """user_id=None (service account) → team duration is NOT applied.""" + fn = _load_local_add_team_member_key_duration() + + data = GenerateKeyRequest(user_id=None) + result = fn(_make_team("30d"), data) + + # Verify the service-account guard prevented the team max from being applied + assert result.duration is None, "Service account should not inherit team duration" + assert result.duration != "30d" diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index 11c803518393..fc2ecce9df8b 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -1058,7 +1058,7 @@ async def test_update_service_account_works_with_team_id(): @pytest.mark.asyncio async def test_prepare_key_update_data_duration_never_expires(): - """Test that duration="-1" sets expires to None (never expires).""" + """Test that duration=null sets expires to None (never expires).""" from litellm.proxy._types import UpdateKeyRequest from litellm.proxy.management_endpoints.key_management_endpoints import ( prepare_key_update_data, @@ -1076,8 +1076,8 @@ async def test_prepare_key_update_data_duration_never_expires(): metadata={}, ) - # Test setting duration to "-1" (never expires) - update_request = UpdateKeyRequest(key="test-token", duration="-1") + # Test setting duration to null (never expires) + update_request = UpdateKeyRequest(key="test-token", duration=None) result = await prepare_key_update_data( data=update_request, existing_key_row=existing_key @@ -6436,7 +6436,7 @@ def test_validate_key_alias_format_valid(self): def test_validate_key_alias_format_invalid(self): from litellm.proxy.management_endpoints.key_management_endpoints import _validate_key_alias_format from litellm.proxy._types import ProxyException - + invalid_aliases = [ "", # empty " ", # whitespace @@ -6449,9 +6449,464 @@ def test_validate_key_alias_format_invalid(self): " leading", "trailing ", ] - + for alias in invalid_aliases: with pytest.raises(ProxyException) as exc: _validate_key_alias_format(alias) assert str(exc.value.code) == "400" assert "Invalid key_alias format" in str(exc.value.message) + + +class TestUpperboundNullDurationValidation: + """Tests for upperbound validation when duration is explicitly null (never expires).""" + + @pytest.mark.asyncio + async def test_explicit_null_duration_raises_when_upperbound_set(self): + """duration=null (never expires) should raise 400 when upperbound duration is set.""" + import litellm + from litellm.types.proxy.management_endpoints.ui_sso import ( + LiteLLM_UpperboundKeyGenerateParams, + ) + + original = litellm.upperbound_key_generate_params + try: + litellm.upperbound_key_generate_params = ( + LiteLLM_UpperboundKeyGenerateParams(duration="30d") + ) + with pytest.raises(HTTPException) as exc_info: + await _common_key_generation_helper( + data=GenerateKeyRequest(user_id="user-1", duration=None), + user_api_key_dict=UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1" + ), + litellm_changed_by=None, + team_table=None, + ) + assert exc_info.value.status_code == 400 + assert "never expires" in str(exc_info.value.detail).lower() + finally: + litellm.upperbound_key_generate_params = original + + @pytest.mark.asyncio + async def test_omitted_duration_uses_upperbound_as_default(self): + """Duration not sent → upperbound is applied as default (no error).""" + import litellm + from litellm.types.proxy.management_endpoints.ui_sso import ( + LiteLLM_UpperboundKeyGenerateParams, + ) + + original = litellm.upperbound_key_generate_params + try: + litellm.upperbound_key_generate_params = ( + LiteLLM_UpperboundKeyGenerateParams(duration="30d") + ) + with patch( + "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn", + new_callable=AsyncMock, + return_value={ + "key": "sk-test", + "expires": None, + "user_id": "user-1", + }, + ), patch("litellm.proxy.proxy_server.prisma_client"), patch( + "litellm.proxy.proxy_server.llm_router" + ), patch( + "litellm.proxy.proxy_server.premium_user", False + ): + # Should not raise — duration omitted, so upperbound fills in as default + await _common_key_generation_helper( + data=GenerateKeyRequest(user_id="user-1"), + user_api_key_dict=UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1" + ), + litellm_changed_by=None, + team_table=None, + ) + finally: + litellm.upperbound_key_generate_params = original + + +class TestCommonKeyGenerationHelperTeamDurationValidation: + """Tests for team duration validation inside _common_key_generation_helper.""" + + @pytest.mark.asyncio + async def test_duration_exceeds_team_max_raises(self): + """Raises HTTP 400 when the requested duration exceeds the team's max.""" + team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + team.metadata = {"team_member_key_duration": "5d"} + + with pytest.raises(HTTPException) as exc_info: + await _common_key_generation_helper( + data=GenerateKeyRequest(user_id="user-1", duration="10d"), + user_api_key_dict=UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1" + ), + litellm_changed_by=None, + team_table=team, + ) + assert exc_info.value.status_code == 400 + assert "Team maximum" in str(exc_info.value.detail) + + @pytest.mark.asyncio + async def test_never_expires_exceeds_team_max_raises(self): + """duration=null (never expires) exceeds any finite team max.""" + team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + team.metadata = {"team_member_key_duration": "30d"} + + with pytest.raises(HTTPException) as exc_info: + await _common_key_generation_helper( + data=GenerateKeyRequest(user_id="user-1", duration=None), + user_api_key_dict=UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1" + ), + litellm_changed_by=None, + team_table=team, + ) + assert exc_info.value.status_code == 400 + assert "Team maximum" in str(exc_info.value.detail) + + @pytest.mark.asyncio + async def test_duration_within_team_max_passes(self): + """Duration within the team max proceeds past the validation block.""" + team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + team.metadata = {"team_member_key_duration": "5d"} + + with patch( + "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn", + new_callable=AsyncMock, + return_value={"key": "sk-test", "expires": None, "user_id": "user-1"}, + ), patch("litellm.proxy.proxy_server.prisma_client"), patch( + "litellm.proxy.proxy_server.llm_router" + ), patch( + "litellm.proxy.proxy_server.premium_user", False + ): + await _common_key_generation_helper( + data=GenerateKeyRequest(user_id="user-1", duration="3d"), + user_api_key_dict=UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1" + ), + litellm_changed_by=None, + team_table=team, + ) + + @pytest.mark.asyncio + async def test_duration_not_sent_skips_team_validation(self): + """Duration field absent from request — team validation is skipped.""" + team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + team.metadata = {"team_member_key_duration": "5d"} + + with patch( + "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn", + new_callable=AsyncMock, + return_value={"key": "sk-test", "expires": None, "user_id": "user-1"}, + ), patch("litellm.proxy.proxy_server.prisma_client"), patch( + "litellm.proxy.proxy_server.llm_router" + ), patch( + "litellm.proxy.proxy_server.premium_user", False + ): + await _common_key_generation_helper( + data=GenerateKeyRequest(user_id="user-1"), + user_api_key_dict=UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1" + ), + litellm_changed_by=None, + team_table=team, + ) + + @pytest.mark.asyncio + async def test_no_team_skips_team_validation(self): + """No team_table — team duration validation is skipped.""" + with patch( + "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn", + new_callable=AsyncMock, + return_value={"key": "sk-test", "expires": None, "user_id": "user-1"}, + ), patch("litellm.proxy.proxy_server.prisma_client"), patch( + "litellm.proxy.proxy_server.llm_router" + ), patch( + "litellm.proxy.proxy_server.premium_user", False + ): + await _common_key_generation_helper( + data=GenerateKeyRequest(user_id="user-1", duration="100d"), + user_api_key_dict=UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1" + ), + litellm_changed_by=None, + team_table=None, + ) + + @pytest.mark.asyncio + async def test_team_max_not_set_skips_validation(self): + """No team_member_key_duration in metadata — any user duration is accepted.""" + team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + team.metadata = {} # no team_member_key_duration + + with patch( + "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn", + new_callable=AsyncMock, + return_value={"key": "sk-test", "expires": None, "user_id": "user-1"}, + ), patch("litellm.proxy.proxy_server.prisma_client"), patch( + "litellm.proxy.proxy_server.llm_router" + ), patch( + "litellm.proxy.proxy_server.premium_user", False + ): + # Should not raise even though "999d" would otherwise exceed any finite team max + await _common_key_generation_helper( + data=GenerateKeyRequest(user_id="user-1", duration="999d"), + user_api_key_dict=UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1" + ), + litellm_changed_by=None, + team_table=team, + ) + + +class TestValidateRegenerateKeyDurationAgainstTeam: + """Tests for _validate_regenerate_key_duration_against_team.""" + + @pytest.mark.asyncio + async def test_no_data_skips_validation(self): + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _validate_regenerate_key_duration_against_team, + ) + + mock_key = MagicMock(spec=LiteLLM_VerificationToken) + mock_key.team_id = "team-123" + mock_key.user_id = "user-123" + mock_prisma = AsyncMock() + mock_cache = MagicMock() + # Should not raise + await _validate_regenerate_key_duration_against_team( + data=None, + key_in_db=mock_key, + prisma_client=mock_prisma, + user_api_key_cache=mock_cache, + ) + + @pytest.mark.asyncio + async def test_duration_not_sent_skips_validation(self): + """Duration field absent from request (leave existing expiry unchanged).""" + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _validate_regenerate_key_duration_against_team, + ) + from litellm.proxy._types import RegenerateKeyRequest + + mock_key = MagicMock(spec=LiteLLM_VerificationToken) + mock_key.team_id = "team-123" + mock_key.user_id = "user-123" + # No duration kwarg at all → not in model_fields_set + data = RegenerateKeyRequest() + mock_prisma = AsyncMock() + mock_cache = MagicMock() + # Should not raise + await _validate_regenerate_key_duration_against_team( + data=data, + key_in_db=mock_key, + prisma_client=mock_prisma, + user_api_key_cache=mock_cache, + ) + + @pytest.mark.asyncio + async def test_null_duration_treated_as_never_expires_raises_when_team_has_limit(self): + """duration=null (Never Expires checkbox) is treated as infinite and rejected when team has a limit.""" + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _validate_regenerate_key_duration_against_team, + ) + from litellm.proxy._types import RegenerateKeyRequest, LiteLLM_TeamTableCachedObj + + mock_key = MagicMock(spec=LiteLLM_VerificationToken) + mock_key.team_id = "team-123" + mock_key.user_id = "user-123" + # Explicitly set duration=None → "duration" IS in model_fields_set + data = RegenerateKeyRequest(duration=None) + assert "duration" in data.model_fields_set + + mock_team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + mock_team.metadata = {"team_member_key_duration": "5d"} + + mock_prisma = AsyncMock() + mock_cache = MagicMock() + + with patch( + "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object", + new_callable=AsyncMock, + return_value=mock_team, + ): + with pytest.raises(HTTPException) as exc_info: + await _validate_regenerate_key_duration_against_team( + data=data, + key_in_db=mock_key, + prisma_client=mock_prisma, + user_api_key_cache=mock_cache, + ) + assert exc_info.value.status_code == 400 + + @pytest.mark.asyncio + async def test_team_max_not_set_skips_validation(self): + """No team_member_key_duration in metadata — skip validation regardless of user duration.""" + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _validate_regenerate_key_duration_against_team, + ) + from litellm.proxy._types import RegenerateKeyRequest, LiteLLM_TeamTableCachedObj + + mock_key = MagicMock(spec=LiteLLM_VerificationToken) + mock_key.team_id = "team-123" + mock_key.user_id = "user-123" + data = RegenerateKeyRequest(duration="999d") + + mock_team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + mock_team.metadata = {} # no team_member_key_duration + + mock_prisma = AsyncMock() + mock_cache = MagicMock() + + with patch( + "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object", + new_callable=AsyncMock, + return_value=mock_team, + ): + # Should not raise — no team max set + await _validate_regenerate_key_duration_against_team( + data=data, + key_in_db=mock_key, + prisma_client=mock_prisma, + user_api_key_cache=mock_cache, + ) + + @pytest.mark.asyncio + async def test_no_team_id_skips_validation(self): + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _validate_regenerate_key_duration_against_team, + ) + from litellm.proxy._types import RegenerateKeyRequest + + mock_key = MagicMock(spec=LiteLLM_VerificationToken) + mock_key.team_id = None + mock_key.user_id = "user-123" + data = RegenerateKeyRequest(duration="10d") + mock_prisma = AsyncMock() + mock_cache = MagicMock() + # Should not raise + await _validate_regenerate_key_duration_against_team( + data=data, + key_in_db=mock_key, + prisma_client=mock_prisma, + user_api_key_cache=mock_cache, + ) + + @pytest.mark.asyncio + async def test_service_account_key_skips_validation(self): + """Service account keys (user_id=None) are exempt from team duration limits.""" + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _validate_regenerate_key_duration_against_team, + ) + from litellm.proxy._types import RegenerateKeyRequest + + mock_key = MagicMock(spec=LiteLLM_VerificationToken) + mock_key.team_id = "team-123" + mock_key.user_id = None # service account key has no user_id + data = RegenerateKeyRequest(duration="999d") + mock_prisma = AsyncMock() + mock_cache = MagicMock() + # Should not raise even though "999d" would exceed a finite team max + await _validate_regenerate_key_duration_against_team( + data=data, + key_in_db=mock_key, + prisma_client=mock_prisma, + user_api_key_cache=mock_cache, + ) + + @pytest.mark.asyncio + async def test_duration_within_team_max_passes(self): + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _validate_regenerate_key_duration_against_team, + ) + from litellm.proxy._types import RegenerateKeyRequest, LiteLLM_TeamTableCachedObj + + mock_key = MagicMock(spec=LiteLLM_VerificationToken) + mock_key.team_id = "team-123" + mock_key.user_id = "user-123" + data = RegenerateKeyRequest(duration="3d") + + mock_team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + mock_team.metadata = {"team_member_key_duration": "5d"} + + mock_prisma = AsyncMock() + mock_cache = MagicMock() + + with patch( + "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object", + new_callable=AsyncMock, + return_value=mock_team, + ): + # Should not raise + await _validate_regenerate_key_duration_against_team( + data=data, + key_in_db=mock_key, + prisma_client=mock_prisma, + user_api_key_cache=mock_cache, + ) + + @pytest.mark.asyncio + async def test_duration_exceeds_team_max_raises(self): + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _validate_regenerate_key_duration_against_team, + ) + from litellm.proxy._types import RegenerateKeyRequest, LiteLLM_TeamTableCachedObj + + mock_key = MagicMock(spec=LiteLLM_VerificationToken) + mock_key.team_id = "team-123" + mock_key.user_id = "user-123" + data = RegenerateKeyRequest(duration="10d") + + mock_team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + mock_team.metadata = {"team_member_key_duration": "5d"} + + mock_prisma = AsyncMock() + mock_cache = MagicMock() + + with patch( + "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object", + new_callable=AsyncMock, + return_value=mock_team, + ): + with pytest.raises(HTTPException) as exc_info: + await _validate_regenerate_key_duration_against_team( + data=data, + key_in_db=mock_key, + prisma_client=mock_prisma, + user_api_key_cache=mock_cache, + ) + assert exc_info.value.status_code == 400 + assert "Team maximum" in str(exc_info.value.detail) + + @pytest.mark.asyncio + async def test_never_expires_duration_exceeds_team_max_raises(self): + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _validate_regenerate_key_duration_against_team, + ) + from litellm.proxy._types import RegenerateKeyRequest, LiteLLM_TeamTableCachedObj + + mock_key = MagicMock(spec=LiteLLM_VerificationToken) + mock_key.team_id = "team-123" + mock_key.user_id = "user-123" + data = RegenerateKeyRequest(duration=None) # null = never expires = infinite + + mock_team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + mock_team.metadata = {"team_member_key_duration": "30d"} + + mock_prisma = AsyncMock() + mock_cache = MagicMock() + + with patch( + "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object", + new_callable=AsyncMock, + return_value=mock_team, + ): + with pytest.raises(HTTPException) as exc_info: + await _validate_regenerate_key_duration_against_team( + data=data, + key_in_db=mock_key, + prisma_client=mock_prisma, + user_api_key_cache=mock_cache, + ) + assert exc_info.value.status_code == 400 diff --git a/ui/litellm-dashboard/src/components/common_components/KeyLifecycleSettings.tsx b/ui/litellm-dashboard/src/components/common_components/KeyLifecycleSettings.tsx index 0f29a47d1dc4..3b0f27a0cbdc 100644 --- a/ui/litellm-dashboard/src/components/common_components/KeyLifecycleSettings.tsx +++ b/ui/litellm-dashboard/src/components/common_components/KeyLifecycleSettings.tsx @@ -1,5 +1,5 @@ import React, { useState } from "react"; -import { Select, Tooltip, Divider, Switch } from "antd"; +import { Select, Tooltip, Divider, Switch, Checkbox } from "antd"; import { InfoCircleOutlined } from "@ant-design/icons"; import { TextInput } from "@tremor/react"; @@ -11,7 +11,7 @@ interface KeyLifecycleSettingsProps { onAutoRotationChange: (enabled: boolean) => void; rotationInterval: string; onRotationIntervalChange: (interval: string) => void; - isCreateMode?: boolean; // If true, shows "leave empty to never expire" instead of "-1 to never expire" + isCreateMode?: boolean; } const KeyLifecycleSettings: React.FC = ({ @@ -31,6 +31,7 @@ const KeyLifecycleSettings: React.FC = ({ const [showCustomInput, setShowCustomInput] = useState(isCustomInterval); const [customInterval, setCustomInterval] = useState(isCustomInterval ? rotationInterval : ""); const [durationValue, setDurationValue] = useState(form?.getFieldValue?.("duration") || ""); + const [neverExpires, setNeverExpires] = useState(false); const handleIntervalChange = (value: string) => { if (value === "custom") { @@ -57,6 +58,27 @@ const KeyLifecycleSettings: React.FC = ({ form.setFieldsValue({ duration: value }); } }; + + const handleNeverExpiresChange = (e: any) => { + const checked = e.target.checked; + setNeverExpires(checked); + if (checked) { + setDurationValue(""); + if (form && typeof form.setFieldValue === "function") { + form.setFieldValue("duration", null); + } else if (form && typeof form.setFieldsValue === "function") { + form.setFieldsValue({ duration: null }); + } + } else { + // Clear the null so duration is omitted from the request (not sent as never-expires) + if (form && typeof form.setFieldValue === "function") { + form.setFieldValue("duration", undefined); + } else if (form && typeof form.setFieldsValue === "function") { + form.setFieldsValue({ duration: undefined }); + } + } + }; + return (
{/* Key Expiry Section */} @@ -64,24 +86,24 @@ const KeyLifecycleSettings: React.FC = ({ Key Expiry Settings
-
diff --git a/ui/litellm-dashboard/src/components/organisms/create_key_button.tsx b/ui/litellm-dashboard/src/components/organisms/create_key_button.tsx index 802dfd14b635..bfc545cd7016 100644 --- a/ui/litellm-dashboard/src/components/organisms/create_key_button.tsx +++ b/ui/litellm-dashboard/src/components/organisms/create_key_button.tsx @@ -350,9 +350,11 @@ const CreateKey: React.FC = ({ team, teams, data, addKey }) => { formValues.rotation_interval = rotationInterval; } - // Handle duration field for key expiry - convert empty string to null - if (!formValues.duration || formValues.duration.trim() === "") { - formValues.duration = null; + // Handle duration field for key expiry: + // - null means Never Expires (explicitly set by checkbox) — keep as-is + // - empty string or undefined means not provided — omit entirely + if (formValues.duration !== null && (!formValues.duration || formValues.duration.trim() === "")) { + delete formValues.duration; } // Update the formValues with the final metadata @@ -1407,7 +1409,7 @@ const CreateKey: React.FC = ({ team, teams, data, addKey }) => { /> -