Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
105 changes: 98 additions & 7 deletions litellm/proxy/management_endpoints/key_management_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
},
)
Comment on lines 545 to +551

Copy link
Copy Markdown
Contributor

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" to float("inf") (infinite duration). This PR changes it to raise HTTP 400 instead.

While the UI is updated to use null instead of "-1", API clients that directly call /key/generate with duration: "-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:

  • Keeping the old "-1" β†’ infinite behaviour (and separately restricting it if a team max applies), or
  • Returning a clear deprecation warning (via response headers or a non-error field in the response) rather than a hard 400, with the hard rejection gated behind a config flag.

Context Used: Rule from dashboard - What: avoid backwards-incompatible changes without user-controlled flags

Why: This breaks current ... (source)

user_duration = duration_in_seconds(duration=value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regression: removed "-1" guard causes ValueError

This line previously had special handling for value == "-1" (mapping it to float("inf")). That branch was removed in this PR, so now duration_in_seconds("-1") is called directly. The regex in _extract_from_regex (r"(\d+)(mo|[smhdw]?)") doesn't match "-1" (negative sign is not a digit), causing an unhandled ValueError.

While the UI now sends null instead of "-1", API users calling /key/generate directly with duration: "-1" will hit this crash. Previously they got a clean 400 response; now they get an unhandled 500.

Consider preserving the guard here:

Suggested change
user_duration = duration_in_seconds(duration=value)
if value is None:
user_duration = float("inf")
else:
user_duration = duration_in_seconds(duration=value)

This mirrors the null-means-infinite convention used in the new team validation block below.

if user_duration > upperbound_duration:
raise HTTPException(
status_code=400,
Expand All @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unhandled ValueError if team max duration is "-1"

If an admin sets team_member_key_duration to "-1" in the team metadata, duration_in_seconds("-1") will raise a ValueError because the parser regex ((\d+)(mo|[smhdw]?)) doesn't match negative numbers. The user-provided duration correctly handles "-1" with the special float("inf") branch, but the team max side does not.

This applies to both this block (line 558) and the regeneration helper (line 3434). Consider adding a symmetric check:

Suggested change
team_max_duration = team_table.metadata["team_member_key_duration"]
team_max_seconds = duration_in_seconds(duration=team_max_duration)
team_max_duration = team_table.metadata["team_member_key_duration"]
if team_max_duration == "-1":
team_max_seconds: float = float("inf")
else:
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 (
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

duration: "-1" crashes /key/update with unhandled ValueError

The change from duration == "-1" to duration is None removes the guard that previously mapped "-1" to expires = None. Now if an API caller sends duration: "-1" to /key/update (which was the documented "never expires" sentinel for this endpoint until this PR), it falls into the elif branch and calls duration_in_seconds("-1"). The regex in _extract_from_regex only matches digits and unit suffixes, so "-1" raises an unhandled ValueError, resulting in an HTTP 500.

Previously: duration == "-1" β†’ expires = None (never expires).
Now: duration == "-1" β†’ duration_in_seconds("-1") β†’ ValueError / 500 crash.

To handle both gracefully β€” preserving backward compat for existing callers while also accepting the new null convention β€” consider rejecting "-1" with a clean 400 similar to the approach in _common_key_generation_helper:

        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"] = expires

Context Used: Rule from dashboard - What: avoid backwards-incompatible changes without user-controlled flags

Why: This breaks current ... (source)

duration_s = duration_in_seconds(duration=duration)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 _insert_deprecated_key (line 3395) and the start of _validate_regenerate_key_duration_against_team (line 3396).

Suggested change
)
async def _validate_regenerate_key_duration_against_team(
)
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

# 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The enterprise add_team_member_key_duration function explicitly skips service accounts with if data.user_id is None: return data. The regeneration helper has no equivalent guard, so service account keys will be subject to team member duration validation during regeneration even though the creation-time check does not apply to them.

Add a consistent check after retrieving the key from the database:

Suggested change
team_id = getattr(key_in_db, "team_id", None)
if not team_id:
return
team_id = getattr(key_in_db, "team_id", None)
if not team_id:
return
if getattr(key_in_db, "user_id", None) is None:
return # service account keys are exempt from team member duration limits


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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check_db_only=True bypasses cache on every regeneration

get_team_object is called with check_db_only=True, which forces a direct database query and skips the in-memory/dual cache. This means every key-regeneration request incurs a synchronous DB round-trip purely for duration validation, even if the team object is already cached.

Consider omitting check_db_only=True so the helper uses the existing cache layer and falls back to the DB only on a cache miss. This aligns with the project guideline of avoiding unnecessary direct DB queries.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bare except silently skips validation

The broad except Exception on line 3418 catches all errors from get_team_object (including DB connectivity issues, timeouts, etc.) and silently returns, skipping the duration validation entirely. Since this PR is specifically fixing a security gap where the regeneration endpoint bypassed the team's max duration, silently skipping validation on any error re-introduces the same bypass.

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 HTTPException specifically and only return on status_code == 404, re-raising otherwise.


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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same "-1" crash risk for team max duration

Same issue as the key creation path β€” if team_member_key_duration is "-1", duration_in_seconds("-1") will raise ValueError. Apply the same fix here:

Suggested change
team_max_duration = team_table.metadata["team_member_key_duration"]
team_max_seconds = duration_in_seconds(duration=team_max_duration)
team_max_duration = team_table.metadata["team_member_key_duration"]
if team_max_duration == "-1":
team_max_seconds: float = float("inf")
else:
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,
Expand All @@ -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:]}"
Expand Down
4 changes: 2 additions & 2 deletions tests/proxy_unit_tests/test_proxy_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
118 changes: 118 additions & 0 deletions tests/test_litellm/enterprise/proxy/test_key_duration_ceiling.py
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fragile dynamic import may fail silently if enterprise module is absent

_load_local_add_team_member_key_duration() uses importlib.util.spec_from_file_location to load the enterprise module via a hard-coded path. If the enterprise directory is missing (open-source install) or the layout changes, spec.loader.exec_module(module) will raise AttributeError at module import time, causing the entire test suite to fail with a confusing error instead of a clear skip message.

Add an explicit guard with pytest.skip:

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test_service_account_returns_unchanged has weak assertion that doesn't exercise the guard

The test constructs GenerateKeyRequest(user_id=None) and asserts result.duration is None. However, GenerateKeyRequest defaults duration to None, so this assertion would pass even if the service-account guard (the if data.user_id is None: return data branch on line 13 of the enterprise module) were accidentally removed.

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

Loading
Loading