From 3ed3255c47d9988a47d96c0dba883b57464d0594 Mon Sep 17 00:00:00 2001 From: yuneng-jiang Date: Tue, 3 Mar 2026 14:06:54 -0800 Subject: [PATCH 1/9] [Fix] Key Expiry Validation Against Team Max Duration Virtual keys created or regenerated with a duration exceeding the team's team_member_key_duration limit were silently accepted. On creation, the backend silently capped the value giving the user a misleading success response. On regeneration, the user value was stored as-is, bypassing the team limit entirely. Add a duration check in _common_key_generation_helper (key creation) and a _validate_regenerate_key_duration_against_team helper called from _execute_virtual_key_regeneration (key regeneration). Both raise HTTP 400 when the requested duration exceeds the team maximum. Co-Authored-By: Claude Sonnet 4.6 --- .../key_management_endpoints.py | 77 +++++ .../test_key_management_endpoints.py | 268 +++++++++++++++++- 2 files changed, 343 insertions(+), 2 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 4d44006369b5..52dd142ea7e8 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -547,6 +547,27 @@ async def _common_key_generation_helper( # noqa: PLR0915 }, ) + # Validate key duration against the team's max key duration + if ( + team_table is not None + and team_table.metadata is not None + and team_table.metadata.get("team_member_key_duration") + and data.duration is not None + ): + team_max_duration = team_table.metadata["team_member_key_duration"] + team_max_seconds = duration_in_seconds(duration=team_max_duration) + if data.duration == "-1": + user_key_duration: float = float("inf") + 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 ( @@ -3372,6 +3393,55 @@ 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 or not data.duration: + return + + 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, + check_db_only=True, + ) + except Exception: + 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 data.duration == "-1": + user_seconds: float = float("inf") + else: + user_seconds = duration_in_seconds(duration=data.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 +3457,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/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index 11c803518393..278dc522ab13 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 @@ -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,273 @@ 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 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 '-1' (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="-1"), + 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_no_duration_skips_team_validation(self): + """No duration provided — 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", duration=None), + 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, + ) + + +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_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_no_duration_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 = "team-123" + data = RegenerateKeyRequest(duration=None) + 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_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 + 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_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" + 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" + 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" + data = RegenerateKeyRequest(duration="-1") + + 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 From b2ed580eff9a0d3fd1c97b661d771f4a73032439 Mon Sep 17 00:00:00 2001 From: yuneng-jiang Date: Tue, 3 Mar 2026 14:20:07 -0800 Subject: [PATCH 2/9] Log warning when team lookup fails during key regeneration duration check The broad except was silently swallowing errors, which could allow the team max duration to be bypassed if get_team_object raised. Add a warning log so bypasses are visible in audit trails while preserving fail-open behavior consistent with the same team lookup pattern in generate_key_fn. Co-Authored-By: Claude Sonnet 4.6 --- .../proxy/management_endpoints/key_management_endpoints.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 52dd142ea7e8..9eafb000a63e 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -3415,7 +3415,12 @@ async def _validate_regenerate_key_duration_against_team( parent_otel_span=None, check_db_only=True, ) - except Exception: + 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 ( From 62c174d455a87d48baad66131a27a3ef474f9501 Mon Sep 17 00:00:00 2001 From: yuneng-jiang Date: Tue, 3 Mar 2026 14:49:59 -0800 Subject: [PATCH 3/9] [Fix] Key Expiry: treat null as never-expires, guard -1 team max, add Never Expires checkbox MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - In `_validate_regenerate_key_duration_against_team`: use `model_fields_set` to distinguish "duration not sent" (leave unchanged) from "duration: null" (never expires / infinite). Guard against team max being "-1" (no limit) before calling `duration_in_seconds` which would crash on that sentinel. - In `_common_key_generation_helper`: same "-1" guard for team max duration so the creation path no longer crashes when the team has no configured limit. - In `prepare_key_update_data`: treat `duration is None` the same as `"-1"` — both set `expires = None` (never expires). - UI: replace the "Enter -1 for unlimited expiry" pattern in `KeyLifecycleSettings.tsx` and `regenerate_key_modal.tsx` with a "Never Expires" checkbox mirroring the budget unlimited approach. - Tests: add/fix tests for all new cases (null-as-infinite, team max "-1" skips, not-sent skips via model_fields_set). Co-Authored-By: Claude Sonnet 4.6 --- .../key_management_endpoints.py | 52 ++++++---- .../test_key_management_endpoints.py | 96 ++++++++++++++++++- .../KeyLifecycleSettings.tsx | 43 ++++++--- .../organisms/regenerate_key_modal.tsx | 43 ++++++++- 4 files changed, 193 insertions(+), 41 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 9eafb000a63e..84cc3b6e8c6b 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -555,18 +555,20 @@ async def _common_key_generation_helper( # noqa: PLR0915 and data.duration is not None ): team_max_duration = team_table.metadata["team_member_key_duration"] - team_max_seconds = duration_in_seconds(duration=team_max_duration) - if data.duration == "-1": - user_key_duration: float = float("inf") - 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}" - }, - ) + # "-1" on the team side means no limit is enforced + if team_max_duration != "-1": + team_max_seconds = duration_in_seconds(duration=team_max_duration) + if data.duration == "-1": + user_key_duration: float = float("inf") + 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: @@ -1483,8 +1485,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 == "-1" or duration is None: + # "-1" (legacy) or null (never-expires checkbox) both mean no expiry non_default_values["expires"] = None elif duration and (isinstance(duration, str)) and len(duration) > 0: duration_s = duration_in_seconds(duration=duration) @@ -3400,9 +3402,20 @@ async def _validate_regenerate_key_duration_against_team( user_api_key_cache: DualCache, ) -> None: """Raise HTTP 400 if the requested duration exceeds the team's max key duration.""" - if data is None or not data.duration: + if data 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 + elif data.duration == "-1": + user_seconds = float("inf") # Legacy sentinel for 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 @@ -3431,12 +3444,11 @@ async def _validate_regenerate_key_duration_against_team( return team_max_duration = team_table.metadata["team_member_key_duration"] - team_max_seconds = duration_in_seconds(duration=team_max_duration) + # "-1" on the team side means no limit is enforced + if team_max_duration == "-1": + return - if data.duration == "-1": - user_seconds: float = float("inf") - else: - user_seconds = duration_in_seconds(duration=data.duration) + team_max_seconds = duration_in_seconds(duration=team_max_duration) if user_seconds > team_max_seconds: raise HTTPException( 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 278dc522ab13..4c7f5981f5a5 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 @@ -6565,6 +6565,31 @@ async def test_no_team_skips_team_validation(self): team_table=None, ) + @pytest.mark.asyncio + async def test_team_max_minus_one_skips_validation(self): + """team_member_key_duration='-1' means no limit — any user duration is accepted.""" + team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + team.metadata = {"team_member_key_duration": "-1"} + + 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.""" @@ -6588,7 +6613,8 @@ async def test_no_data_skips_validation(self): ) @pytest.mark.asyncio - async def test_no_duration_skips_validation(self): + 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, ) @@ -6596,7 +6622,8 @@ async def test_no_duration_skips_validation(self): mock_key = MagicMock(spec=LiteLLM_VerificationToken) mock_key.team_id = "team-123" - data = RegenerateKeyRequest(duration=None) + # No duration kwarg at all → not in model_fields_set + data = RegenerateKeyRequest() mock_prisma = AsyncMock() mock_cache = MagicMock() # Should not raise @@ -6607,6 +6634,71 @@ async def test_no_duration_skips_validation(self): 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" + # 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_duration_minus_one_skips_validation(self): + """team_member_key_duration='-1' means no team limit — 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" + data = RegenerateKeyRequest(duration="999d") + + mock_team = MagicMock(spec=LiteLLM_TeamTableCachedObj) + mock_team.metadata = {"team_member_key_duration": "-1"} + + 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 — team max is "-1" (no limit) + 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 ( diff --git a/ui/litellm-dashboard/src/components/common_components/KeyLifecycleSettings.tsx b/ui/litellm-dashboard/src/components/common_components/KeyLifecycleSettings.tsx index 0f29a47d1dc4..e7a0bff41a8d 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,20 @@ 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 }); + } + } + }; + return (
{/* Key Expiry Section */} @@ -64,24 +79,24 @@ const KeyLifecycleSettings: React.FC = ({ Key Expiry Settings
-
diff --git a/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsx b/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsx index 2fad101c20fb..6142bcffb789 100644 --- a/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsx +++ b/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsx @@ -1,6 +1,6 @@ import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized"; import { Button, Col, Grid, Text, TextInput, Title } from "@tremor/react"; -import { Form, InputNumber, Modal } from "antd"; +import { Checkbox, Form, InputNumber, Modal } from "antd"; import { add } from "date-fns"; import { useEffect, useState } from "react"; import { CopyToClipboard } from "react-copy-to-clipboard"; @@ -22,6 +22,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat const [regenerateFormData, setRegenerateFormData] = useState(null); const [newExpiryTime, setNewExpiryTime] = useState(null); const [isRegenerating, setIsRegenerating] = useState(false); + const [neverExpires, setNeverExpires] = useState(false); // Track whether this is the user's own authentication key const [isOwnKey, setIsOwnKey] = useState(false); @@ -31,12 +32,14 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat useEffect(() => { if (visible && selectedToken && accessToken) { + const currentlyNeverExpires = !selectedToken.expires; + setNeverExpires(currentlyNeverExpires); form.setFieldsValue({ key_alias: selectedToken.key_alias, max_budget: selectedToken.max_budget, tpm_limit: selectedToken.tpm_limit, rpm_limit: selectedToken.rpm_limit, - duration: selectedToken.duration || "", + duration: currentlyNeverExpires ? null : (selectedToken.duration || ""), grace_period: "", }); @@ -56,6 +59,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat setIsRegenerating(false); setIsOwnKey(false); setCurrentAccessToken(null); + setNeverExpires(false); form.resetFields(); } }, [visible, form]); @@ -98,6 +102,13 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat try { const formValues = await form.validateFields(); + // Translate "Never Expires" checkbox to an explicit null duration + if (neverExpires) { + formValues.duration = null; + } else if (!formValues.duration || formValues.duration.trim() === "") { + delete formValues.duration; // Not provided — leave existing expiry unchanged + } + // Use the current access token for the API call const response = await regenerateKeyCall( currentAccessToken, @@ -217,13 +228,35 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat - - + + Expire Key (eg: 30s, 30h, 30d) + { + const checked = e.target.checked; + setNeverExpires(checked); + if (checked) { + form.setFieldValue("duration", null); + setRegenerateFormData((prev: any) => ({ ...prev, duration: null })); + } + }} + > + Never Expires + + + } + name="duration" + className="mt-8" + > +
Current expiry: {selectedToken?.expires ? new Date(selectedToken.expires).toLocaleString() : "Never"}
- {newExpiryTime &&
New expiry: {newExpiryTime}
} + {!neverExpires && newExpiryTime &&
New expiry: {newExpiryTime}
} + {neverExpires &&
New expiry: Never
} Date: Tue, 3 Mar 2026 15:50:45 -0800 Subject: [PATCH 4/9] [Fix] Key Expiry: remove -1 magic number, use null for never-expires Replace the legacy "-1" sentinel string with proper null semantics: - User duration: null means never-expires (no more "-1" accepted) - Team max: absence of the field means no limit (no more "-1" stored) - Creation path team validation now uses model_fields_set to distinguish "duration not sent" (skip) from "duration: null" (never-expires, validate) - Tests updated: -1 sentinels replaced with None, -1 team max tests replaced with "field not set" equivalent Co-Authored-By: Claude Sonnet 4.6 --- .../key_management_endpoints.py | 50 ++++++++----------- tests/proxy_unit_tests/test_proxy_utils.py | 4 +- .../test_key_management_endpoints.py | 32 ++++++------ 3 files changed, 38 insertions(+), 48 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 84cc3b6e8c6b..82db6e140e84 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -534,11 +534,7 @@ 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) + user_duration = duration_in_seconds(duration=value) if user_duration > upperbound_duration: raise HTTPException( status_code=400, @@ -547,28 +543,28 @@ async def _common_key_generation_helper( # noqa: PLR0915 }, ) - # Validate key duration against the team's max key duration + # 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 data.duration is not None + and "duration" in data.model_fields_set ): team_max_duration = team_table.metadata["team_member_key_duration"] - # "-1" on the team side means no limit is enforced - if team_max_duration != "-1": - team_max_seconds = duration_in_seconds(duration=team_max_duration) - if data.duration == "-1": - user_key_duration: float = float("inf") - 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}" - }, - ) + 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: @@ -1485,8 +1481,8 @@ async def prepare_key_update_data( if "duration" in non_default_values: duration = non_default_values.pop("duration") - if duration == "-1" or duration is None: - # "-1" (legacy) or null (never-expires checkbox) both mean no expiry + 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) @@ -1809,7 +1805,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 @@ -3411,8 +3407,6 @@ async def _validate_regenerate_key_duration_against_team( 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 - elif data.duration == "-1": - user_seconds = float("inf") # Legacy sentinel for never-expires else: user_seconds = duration_in_seconds(duration=data.duration) @@ -3444,10 +3438,6 @@ async def _validate_regenerate_key_duration_against_team( return team_max_duration = team_table.metadata["team_member_key_duration"] - # "-1" on the team side means no limit is enforced - if team_max_duration == "-1": - return - team_max_seconds = duration_in_seconds(duration=team_max_duration) if user_seconds > team_max_seconds: 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/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index 4c7f5981f5a5..3fb4b1149d69 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 @@ -6480,13 +6480,13 @@ async def test_duration_exceeds_team_max_raises(self): @pytest.mark.asyncio async def test_never_expires_exceeds_team_max_raises(self): - """Duration '-1' (never expires) exceeds any finite team max.""" + """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="-1"), + data=GenerateKeyRequest(user_id="user-1", duration=None), user_api_key_dict=UserAPIKeyAuth( user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1" ), @@ -6521,8 +6521,8 @@ async def test_duration_within_team_max_passes(self): ) @pytest.mark.asyncio - async def test_no_duration_skips_team_validation(self): - """No duration provided — team validation is skipped.""" + 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"} @@ -6536,7 +6536,7 @@ async def test_no_duration_skips_team_validation(self): "litellm.proxy.proxy_server.premium_user", False ): await _common_key_generation_helper( - data=GenerateKeyRequest(user_id="user-1", duration=None), + data=GenerateKeyRequest(user_id="user-1"), user_api_key_dict=UserAPIKeyAuth( user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1" ), @@ -6566,10 +6566,10 @@ async def test_no_team_skips_team_validation(self): ) @pytest.mark.asyncio - async def test_team_max_minus_one_skips_validation(self): - """team_member_key_duration='-1' means no limit — any user duration is accepted.""" + 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 = {"team_member_key_duration": "-1"} + team.metadata = {} # no team_member_key_duration with patch( "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn", @@ -6669,8 +6669,8 @@ async def test_null_duration_treated_as_never_expires_raises_when_team_has_limit assert exc_info.value.status_code == 400 @pytest.mark.asyncio - async def test_team_max_duration_minus_one_skips_validation(self): - """team_member_key_duration='-1' means no team limit — skip validation regardless of user duration.""" + 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, ) @@ -6681,7 +6681,7 @@ async def test_team_max_duration_minus_one_skips_validation(self): data = RegenerateKeyRequest(duration="999d") mock_team = MagicMock(spec=LiteLLM_TeamTableCachedObj) - mock_team.metadata = {"team_member_key_duration": "-1"} + mock_team.metadata = {} # no team_member_key_duration mock_prisma = AsyncMock() mock_cache = MagicMock() @@ -6691,7 +6691,7 @@ async def test_team_max_duration_minus_one_skips_validation(self): new_callable=AsyncMock, return_value=mock_team, ): - # Should not raise — team max is "-1" (no limit) + # Should not raise — no team max set await _validate_regenerate_key_duration_against_team( data=data, key_in_db=mock_key, @@ -6790,7 +6790,7 @@ async def test_never_expires_duration_exceeds_team_max_raises(self): mock_key = MagicMock(spec=LiteLLM_VerificationToken) mock_key.team_id = "team-123" - data = RegenerateKeyRequest(duration="-1") + data = RegenerateKeyRequest(duration=None) # null = never expires = infinite mock_team = MagicMock(spec=LiteLLM_TeamTableCachedObj) mock_team.metadata = {"team_member_key_duration": "30d"} From 4b8b7bb557394299d7dbda48db16aaaf94f1a552 Mon Sep 17 00:00:00 2001 From: yuneng-jiang Date: Thu, 5 Mar 2026 15:07:44 -0800 Subject: [PATCH 5/9] [Fix] Key Expiry: return 400 for legacy -1 duration, fix Never Expires uncheck - Return HTTP 400 with a clear migration message when duration="-1" is passed to the upperbound validation path, instead of crashing with an unhandled ValueError (500). - Fix KeyLifecycleSettings: add else branch to handleNeverExpiresChange so unchecking "Never Expires" resets the form's duration field to undefined, preventing it from being submitted as null (never-expires). Co-Authored-By: Claude Sonnet 4.6 --- .../proxy/management_endpoints/key_management_endpoints.py | 7 +++++++ .../components/common_components/KeyLifecycleSettings.tsx | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 82db6e140e84..45542cba7a3e 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -534,6 +534,13 @@ async def _common_key_generation_helper( # noqa: PLR0915 upperbound_duration = duration_in_seconds( duration=upperbound_value ) + if value == "-1": + 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( diff --git a/ui/litellm-dashboard/src/components/common_components/KeyLifecycleSettings.tsx b/ui/litellm-dashboard/src/components/common_components/KeyLifecycleSettings.tsx index e7a0bff41a8d..3b0f27a0cbdc 100644 --- a/ui/litellm-dashboard/src/components/common_components/KeyLifecycleSettings.tsx +++ b/ui/litellm-dashboard/src/components/common_components/KeyLifecycleSettings.tsx @@ -69,6 +69,13 @@ const KeyLifecycleSettings: React.FC = ({ } 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 }); + } } }; From 6c8eea67a5e9ecd392488ff3a42e477697580159 Mon Sep 17 00:00:00 2001 From: yuneng-jiang Date: Thu, 5 Mar 2026 15:27:29 -0800 Subject: [PATCH 6/9] [Fix] Key Expiry: omit duration from payload when not set by user - create_key_button: remove initialValue={null} on hidden duration field; change submit handler to delete duration when empty/undefined rather than converting to null, so untouched expiry settings don't accidentally trigger never-expires behavior on the backend. - key_edit_view: remove initialValue="" on hidden duration field; add same duration cleanup to handleSubmit so an untouched field sends no duration key instead of an empty string. - In both cases duration: null is preserved (Never Expires checkbox). Co-Authored-By: Claude Sonnet 4.6 --- .../src/components/organisms/create_key_button.tsx | 10 ++++++---- .../src/components/templates/key_edit_view.tsx | 7 ++++++- 2 files changed, 12 insertions(+), 5 deletions(-) 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 }) => { /> -