Repository navigation
[Fix] Key Expiry Default Duration #22712
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 7 commits
3ed3255
b2ed580
62c174d
1a5a6e7
4b8b7bb
6c8eea6
fe6fe25
ca0aef1
74b4ab2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -534,11 +534,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) | ||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Regression: removed This line previously had special handling for While the UI now sends Consider preserving the guard here:
Suggested change
This mirrors the |
||||||||||||||||||||
| if user_duration > upperbound_duration: | ||||||||||||||||||||
| raise HTTPException( | ||||||||||||||||||||
| status_code=400, | ||||||||||||||||||||
|
|
@@ -547,6 +550,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) | ||||||||||||||||||||
|
Comment on lines
+570
to
+571
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Unhandled If an admin sets This applies to both this block (line 558) and the regeneration helper (line 3434). Consider adding a symmetric check:
Suggested change
|
||||||||||||||||||||
| 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 +1488,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: | ||||||||||||||||||||
|
Comment on lines
+1499
to
1502
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The change from Previously: To handle both gracefully β preserving backward compat for existing callers while also accepting the new if duration is None:
# null (never-expires checkbox) means no expiry
non_default_values["expires"] = None
elif duration == "-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."
},
)
elif duration and (isinstance(duration, str)) and len(duration) > 0:
duration_s = duration_in_seconds(duration=duration)
expires = datetime.now(timezone.utc) + timedelta(seconds=duration_s)
non_default_values["expires"] = expiresContext Used: Rule from Why: This breaks current ... (source) |
||||||||||||||||||||
| duration_s = duration_in_seconds(duration=duration) | ||||||||||||||||||||
|
|
@@ -1786,7 +1812,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 +3398,64 @@ async def _insert_deprecated_key( | |||||||||||||||||||
| "Failed to insert deprecated key for grace period: %s", | ||||||||||||||||||||
| deprecated_err, | ||||||||||||||||||||
| ) | ||||||||||||||||||||
| async def _validate_regenerate_key_duration_against_team( | ||||||||||||||||||||
|
Comment on lines
3408
to
+3409
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Missing blank line between functions PEP 8 requires two blank lines between top-level function definitions. There's no blank line between the end of
Suggested change
|
||||||||||||||||||||
| 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 | ||||||||||||||||||||
|
|
||||||||||||||||||||
| # 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 | ||||||||||||||||||||
|
Comment on lines
+3433
to
+3435
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The enterprise Add a consistent check after retrieving the key from the database:
Suggested change
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| 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, | ||||||||||||||||||||
| ) | ||||||||||||||||||||
|
Comment on lines
+3437
to
+3443
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Consider omitting |
||||||||||||||||||||
| 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 | ||||||||||||||||||||
|
Comment on lines
+3437
to
+3450
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bare The broad Consider narrowing the exception to only catch "team not found" (HTTP 404) or failing closed (rejecting the request when the team can't be looked up). For example, catch |
||||||||||||||||||||
|
|
||||||||||||||||||||
| 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) | ||||||||||||||||||||
|
Comment on lines
+3459
to
+3460
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same Same issue as the key creation path β if
Suggested change
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| 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 +3471,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:]}" | ||||||||||||||||||||
|
|
||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| """ | ||
| 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 | ||
|
|
||
|
|
||
| def _load_local_add_team_member_key_duration(): | ||
| """Load add_team_member_key_duration from the local enterprise source tree.""" | ||
| local_path = os.path.normpath( | ||
| os.path.join( | ||
| os.path.dirname(__file__), | ||
| "..", "..", "..", "..", | ||
| "enterprise", "litellm_enterprise", "proxy", | ||
| "management_endpoints", "key_management_endpoints.py", | ||
| ) | ||
| ) | ||
| 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, local_path) | ||
| 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 | ||
|
Comment on lines
+35
to
+43
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fragile dynamic import may fail silently if enterprise module is absent
Add an explicit guard with def _load_local_add_team_member_key_duration():
"""Load add_team_member_key_duration from the local enterprise source tree."""
local_path = os.path.normpath(
os.path.join(
os.path.dirname(__file__),
"..", "..", "..", "..",
"enterprise", "litellm_enterprise", "proxy",
"management_endpoints", "key_management_endpoints.py",
)
)
if not os.path.exists(local_path):
pytest.skip("enterprise module not found")
module_name = "_local_enterprise_key_management_endpoints"
sys.modules.pop(module_name, None)
spec = importlib.util.spec_from_file_location(module_name, local_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
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) β data is returned unchanged.""" | ||
| fn = _load_local_add_team_member_key_duration() | ||
|
|
||
| data = GenerateKeyRequest(user_id=None) | ||
| result = fn(_make_team("30d"), data) | ||
|
|
||
| assert result.duration is None | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The test constructs A stronger test would explicitly set a non-default duration to verify the guard actually prevented modification: def test_service_account_returns_unchanged(self):
"""user_id=None (service account) β data is returned unchanged."""
fn = _load_local_add_team_member_key_duration()
data = GenerateKeyRequest(user_id=None)
data.duration = "99d" # service account: set a non-default to make the guard observable
result = fn(_make_team("30d"), data)
assert result.duration == "99d" # guard fired; team max was NOT applied |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Breaking change for existing API clients using
duration: "-1"The enterprise params validation block previously mapped
value == "-1"tofloat("inf")(infinite duration). This PR changes it to raise HTTP 400 instead.While the UI is updated to use
nullinstead of"-1", API clients that directly call/key/generatewithduration: "-1"β which was previously documented and silently accepted β will now receive an unexpected 400 error. This is a backwards-incompatible change with no migration path or feature flag, meaning existing integrations break silently on upgrade.Per the project's compatibility policy, breaking changes to existing behavior should be guarded by a user-controlled flag rather than changed unconditionally. Consider either:
"-1"β infinite behaviour (and separately restricting it if a team max applies), orContext Used: Rule from
dashboard- What: avoid backwards-incompatible changes without user-controlled flagsWhy: This breaks current ... (source)