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]

harden cli sso review findings

user6293252f93d6
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index 5485d618d57..c4564a4eb04 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -13,6 +13,7 @@ import base64
import hashlib
import inspect
import os
+import re
import secrets
from html import escape
from copy import deepcopy
@@ -74,7 +75,7 @@ from litellm.proxy._types import (
UserAPIKeyAuth,
)
from litellm.proxy.auth.auth_checks import ExperimentalUIJWTToken, get_user_object
-from litellm.proxy.auth.auth_utils import _has_user_setup_sso
+from litellm.proxy.auth.auth_utils import _get_request_ip_address, _has_user_setup_sso
from litellm.proxy.auth.handle_jwt import JWTHandler
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.common_utils.admin_ui_utils import (
@@ -128,7 +129,13 @@ router = APIRouter()
# response convertors see the same fields in the PKCE path as in the non-PKCE path.
_OAUTH_TOKEN_FIELDS = frozenset({"access_token", "id_token", "refresh_token"})
_CLI_SSO_FLOW_CACHE_KEY_PREFIX = f"{CLI_SSO_SESSION_CACHE_KEY_PREFIX}:flow"
+_CLI_SSO_START_RATE_LIMIT_CACHE_KEY_PREFIX = (
+ f"{_CLI_SSO_FLOW_CACHE_KEY_PREFIX}:start_rate_limit"
+)
+_CLI_SSO_START_RATE_LIMIT_WINDOW_SECONDS = 60
+_CLI_SSO_START_RATE_LIMIT_MAX_ATTEMPTS = 30
_CLI_SSO_USER_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
+_CLI_SSO_LOGIN_ID_RE = re.compile(r"^cli-[A-Za-z0-9_-]{12,124}$")
def _hash_cli_sso_secret(secret: str) -> str:
@@ -149,11 +156,40 @@ def _get_cli_sso_flow_cache_key(login_id: str) -> str:
def _is_valid_cli_sso_login_id(login_id: Optional[str]) -> bool:
- return (
- isinstance(login_id, str)
- and login_id.startswith("cli-")
- and 16 <= len(login_id) <= 128
+ return isinstance(login_id, str) and bool(_CLI_SSO_LOGIN_ID_RE.fullmatch(login_id))
+
+
+def _get_cli_sso_start_rate_limit_cache_key(
+ request: Request, use_x_forwarded_for: Optional[bool] = False
+) -> str:
+ client_ip = (
+ _get_request_ip_address(
+ request=request, use_x_forwarded_for=use_x_forwarded_for
+ )
+ or "unknown"
)
+ client_ip_hash = _hash_cli_sso_secret(client_ip)
+ return f"{_CLI_SSO_START_RATE_LIMIT_CACHE_KEY_PREFIX}:{client_ip_hash}"
+
+
+def _check_cli_sso_start_rate_limit(
+ request: Request,
+ cache: DualCache,
+ use_x_forwarded_for: Optional[bool] = False,
+) -> None:
+ rate_limit_cache_key = _get_cli_sso_start_rate_limit_cache_key(
+ request=request, use_x_forwarded_for=use_x_forwarded_for
+ )
+ current_attempts = cache.increment_cache(
+ key=rate_limit_cache_key,
+ value=1,
+ ttl=_CLI_SSO_START_RATE_LIMIT_WINDOW_SECONDS,
+ )
+ if current_attempts > _CLI_SSO_START_RATE_LIMIT_MAX_ATTEMPTS:
+ raise HTTPException(
+ status_code=429,
+ detail="Too many CLI login attempts. Try again later.",
+ )
def _get_cli_sso_flow_or_raise(login_id: Optional[str], cache: DualCache) -> dict:
@@ -257,8 +293,16 @@ def _render_cli_sso_verification_page(
@router.post("/sso/cli/start", tags=["experimental"], include_in_schema=False)
-async def cli_sso_start():
- from litellm.proxy.proxy_server import user_api_key_cache
+async def cli_sso_start(request: Request):
+ from litellm.proxy.proxy_server import general_settings, user_api_key_cache
+
+ _check_cli_sso_start_rate_limit(
+ request=request,
+ cache=user_api_key_cache,
+ use_x_forwarded_for=bool(
+ (general_settings or {}).get("use_x_forwarded_for", False)
+ ),
+ )
login_id = f"cli-{secrets.token_urlsafe(24)}"
poll_secret = secrets.token_urlsafe(32)
@@ -293,6 +337,9 @@ async def cli_sso_complete(request: Request, login_id: str):
from litellm.proxy.proxy_server import user_api_key_cache
flow = _get_cli_sso_flow_or_raise(login_id=login_id, cache=user_api_key_cache)
+ if not flow.get("sso_complete") or not flow.get("session_data"):
+ raise HTTPException(status_code=400, detail="CLI login is not ready")
+
body = (await request.body()).decode("utf-8")
form_values = parse_qs(body)
supplied_user_code = (form_values.get("user_code") or [""])[0]
@@ -320,9 +367,6 @@ async def cli_sso_complete(request: Request, login_id: str):
):
raise HTTPException(status_code=400, detail="Invalid verification code")
- if not flow.get("sso_complete") or not flow.get("session_data"):
- raise HTTPException(status_code=400, detail="CLI login is not ready")
-
flow["user_code_verified"] = True
_set_cli_sso_flow(login_id=login_id, cache=user_api_key_cache, flow=flow)
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 b4c843d0b89..a0ae95df589 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
@@ -2,6 +2,7 @@ import asyncio
import json
import os
import sys
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -1998,6 +1999,18 @@ class TestCustomUISSO:
class TestCLIKeyRegenerationFlow:
"""Test the end-to-end CLI key regeneration flow"""
+ def test_cli_sso_login_id_validation_restricts_charset(self):
+ """Test CLI SSO login IDs only allow the generated character set"""
+ from litellm.proxy.management_endpoints.ui_sso import (
+ _is_valid_cli_sso_login_id,
+ )
+
+ assert _is_valid_cli_sso_login_id("cli-test_1234567890")
+ assert not _is_valid_cli_sso_login_id("cli-session")
+ assert not _is_valid_cli_sso_login_id("cli-test\n1234567890")
+ assert not _is_valid_cli_sso_login_id("cli-test\x001234567890")
+ assert not _is_valid_cli_sso_login_id("sk-test1234567890")
+
@pytest.mark.asyncio
async def test_cli_sso_start_creates_bound_flow(self):
"""Test CLI SSO start creates a polling secret bound flow"""
@@ -2007,15 +2020,21 @@ class TestCLIKeyRegenerationFlow:
cli_sso_start,
)
+ mock_request = MagicMock(spec=Request)
+ mock_request.client = SimpleNamespace(host="127.0.0.1")
+ mock_request.headers = {}
mock_cache = MagicMock()
+ mock_cache.increment_cache.return_value = 1
with patch("litellm.proxy.proxy_server.user_api_key_cache", mock_cache):
- result = await cli_sso_start()
+ result = await cli_sso_start(request=mock_request)
assert result["login_id"].startswith("cli-")
assert result["poll_secret"]
assert result["user_code"]
+ mock_cache.increment_cache.assert_called_once()
+ assert mock_cache.increment_cache.call_args.kwargs["ttl"] == 60
mock_cache.set_cache.assert_called_once()
flow_data = mock_cache.set_cache.call_args.kwargs["value"]
assert flow_data["poll_secret_hash"] == _hash_cli_sso_secret(
@@ -2027,6 +2046,24 @@ class TestCLIKeyRegenerationFlow:
assert flow_data["poll_secret_hash"] != result["poll_secret"]
assert flow_data["user_code_hash"] != result["user_code"]
+ @pytest.mark.asyncio
+ async def test_cli_sso_start_rate_limits_by_client_ip(self):
+ """Test CLI SSO start enforces a coarse per-client rate limit"""
+ from litellm.proxy.management_endpoints.ui_sso import cli_sso_start
+
+ mock_request = MagicMock(spec=Request)
+ mock_request.client = SimpleNamespace(host="127.0.0.1")
+ mock_request.headers = {}
+ mock_cache = MagicMock()
+ mock_cache.increment_cache.return_value = 31
+
+ with patch("litellm.proxy.proxy_server.user_api_key_cache", mock_cache):
+ with pytest.raises(HTTPException) as exc_info:
+ await cli_sso_start(request=mock_request)
+
+ assert exc_info.value.status_code == 429
+ mock_cache.set_cache.assert_not_called()
+
@pytest.mark.asyncio
async def test_cli_sso_complete_verifies_user_code(self):
"""Test CLI SSO complete marks a session as verified"""
@@ -2099,6 +2136,41 @@ class TestCLIKeyRegenerationFlow:
assert exc_info.value.status_code == 400
mock_cache.set_cache.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_cli_sso_complete_waits_for_callback_before_token_checks(self):
+ """Test CLI SSO complete returns not-ready before verification checks"""
+ from litellm.proxy.management_endpoints.ui_sso import (
+ _hash_cli_sso_secret,
+ _normalize_cli_sso_user_code,
+ cli_sso_complete,
+ )
+
+ mock_request = MagicMock(spec=Request)
+ mock_request.body = AsyncMock(
+ return_value=b"user_code=ABCD-EFGH&browser_complete_token=browser-token"
+ )
+ mock_cache = MagicMock()
+ mock_cache.get_cache.return_value = {
+ "poll_secret_hash": _hash_cli_sso_secret("poll-secret"),
+ "user_code_hash": _hash_cli_sso_secret(
+ _normalize_cli_sso_user_code("ABCD-EFGH")
+ ),
+ "sso_complete": False,
+ "user_code_verified": False,
+ "session_data": None,
+ }
+
+ with patch("litellm.proxy.proxy_server.user_api_key_cache", mock_cache):
+ with pytest.raises(HTTPException) as exc_info:
+ await cli_sso_complete(
+ request=mock_request, login_id="cli-session-4567890"
+ )
+
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.detail == "CLI login is not ready"
+ mock_request.body.assert_not_awaited()
+ mock_cache.set_cache.assert_not_called()
+
@pytest.mark.asyncio
async def test_cli_sso_callback_stores_session(self):
"""Test CLI SSO callback stores session data in cache for JWT generation"""