The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix: virutal key grace period from env/UI
Harshit Jain768f9a44b21a
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.mdindex 264c7d765b3..1a1bf975d2d 100644--- a/docs/my-website/docs/proxy/config_settings.md+++ b/docs/my-website/docs/proxy/config_settings.md@@ -755,6 +755,7 @@ router_settings:| LITELM_ENVIRONMENT | Environment of LiteLLM Instance, used by logging services. Currently only used by DeepEval.| LITELLM_KEY_ROTATION_ENABLED | Enable auto-key rotation for LiteLLM (boolean). Default is false.| LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS | Interval in seconds for how often to run job that auto-rotates keys. Default is 86400 (24 hours).+| LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS | Hours to keep old key valid after rotation (e.g. 24, 48, 72). Default is 0 (immediate revoke). Used for scheduled rotations and as fallback when not specified in regenerate request.| LITELLM_LICENSE | License key for LiteLLM usage| LITELLM_LOCAL_MODEL_COST_MAP | Local configuration for model cost mapping in LiteLLM| LITELLM_LOG | Enable detailed logging for LiteLLMdiff --git a/docs/my-website/docs/proxy/virtual_keys.md b/docs/my-website/docs/proxy/virtual_keys.mdindex 38ff4ede280..31506ea2611 100644--- a/docs/my-website/docs/proxy/virtual_keys.md+++ b/docs/my-website/docs/proxy/virtual_keys.md@@ -549,11 +549,14 @@ curl 'http://localhost:4000/key/sk-1234/regenerate' \"models": ["gpt-4","gpt-3.5-turbo"- ]+ ],+ "grace_period_hours": 48}'```+**Grace period (optional)**: Set `grace_period_hours` (e.g. 24, 48, 72) to keep the old key valid for a transitional period. Both old and new keys work until the grace period elapses, enabling seamless cutover without production downtime. Default is 0 (immediate revoke). Can also be set via `LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS` for scheduled rotations.+**Read More**- [Write rotated keys to secrets manager](https://docs.litellm.ai/docs/secret#aws-secret-manager)@@ -640,11 +643,13 @@ Set these environment variables when starting the proxy:|----------|-------------|---------|| `LITELLM_KEY_ROTATION_ENABLED` | Enable the rotation worker | `false` || `LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS` | How often to scan for keys to rotate (in seconds) | `86400` (24 hours) |+| `LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS` | Hours to keep old key valid after rotation (24–72 recommended) | `0` (immediate revoke) |**Example:**```bashexport LITELLM_KEY_ROTATION_ENABLED=trueexport LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS=3600 # Check every hour+export LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS=48 # Keep old key valid for 48h during cutoverlitellm --config config.yaml```diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260203120000_add_deprecated_verification_token_table/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260203120000_add_deprecated_verification_token_table/migration.sqlnew file mode 100644index 00000000000..51d88444191--- /dev/null+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260203120000_add_deprecated_verification_token_table/migration.sql@@ -0,0 +1,19 @@+-- CreateTable+CREATE TABLE "LiteLLM_DeprecatedVerificationToken" (+ "id" TEXT NOT NULL,+ "token" TEXT NOT NULL,+ "active_token_id" TEXT NOT NULL,+ "revoke_at" TIMESTAMP(3) NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "LiteLLM_DeprecatedVerificationToken_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "LiteLLM_DeprecatedVerificationToken_token_key" ON "LiteLLM_DeprecatedVerificationToken"("token");++-- CreateIndex+CREATE INDEX "LiteLLM_DeprecatedVerificationToken_token_revoke_at_idx" ON "LiteLLM_DeprecatedVerificationToken"("token", "revoke_at");++-- CreateIndex+CREATE INDEX "LiteLLM_DeprecatedVerificationToken_revoke_at_idx" ON "LiteLLM_DeprecatedVerificationToken"("revoke_at");diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prismaindex 3b81da10923..8992f4d8df6 100644--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma@@ -317,6 +317,19 @@ model LiteLLM_VerificationToken {@@index([budget_reset_at, expires])}+// Deprecated keys during grace period - allows old key to work until revoke_at+model LiteLLM_DeprecatedVerificationToken {+ id String @id @default(uuid())+ token String // Hashed old key+ active_token_id String // Current token hash in LiteLLM_VerificationToken+ revoke_at DateTime // When the old key stops working+ created_at DateTime @default(now()) @map("created_at")++ @@unique([token])+ @@index([token, revoke_at])+ @@index([revoke_at])+}+// Audit table for deleted keys - preserves spend and key information for historical trackingmodel LiteLLM_DeletedVerificationToken {id String @id @default(uuid())diff --git a/litellm/constants.py b/litellm/constants.pyindex 6427c367924..7625d55f003 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -125,15 +125,19 @@ _DEFAULT_TTL_FOR_HTTPX_CLIENTS = 3600 # 1 hour, re-use the same httpx client fo# Aiohttp connection pooling - prevents memory leaks from unbounded connection growth# Set to 0 for unlimited (not recommended for production)AIOHTTP_CONNECTOR_LIMIT = int(os.getenv("AIOHTTP_CONNECTOR_LIMIT", 300))-AIOHTTP_CONNECTOR_LIMIT_PER_HOST = int(os.getenv("AIOHTTP_CONNECTOR_LIMIT_PER_HOST", 50))+AIOHTTP_CONNECTOR_LIMIT_PER_HOST = int(+ os.getenv("AIOHTTP_CONNECTOR_LIMIT_PER_HOST", 50)+)AIOHTTP_KEEPALIVE_TIMEOUT = int(os.getenv("AIOHTTP_KEEPALIVE_TIMEOUT", 120))AIOHTTP_TTL_DNS_CACHE = int(os.getenv("AIOHTTP_TTL_DNS_CACHE", 300))# enable_cleanup_closed is only needed for Python versions with the SSL leak bug# Fixed in Python 3.12.7+ and 3.13.1+ (see https://github.com/python/cpython/pull/118960)# Reference: https://github.com/aio-libs/aiohttp/blob/master/aiohttp/connector.py#L74-L78-AIOHTTP_NEEDS_CLEANUP_CLOSED = (- (3, 13, 0) <= sys.version_info < (3, 13, 1) or sys.version_info < (3, 12, 7)-)+AIOHTTP_NEEDS_CLEANUP_CLOSED = (3, 13, 0) <= sys.version_info < (+ 3,+ 13,+ 1,+) or sys.version_info < (3, 12, 7)# WebSocket constants# Default to None (unlimited) to match OpenAI's official agents SDK behavior@@ -171,7 +175,9 @@ REDIS_UPDATE_BUFFER_KEY = "litellm_spend_update_buffer"REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_spend_update_buffer"REDIS_DAILY_TEAM_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_team_spend_update_buffer"REDIS_DAILY_ORG_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_org_spend_update_buffer"-REDIS_DAILY_END_USER_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_end_user_spend_update_buffer"+REDIS_DAILY_END_USER_SPEND_UPDATE_BUFFER_KEY = (+ "litellm_daily_end_user_spend_update_buffer"+)REDIS_DAILY_AGENT_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_agent_spend_update_buffer"REDIS_DAILY_TAG_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_tag_spend_update_buffer"MAX_REDIS_BUFFER_DEQUEUE_COUNT = int(os.getenv("MAX_REDIS_BUFFER_DEQUEUE_COUNT", 100))@@ -297,7 +303,9 @@ MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB = int(DEFAULT_MAX_TOKENS_FOR_TRITON = int(os.getenv("DEFAULT_MAX_TOKENS_FOR_TRITON", 2000))#### Networking settings ####request_timeout: float = float(os.getenv("REQUEST_TIMEOUT", 6000)) # time in seconds-DEFAULT_A2A_AGENT_TIMEOUT: float = float(os.getenv("DEFAULT_A2A_AGENT_TIMEOUT", 6000)) # 10 minutes+DEFAULT_A2A_AGENT_TIMEOUT: float = float(+ os.getenv("DEFAULT_A2A_AGENT_TIMEOUT", 6000)+) # 10 minutesSTREAM_SSE_DONE_STRING: str = "[DONE]"STREAM_SSE_DATA_PREFIX: str = "data: "### SPEND TRACKING ###@@ -333,8 +341,12 @@ DD_TRACER_STREAMING_CHUNK_YIELD_RESOURCE = os.getenv("DD_TRACER_STREAMING_CHUNK_YIELD_RESOURCE", "streaming.chunk.yield")-EMAIL_BUDGET_ALERT_TTL = int(os.getenv("EMAIL_BUDGET_ALERT_TTL", 24 * 60 * 60)) # 24 hours in seconds-EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE = float(os.getenv("EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE", 0.8)) # 80% of max budget+EMAIL_BUDGET_ALERT_TTL = int(+ os.getenv("EMAIL_BUDGET_ALERT_TTL", 24 * 60 * 60)+) # 24 hours in seconds+EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE = float(+ os.getenv("EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE", 0.8)+) # 80% of max budget############### LLM Provider Constants ################## ANTHROPIC CONSTANTS ###ANTHROPIC_TOKEN_COUNTING_BETA_VERSION = os.getenv(@@ -1082,7 +1094,17 @@ known_tokenizer_config = {}-OPENAI_FINISH_REASONS = ["stop", "length", "function_call", "content_filter", "null", "finish_reason_unspecified", "malformed_function_call", "guardrail_intervened", "eos"]+OPENAI_FINISH_REASONS = [+ "stop",+ "length",+ "function_call",+ "content_filter",+ "null",+ "finish_reason_unspecified",+ "malformed_function_call",+ "guardrail_intervened",+ "eos",+]HUMANLOOP_PROMPT_CACHE_TTL_SECONDS = int(os.getenv("HUMANLOOP_PROMPT_CACHE_TTL_SECONDS", 60)) # 1 minute@@ -1172,6 +1194,9 @@ LITELLM_KEY_ROTATION_ENABLED = os.getenv("LITELLM_KEY_ROTATION_ENABLED", "false"LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS = int(os.getenv("LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS", 86400)) # 24 hours default+LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS = int(+ os.getenv("LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS", 0)+) # Hours to keep old key valid after rotation; 0 = immediate revoke (default)UI_SESSION_TOKEN_TEAM_ID = "litellm-dashboard"LITELLM_PROXY_ADMIN_NAME = "default_user_id"@@ -1182,8 +1207,8 @@ CLI_SSO_SESSION_CACHE_KEY_PREFIX = "cli_sso_session"CLI_JWT_TOKEN_NAME = "cli-jwt-token"# Support both CLI_JWT_EXPIRATION_HOURS and LITELLM_CLI_JWT_EXPIRATION_HOURS for backwards compatibilityCLI_JWT_EXPIRATION_HOURS = int(- os.getenv("CLI_JWT_EXPIRATION_HOURS")- or os.getenv("LITELLM_CLI_JWT_EXPIRATION_HOURS")+ os.getenv("CLI_JWT_EXPIRATION_HOURS")+ or os.getenv("LITELLM_CLI_JWT_EXPIRATION_HOURS")or 24)@@ -1361,9 +1386,7 @@ MICROSOFT_USER_EMAIL_ATTRIBUTE = str(MICROSOFT_USER_DISPLAY_NAME_ATTRIBUTE = str(os.getenv("MICROSOFT_USER_DISPLAY_NAME_ATTRIBUTE", "displayName"))-MICROSOFT_USER_ID_ATTRIBUTE = str(- os.getenv("MICROSOFT_USER_ID_ATTRIBUTE", "id")-)+MICROSOFT_USER_ID_ATTRIBUTE = str(os.getenv("MICROSOFT_USER_ID_ATTRIBUTE", "id"))MICROSOFT_USER_FIRST_NAME_ATTRIBUTE = str(os.getenv("MICROSOFT_USER_FIRST_NAME_ATTRIBUTE", "givenName"))diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 9ae95085f55..dd3f83713f8 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -359,7 +359,6 @@ class LiteLLMRoutes(enum.Enum):"/v1/vector_stores/{vector_store_id}/files/{file_id}/content","/vector_store/list","/v1/vector_store/list",-# search"/search","/v1/search",@@ -986,6 +985,9 @@ class RegenerateKeyRequest(GenerateKeyRequest):spend: Optional[float] = Nonemetadata: Optional[dict] = Nonenew_master_key: Optional[str] = None+ grace_period_hours: Optional[+ int+ ] = None # Hours to keep old key valid; 0/None = immediate revokeclass ResetSpendRequest(LiteLLMPydanticObjectBase):diff --git a/litellm/proxy/common_utils/key_rotation_manager.py b/litellm/proxy/common_utils/key_rotation_manager.pyindex 13bbf2272f7..7ef26bf07b9 100644--- a/litellm/proxy/common_utils/key_rotation_manager.py+++ b/litellm/proxy/common_utils/key_rotation_manager.py@@ -8,7 +8,10 @@ from datetime import datetime, timezonefrom typing import Listfrom litellm._logging import verbose_proxy_logger-from litellm.constants import LITELLM_INTERNAL_JOBS_SERVICE_ACCOUNT_NAME+from litellm.constants import (+ LITELLM_INTERNAL_JOBS_SERVICE_ACCOUNT_NAME,+ LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS,+)from litellm.proxy._types import (GenerateKeyResponse,LiteLLM_VerificationToken,@@ -37,6 +40,9 @@ class KeyRotationManager:try:verbose_proxy_logger.info("Starting scheduled key rotation check...")+ # Clean up expired deprecated keys first+ await self._cleanup_expired_deprecated_keys()+# Find keys that are due for rotationkeys_to_rotate = await self._find_keys_needing_rotation()@@ -97,6 +103,24 @@ class KeyRotationManager:return keys_with_rotation+ async def _cleanup_expired_deprecated_keys(self) -> None:+ """+ Remove deprecated key entries whose revoke_at has passed.+ """+ try:+ now = datetime.now(timezone.utc)+ result = await self.prisma_client.db.litellm_deprecatedverificationtoken.delete_many(+ where={"revoke_at": {"lt": now}}+ )+ if result.get("count", 0) > 0:+ verbose_proxy_logger.debug(+ "Cleaned up %s expired deprecated key(s)", result["count"]+ )+ except Exception as e:+ verbose_proxy_logger.debug(+ "Deprecated key cleanup skipped (table may not exist): %s", e+ )+def _should_rotate_key(self, key: LiteLLM_VerificationToken, now: datetime) -> bool:"""Determine if a key should be rotated based on key_rotation_at timestamp.@@ -115,10 +139,11 @@ class KeyRotationManager:"""Rotate a single key using existing regenerate_key_fn and call the rotation hook"""- # Create regenerate request+ # Create regenerate request with grace period for seamless cutoverregenerate_request = RegenerateKeyRequest(key=key.token or "",key_alias=key.key_alias, # Pass key alias to ensure correct secret is updated in AWS Secrets Manager+ grace_period_hours=LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS,)# Create a system user for key rotationdiff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.pyindex d1840363009..dea1e55f7f9 100644--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@ -12,6 +12,7 @@ All /key management endpointsimport asyncioimport copyimport json+import osimport secretsimport tracebackfrom datetime import datetime, timedelta, timezone@@ -518,7 +519,7 @@ async def _common_key_generation_helper( # noqa: PLR0915)# Handle special case where duration is "-1" (never expires)if value == "-1":- user_duration = float('inf') # Infinite duration+ user_duration = float("inf") # Infinite durationelse:user_duration = duration_in_seconds(duration=value)if user_duration > upperbound_duration:@@ -660,9 +661,9 @@ async def _common_key_generation_helper( # noqa: PLR0915request_type="key", **data_json, table_name="key")- response["soft_budget"] = (- data.soft_budget- ) # include the user-input soft budget in the response+ response[+ "soft_budget"+ ] = data.soft_budget # include the user-input soft budget in the responseresponse = GenerateKeyResponse(**response)@@ -1083,12 +1084,16 @@ async def generate_key_fn(if data.max_budget is not None and data.max_budget < 0:raise HTTPException(status_code=400,- detail={"error": f"max_budget cannot be negative. Received: {data.max_budget}"}+ detail={+ "error": f"max_budget cannot be negative. Received: {data.max_budget}"+ },)if data.soft_budget is not None and data.soft_budget < 0:raise HTTPException(status_code=400,- detail={"error": f"soft_budget cannot be negative. Received: {data.soft_budget}"}+ detail={+ "error": f"soft_budget cannot be negative. Received: {data.soft_budget}"+ },)if user_custom_key_generate is not None:@@ -1336,6 +1341,7 @@ async def prepare_key_update_data(data_json: dict = data.model_dump(exclude_unset=True)data_json.pop("key", None)data_json.pop("new_key", None)+ data_json.pop("grace_period_hours", None) # Request-only param, not a DB columnif (data.metadata is not Noneand data.metadata.get("service_account_id") is not None@@ -1399,8 +1405,13 @@ async def prepare_key_update_data(validate_model_max_budget(non_default_values["model_max_budget"])# Serialize router_settings to JSON if present- if "router_settings" in non_default_values and non_default_values["router_settings"] is not None:- non_default_values["router_settings"] = safe_dumps(non_default_values["router_settings"])+ if (+ "router_settings" in non_default_values+ and non_default_values["router_settings"] is not None+ ):+ non_default_values["router_settings"] = safe_dumps(+ non_default_values["router_settings"]+ )non_default_values = prepare_metadata_fields(data=data, non_default_values=non_default_values, existing_metadata=_metadata@@ -1448,19 +1459,17 @@ def is_different_team(def _validate_max_budget(max_budget: Optional[float]) -> None:"""Validate that max_budget is not negative.-+Args:max_budget: The max_budget value to validate-+Raises:HTTPException: If max_budget is negative"""if max_budget is not None and max_budget < 0:raise HTTPException(status_code=400,- detail={- "error": f"max_budget cannot be negative. Received: {max_budget}"- },+ detail={"error": f"max_budget cannot be negative. Received: {max_budget}"},)@@ -1469,14 +1478,14 @@ async def _get_and_validate_existing_key() -> LiteLLM_VerificationToken:"""Get existing key from database and validate it exists.-+Args:token: The key token to look upprisma_client: Prisma client instance-+Returns:LiteLLM_VerificationToken: The existing key row-+Raises:HTTPException: If key is not found"""@@ -1485,19 +1494,19 @@ async def _get_and_validate_existing_key(status_code=500,detail={"error": "Database not connected"},)-+existing_key_row = await prisma_client.get_data(token=token,table_name="key",query_type="find_unique",)-+if existing_key_row is None:raise HTTPException(status_code=404,detail={"error": f"Key not found: {token}"},)-+return existing_key_row@@ -1512,10 +1521,10 @@ async def _process_single_key_update() -> Dict[str, Any]:"""Process a single key update with all validations and checks.-+This function encapsulates all the logic for updating a single key,including validation, permission checks, team checks, and database updates.-+Args:key_update_item: The key update request itemuser_api_key_dict: The authenticated user's API key info@@ -1524,22 +1533,22 @@ async def _process_single_key_update(user_api_key_cache: User API key cacheproxy_logging_obj: Proxy logging objectllm_router: LLM router instance-+Returns:Dict containing the updated key information-+Raises:HTTPException: For various validation and permission errors"""# Validate max_budget_validate_max_budget(key_update_item.max_budget)-+# Get and validate existing keyexisting_key_row = await _get_and_validate_existing_key(token=key_update_item.key,prisma_client=prisma_client,)-+# Check team member permissionsif prisma_client is not None:await TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint(@@ -1549,7 +1558,7 @@ async def _process_single_key_update(existing_key_row=existing_key_row,user_api_key_cache=user_api_key_cache,)-+# Create UpdateKeyRequest from BulkUpdateKeyRequestItemupdate_key_request = UpdateKeyRequest(key=key_update_item.key,@@ -1558,7 +1567,7 @@ async def _process_single_key_update(team_id=key_update_item.team_id,tags=key_update_item.tags,)-+# Get team object and check team limits if team_id is providedteam_obj: Optional[LiteLLM_TeamTableCachedObj] = Noneif update_key_request.team_id is not None:@@ -1568,18 +1577,16 @@ async def _process_single_key_update(user_api_key_cache=user_api_key_cache,check_db_only=True,)-+if team_obj is not None and prisma_client is not None:await _check_team_key_limits(team_table=team_obj,data=update_key_request,prisma_client=prisma_client,)-+# Validate team change if team is being changed- if is_different_team(- data=update_key_request, existing_key_row=existing_key_row- ):+ if is_different_team(data=update_key_request, existing_key_row=existing_key_row):if llm_router is None:raise HTTPException(status_code=400,@@ -1590,9 +1597,7 @@ async def _process_single_key_update(if team_obj is None:raise HTTPException(status_code=500,- detail={- "error": "Team object not found for team change validation"- },+ detail={"error": "Team object not found for team change validation"},)validate_key_team_change(key=existing_key_row,@@ -1600,31 +1605,29 @@ async def _process_single_key_update(change_initiated_by=user_api_key_dict,llm_router=llm_router,)-+# Prepare update datanon_default_values = await prepare_key_update_data(data=update_key_request, existing_key_row=existing_key_row)-+# Update key in databaseif prisma_client is None:raise HTTPException(status_code=500,detail={"error": "Database not connected"},)-+_data = {**non_default_values, "token": key_update_item.key}- response = await prisma_client.update_data(- token=key_update_item.key, data=_data- )-+ response = await prisma_client.update_data(token=key_update_item.key, data=_data)+# Delete cacheawait _delete_cache_key_object(hashed_token=hash_token(key_update_item.key),user_api_key_cache=user_api_key_cache,proxy_logging_obj=proxy_logging_obj,)-+# Trigger async hookasyncio.create_task(KeyManagementEventHooks.async_key_updated_hook(@@ -1635,19 +1638,19 @@ async def _process_single_key_update(litellm_changed_by=litellm_changed_by,))-+if response is None:raise ValueError("Failed to update key got response = None")-+# Extract and format updated key infoupdated_key_info = response.get("data", {})if hasattr(updated_key_info, "model_dump"):updated_key_info = updated_key_info.model_dump()elif hasattr(updated_key_info, "dict"):updated_key_info = updated_key_info.dict()-+updated_key_info.pop("token", None)-+return updated_key_info@@ -1740,7 +1743,9 @@ async def update_key_fn(if data.max_budget is not None and data.max_budget < 0:raise HTTPException(status_code=400,- detail={"error": f"max_budget cannot be negative. Received: {data.max_budget}"}+ detail={+ "error": f"max_budget cannot be negative. Received: {data.max_budget}"+ },)data_json: dict = data.model_dump(exclude_unset=True, exclude_none=True)@@ -1959,13 +1964,11 @@ async def bulk_update_keys(proxy_logging_obj,user_api_key_cache,)-+if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN.value:raise HTTPException(status_code=403,- detail={- "error": "Only proxy admins can perform bulk key updates"- },+ detail={"error": "Only proxy admins can perform bulk key updates"},)if prisma_client is None:@@ -2505,7 +2508,9 @@ async def generate_key_helper_fn( # noqa: PLR0915aliases_json = json.dumps(aliases)config_json = json.dumps(config)permissions_json = json.dumps(permissions)- router_settings_json = safe_dumps(router_settings) if router_settings is not None else safe_dumps({})+ router_settings_json = (+ safe_dumps(router_settings) if router_settings is not None else safe_dumps({})+ )# Add model_rpm_limit and model_tpm_limit to metadataif model_rpm_limit is not None:@@ -2672,10 +2677,12 @@ async def generate_key_helper_fn( # noqa: PLR0915)key_data["created_at"] = getattr(create_key_response, "created_at", None)key_data["updated_at"] = getattr(create_key_response, "updated_at", None)-+# Deserialize router_settings from JSON string to dict for responserouter_settings_value = key_data.get("router_settings")- if router_settings_value is not None and isinstance(router_settings_value, str):+ if router_settings_value is not None and isinstance(+ router_settings_value, str+ ):try:key_data["router_settings"] = yaml.safe_load(router_settings_value)except yaml.YAMLError:@@ -2758,27 +2765,27 @@ async def can_modify_verification_token() -> bool:"""Check if user has permission to modify (delete/regenerate) a verification token.-+Rules:- Proxy admin can modify any key- For team keys: only team admin or key owner can modify- For personal keys: only key owner can modify-+Args:key_info: The verification token to checkuser_api_key_cache: Cache for user API keysuser_api_key_dict: The user making the requestprisma_client: Prisma client for database access-+Returns:True if user can modify the key, False otherwise"""is_team_key = _is_team_key(data=key_info)-+# 1. Proxy admin can modify any keyif user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN.value:return True-+# 2. For team keys: only team admin or key owner can modifyif is_team_key and key_info.team_id is not None:# Get team object to check if user is team admin@@ -2788,34 +2795,35 @@ async def can_modify_verification_token(user_api_key_cache=user_api_key_cache,check_db_only=True,)-+if team_table is None:return False-+# Check if user is team adminif _is_user_team_admin(user_api_key_dict=user_api_key_dict,team_obj=team_table,):return True-+# Check if the key belongs to the user (they own it)- if key_info.user_id is not None and key_info.user_id == user_api_key_dict.user_id:+ if (+ key_info.user_id is not None+ and key_info.user_id == user_api_key_dict.user_id+ ):return True-+# Not team admin and doesn't own the keyreturn False-+# 3. For personal keys: only key owner can modifyif key_info.user_id is not None and key_info.user_id == user_api_key_dict.user_id:return True-+# Default: denyreturn False--async def delete_verification_tokens(tokens: List,user_api_key_cache: DualCache,@@ -2845,10 +2853,10 @@ async def delete_verification_tokens(try:if prisma_client:tokens = [_hash_token_if_needed(token=key) for key in tokens]- _keys_being_deleted: List[LiteLLM_VerificationToken] = (- await prisma_client.db.litellm_verificationtoken.find_many(- where={"token": {"in": tokens}}- )+ _keys_being_deleted: List[+ LiteLLM_VerificationToken+ ] = await prisma_client.db.litellm_verificationtoken.find_many(+ where={"token": {"in": tokens}})if len(_keys_being_deleted) == 0:@@ -2948,11 +2956,24 @@ def _transform_verification_tokens_to_deleted_records(if org_id_value is not None:record["organization_id"] = org_id_value- for json_field in ["aliases", "config", "permissions", "metadata", "model_spend", "model_max_budget", "router_settings"]:+ for json_field in [+ "aliases",+ "config",+ "permissions",+ "metadata",+ "model_spend",+ "model_max_budget",+ "router_settings",+ ]:if json_field in record and record[json_field] is not None:record[json_field] = json.dumps(record[json_field])- for rel_key in ("litellm_budget_table", "litellm_organization_table", "object_permission", "id"):+ for rel_key in (+ "litellm_budget_table",+ "litellm_organization_table",+ "object_permission",+ "id",+ ):record.pop(rel_key, None)records.append(record)@@ -2967,9 +2988,7 @@ async def _save_deleted_verification_token_records("""Save deleted verification token records to the database."""if not records:return- await prisma_client.db.litellm_deletedverificationtoken.create_many(- data=records- )+ await prisma_client.db.litellm_deletedverificationtoken.create_many(data=records)async def _persist_deleted_verification_tokens(@@ -3032,9 +3051,9 @@ async def _rotate_master_key(from litellm.proxy.proxy_server import proxy_configtry:- models: Optional[List] = (- await prisma_client.db.litellm_proxymodeltable.find_many()- )+ models: Optional[+ List+ ] = await prisma_client.db.litellm_proxymodeltable.find_many()except Exception:models = None# 2. process model table@@ -3111,7 +3130,9 @@ async def _rotate_master_key(updated_patch=decrypted_cred,new_encryption_key=new_master_key,)- credential_object_jsonified = jsonify_object(encrypted_cred.model_dump())+ credential_object_jsonified = jsonify_object(+ encrypted_cred.model_dump()+ )await prisma_client.db.litellm_credentialstable.update(where={"credential_name": cred.credential_name},data={@@ -3156,7 +3177,7 @@ def get_new_token(data: Optional[RegenerateKeyRequest]) -> str:dependencies=[Depends(user_api_key_auth)],)@management_endpoint_wrapper-async def regenerate_key_fn(+async def regenerate_key_fn( # noqa: PLR0915key: Optional[str] = None,data: Optional[RegenerateKeyRequest] = None,user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),@@ -3195,6 +3216,7 @@ async def regenerate_key_fn(- permissions: Optional[dict] - Key-specific permissions- guardrails: Optional[List[str]] - List of active guardrails for the key- blocked: Optional[bool] - Whether the key is blocked+ - grace_period_hours: Optional[int] - Hours to keep old key valid after rotation (e.g. 24, 48, 72). 0 or omitted = immediate revoke. Env: LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURSReturns:@@ -3330,6 +3352,37 @@ async def regenerate_key_fn(update_data.update(non_default_values)update_data = prisma_client.jsonify_object(data=update_data)++ # If grace period > 0, insert deprecated key so old key remains valid+ if data is not None and data.grace_period_hours is not None:+ grace_period_hours = data.grace_period_hours+ else:+ grace_period_hours = int(+ os.getenv("LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS", "0")+ )+ if grace_period_hours > 0:+ try:+ revoke_at = datetime.now(timezone.utc) + timedelta(+ hours=grace_period_hours+ )+ await prisma_client.db.litellm_deprecatedverificationtoken.create(+ data={+ "token": hashed_api_key,+ "active_token_id": new_token_hash,+ "revoke_at": revoke_at,+ }+ )+ verbose_proxy_logger.debug(+ "Deprecated key retained for %s hours (revoke_at: %s)",+ grace_period_hours,+ revoke_at,+ )+ except Exception as deprecated_err:+ verbose_proxy_logger.warning(+ "Failed to insert deprecated key for grace period: %s",+ deprecated_err,+ )+# Update the token in the databaseupdated_token = await prisma_client.db.litellm_verificationtoken.update(where={"token": hashed_api_key},@@ -3423,7 +3476,9 @@ def _validate_reset_spend_value(if reset_to > current_spend:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,- detail={"error": f"reset_to ({reset_to}) must be <= current spend ({current_spend})"},+ detail={+ "error": f"reset_to ({reset_to}) must be <= current spend ({current_spend})"+ },)max_budget = key_in_db.max_budget@@ -3549,11 +3604,11 @@ async def validate_key_list_check(param="user_id",code=status.HTTP_403_FORBIDDEN,)- complete_user_info_db_obj: Optional[BaseModel] = (- await prisma_client.db.litellm_usertable.find_unique(- where={"user_id": user_api_key_dict.user_id},- include={"organization_memberships": True},- )+ complete_user_info_db_obj: Optional[+ BaseModel+ ] = await prisma_client.db.litellm_usertable.find_unique(+ where={"user_id": user_api_key_dict.user_id},+ include={"organization_memberships": True},)if complete_user_info_db_obj is None:@@ -3639,10 +3694,10 @@ async def get_admin_team_ids(if complete_user_info is None:return []# Get all teams that user is an admin of- teams: Optional[List[BaseModel]] = (- await prisma_client.db.litellm_teamtable.find_many(- where={"team_id": {"in": complete_user_info.teams}}- )+ teams: Optional[+ List[BaseModel]+ ] = await prisma_client.db.litellm_teamtable.find_many(+ where={"team_id": {"in": complete_user_info.teams}})if teams is None:return []@@ -3687,8 +3742,12 @@ async def list_keys(description="Column to sort by (e.g. 'user_id', 'created_at', 'spend')",),sort_order: str = Query(default="desc", description="Sort order ('asc' or 'desc')"),- expand: Optional[List[str]] = Query(None, description="Expand related objects (e.g. 'user')"),- status: Optional[str] = Query(None, description="Filter by status (e.g. 'deleted')"),+ expand: Optional[List[str]] = Query(+ None, description="Expand related objects (e.g. 'user')"+ ),+ status: Optional[str] = Query(+ None, description="Filter by status (e.g. 'deleted')"+ ),) -> KeyListResponseObject:"""List all keys for a given user / team / organization.@@ -3780,7 +3839,9 @@ async def list_keys(message=getattr(e, "detail", f"error({str(e)})"),type=ProxyErrorTypes.internal_server_error,param=getattr(e, "param", "None"),- code=getattr(e, "status_code", fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR),+ code=getattr(+ e, "status_code", fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR+ ),)elif isinstance(e, ProxyException):raise ediff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex 3b81da10923..8992f4d8df6 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -317,6 +317,19 @@ model LiteLLM_VerificationToken {@@index([budget_reset_at, expires])}+// Deprecated keys during grace period - allows old key to work until revoke_at+model LiteLLM_DeprecatedVerificationToken {+ id String @id @default(uuid())+ token String // Hashed old key+ active_token_id String // Current token hash in LiteLLM_VerificationToken+ revoke_at DateTime // When the old key stops working+ created_at DateTime @default(now()) @map("created_at")++ @@unique([token])+ @@index([token, revoke_at])+ @@index([revoke_at])+}+// Audit table for deleted keys - preserves spend and key information for historical trackingmodel LiteLLM_DeletedVerificationToken {id String @id @default(uuid())diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 6bbf0df74de..c9b07ce447d 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -2644,6 +2644,71 @@ class PrismaClient:sql_query)+ # If not found in main table, check deprecated keys (grace period)+ if response is None:+ try:+ deprecated_sql = f"""+ SELECT active_token_id FROM "LiteLLM_DeprecatedVerificationToken"+ WHERE token = '{hashed_token}' AND revoke_at > NOW()+ LIMIT 1+ """+ deprecated_row = (+ await self._query_first_with_cached_plan_fallback(+ deprecated_sql+ )+ )+ if deprecated_row and deprecated_row.get("active_token_id"):+ active_token_id = deprecated_row["active_token_id"]+ sql_query_active = f"""+ SELECT+ v.*,+ t.spend AS team_spend,+ t.max_budget AS team_max_budget,+ t.tpm_limit AS team_tpm_limit,+ t.rpm_limit AS team_rpm_limit,+ t.models AS team_models,+ t.metadata AS team_metadata,+ t.blocked AS team_blocked,+ t.team_alias AS team_alias,+ t.metadata AS team_metadata,+ t.members_with_roles AS team_members_with_roles,+ t.object_permission_id AS team_object_permission_id,+ t.organization_id as org_id,+ tm.spend AS team_member_spend,+ m.aliases AS team_model_aliases,+ b.max_budget AS litellm_budget_table_max_budget,+ b.tpm_limit AS litellm_budget_table_tpm_limit,+ b.rpm_limit AS litellm_budget_table_rpm_limit,+ b.model_max_budget as litellm_budget_table_model_max_budget,+ b.soft_budget as litellm_budget_table_soft_budget,+ o.metadata as organization_metadata,+ b2.max_budget as organization_max_budget,+ b2.tpm_limit as organization_tpm_limit,+ b2.rpm_limit as organization_rpm_limit+ FROM "LiteLLM_VerificationToken" AS v+ LEFT JOIN "LiteLLM_TeamTable" AS t ON v.team_id = t.team_id+ LEFT JOIN "LiteLLM_TeamMembership" AS tm ON v.team_id = tm.team_id AND tm.user_id = v.user_id+ LEFT JOIN "LiteLLM_ModelTable" m ON t.model_id = m.id+ LEFT JOIN "LiteLLM_BudgetTable" AS b ON v.budget_id = b.budget_id+ LEFT JOIN "LiteLLM_OrganizationTable" AS o ON v.organization_id = o.organization_id+ LEFT JOIN "LiteLLM_BudgetTable" AS b2 ON o.budget_id = b2.budget_id+ WHERE v.token = '{active_token_id}'+ """+ response = (+ await self._query_first_with_cached_plan_fallback(+ sql_query_active+ )+ )+ if response is not None:+ verbose_proxy_logger.debug(+ "Deprecated key used during grace period"+ )+ except Exception as deprecated_lookup_error:+ verbose_proxy_logger.debug(+ "Deprecated key lookup skipped: %s",+ deprecated_lookup_error,+ )+if response is not None:if response["team_models"] is None:response["team_models"] = []diff --git a/schema.prisma b/schema.prismaindex 3b81da10923..8992f4d8df6 100644--- a/schema.prisma+++ b/schema.prisma@@ -317,6 +317,19 @@ model LiteLLM_VerificationToken {@@index([budget_reset_at, expires])}+// Deprecated keys during grace period - allows old key to work until revoke_at+model LiteLLM_DeprecatedVerificationToken {+ id String @id @default(uuid())+ token String // Hashed old key+ active_token_id String // Current token hash in LiteLLM_VerificationToken+ revoke_at DateTime // When the old key stops working+ created_at DateTime @default(now()) @map("created_at")++ @@unique([token])+ @@index([token, revoke_at])+ @@index([revoke_at])+}+// Audit table for deleted keys - preserves spend and key information for historical trackingmodel LiteLLM_DeletedVerificationToken {id String @id @default(uuid())diff --git a/tests/test_litellm/proxy/common_utils/test_key_rotation_manager.py b/tests/test_litellm/proxy/common_utils/test_key_rotation_manager.pyindex 6b3b4c92416..1f5fab71ef3 100644--- a/tests/test_litellm/proxy/common_utils/test_key_rotation_manager.py+++ b/tests/test_litellm/proxy/common_utils/test_key_rotation_manager.py@@ -4,7 +4,7 @@ Test key rotation manager functionalityimport osimport sysfrom datetime import datetime, timedelta, timezone-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import AsyncMockimport pytest@@ -24,7 +24,7 @@ class TestKeyRotationManager:async def test_should_rotate_key_logic(self):"""Test the core logic for determining when a key should be rotated.-+This tests:- Keys with null key_rotation_at should rotate immediately- Keys with future key_rotation_at should not rotate@@ -33,69 +33,69 @@ class TestKeyRotationManager:# Setupmock_prisma_client = AsyncMock()manager = KeyRotationManager(mock_prisma_client)-+now = datetime.now(timezone.utc)-+# Test Case 1: No rotation time set (key_rotation_at = None) - should rotatekey_no_rotation_time = LiteLLM_VerificationToken(token="test-token-1",auto_rotate=True,rotation_interval="30s",key_rotation_at=None,- rotation_count=0+ rotation_count=0,)-- assert manager._should_rotate_key(key_no_rotation_time, now) == True-++ assert manager._should_rotate_key(key_no_rotation_time, now) is True+# Test Case 2: Future rotation time - should NOT rotatekey_future_rotation = LiteLLM_VerificationToken(token="test-token-2",auto_rotate=True,rotation_interval="30s",key_rotation_at=now + timedelta(seconds=10),- rotation_count=1+ rotation_count=1,)-- assert manager._should_rotate_key(key_future_rotation, now) == False-++ assert manager._should_rotate_key(key_future_rotation, now) is False+# Test Case 3: Past rotation time - should rotatekey_past_rotation = LiteLLM_VerificationToken(token="test-token-3",auto_rotate=True,rotation_interval="30s",key_rotation_at=now - timedelta(seconds=10),- rotation_count=2+ rotation_count=2,)-- assert manager._should_rotate_key(key_past_rotation, now) == True-++ assert manager._should_rotate_key(key_past_rotation, now) is True+# Test Case 4: Exact rotation time - should rotatekey_exact_rotation = LiteLLM_VerificationToken(token="test-token-4",auto_rotate=True,rotation_interval="30s",key_rotation_at=now,- rotation_count=1+ rotation_count=1,)-- assert manager._should_rotate_key(key_exact_rotation, now) == True-++ assert manager._should_rotate_key(key_exact_rotation, now) is True+# Test Case 5: No rotation interval - should NOT rotatekey_no_interval = LiteLLM_VerificationToken(token="test-token-5",auto_rotate=True,rotation_interval=None,key_rotation_at=None,- rotation_count=0+ rotation_count=0,)-- assert manager._should_rotate_key(key_no_interval, now) == False++ assert manager._should_rotate_key(key_no_interval, now) is False@pytest.mark.asyncioasync def test_find_keys_needing_rotation(self):"""Test finding keys that need rotation from database.-+This tests:- Only keys with auto_rotate=True are considered- Database query filters by key_rotation_at properly@@ -104,10 +104,10 @@ class TestKeyRotationManager:# Setupmock_prisma_client = AsyncMock()manager = KeyRotationManager(mock_prisma_client)-+# Use a fixed timestamp to avoid timing issues in testsnow = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)-+# Mock database response - these are the keys the database query would returnmock_keys = [LiteLLM_VerificationToken(@@ -115,42 +115,47 @@ class TestKeyRotationManager:auto_rotate=True,rotation_interval="30s",key_rotation_at=None, # Should rotate (null key_rotation_at)- rotation_count=0+ rotation_count=0,),LiteLLM_VerificationToken(token="token-2",auto_rotate=True,rotation_interval="60s",- key_rotation_at=now - timedelta(seconds=10), # Should rotate (past time)- rotation_count=1- )+ key_rotation_at=now+ - timedelta(seconds=10), # Should rotate (past time)+ rotation_count=1,+ ),]-- mock_prisma_client.db.litellm_verificationtoken.find_many.return_value = mock_keys-++ mock_prisma_client.db.litellm_verificationtoken.find_many.return_value = (+ mock_keys+ )+# Mock datetime.now to return our fixed timestampfrom unittest.mock import patch- with patch('litellm.proxy.common_utils.key_rotation_manager.datetime') as mock_datetime:++ with patch(+ "litellm.proxy.common_utils.key_rotation_manager.datetime"+ ) as mock_datetime:mock_datetime.now.return_value = now- mock_datetime.side_effect = lambda *args, **kwargs: datetime(*args, **kwargs)-+ mock_datetime.side_effect = lambda *args, **kwargs: datetime(+ *args, **kwargs+ )+# Executekeys_needing_rotation = await manager._find_keys_needing_rotation()-+# Verify database query - should use OR condition for key_rotation_atmock_prisma_client.db.litellm_verificationtoken.find_many.assert_called_once_with(where={"auto_rotate": True,- "OR": [- {"key_rotation_at": None},- {"key_rotation_at": {"lte": now}}- ]+ "OR": [{"key_rotation_at": None}, {"key_rotation_at": {"lte": now}}],})-+# Verify all keys returned by database query are included (no additional filtering)assert len(keys_needing_rotation) == 2-+tokens_needing_rotation = [key.token for key in keys_needing_rotation]assert "token-1" in tokens_needing_rotation # Null key_rotation_atassert "token-2" in tokens_needing_rotation # Past key_rotation_at@@ -159,7 +164,7 @@ class TestKeyRotationManager:async def test_rotate_key_updates_database(self):"""Test that key rotation properly updates the database with new rotation info.-+This tests:- Rotation count is incremented- last_rotation_at is set to current time@@ -169,7 +174,7 @@ class TestKeyRotationManager:# Setupmock_prisma_client = AsyncMock()manager = KeyRotationManager(mock_prisma_client)-+# Mock key to rotatekey_to_rotate = LiteLLM_VerificationToken(token="old-token",@@ -177,31 +182,35 @@ class TestKeyRotationManager:rotation_interval="30s",last_rotation_at=None,key_rotation_at=None,- rotation_count=0+ rotation_count=0,)-+# Mock regenerate_key_fn responsemock_response = GenerateKeyResponse(- key="new-api-key",- token_id="new-token-id",- user_id="test-user"+ key="new-api-key", token_id="new-token-id", user_id="test-user")-+# Mock the regenerate functionfrom unittest.mock import patch- with patch('litellm.proxy.common_utils.key_rotation_manager.regenerate_key_fn', return_value=mock_response):- with patch('litellm.proxy.common_utils.key_rotation_manager.KeyManagementEventHooks.async_key_rotated_hook'):++ with patch(+ "litellm.proxy.common_utils.key_rotation_manager.regenerate_key_fn",+ return_value=mock_response,+ ):+ with patch(+ "litellm.proxy.common_utils.key_rotation_manager.KeyManagementEventHooks.async_key_rotated_hook"+ ):# Executeawait manager._rotate_key(key_to_rotate)-+# Verify database update was called with correct datamock_prisma_client.db.litellm_verificationtoken.update.assert_called_once()-+call_args = mock_prisma_client.db.litellm_verificationtoken.update.call_args-+# Check the WHERE clause targets the new tokenassert call_args[1]["where"]["token"] == "new-token-id"-+# Check the data being updatedupdate_data = call_args[1]["data"]assert update_data["rotation_count"] == 1 # Incremented from 0@@ -209,9 +218,75 @@ class TestKeyRotationManager:assert isinstance(update_data["last_rotation_at"], datetime)assert "key_rotation_at" in update_dataassert isinstance(update_data["key_rotation_at"], datetime)-+# Verify key_rotation_at is set to future time (30s from now)now = datetime.now(timezone.utc)next_rotation = update_data["key_rotation_at"]time_diff = (next_rotation - now).total_seconds()- assert 25 <= time_diff <= 35 # Should be around 30 seconds, allow some tolerance+ assert (+ 25 <= time_diff <= 35+ ) # Should be around 30 seconds, allow some tolerance++ @pytest.mark.asyncio+ async def test_cleanup_expired_deprecated_keys(self):+ """+ Test that _cleanup_expired_deprecated_keys deletes expired deprecated keys.+ """+ mock_prisma_client = AsyncMock()+ mock_prisma_client.db.litellm_deprecatedverificationtoken.delete_many.return_value = {+ "count": 3+ }+ manager = KeyRotationManager(mock_prisma_client)++ await manager._cleanup_expired_deprecated_keys()++ mock_prisma_client.db.litellm_deprecatedverificationtoken.delete_many.assert_called_once()+ call_args = (+ mock_prisma_client.db.litellm_deprecatedverificationtoken.delete_many.call_args+ )+ assert "revoke_at" in call_args[1]["where"]+ assert call_args[1]["where"]["revoke_at"]["lt"] is not None++ @pytest.mark.asyncio+ async def test_rotate_key_passes_grace_period_hours(self):+ """+ Test that _rotate_key passes grace_period_hours in RegenerateKeyRequest.+ """+ mock_prisma_client = AsyncMock()+ manager = KeyRotationManager(mock_prisma_client)++ key_to_rotate = LiteLLM_VerificationToken(+ token="old-token",+ auto_rotate=True,+ rotation_interval="30s",+ key_rotation_at=None,+ rotation_count=0,+ )++ mock_response = GenerateKeyResponse(+ key="new-api-key",+ token_id="new-token-id",+ user_id="test-user",+ )++ from unittest.mock import patch++ with patch(+ "litellm.proxy.common_utils.key_rotation_manager.regenerate_key_fn",+ new_callable=AsyncMock,+ ) as mock_regenerate:+ mock_regenerate.return_value = mock_response+ with patch(+ "litellm.proxy.common_utils.key_rotation_manager.KeyManagementEventHooks.async_key_rotated_hook",+ new_callable=AsyncMock,+ ):+ with patch(+ "litellm.proxy.common_utils.key_rotation_manager.LITELLM_KEY_ROTATION_GRACE_PERIOD_HOURS",+ 48,+ ):+ await manager._rotate_key(key_to_rotate)++ mock_regenerate.assert_called_once()+ call_args = mock_regenerate.call_args+ regenerate_request = call_args[1]["data"]+ assert regenerate_request.grace_period_hours == 48diff --git a/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsx b/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsxindex a4339e11920..3cea198c62a 100644--- a/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsx+++ b/ui/litellm-dashboard/src/components/organisms/regenerate_key_modal.tsx@@ -37,6 +37,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdattpm_limit: selectedToken.tpm_limit,rpm_limit: selectedToken.rpm_limit,duration: selectedToken.duration || "",+ grace_period_hours: 0,});// Initialize the current access token@@ -223,6 +224,17 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdatCurrent expiry: {selectedToken?.expires ? new Date(selectedToken.expires).toLocaleString() : "Never"}</div>{newExpiryTime && <div className="mt-2 text-sm text-green-600">New expiry: {newExpiryTime}</div>}+ <Form.Item+ name="grace_period_hours"+ label="Grace Period (hours)"+ tooltip="Keep the old key valid for this many hours after rotation. Both keys work during this period for seamless cutover. 0 = immediate revoke."+ className="mt-8"+ >+ <InputNumber min={0} max={168} placeholder="0 (immediate revoke)" style={{ width: "100%" }} />+ </Form.Item>+ <div className="mt-2 text-sm text-gray-500">+ Recommended: 24-72 hours for production keys to allow seamless client migration.+ </div></Form>)}</Modal>