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 main into litellm_cherry_pick_password_breach_reset

ryan7c8aed072f1a
diff --cc tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
index 6e11dbb6bae,ede0ecb2790..75545a574e3
--- a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
@@@ -4468,149 -4691,42 +4468,188 @@@ async def test_user_update_hashes_and_p
written_data = mock_prisma_client.update_data.call_args.kwargs["data"]
assert written_data.get("password") is not None
assert written_data["password"] != strong_password
+ # An admin-set password is known to the admin, so the user must be forced
+ # to change it at next login and the breach screen re-armed.
+ assert written_data["password_reset_required"] is True
+ assert written_data["last_breach_check_at"] is None
+
+
+async def test_user_update_rejects_breached_password(_admin_prisma):
+ """A strength-passing password found in the HIBP corpus must be rejected
+ before it ever reaches the DB write."""
+ from litellm.proxy.management_endpoints.internal_user_endpoints import (
+ _update_single_user_helper,
+ )
+
+ password = "Str0ng!Passw0rd"
+ sha1 = hashlib.sha1(password.encode("utf-8"), usedforsecurity=False).hexdigest().upper()
+ respx.get(f"https://api.pwnedpasswords.com/range/{sha1[:5]}").mock(
+ return_value=httpx.Response(200, text=f"{sha1[5:]}:1387")
+ )
+
+ user_request = UpdateUserRequest(user_id="target-user", password=password)
+ admin_caller = UserAPIKeyAuth(user_id="admin-1", user_role=LitellmUserRoles.PROXY_ADMIN)
+
+ with pytest.raises(ProxyException) as exc_info:
+ await _update_single_user_helper(user_request=user_request, user_api_key_dict=admin_caller)
+
+ assert exc_info.value.code == "400"
+ assert "data breaches" in exc_info.value.message
+ _admin_prisma.db.litellm_usertable.find_first.assert_not_called()
+
+
+async def test_bulk_update_all_users_rejects_a_password(_admin_prisma):
+ """The all_users fast path writes user_updates straight to update_many,
+ bypassing _update_single_user_helper. A password riding along would be
+ stored as unvalidated plaintext on every row, so it must be rejected
+ before any DB access."""
+ from fastapi import HTTPException
+
+ from litellm.proxy._types import UpdateUserRequestNoUserIDorEmail
+ from litellm.proxy.management_endpoints.internal_user_endpoints import bulk_user_update
+ from litellm.types.proxy.management_endpoints.internal_user_endpoints import (
+ BulkUpdateUserRequest,
+ )
+
+ data = BulkUpdateUserRequest(
+ all_users=True,
+ user_updates=UpdateUserRequestNoUserIDorEmail(password="Str0ng!Passw0rd"),
+ )
+ admin_caller = UserAPIKeyAuth(user_id="admin-1", user_role=LitellmUserRoles.PROXY_ADMIN)
+
+ with pytest.raises(HTTPException) as exc_info:
+ await bulk_user_update(data=data, user_api_key_dict=admin_caller)
+
+ assert exc_info.value.status_code == 400
+ assert "not supported" in str(exc_info.value.detail)
+ _admin_prisma.db.litellm_usertable.find_many.assert_not_called()
+ _admin_prisma.db.litellm_usertable.update_many.assert_not_called()
+
+
+def _hibp_client_with_handler(handler) -> AsyncHTTPHandler:
+ """A real AsyncHTTPHandler over httpx.MockTransport (the DI seam used
+ throughout test_password_policy.py), so no network is touched."""
+ http_handler = AsyncHTTPHandler()
+ http_handler.client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
+ return http_handler
+
+
+async def test_bulk_update_breached_password_fails_only_that_user(_admin_prisma, mocker):
+ """In a bulk batch, a breached password fails only its own entry, before
+ any DB write for it; sibling entries with acceptable passwords persist."""
+ from litellm.proxy.management_endpoints.internal_user_endpoints import (
+ bulk_update_processed_users,
+ )
+
+ breached = "Br3ached!Passw0rd"
+ clean = "NewP@ssw0rd123"
+ breached_sha1 = hashlib.sha1(breached.encode("utf-8"), usedforsecurity=False).hexdigest().upper()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path == f"/range/{breached_sha1[:5]}":
+ return httpx.Response(200, text=f"{breached_sha1[5:]}:1387")
+ return httpx.Response(200, text="0000000000000000000000000000000000A:1")
+
+ mock_prisma_client = _admin_prisma
+ existing_user = mocker.MagicMock()
+ existing_user.model_dump.return_value = {"user_id": "user-clean"}
+ existing_user.user_id = "user-clean"
+ mock_prisma_client.db.litellm_usertable.find_first = mocker.AsyncMock(return_value=existing_user)
+ mock_prisma_client.update_data = mocker.AsyncMock(return_value={"user_id": "user-clean"})
+ mock_prisma_client.jsonify_object = mocker.MagicMock(side_effect=lambda x: x)
+
+ admin_caller = UserAPIKeyAuth(user_id="admin-1", user_role=LitellmUserRoles.PROXY_ADMIN)
+ response = await bulk_update_processed_users(
+ users_to_update=[
+ UpdateUserRequest(user_id="user-breached", password=breached),
+ UpdateUserRequest(user_id="user-clean", password=clean),
+ ],
+ user_api_key_dict=admin_caller,
+ hibp_client=_hibp_client_with_handler(handler),
+ )
+
+ assert response.successful_updates == 1
+ assert response.failed_updates == 1
+ by_user = {r.user_id: r for r in response.results}
+ assert by_user["user-breached"].success is False
+ assert "data breaches" in by_user["user-breached"].error
+ assert by_user["user-clean"].success is True
+ (write_call,) = mock_prisma_client.update_data.call_args_list
+ assert write_call.kwargs["user_id"] == "user-clean"
+
+
+async def test_bulk_update_screens_shared_password_with_single_lookup(_admin_prisma, mocker):
+ """A batch where every user gets the same password costs one HIBP lookup,
+ not one per user (the serial per-user checks this regresses against)."""
+ from litellm.proxy.management_endpoints.internal_user_endpoints import (
+ bulk_update_processed_users,
+ )
+
+ lookup_count = 0
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal lookup_count
+ lookup_count += 1
+ return httpx.Response(200, text="0000000000000000000000000000000000A:1")
+
+ mock_prisma_client = _admin_prisma
+ existing_user = mocker.MagicMock()
+ existing_user.model_dump.return_value = {"user_id": "user-0"}
+ existing_user.user_id = "user-0"
+ mock_prisma_client.db.litellm_usertable.find_first = mocker.AsyncMock(return_value=existing_user)
+ mock_prisma_client.update_data = mocker.AsyncMock(return_value={"user_id": "user-0"})
+ mock_prisma_client.jsonify_object = mocker.MagicMock(side_effect=lambda x: x)
+
+ admin_caller = UserAPIKeyAuth(user_id="admin-1", user_role=LitellmUserRoles.PROXY_ADMIN)
+ response = await bulk_update_processed_users(
+ users_to_update=[UpdateUserRequest(user_id=f"user-{i}", password="NewP@ssw0rd123") for i in range(5)],
+ user_api_key_dict=admin_caller,
+ hibp_client=_hibp_client_with_handler(handler),
+ )
+
+ assert response.successful_updates == 5
+ assert lookup_count == 1
+
+
+ @pytest.mark.asyncio
+ async def test_delete_user_evicts_cached_user_rows(mocker: MockerFixture) -> None:
+ from litellm.proxy._types import DeleteUserRequest, LiteLLM_UserTable
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+ from litellm.proxy.management_endpoints.internal_user_endpoints import delete_user
+
+ deleted: Final = LiteLLM_UserTable(user_id="user-gone", user_email="[email protected]", teams=[])
+ survivor: Final = LiteLLM_UserTable(user_id="user-stays", user_email="[email protected]", teams=[])
+ prisma_client: Final = mocker.MagicMock()
+ prisma_client.db.litellm_usertable.find_unique = mocker.AsyncMock(return_value=deleted)
+ prisma_client.db.litellm_teamtable.find_many = mocker.AsyncMock(return_value=[])
+ prisma_client.db.litellm_jwtkeymapping.find_many = mocker.AsyncMock(return_value=[])
+ prisma_client.db.litellm_verificationtoken.find_many = mocker.AsyncMock(return_value=[])
+ prisma_client.db.litellm_verificationtoken.delete_many = mocker.AsyncMock(return_value=0)
+ prisma_client.db.litellm_invitationlink.delete_many = mocker.AsyncMock(return_value=0)
+ prisma_client.db.litellm_organizationmembership.delete_many = mocker.AsyncMock(return_value=0)
+ prisma_client.db.litellm_teammembership.delete_many = mocker.AsyncMock(return_value=0)
+ prisma_client.db.litellm_usertable.delete_many = mocker.AsyncMock(return_value=1)
+ mocker.patch("litellm.proxy.proxy_server.prisma_client", prisma_client) # test-quality-ok: substitute the database dependency
+ cache: Final = UserApiKeyCache()
+ for row in (deleted, survivor):
+ await cache.async_set_cache(key=row.user_id, value=row, model_type=LiteLLM_UserTable)
+ mocker.patch("litellm.proxy.proxy_server.user_api_key_cache", cache) # test-quality-ok: exercise a real isolated cache
+ mocker.patch("litellm.proxy.proxy_server.proxy_logging_obj", None) # test-quality-ok: delete_user reads it off proxy_server at call time
+ broadcast: Final = mocker.patch( # test-quality-ok: observe the Redis publication boundary
+ "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.publish_auth_cache_invalidation",
+ new_callable=mocker.AsyncMock,
+ )
+
+ await delete_user(
+ data=DeleteUserRequest(user_ids=[deleted.user_id]),
+ user_api_key_dict=UserAPIKeyAuth(user_id="proxy-admin", user_role=LitellmUserRoles.PROXY_ADMIN),
+ )
+
+ assert await cache.async_get_cache(key=deleted.user_id, model_type=LiteLLM_UserTable) is None
+ assert await cache.async_get_cache(key=survivor.user_id, model_type=LiteLLM_UserTable) == survivor
+ broadcast.assert_awaited_once_with(cache_key=deleted.user_id)