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]

chore: merge litellm_internal_staging into litellm_lit5285_login_rate_limit

yucheng68db6c1177bf
diff --cc litellm/proxy/auth/login_utils.py
index 8835227cd1c,c0a76a4fc20..5b0d5e6edd7
--- a/litellm/proxy/auth/login_utils.py
+++ b/litellm/proxy/auth/login_utils.py
@@@ -24,7 -26,7 +26,8 @@@ from litellm.proxy._types import
UpdateUserRequest,
UserAPIKeyAuth,
)
+ from litellm.proxy.auth.auth_utils import is_sso_provider_fully_configured
+from litellm.proxy.auth.login_throttle import LoginThrottle
from litellm.proxy.management_endpoints.internal_user_endpoints import user_update
from litellm.proxy.management_endpoints.key_management_endpoints import (
generate_key_helper_fn,
@@@ -42,10 -44,6 +45,11 @@@ from litellm.repositories.user_reposito
from litellm.secret_managers.main import get_secret_bool
from litellm.types.proxy.ui_sso import ReturnedUITokenObject
+INVALID_UI_CREDENTIALS_MESSAGE: Final = (
+ "Invalid credentials used to access UI. Check 'UI_USERNAME' and 'UI_PASSWORD', or the password set for your user"
+)
++INVALID_USER_PASSWORD_MESSAGE: Final = "Invalid credentials used to access UI. Check the password set for your user"
+
async def _rehash_password_if_needed(user_id: str, password: str, stored: str) -> None:
"""Rehash legacy password (SHA256) to scrypt on successful login."""
@@@ -87,6 -85,29 +91,36 @@@ def get_ui_credentials(master_key: str
return ui_username, ui_password
+ def _matches_env_credentials(username: str, password: str, master_key: str | None) -> bool:
+ ui_username, ui_password = get_ui_credentials(master_key)
+ return secrets.compare_digest(username.encode("utf-8"), ui_username.encode("utf-8")) and secrets.compare_digest(
+ password.encode("utf-8"), ui_password.encode("utf-8")
+ )
+
+
++def _invalid_credentials_message(general_settings: Mapping[str, object]) -> str:
++ """One rejection message for unknown usernames and wrong passwords alike, so neither can be enumerated."""
++ if is_env_credential_login_enabled(general_settings):
++ return INVALID_UI_CREDENTIALS_MESSAGE
++ return INVALID_USER_PASSWORD_MESSAGE
++
++
+ def is_env_credential_login_enabled(general_settings: Mapping[str, object]) -> bool:
+ """Whether a login with UI_USERNAME/UI_PASSWORD (or the master-key fallback) can succeed.
+
+ Two settings can turn it off: `disable_env_credential_login` unconditionally, and
+ `disable_password_login_when_sso_enabled` as a side effect, since its gate rejects
+ every username/password login before the env comparison runs. Feeds both the
+ `authenticate_user` gate and the Admin UI warning banner, so the banner never nags
+ about a login path that is already unreachable.
+ """
+ if general_settings.get("disable_env_credential_login") is True:
+ return False
+ if general_settings.get("disable_password_login_when_sso_enabled") is True and is_sso_provider_fully_configured():
+ return False
+ return True
+
+
class LoginResult:
"""Result object containing authentication data from login."""
@@@ -116,7 -137,7 +150,8 @@@ async def authenticate_user
password: str,
master_key: str | None,
prisma_client: PrismaClient | None,
+ throttle: LoginThrottle,
+ general_settings: Mapping[str, object] = MappingProxyType({}),
) -> LoginResult:
"""
Authenticate a user and generate an API key for UI access.
@@@ -130,6 -151,9 +165,10 @@@
password: Password from the login form
master_key: Master key for the proxy (required)
prisma_client: Prisma database client (optional)
++ throttle: Failed sign-in accounting for this request's source address
+ general_settings: Proxy general_settings, checked for
+ `disable_password_login_when_sso_enabled` and
+ `disable_env_credential_login`
Returns:
LoginResult: Object containing authentication data
@@@ -145,15 -194,6 +209,13 @@@
code=500,
)
- ui_username, ui_password = get_ui_credentials(master_key)
-
- admin_credentials_match: Final = secrets.compare_digest(
- username.encode("utf-8"), ui_username.encode("utf-8")
- ) and secrets.compare_digest(password.encode("utf-8"), ui_password.encode("utf-8"))
++ admin_credentials_match: Final = general_settings.get("disable_env_credential_login") is not True and (
++ _matches_env_credentials(username, password, master_key)
++ )
+
+ if not admin_credentials_match:
+ await throttle.raise_if_blocked(username)
+
# Check if we can find the `username` in the db. On the UI, users can enter username=their email
_user_row: LiteLLM_UserTable | None = None
user_role: (
@@@ -317,17 -355,20 +379,17 @@@
login_method="username_password",
)
else:
+ await throttle.delay_for(username, await throttle.record_failure(username))
raise ProxyException(
- message=INVALID_UI_CREDENTIALS_MESSAGE,
- message=f"Invalid credentials used to access UI.\nNot valid credentials for {username}",
++ message=_invalid_credentials_message(general_settings),
type=ProxyErrorTypes.auth_error,
param="invalid_credentials",
code=401,
)
else:
- env_credentials_hint: Final = (
- "\nCheck 'UI_USERNAME', 'UI_PASSWORD' in .env file"
- if is_env_credential_login_enabled(general_settings)
- else ""
- )
+ await throttle.delay_for(username, await throttle.record_failure(username))
raise ProxyException(
- message=INVALID_UI_CREDENTIALS_MESSAGE,
- message=f"Invalid credentials used to access UI.{env_credentials_hint}",
++ message=_invalid_credentials_message(general_settings),
type=ProxyErrorTypes.auth_error,
param="invalid_credentials",
code=401,
diff --cc litellm/proxy/proxy_cli.py
index 59485d3e96b,c2d60cd5488..42dc6c57a90
--- a/litellm/proxy/proxy_cli.py
+++ b/litellm/proxy/proxy_cli.py
@@@ -1358,14 -1412,11 +1412,15 @@@ def run_server
# DO NOT DELETE - enables global variables to work across files
from litellm.proxy.proxy_server import app
+ # Write the resolved --num_workers back to its env var so worker processes can read
+ # the fleet size at startup (the failed-login accounting warning keys off it)
+ os.environ["NUM_WORKERS"] = str(num_workers)
+
# Auto-create PROMETHEUS_MULTIPROC_DIR for multi-worker setups
- ProxyInitializationHelpers._maybe_setup_prometheus_multiproc_dir(
+ prometheus_multiproc_dir: Final = ProxyInitializationHelpers._maybe_setup_prometheus_multiproc_dir(
num_workers=num_workers,
litellm_settings=litellm_settings if config else None,
+ prometheus_metrics_port=prometheus_metrics_port,
)
# Skip server startup if requested (after all setup is done)
diff --cc litellm/proxy/proxy_server.py
index 56a9ba390c4,0f24acb8bb4..24532cc051c
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@@ -298,8 -322,7 +322,8 @@@ from litellm.proxy.auth.auth_utils impo
)
from litellm.proxy.auth.fallback_model_access import router_fallback_access_check
from litellm.proxy.auth.handle_jwt import JWTHandler
- from litellm.proxy.auth.litellm_license import LicenseCheck
+ from litellm.proxy.auth.litellm_license import AUTO_ROUTER_LICENSE_REMEDY, LicenseCheck
+from litellm.proxy.auth.login_throttle import LoginThrottle, warn_login_counters_are_per_worker
from litellm.proxy.auth.model_checks import (
expand_wildcard_deployments_for_model_info,
get_all_fallbacks,
@@@ -15180,26 -15747,13 +15753,27 @@@ async def login(request: Request)
password: Final = str(form.get("password"))
# Authenticate user and get login result
- login_result: Final = await authenticate_user(
- username=username,
- password=password,
- master_key=master_key,
- prisma_client=prisma_client,
- general_settings=general_settings,
- )
+ try:
+ login_result: Final = await authenticate_user(
+ username=username,
+ password=password,
+ master_key=master_key,
+ prisma_client=prisma_client,
+ throttle=LoginThrottle.from_request(request),
++ general_settings=general_settings,
+ )
+ except ProxyException as exc:
+ if int(exc.code) != status.HTTP_429_TOO_MANY_REQUESTS:
+ raise
+ retry_after: Final = exc.headers.get("Retry-After", "30")
+ return HTMLResponse(
+ content=(
+ "<html><body><h1>Too many sign-in attempts</h1>"
+ f"<p>Try again in about {retry_after} seconds</p></body></html>"
+ ),
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
+ headers=exc.headers,
+ )
# Create UI token object
returned_ui_token_object: Final = create_ui_token_object(
@@@ -15273,7 -15832,7 +15852,8 @@@ async def login_v2(request: Request)
password=password,
master_key=master_key,
prisma_client=prisma_client,
+ throttle=LoginThrottle.from_request(request),
+ general_settings=general_settings,
)
returned_ui_token_object: Final = create_ui_token_object(
@@@ -15344,7 -15903,7 +15924,8 @@@ async def login_v3(request: Request)
password=password,
master_key=master_key,
prisma_client=prisma_client,
+ throttle=LoginThrottle.from_request(request),
+ general_settings=general_settings,
)
returned_ui_token_object: Final = create_ui_token_object(
diff --cc tests/test_litellm/proxy/auth/test_login_utils.py
index 969103add6f,e209a491b0a..73154c5ecb0
--- a/tests/test_litellm/proxy/auth/test_login_utils.py
+++ b/tests/test_litellm/proxy/auth/test_login_utils.py
@@@ -6,7 -6,7 +6,8 @@@ to login_utils.py for better reusabilit
"""
import os
+ from contextlib import ExitStack
+from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@@ -654,705 -603,356 +657,1069 @@@ class TestEncodeUiSessionJwt
assert _user_id_from_session_cookie(request) == "cornell-user"
+# ---------------------------------------------------------------------------
+# Failed-login accounting (LIT-5285)
+# ---------------------------------------------------------------------------
+
+
+def _throttle(
+ max_attempts: int = 3,
+ window_seconds: int = 900,
+ client_ip: str = "1.2.3.4",
+ cache=None,
+ redis_cache=None,
+ max_attempts_per_source: int = 10_000,
+):
+ """A throttle over a real in-memory store, so the tests exercise the true counters."""
+ from litellm.caching.dual_cache import DualCache
+ from litellm.proxy.auth.login_throttle import LoginThrottle
+
+ store: Final = cache if cache is not None else DualCache()
+ return LoginThrottle(
+ client_ip=client_ip,
+ max_attempts=max_attempts,
+ max_attempts_per_source=max_attempts_per_source,
+ window_seconds=window_seconds,
+ username_cache=store,
+ source_cache=store,
+ redis_cache=redis_cache,
+ )
+
+
+async def _guess(throttle, username: str = "admin", password: str = "wrong"):
+ from litellm.proxy.auth.login_utils import authenticate_user
+
+ return await authenticate_user(
+ username=username,
+ password=password,
+ master_key="sk-master",
+ prisma_client=None,
+ throttle=throttle,
+ )
+
+
+async def test_attempts_are_refused_once_the_limit_is_reached(monkeypatch):
+ """The limit denies further attempts for the window, and the denial carries Retry-After."""
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ throttle = _throttle(max_attempts=3, window_seconds=77)
+
+ for _ in range(3):
+ with pytest.raises(ProxyException) as first:
+ await _guess(throttle)
+ assert first.value.code == "401"
+
+ with pytest.raises(ProxyException) as blocked:
+ await _guess(throttle)
+ assert blocked.value.code == "429"
+ assert blocked.value.headers.get("Retry-After") == "77"
+
+
+async def test_a_correct_admin_password_is_accepted_while_blocked(monkeypatch):
+ """The configured admin credentials are compared before the gate, so the operator gets in.
+
+ A throttle that refuses a valid password hands anyone who can reach the login form a
+ denial of service against the one account that can fix it.
+ """
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ monkeypatch.setenv("DATABASE_URL", "postgresql://stub")
+ throttle = _throttle(max_attempts=2)
+
+ for _ in range(2):
+ with pytest.raises(ProxyException):
+ await _guess(throttle)
+
+ with pytest.raises(ProxyException) as still_blocked:
+ await _guess(throttle)
+ assert still_blocked.value.code == "429", "a wrong password is still refused"
+
+ with patch("litellm.proxy.auth.login_utils.user_update", new=AsyncMock()), patch( # test-quality-ok: success mints a UI key and persists the user; faked so no DB is needed
+ "litellm.proxy.auth.login_utils.generate_key_helper_fn", new=AsyncMock(return_value={"token": "sk-ui"})
+ ):
+ result = await _guess(throttle, password="right")
+ assert result.key == "sk-ui"
+
+
+async def test_a_blocked_attempt_does_not_extend_the_window(monkeypatch):
+ """Hammering while blocked must not push the counter or refresh its TTL."""
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ throttle = _throttle(max_attempts=2)
+ key = throttle._username_key("admin")
+
+ for _ in range(2):
+ with pytest.raises(ProxyException):
+ await _guess(throttle)
+ counted_at_limit = await throttle._failures(throttle.username_cache, key)
+
+ for _ in range(5):
+ with pytest.raises(ProxyException):
+ await _guess(throttle)
+
+ assert await throttle._failures(throttle.username_cache, key) == counted_at_limit == 2
+
+
+async def test_a_successful_sign_in_clears_the_bucket(monkeypatch):
+ """Success resets the budget rather than leaving the operator near the limit."""
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ monkeypatch.setenv("DATABASE_URL", "postgresql://stub")
+ throttle = _throttle(max_attempts=3)
+
+ for _ in range(2):
+ with pytest.raises(ProxyException):
+ await _guess(throttle)
+
+ with patch("litellm.proxy.auth.login_utils.user_update", new=AsyncMock()), patch( # test-quality-ok: success mints a UI key and persists the user; faked so no DB is needed
+ "litellm.proxy.auth.login_utils.generate_key_helper_fn", new=AsyncMock(return_value={"token": "sk-ui"})
+ ):
+ await _guess(throttle, password="right")
+
+ assert await throttle._failures(throttle.username_cache, throttle._username_key("admin")) == 0
+
+
+async def test_a_configuration_error_never_counts(monkeypatch):
+ """A 500 from an unset master key is not a guess and must not consume the budget."""
+ from litellm.proxy._types import ProxyException
+
+ throttle = _throttle(max_attempts=2)
+ for _ in range(5):
+ with pytest.raises(ProxyException) as exc:
+ await authenticate_user(
+ username="admin", password="x", master_key=None, prisma_client=None, throttle=throttle
+ )
+ assert exc.value.code == "500"
+
+ assert await throttle._failures(throttle.username_cache, throttle._username_key("admin")) == 0
+
+
+async def test_the_username_is_case_folded_into_one_bucket(monkeypatch):
+ """The DB lookup is case-insensitive, so casing must not multiply the budget."""
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ throttle = _throttle(max_attempts=4)
+
+ with pytest.raises(ProxyException) as exc:
+ await _guess(throttle, username=name)
+ assert exc.value.code == "401"
+
+ with pytest.raises(ProxyException) as blocked:
+ await _guess(throttle, username="[email protected]")
+ assert blocked.value.code == "429"
+
+
+async def test_a_different_username_from_the_same_source_is_unaffected(monkeypatch):
+ """The counters are independent, so one username's failures do not exhaust another's."""
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ throttle = _throttle(max_attempts=2)
+
+ for _ in range(3):
+ with pytest.raises(ProxyException):
+ await _guess(throttle, username="admin")
+
+ with pytest.raises(ProxyException) as other:
+ await _guess(throttle, username="[email protected]")
+ assert other.value.code == "401", "a second username must still reach the credential check"
+
+
+async def test_both_credential_rejections_are_indistinguishable(monkeypatch):
+ """One message for the known and the unknown username, so responses do not enumerate."""
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+
+ with pytest.raises(ProxyException) as unknown:
+ await _guess(_throttle(max_attempts=99), username="[email protected]")
+
+ fake_user = MagicMock()
+ fake_user.user_id = "u-1"
+ fake_user.user_email = "[email protected]"
+ fake_user.user_role = "internal_user"
+ fake_user.password = "scrypt:fake"
+ repo = MagicMock()
+ repo.return_value.table.find_first = AsyncMock(return_value=fake_user)
+ with patch("litellm.proxy.auth.login_utils.UserRepository", repo), patch( # test-quality-ok: reaches the known-DB-user branch without a database
+ "litellm.proxy.auth.login_utils.verify_password", return_value=False
+ ):
+ with pytest.raises(ProxyException) as known:
+ await authenticate_user(
+ username="[email protected]",
+ password="wrong",
+ master_key="sk-master",
+ prisma_client=MagicMock(),
+ throttle=_throttle(max_attempts=99),
+ )
+
+ assert unknown.value.message == known.value.message
+ assert "[email protected]" not in unknown.value.message + known.value.message
+
+
+async def test_a_user_with_no_password_set_does_not_consume_the_budget(monkeypatch):
+ """That 401 is deterministic and guards no secret, so counting it would only let
+ someone burn a passwordless account's bucket."""
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ throttle = _throttle(max_attempts=2)
+
+ passwordless = MagicMock()
+ passwordless.user_id = "u-2"
+ passwordless.user_email = "[email protected]"
+ passwordless.user_role = "internal_user"
+ passwordless.password = None
+ repo = MagicMock()
+ repo.return_value.table.find_first = AsyncMock(return_value=passwordless)
+
+ with patch("litellm.proxy.auth.login_utils.UserRepository", repo): # test-quality-ok: reaches the passwordless-DB-user branch without a database
+ for _ in range(5):
+ with pytest.raises(ProxyException) as exc:
+ await authenticate_user(
+ username="[email protected]",
+ password="x",
+ master_key="sk-master",
+ prisma_client=MagicMock(),
+ throttle=throttle,
+ )
+ assert exc.value.code == "401"
+
+ assert await throttle._failures(throttle.username_cache, throttle._username_key("[email protected]")) == 0
+
+
+async def test_a_wrong_password_for_a_known_user_also_counts(monkeypatch):
+ """The database-user branch must charge the bucket too, not just the unknown-user branch."""
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ throttle = _throttle(max_attempts=3)
+
+ known = MagicMock()
+ known.user_id = "u-1"
+ known.user_email = "[email protected]"
+ known.user_role = "internal_user"
+ known.password = "scrypt:stored"
+ repo = MagicMock()
+ repo.return_value.table.find_first = AsyncMock(return_value=known)
+
+ async def _attempt():
+ return await authenticate_user(
+ username="[email protected]",
+ password="wrong",
+ master_key="sk-master",
+ prisma_client=MagicMock(),
+ throttle=throttle,
+ )
+
+ with patch("litellm.proxy.auth.login_utils.UserRepository", repo), patch( # test-quality-ok: reaches the known-DB-user branch without a database
+ "litellm.proxy.auth.login_utils.verify_password", return_value=False
+ ):
+ for _ in range(3):
+ with pytest.raises(ProxyException) as rejected:
+ await _attempt()
+ assert rejected.value.code == "401"
+
+ with pytest.raises(ProxyException) as blocked:
+ await _attempt()
+ assert blocked.value.code == "429"
+
+
+async def test_one_source_exhausting_its_own_budget_does_not_refuse_another_source(monkeypatch):
+ """The source counter is per address, so a noisy office does not take its neighbour down."""
+ from litellm.caching.dual_cache import DualCache
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ shared_store = DualCache()
+ attacker = _throttle(
+ max_attempts=10_000, max_attempts_per_source=2, client_ip="203.0.113.9", cache=shared_store
+ )
+ operator = _throttle(
+ max_attempts=10_000, max_attempts_per_source=2, client_ip="198.51.100.7", cache=shared_store
+ )
+
+ for i in range(2):
+ with pytest.raises(ProxyException):
+ await _guess(attacker, username=f"target-{i}@corp.com")
+
+ with pytest.raises(ProxyException) as blocked:
+ await _guess(attacker, username="[email protected]")
+ assert blocked.value.code == "429"
+
+ with pytest.raises(ProxyException) as unaffected:
+ await _guess(operator, username="[email protected]")
+ assert unaffected.value.code == "401", "the other address must still reach the credential check"
+
+
+async def test_a_username_exhausted_from_one_source_is_refused_from_another(monkeypatch):
+ """The username counter carries no address, so spreading the guesses buys nothing.
+
+ The pair key this replaced reset the budget for every new address, which is exactly the
+ shape of a credential-stuffing run from a proxy pool.
+ """
+ from litellm.caching.dual_cache import DualCache
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ shared_store = DualCache()
+ first_hop = _throttle(max_attempts=2, client_ip="203.0.113.9", cache=shared_store)
+ second_hop = _throttle(max_attempts=2, client_ip="198.51.100.7", cache=shared_store)
+
+ for _ in range(2):
+ with pytest.raises(ProxyException):
+ await _guess(first_hop, username="[email protected]")
+
+ with pytest.raises(ProxyException) as rotated:
+ await _guess(second_hop, username="[email protected]")
+ assert rotated.value.code == "429"
+
+
+async def test_a_source_wide_spray_is_counted_even_though_each_username_is_fresh(monkeypatch):
+ """One guess against each of many usernames never trips a username counter, only the source one."""
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ throttle = _throttle(max_attempts=10_000, max_attempts_per_source=6, client_ip="203.0.113.11")
+
+ for i in range(6):
+ with pytest.raises(ProxyException) as rejected:
+ await _guess(throttle, username=f"sprayed-{i}@corp.com")
+ assert rejected.value.code == "401"
+
+ with pytest.raises(ProxyException) as blocked:
+ await _guess(throttle, username="[email protected]")
+ assert blocked.value.code == "429"
+ assert await throttle._failures(throttle.username_cache, throttle._username_key("[email protected]")) == 0
+
+
+async def test_a_successful_sign_in_leaves_the_source_counter_alone(monkeypatch):
+ """One account's success says nothing about the other attempts the address is making."""
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ monkeypatch.setenv("DATABASE_URL", "postgresql://stub")
+ throttle = _throttle(max_attempts=10)
+
+ for _ in range(2):
+ with pytest.raises(ProxyException):
+ await _guess(throttle)
+
+ with patch("litellm.proxy.auth.login_utils.user_update", new=AsyncMock()), patch( # test-quality-ok: success mints a UI key and persists the user; faked so no DB is needed
+ "litellm.proxy.auth.login_utils.generate_key_helper_fn", new=AsyncMock(return_value={"token": "sk-ui"})
+ ):
+ await _guess(throttle, password="right")
+
+ assert await throttle._failures(throttle.username_cache, throttle._username_key("admin")) == 0
+ assert await throttle._failures(throttle.source_cache, throttle._source_key()) == 2
+
+
+async def test_the_delay_doubles_from_one_second_and_is_capped(monkeypatch, login_delays):
+ """Guessing has to cost wall clock, and the cost has to stop short of an unbounded hang."""
+ from litellm.proxy._types import ProxyException
+ from litellm.proxy.auth.login_throttle import MAX_DELAY_SECONDS
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ throttle = _throttle(max_attempts=10_000)
+
+ for _ in range(9):
+ with pytest.raises(ProxyException):
+ await _guess(throttle)
+
+ assert login_delays.seconds == [1.0, 2.0, 4.0, 8.0, 16.0, 30.0, 30.0], (
+ "the first two failures answer immediately, then the wait doubles up to the cap"
+ )
+ assert max(login_delays.seconds) == MAX_DELAY_SECONDS
+
+
+async def test_the_delay_tracks_whichever_counter_is_further_past_its_onset(monkeypatch):
+ """A source deep into a spray must not be answered instantly just because the username is fresh."""
+ from litellm.proxy.auth.login_throttle import FailureCounts, LoginThrottle
+
+ assert LoginThrottle.delay_seconds(FailureCounts(username=1, source=1)) == 0.0
+ assert LoginThrottle.delay_seconds(FailureCounts(username=2, source=24)) == 0.0
+ assert LoginThrottle.delay_seconds(FailureCounts(username=3, source=1)) == 1.0
+ assert LoginThrottle.delay_seconds(FailureCounts(username=1, source=25)) == 1.0
+ assert LoginThrottle.delay_seconds(FailureCounts(username=4, source=28)) == 8.0
+
+
+async def test_held_attempts_from_one_source_are_capped(monkeypatch):
+ """Holding a rejected attempt open must not let one address park unlimited sockets."""
+ import asyncio
+
+ from litellm.proxy._types import ProxyException
+ from litellm.proxy.auth import login_throttle as lt
+ from litellm.proxy.auth.login_throttle import MAX_CONCURRENT_DELAYS_PER_SOURCE
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ release = asyncio.Event()
+
+ async def _park(_seconds: float) -> None:
+ await release.wait()
+
+ monkeypatch.setattr(lt, "_sleep", _park)
+ throttle = _throttle(max_attempts=10_000, client_ip="203.0.113.44")
+ await throttle.record_failure("admin")
+ await throttle.record_failure("admin")
+
+ held = [asyncio.create_task(_guess(throttle)) for _ in range(MAX_CONCURRENT_DELAYS_PER_SOURCE)]
+ for _ in range(1000):
+ if lt._DELAYS_IN_FLIGHT.get("203.0.113.44") == MAX_CONCURRENT_DELAYS_PER_SOURCE:
+ break
+ await asyncio.sleep(0)
+ assert lt._DELAYS_IN_FLIGHT.get("203.0.113.44") == MAX_CONCURRENT_DELAYS_PER_SOURCE
+
+ try:
+ with pytest.raises(ProxyException) as over_cap:
+ await _guess(throttle)
+ assert over_cap.value.code == "429"
+ assert over_cap.value.headers.get("Retry-After") == "30"
+ finally:
+ release.set()
+ for task in held:
+ with pytest.raises(ProxyException):
+ await task
+
+ with pytest.raises(ProxyException) as after_drain:
+ await _guess(throttle)
+ assert after_drain.value.code == "401", "the cap must release once the held attempts answer"
+
+
+async def test_disabling_the_control_removes_the_delay_as_well(monkeypatch, login_delays):
+ """The escape hatch has to turn off the whole control, not only the refusal."""
+ import dataclasses
+
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ throttle = dataclasses.replace(_throttle(max_attempts=2), enabled=False)
+
+ for _ in range(6):
+ with pytest.raises(ProxyException) as rejected:
+ await _guess(throttle)
+ assert rejected.value.code == "401"
+
+ assert login_delays.seconds == []
+
+
+class _NoExpiryRedis:
+ """Redis that stores the counter but never records an expiry for it.
+
+ Models the window between INCRBYFLOAT committing and the TTL call failing.
+ """
+
+ def __init__(self):
+ self.values: dict = {}
+ self.expiry_repairs = 0
+
+ async def async_get_cache(self, key, **kwargs):
+ return self.values.get(key)
+
+ async def async_increment(self, key, value, ttl=None, **kwargs):
+ if int(value) == 0:
+ self.expiry_repairs += 1
+ self.values[key] = self.values.get(key, 0) + int(value)
+ return self.values[key]
+
+ async def async_get_ttl(self, key):
+ return None
+
+ async def async_delete_cache(self, key):
+ self.values.pop(key, None)
+
+
+async def test_a_counter_left_without_an_expiry_is_repaired(monkeypatch):
+ """Regression: a counter with no TTL would refuse the pair forever.
+
+ Redis commits the increment before setting the expiry, and nothing increments the key
+ again once the limit is reached, so a TTL that never landed is never repaired on its
+ own and the username and source pair stays refused with no way back.
+ """
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ redis = _NoExpiryRedis()
+ throttle = _throttle(max_attempts=2, redis_cache=redis)
+
+ for _ in range(2):
+ with pytest.raises(ProxyException):
+ await _guess(throttle)
+
+ assert redis.expiry_repairs >= 1, "each recorded failure must leave the counter with an expiry"
+
+ repairs_before_block = redis.expiry_repairs
+ with pytest.raises(ProxyException) as blocked:
+ await _guess(throttle)
+ assert blocked.value.code == "429"
+ assert redis.expiry_repairs > repairs_before_block, "the refusal path must repair a missing expiry too"
+
+
+async def test_counters_do_not_share_the_key_authentication_cache(monkeypatch):
+ """Regression: throttle entries must not evict cached credentials.
+
+ user_api_key_cache holds at most 200 in-memory entries and evicts the soonest to
+ expire first, so parking 900s sign-in counters there let a stream of made-up usernames
+ push out the much shorter lived credential entries, sending every ordinary API request
+ back to the database.
+ """
+ from litellm.proxy import proxy_server as ps
+ from litellm.proxy.auth.login_throttle import _CACHE_KEY_PREFIX, LoginThrottle
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ monkeypatch.setattr(ps, "redis_usage_cache", None)
+
+ auth_cache_keys_before = set(ps.user_api_key_cache.in_memory_cache.cache_dict)
+
+ request = MagicMock()
+ request.headers = {}
+ request.client = MagicMock()
+ request.client.host = "1.2.3.4"
+ throttle = LoginThrottle.from_request(request)
+
+ for i in range(25):
+ with pytest.raises(ProxyException, match="Invalid credentials"):
+ await _guess(throttle, username=f"made-up-{i}@example.com")
+
+ added = set(ps.user_api_key_cache.in_memory_cache.cache_dict) - auth_cache_keys_before
+ assert not [k for k in added if str(k).startswith(_CACHE_KEY_PREFIX)], (
+ "sign-in counters must live in their own cache, not the key-authentication cache"
+ )
+
+
+def test_settings_that_arrive_as_environment_strings_are_honored(monkeypatch):
+ """An `os.environ/VAR` reference in general_settings resolves to a string, not an int.
+
+ Regression: a digit string fell back to the default with only a log line, so an operator
+ tightening the limits through environment substitution silently kept the stock ceilings.
+ """
+ from litellm.proxy import proxy_server as ps
+ from litellm.proxy.auth.login_throttle import LoginThrottle
+
+ monkeypatch.setattr(
+ ps,
+ "general_settings",
+ {
+ "max_failed_login_attempts": "7",
+ "max_failed_login_attempts_per_source": " 70 ",
+ "failed_login_window_seconds": "not-a-number",
+ },
+ )
+ request = MagicMock()
+ request.headers = {}
+ request.client = MagicMock()
+ request.client.host = "1.2.3.4"
+
+ throttle = LoginThrottle.from_request(request)
+
+ assert throttle.max_attempts == 7
+ assert throttle.max_attempts_per_source == 70
+ assert throttle.window_seconds == 900, "garbage still falls back to the default"
+
+
+def test_a_negative_or_boolean_setting_falls_back_to_the_default(monkeypatch):
+ """A limit below one would refuse everyone; a bool is a typo, not a count."""
+ from litellm.proxy import proxy_server as ps
+ from litellm.proxy.auth.login_throttle import LoginThrottle
+
+ monkeypatch.setattr(
+ ps,
+ "general_settings",
+ {"max_failed_login_attempts": "-7", "max_failed_login_attempts_per_source": True},
+ )
+ request = MagicMock()
+ request.headers = {}
+ request.client = MagicMock()
+ request.client.host = "1.2.3.4"
+
+ throttle = LoginThrottle.from_request(request)
+
+ assert throttle.max_attempts == 50
+ assert throttle.max_attempts_per_source == 250
+
+
+async def test_a_refused_username_cannot_forge_log_lines(monkeypatch):
+ """The username reaches a warning log, so it must not carry newlines or control bytes."""
+ import logging
+
+ from litellm._logging import verbose_proxy_logger
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ throttle = _throttle(max_attempts=1)
+ forged = "[email protected]\nWARNING: sign-in succeeded for attacker\x00"
+
+ with pytest.raises(ProxyException):
+ await _guess(throttle, username=forged)
+
+ records: list[logging.LogRecord] = []
+ handler = logging.Handler()
+ handler.emit = records.append
+ verbose_proxy_logger.addHandler(handler)
+ try:
+ with pytest.raises(ProxyException) as blocked:
+ await _guess(throttle, username=forged)
+ finally:
+ verbose_proxy_logger.removeHandler(handler)
+
+ assert blocked.value.code == "429"
+ emitted = [r.getMessage() for r in records if "sign-in attempts exhausted" in r.getMessage()]
+ assert emitted, "the refusal must be logged"
+ assert "\n" not in emitted[0] and "\x00" not in emitted[0]
+ assert "[email protected]" in emitted[0]
+
+
+async def test_a_username_spray_cannot_evict_an_existing_counter(monkeypatch):
+ """Regression: the in-memory tier must hold more counters than a spray can create.
+
+ The default in-memory cache keeps 200 entries and evicts the soonest to expire, and
+ every counter shares one window, so eviction was effectively oldest-first. A few
+ hundred made-up usernames therefore pushed out the attacker's own counter and handed
+ back a fresh allowance against the real account.
+ """
+ from litellm.proxy._types import ProxyException
+ from litellm.proxy.auth.login_throttle import (
+ LoginThrottle,
+ _FAILED_LOGIN_SOURCE_CACHE,
+ _FAILED_LOGIN_USERNAME_CACHE,
+ _MAX_TRACKED_LOGIN_SOURCES,
+ _MAX_TRACKED_LOGIN_USERNAMES,
+ )
+
+ monkeypatch.setenv("UI_USERNAME", "admin")
+ monkeypatch.setenv("UI_PASSWORD", "right")
+ assert _MAX_TRACKED_LOGIN_SOURCES >= 10_000
+ assert _MAX_TRACKED_LOGIN_USERNAMES >= 10_000
+ assert _FAILED_LOGIN_SOURCE_CACHE.in_memory_cache.max_size_in_memory == _MAX_TRACKED_LOGIN_SOURCES
+ assert _FAILED_LOGIN_USERNAME_CACHE.in_memory_cache.max_size_in_memory == _MAX_TRACKED_LOGIN_USERNAMES
+
+ throttle = LoginThrottle(
+ client_ip="10.9.9.9",
+ max_attempts=3,
+ max_attempts_per_source=10_000,
+ window_seconds=900,
+ username_cache=_FAILED_LOGIN_USERNAME_CACHE,
+ source_cache=_FAILED_LOGIN_SOURCE_CACHE,
+ )
+ victim = "[email protected]"
+ for _ in range(3):
+ with pytest.raises(ProxyException):
+ await _guess(throttle, username=victim)
+
+ for i in range(500):
+ await throttle.record_failure(f"spray-filler-{i}@corp.com")
+
+ assert await throttle._failures(throttle.username_cache, throttle._username_key(victim)) == 3, "the counter must survive a spray"
+ with pytest.raises(ProxyException) as blocked:
+ await _guess(throttle, username=victim)
+ assert blocked.value.code == "429"
++
++
+ def _patch_sso_configured(stack: ExitStack, *, configured: bool) -> None:
+ stack.enter_context(
+ patch( # test-quality-ok: no HTTP boundary here; same internal the pre-existing tests above already mock
+ "litellm.proxy.auth.login_utils.is_sso_provider_fully_configured", return_value=configured
+ )
+ )
+
+
+ def _patch_successful_admin_login_deps(stack: ExitStack) -> None:
+ """The collaborators a real admin login exercises past the SSO gate:
+ generating the UI session key, syncing the admin role, and reading the
+ experimental-login flag. Shared so the two "still allowed" tests below
+ don't each repeat the same three-mock wiring."""
+ stack.enter_context(
+ patch( # test-quality-ok: internal orchestration, no HTTP boundary; matches pre-existing tests
+ "litellm.proxy.auth.login_utils.generate_key_helper_fn",
+ new_callable=AsyncMock,
+ return_value={"token": "test-token", "user_id": LITELLM_PROXY_ADMIN_NAME},
+ )
+ )
+ stack.enter_context(
+ patch( # test-quality-ok: internal orchestration, no HTTP boundary; matches pre-existing tests
+ "litellm.proxy.auth.login_utils.user_update",
+ new_callable=AsyncMock,
+ return_value=None,
+ )
+ )
+ stack.enter_context(
+ patch( # test-quality-ok: internal orchestration, no HTTP boundary; matches pre-existing tests
+ "litellm.proxy.auth.login_utils.get_secret_bool",
+ return_value=False,
+ )
+ )
+
+
+ class TestDisablePasswordLoginWhenSSOEnabled:
+ """`disable_password_login_when_sso_enabled` must reject every
+ username/password login attempt (including the UI_USERNAME/UI_PASSWORD
+ admin fallback) once SSO is configured, so SSO becomes the only way to
+ reach the Admin UI. It must not affect logins when SSO is unconfigured,
+ so admins can never lock themselves out with no SSO to fall back to."""
+
+ @pytest.mark.asyncio
+ async def test_rejects_correct_admin_credentials_when_sso_configured(self):
+ master_key = "sk-1234"
+ ui_username = "admin"
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_usertable.find_first = AsyncMock(return_value=None)
+
+ with patch.dict(os.environ, {"UI_USERNAME": ui_username, "UI_PASSWORD": master_key}):
+ with ExitStack() as stack:
+ _patch_sso_configured(stack, configured=True)
+ with pytest.raises(ProxyException) as exc_info:
+ await authenticate_user(
+ username=ui_username,
+ password=master_key,
+ master_key=master_key,
+ prisma_client=mock_prisma_client,
++ throttle=_unlimited_throttle(),
+ general_settings={"disable_password_login_when_sso_enabled": True},
+ )
+
+ assert exc_info.value.type == ProxyErrorTypes.auth_error
+ assert exc_info.value.code == "403"
+ # The credential comparison must never even run.
+ mock_prisma_client.db.litellm_usertable.find_first.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_rejects_correct_db_user_credentials_when_sso_configured(self):
+ master_key = "sk-1234"
+ user_email = "[email protected]"
+ password = "correct-password"
+
+ mock_user = LiteLLM_UserTable(
+ user_id="test-user-123",
+ user_email=user_email,
+ password=hash_token(token=password),
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ )
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_usertable.find_first = AsyncMock(return_value=mock_user)
+
+ with patch.dict(os.environ, {"UI_USERNAME": "admin", "UI_PASSWORD": "unrelated"}):
+ with ExitStack() as stack:
+ _patch_sso_configured(stack, configured=True)
+ with pytest.raises(ProxyException) as exc_info:
+ await authenticate_user(
+ username=user_email,
+ password=password,
+ master_key=master_key,
+ prisma_client=mock_prisma_client,
++ throttle=_unlimited_throttle(),
+ general_settings={"disable_password_login_when_sso_enabled": True},
+ )
+
+ assert exc_info.value.code == "403"
+ mock_prisma_client.db.litellm_usertable.find_first.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_allows_password_login_when_setting_enabled_but_sso_not_configured(self):
+ """The setting alone must not lock out an admin who has not actually
+ configured SSO — there would be no fallback left."""
+ master_key = "sk-1234"
+ ui_username = "admin"
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_usertable.find_first = AsyncMock(return_value=None)
+
+ with patch.dict(
+ os.environ,
+ {
+ "UI_USERNAME": ui_username,
+ "UI_PASSWORD": master_key,
+ "DATABASE_URL": "postgresql://test:test@localhost/test",
+ },
+ clear=True,
+ ):
+ with ExitStack() as stack:
+ _patch_sso_configured(stack, configured=False)
+ _patch_successful_admin_login_deps(stack)
+ result = await authenticate_user(
+ username=ui_username,
+ password=master_key,
+ master_key=master_key,
+ prisma_client=mock_prisma_client,
++ throttle=_unlimited_throttle(),
+ general_settings={"disable_password_login_when_sso_enabled": True},
+ )
+
+ assert isinstance(result, LoginResult)
+ assert result.user_id == LITELLM_PROXY_ADMIN_NAME
+
+ @pytest.mark.asyncio
+ async def test_allows_password_login_when_sso_env_is_incomplete(self):
+ """Regression: a lone MICROSOFT_CLIENT_ID with no client secret or
+ tenant makes has_user_setup_sso() True, but a real SSO sign-in would
+ fail. The gate must read the real env (no is_sso_provider_fully_configured
+ mock here) and still let password login through, or an admin who set
+ one env var by mistake is locked out with no way in."""
+ master_key = "sk-1234"
+ ui_username = "admin"
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_usertable.find_first = AsyncMock(return_value=None)
+
+ with patch.dict(
+ os.environ,
+ {
+ "UI_USERNAME": ui_username,
+ "UI_PASSWORD": master_key,
+ "DATABASE_URL": "postgresql://test:test@localhost/test",
+ "MICROSOFT_CLIENT_ID": "ms-client-id-only",
+ },
+ clear=True,
+ ):
+ with ExitStack() as stack:
+ _patch_successful_admin_login_deps(stack)
+ result = await authenticate_user(
+ username=ui_username,
+ password=master_key,
+ master_key=master_key,
+ prisma_client=mock_prisma_client,
++ throttle=_unlimited_throttle(),
+ general_settings={"disable_password_login_when_sso_enabled": True},
+ )
+
+ assert isinstance(result, LoginResult)
+ assert result.user_id == LITELLM_PROXY_ADMIN_NAME
+
+ @pytest.mark.asyncio
+ async def test_allows_password_login_when_sso_configured_but_setting_not_enabled(self):
+ """SSO being configured must not, by itself, disable the password
+ fallback: the setting is opt-in."""
+ master_key = "sk-1234"
+ ui_username = "admin"
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_usertable.find_first = AsyncMock(return_value=None)
+
+ with patch.dict(
+ os.environ,
+ {
+ "UI_USERNAME": ui_username,
+ "UI_PASSWORD": master_key,
+ "DATABASE_URL": "postgresql://test:test@localhost/test",
+ },
+ clear=True,
+ ):
+ with ExitStack() as stack:
+ _patch_sso_configured(stack, configured=True)
+ _patch_successful_admin_login_deps(stack)
+ result = await authenticate_user(
+ username=ui_username,
+ password=master_key,
+ master_key=master_key,
+ prisma_client=mock_prisma_client,
++ throttle=_unlimited_throttle(),
+ general_settings={},
+ )
+
+ assert isinstance(result, LoginResult)
+ assert result.user_id == LITELLM_PROXY_ADMIN_NAME
+
+
+ class TestDisableEnvCredentialLogin:
+ """`disable_env_credential_login` must reject a login with the env
+ credentials (UI_USERNAME/UI_PASSWORD, or the master-key fallback when
+ UI_PASSWORD is unset) while leaving database-user password logins
+ untouched, so admins with real accounts keep a way in."""
+
+ @pytest.mark.asyncio
+ async def test_rejects_correct_env_credentials_when_disabled(self):
+ master_key = "sk-1234"
+ ui_username = "admin"
+ ui_password = "env-only-password"
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_usertable.find_first = AsyncMock(return_value=None)
+
+ with patch.dict(os.environ, {"UI_USERNAME": ui_username, "UI_PASSWORD": ui_password}):
+ with pytest.raises(ProxyException) as exc_info:
+ await authenticate_user(
+ username=ui_username,
+ password=ui_password,
+ master_key=master_key,
+ prisma_client=mock_prisma_client,
++ throttle=_unlimited_throttle(),
+ general_settings={"disable_env_credential_login": True},
+ )
+
+ assert exc_info.value.type == ProxyErrorTypes.auth_error
+ assert exc_info.value.code == "401"
+ assert "UI_USERNAME" not in exc_info.value.message
+ assert "UI_PASSWORD" not in exc_info.value.message
+
+ @pytest.mark.asyncio
+ async def test_rejects_master_key_fallback_when_disabled(self):
+ """With UI_PASSWORD unset, the master key IS the env password, so the
+ setting must reject it too or it protects nothing by default."""
+ master_key = "sk-1234"
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_usertable.find_first = AsyncMock(return_value=None)
+
+ with patch.dict(os.environ, {"UI_USERNAME": "admin"}, clear=True):
+ with pytest.raises(ProxyException) as exc_info:
+ await authenticate_user(
+ username="admin",
+ password=master_key,
+ master_key=master_key,
+ prisma_client=mock_prisma_client,
++ throttle=_unlimited_throttle(),
+ general_settings={"disable_env_credential_login": True},
+ )
+
+ assert exc_info.value.code == "401"
+
+ @pytest.mark.asyncio
+ async def test_db_user_login_still_works_when_disabled(self):
+ master_key = "sk-1234"
+ user_email = "[email protected]"
+ password = "Str0ng!Passw0rd"
+
+ mock_user = LiteLLM_UserTable(
+ user_id="db-admin-1",
+ user_email=user_email,
+ password=hash_token(token=password),
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ )
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_usertable.find_first = AsyncMock(return_value=mock_user)
+
+ with patch.dict(
+ os.environ,
+ {
+ "UI_USERNAME": "admin",
+ "UI_PASSWORD": "env-password",
+ "DATABASE_URL": "postgresql://test:test@localhost/test",
+ },
+ clear=True,
+ ):
+ with ExitStack() as stack:
+ stack.enter_context(
+ patch( # test-quality-ok: internal orchestration, no HTTP boundary; matches pre-existing tests
+ "litellm.proxy.auth.login_utils.generate_key_helper_fn",
+ new_callable=AsyncMock,
+ return_value={"token": "db-user-token"},
+ )
+ )
+ result = await authenticate_user(
+ username=user_email,
+ password=password,
+ master_key=master_key,
+ prisma_client=mock_prisma_client,
++ throttle=_unlimited_throttle(),
+ general_settings={"disable_env_credential_login": True},
+ )
+
+ assert isinstance(result, LoginResult)
+ assert result.user_id == "db-admin-1"
+ assert result.user_role == LitellmUserRoles.PROXY_ADMIN
+
+ @pytest.mark.asyncio
+ async def test_env_login_still_works_when_setting_absent(self):
+ """Env-credential login is the bootstrap path on a fresh install and
+ must stay on by default."""
+ master_key = "sk-1234"
+ ui_username = "admin"
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_usertable.find_first = AsyncMock(return_value=None)
+
+ with patch.dict(
+ os.environ,
+ {
+ "UI_USERNAME": ui_username,
+ "UI_PASSWORD": master_key,
+ "DATABASE_URL": "postgresql://test:test@localhost/test",
+ },
+ clear=True,
+ ):
+ with ExitStack() as stack:
+ _patch_successful_admin_login_deps(stack)
+ result = await authenticate_user(
+ username=ui_username,
+ password=master_key,
+ master_key=master_key,
+ prisma_client=mock_prisma_client,
++ throttle=_unlimited_throttle(),
+ general_settings={},
+ )
+
+ assert isinstance(result, LoginResult)
+ assert result.user_id == LITELLM_PROXY_ADMIN_NAME
+
+
+ class TestIsEnvCredentialLoginEnabled:
+ """Drives the Admin UI warning banner: it must be True exactly when a
+ login with the env credentials could actually succeed."""
+
+ def test_enabled_by_default(self):
+ assert is_env_credential_login_enabled({}) is True
+
+ def test_disabled_by_dedicated_setting(self):
+ assert is_env_credential_login_enabled({"disable_env_credential_login": True}) is False
+
+ def test_explicit_false_keeps_it_enabled(self):
+ assert is_env_credential_login_enabled({"disable_env_credential_login": False}) is True
+
+ def test_disabled_when_sso_gate_blocks_all_password_logins(self):
+ """`disable_password_login_when_sso_enabled` with SSO configured
+ rejects every username/password login before the env comparison runs,
+ so the banner must not nag about an already-unreachable path."""
+ with ExitStack() as stack:
+ _patch_sso_configured(stack, configured=True)
+ assert is_env_credential_login_enabled({"disable_password_login_when_sso_enabled": True}) is False
+
+ def test_enabled_when_sso_gate_is_set_but_sso_not_configured(self):
+ with ExitStack() as stack:
+ _patch_sso_configured(stack, configured=False)
+ assert is_env_credential_login_enabled({"disable_password_login_when_sso_enabled": True}) is True
diff --cc tests/test_litellm/proxy/proxy_server/test_routes_login_sso.py
index 22d96fdc254,45460dcecf1..a803f294ebc
--- a/tests/test_litellm/proxy/proxy_server/test_routes_login_sso.py
+++ b/tests/test_litellm/proxy/proxy_server/test_routes_login_sso.py
@@@ -30,7 -29,7 +30,7 @@@ def _install_login_mocks(monkeypatch, r
"""
from litellm.proxy import proxy_server as ps
- async def _fake_auth(username, password, master_key, prisma_client, throttle=None):
- async def _fake_auth(username, password, master_key, prisma_client, general_settings=None):
++ async def _fake_auth(username, password, master_key, prisma_client, throttle=None, general_settings=None):
if raise_on_auth:
raise Exception("boom-auth-failure")
fake = MagicMock()
diff --cc tests/test_litellm/proxy/test_proxy_server.py
index 3128d58b566,e058a4f6396..2f8d5cbc43a
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@@ -26,8 -29,7 +28,8 @@@ from litellm.caching.caching import Red
from litellm.caching.redis_cluster_cache import RedisClusterCache
from litellm.litellm_core_utils.get_model_cost_map import ModelCostMapReloaded
from litellm.caching.dual_cache import DualCache
- from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
+ from litellm.proxy._types import LitellmUserRoles, TokenCountRequest, UserAPIKeyAuth
+from litellm.proxy.auth.login_throttle import LoginThrottle
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.proxy_server import app, initialize
from litellm.utils import _invalidate_model_cost_lowercase_map
@@@ -125,13 -127,13 +127,14 @@@ def test_login_v2_returns_redirect_url_
}
assert response.cookies.get("token") == "signed-token"
- mock_authenticate_user.assert_awaited_once_with(
- username="alice",
- password="secret",
- master_key="test-master-key",
- prisma_client=mock_prisma_client,
- general_settings={},
- )
+ mock_authenticate_user.assert_awaited_once()
+ auth_kwargs = mock_authenticate_user.call_args.kwargs
+ assert auth_kwargs["username"] == "alice"
+ assert auth_kwargs["password"] == "secret"
+ assert auth_kwargs["master_key"] == "test-master-key"
+ assert auth_kwargs["prisma_client"] is mock_prisma_client
++ assert auth_kwargs["general_settings"] == {}
+ assert isinstance(auth_kwargs["throttle"], LoginThrottle), "the endpoint must thread a throttle through"
mock_create_ui_token_object.assert_called_once_with(
login_result=mock_login_result,
general_settings={},
diff --cc ui/litellm-dashboard/src/lib/http/schema.d.ts
index 684ddb982a6,6826cded6f5..dfe0febc42f
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@@ -25520,16 -25954,16 +25959,26 @@@ export interface components
* @description max batch input file size in MB for /v1/files uploads with purpose=batch, if a file is larger than this size it will be rejected before being forwarded to the provider
*/
max_batch_file_size_mb?: number | null;
+ /**
+ * Max Failed Login Attempts
+ * @description Number of failed Admin UI sign-in attempts allowed for one username, from any source address, within `failed_login_window_seconds`, before further attempts for that username are refused with 429. Attempts are answered with a doubling delay well before this ceiling. Set under `general_settings` in config.yaml. Defaults to 50
+ */
+ max_failed_login_attempts?: number | null;
+ /**
+ * Max Failed Login Attempts Per Source
+ * @description Number of failed Admin UI sign-in attempts allowed from one source address, across every username, within `failed_login_window_seconds`, before further attempts from that address are refused with 429. Counted independently of `max_failed_login_attempts`. Set under `general_settings` in config.yaml. Defaults to 250
+ */
+ max_failed_login_attempts_per_source?: number | null;
+ /**
+ * Max File Size Mb
+ * @description max file size in MB for /v1/files uploads, for any purpose, if a file is larger than this size it will be rejected before being forwarded to the provider
+ */
+ max_file_size_mb?: number | null;
+ /**
+ * Max In Flight Requests Per Worker
+ * @description maximum concurrent requests handled by each worker
+ */
+ max_in_flight_requests_per_worker?: number | null;
/**
* Max Parallel Requests
* @description maximum parallel requests for each api key