Skip to content

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]

[Feat] Proxy CLI - dont store existing key in the URL, store it in the state param (#15290)

Ishaan Jaff07a17d6d6b92
diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.py
index ff9f05fd32a..1ac6ce3b13b 100644
--- a/litellm/proxy/client/cli/commands/auth.py
+++ b/litellm/proxy/client/cli/commands/auth.py
@@ -353,7 +353,8 @@ def login(ctx: click.Context):
# Construct SSO login URL with CLI source and pre-generated key
sso_url = f"{base_url}/sso/key/generate?source={LITELLM_CLI_SOURCE_IDENTIFIER}&key={key_id}"
- # If we have an existing key, include it so the server can regenerate it
+ # If we have an existing key, include it as a parameter to the login endpoint
+ # The server will encode it in the OAuth state parameter for the SSO flow
if existing_key:
sso_url += f"&existing_key={existing_key}"
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index a65b9cc95d2..9eec551fb7a 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -669,11 +669,11 @@ async def auth_callback(request: Request, state: Optional[str] = None): # noqa:
)
if state and state.startswith(f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:"):
- # Extract the key ID from the state
- key_id = state.split(":", 1)[1]
-
- # Get existing_key from query parameters if provided
- existing_key = request.query_params.get("existing_key")
+ # Extract the key ID and existing_key from the state
+ # State format: {PREFIX}:{key}:{existing_key} or {PREFIX}:{key}
+ state_parts = state.split(":", 2) # Split into max 3 parts
+ key_id = state_parts[1] if len(state_parts) > 1 else None
+ existing_key = state_parts[2] if len(state_parts) > 2 else None
verbose_proxy_logger.info(
f"CLI SSO callback detected for key: {key_id}, existing_key: {existing_key}"
@@ -1145,6 +1145,9 @@ class SSOAuthenticationHandler:
) -> str:
"""
Get the redirect URL for SSO
+
+ Note: existing_key is not added to the URL to avoid changing the callback URL.
+ It should be passed via the state parameter instead.
"""
from litellm.proxy.utils import get_custom_url
@@ -1154,10 +1157,6 @@ class SSOAuthenticationHandler:
else:
redirect_url += "/" + sso_callback_route
- # Append existing_key as query parameter if provided
- if existing_key:
- redirect_url += f"?existing_key={existing_key}"
-
return redirect_url
@staticmethod
@@ -1348,7 +1347,11 @@ class SSOAuthenticationHandler:
"""
Checks the request 'source' if a cli state token was passed in
- This is used to authenticate through the CLI login flow
+ This is used to authenticate through the CLI login flow.
+
+ The state parameter format is: {PREFIX}:{key}:{existing_key}
+ - If existing_key is provided, it's included in the state
+ - The state parameter is used to pass data through the OAuth flow without changing the callback URL
"""
from litellm.constants import (
LITELLM_CLI_SESSION_TOKEN_PREFIX,
@@ -1356,8 +1359,10 @@ class SSOAuthenticationHandler:
)
if source == LITELLM_CLI_SOURCE_IDENTIFIER and key:
- # Just use the key - existing_key will be passed separately via query params
- return f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:{key}"
+ if existing_key:
+ return f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:{key}:{existing_key}"
+ else:
+ return f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:{key}"
else:
return None
diff --git a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
index 86339c0d227..bfd5358dba6 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
@@ -993,6 +993,40 @@ class TestSSOStateHandling:
assert state is None
+ def test_get_cli_state_with_existing_key(self):
+ """Test generating CLI state with existing_key embedded in state parameter"""
+ from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler
+
+ state = SSOAuthenticationHandler._get_cli_state(
+ source="litellm-cli",
+ key="sk-new-key-123",
+ existing_key="sk-existing-key-456"
+ )
+
+ assert state is not None
+ assert state.startswith("litellm-session-token:")
+ assert "sk-new-key-123" in state
+ assert "sk-existing-key-456" in state
+ # Verify the format: {PREFIX}:{key}:{existing_key}
+ assert state == "litellm-session-token:sk-new-key-123:sk-existing-key-456"
+
+ def test_get_cli_state_without_existing_key(self):
+ """Test generating CLI state without existing_key"""
+ from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler
+
+ state = SSOAuthenticationHandler._get_cli_state(
+ source="litellm-cli",
+ key="sk-new-key-789",
+ existing_key=None
+ )
+
+ assert state is not None
+ assert state.startswith("litellm-session-token:")
+ assert "sk-new-key-789" in state
+ # Verify the format: {PREFIX}:{key} (no third part)
+ assert state == "litellm-session-token:sk-new-key-789"
+ assert state.count(":") == 1 # Only one colon separator
+
class TestStateRouting:
"""Test state parameter routing logic"""
@@ -1009,6 +1043,36 @@ class TestStateRouting:
key_id = cli_state.split(":", 1)[1]
assert key_id == "sk-test123"
+ def test_cli_state_parsing_with_existing_key(self):
+ """Test parsing CLI state with existing_key embedded"""
+ from litellm.constants import LITELLM_CLI_SESSION_TOKEN_PREFIX
+
+ # State format: {PREFIX}:{key}:{existing_key}
+ cli_state = f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:sk-new-key-456:sk-existing-key-789"
+
+ # Parse as done in auth_callback
+ state_parts = cli_state.split(":", 2) # Split into max 3 parts
+ key_id = state_parts[1] if len(state_parts) > 1 else None
+ existing_key = state_parts[2] if len(state_parts) > 2 else None
+
+ assert key_id == "sk-new-key-456"
+ assert existing_key == "sk-existing-key-789"
+
+ def test_cli_state_parsing_without_existing_key(self):
+ """Test parsing CLI state without existing_key"""
+ from litellm.constants import LITELLM_CLI_SESSION_TOKEN_PREFIX
+
+ # State format: {PREFIX}:{key}
+ cli_state = f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:sk-new-key-999"
+
+ # Parse as done in auth_callback
+ state_parts = cli_state.split(":", 2) # Split into max 3 parts
+ key_id = state_parts[1] if len(state_parts) > 1 else None
+ existing_key = state_parts[2] if len(state_parts) > 2 else None
+
+ assert key_id == "sk-new-key-999"
+ assert existing_key is None
+
def test_non_cli_state_detection(self):
"""Test detection of non-CLI state parameters"""
from litellm.constants import LITELLM_CLI_SESSION_TOKEN_PREFIX
@@ -1310,16 +1374,15 @@ class TestCLIKeyRegenerationFlow:
@pytest.mark.asyncio
async def test_auth_callback_routes_to_cli_with_existing_key(self):
- """Test that auth_callback properly routes CLI requests and preserves existing_key parameter"""
+ """Test that auth_callback properly routes CLI requests and extracts existing_key from state parameter"""
from litellm.constants import LITELLM_CLI_SESSION_TOKEN_PREFIX
from litellm.proxy.management_endpoints.ui_sso import auth_callback
- # Mock request with existing_key query parameter
+ # Mock request (no query params needed - existing_key is in state)
mock_request = MagicMock(spec=Request)
- mock_request.query_params.get.return_value = "sk-existing-cli-key-123"
- # CLI state
- cli_state = f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:sk-new-session-key-456"
+ # CLI state with existing_key embedded: {PREFIX}:{key}:{existing_key}
+ cli_state = f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:sk-new-session-key-456:sk-existing-cli-key-123"
# Mock the CLI callback and required proxy server components
mock_result = {"user_id": "test-user", "email": "[email protected]"}
@@ -1337,7 +1400,7 @@ class TestCLIKeyRegenerationFlow:
# Act
await auth_callback(request=mock_request, state=cli_state)
- # Assert
+ # Assert - existing_key should be extracted from state parameter
mock_cli_callback.assert_called_once_with(
request=mock_request,
key="sk-new-session-key-456",
@@ -1345,8 +1408,8 @@ class TestCLIKeyRegenerationFlow:
result=mock_result
)
- def test_get_redirect_url_preserves_existing_key(self):
- """Test that redirect URL generation preserves existing_key parameter"""
+ def test_get_redirect_url_does_not_include_existing_key_in_url(self):
+ """Test that redirect URL generation does NOT include existing_key in URL (uses state parameter instead)"""
from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler
# Mock request
@@ -1354,14 +1417,16 @@ class TestCLIKeyRegenerationFlow:
mock_request.base_url = "https://test.litellm.ai/"
with patch("litellm.proxy.utils.get_custom_url", return_value="https://test.litellm.ai"):
- # Test with existing_key
+ # Test with existing_key - should NOT be in URL
redirect_url = SSOAuthenticationHandler.get_redirect_url_for_sso(
request=mock_request,
sso_callback_route="sso/callback",
existing_key="sk-existing-123"
)
- assert "https://test.litellm.ai/sso/callback?existing_key=sk-existing-123" == redirect_url
+ # existing_key should NOT be in the URL
+ assert "https://test.litellm.ai/sso/callback" == redirect_url
+ assert "existing_key" not in redirect_url
def test_get_redirect_url_without_existing_key(self):
"""Test that redirect URL generation works without existing_key parameter"""