From 722df5581ff20c57cb5c8c01f7f92dced5b43703 Mon Sep 17 00:00:00 2001 From: Mrinal Chanshetty Date: Mon, 2 Nov 2026 13:41:16 -0800 Subject: [PATCH] feat(users): support custom IDs in user invitations --- .../internal_user_endpoints.py | 4 +- .../key_management_endpoints.py | 22 +++- .../management_endpoints/user_requests.py | 14 ++- .../test_internal_user_endpoints.py | 43 ++++++++ .../CreateUserButton.integration.test.tsx | 104 ++++++++++++++++++ .../src/components/CreateUserButton.test.tsx | 2 +- .../src/components/CreateUserButton.tsx | 55 ++++++++- 7 files changed, 235 insertions(+), 9 deletions(-) create mode 100644 ui/litellm-dashboard/src/components/CreateUserButton.integration.test.tsx diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py index 54a2d4062d2..302ae444bcb 100644 --- a/litellm/proxy/management_endpoints/internal_user_endpoints.py +++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py @@ -605,7 +605,9 @@ async def new_user( teams = check_if_default_team_set() organization_ids: Final = cast(list[str] | None, data_json.pop("organizations", None)) - response: Final = await generate_key_helper_fn(request_type="user", **data_json, llm_router=None) + response: Final = await generate_key_helper_fn( + request_type="user", **data_json, llm_router=None, query_type="create_data" + ) created_user_id: Final = cast(str | None, response.get("user_id", None)) if created_user_id is not None: forget_missing_user(created_user_id) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index c8895c01f7b..dcee367810f 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -5268,7 +5268,7 @@ async def generate_key_helper_fn( tpm_limit: int | None = None, rpm_limit: int | None = None, tpd_limit: int | None = None, - query_type: Literal["insert_data", "update_data"] = "insert_data", + query_type: Literal["insert_data", "update_data", "create_data"] = "insert_data", update_key_values: dict | None = None, key_alias: str | None = None, allowed_cache_controls: list | None = [], @@ -5479,7 +5479,25 @@ async def generate_key_helper_fn( if prisma_client is not None: if table_name is None or table_name == "user": # do not auto-create users for `/key/generate` ## CREATE USER (If necessary) - if query_type == "insert_data": + if query_type == "create_data": + from prisma.errors import ForeignKeyViolationError, UniqueViolationError + + create_data: Final = cast( # cast-ok: locally built user fields have string keys + Mapping[str, object], user_data + ) + try: + await UserRepository(prisma_client).create(prisma_client.jsonify_object(data=create_data)) + except UniqueViolationError as exc: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail={"error": f"User with id {user_id} already exists"}, + ) from exc + except ForeignKeyViolationError as exc: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail={"error": "A referenced user resource does not exist."}, + ) from exc + elif query_type == "insert_data": user_row = cast( # cast-ok: table_name="user" is the insert_data branch returning the user row "prisma_models.LiteLLM_UserTable | None", await prisma_client.insert_data(data=user_data, table_name="user"), diff --git a/litellm/types/proxy/management_endpoints/user_requests.py b/litellm/types/proxy/management_endpoints/user_requests.py index e53dc4152c3..dd01e7c9a84 100644 --- a/litellm/types/proxy/management_endpoints/user_requests.py +++ b/litellm/types/proxy/management_endpoints/user_requests.py @@ -1,5 +1,5 @@ from collections.abc import Mapping -from typing import Literal +from typing import Final, Literal from pydantic import Field, field_validator, model_validator @@ -37,6 +37,18 @@ class NewUserRequest(GenerateRequestBase): organizations: list[str] | None = None password: str | None = None + @field_validator("user_id") + @classmethod + def validate_user_id(cls, value: str | None) -> str | None: + if value is None: + return None + normalized: Final = value.strip() + if not normalized: + raise ValueError("user_id must not be empty or contain only whitespace") + if "\x00" in normalized: + raise ValueError("user_id must not contain NUL characters") + return normalized + @field_validator("password") @classmethod def password_not_supported(cls, value: str | None) -> str | None: diff --git a/tests/unit/proxy/management_endpoints/test_internal_user_endpoints.py b/tests/unit/proxy/management_endpoints/test_internal_user_endpoints.py index 39586a1a204..2005073ebb9 100644 --- a/tests/unit/proxy/management_endpoints/test_internal_user_endpoints.py +++ b/tests/unit/proxy/management_endpoints/test_internal_user_endpoints.py @@ -13,6 +13,7 @@ import httpx import pytest from fastapi import HTTPException from fastapi.testclient import TestClient +from pydantic import ValidationError from pytest_mock import MockerFixture from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler @@ -48,6 +49,48 @@ from tests.unit.proxy.management_endpoints.jwt_key_mapping_doubles import ( client = TestClient(app) + +@pytest.mark.parametrize("user_id", ["", " \t\n", "user\x00id", 123, True, [], {}]) +def test_new_user_rejects_invalid_custom_id(user_id: object) -> None: + with pytest.raises(ValidationError) as exc: + NewUserRequest.model_validate({"user_id": user_id}) + assert exc.value.errors()[0]["loc"] == ("user_id",) + + +@pytest.mark.parametrize("user_id", [None, "employee-42", "社員@example.test", " employee-42 "]) +def test_new_user_normalizes_custom_id_and_preserves_auto_generation(user_id: str | None) -> None: + request: Final = NewUserRequest(user_id=user_id) + assert request.user_id == (user_id.strip() if user_id is not None else None) + + +@pytest.mark.asyncio +async def test_new_user_returns_conflict_when_id_is_taken_after_duplicate_check(mocker: MockerFixture) -> None: + from prisma.errors import UniqueViolationError + + from litellm.proxy import proxy_server + from litellm.proxy.utils import PrismaClient + + table: Final = SimpleNamespace( + find_first=AsyncMock(return_value=None), + count=AsyncMock(return_value=0), + create=AsyncMock(side_effect=UniqueViolationError({}, message="Unique constraint failed on user_id")), + upsert=AsyncMock(return_value=LiteLLM_UserTable(user_id="employee-42")), + ) + mocker.patch("prisma.Prisma", return_value=SimpleNamespace(litellm_usertable=table)) + database: Final = PrismaClient( + database_url="postgresql://unused:unused@localhost/unused", + proxy_logging_obj=proxy_server.proxy_logging_obj, + ) + mocker.patch("litellm.proxy.proxy_server.prisma_client", database) + with pytest.raises(ProxyException) as exc: + await new_user( + data=NewUserRequest(user_id="employee-42", auto_create_key=False, send_invite_email=False), + user_api_key_dict=UserAPIKeyAuth(user_id="admin", user_role=LitellmUserRoles.PROXY_ADMIN), + ) + assert str(exc.value.code) == "409" + assert "employee-42" in exc.value.message + + if TYPE_CHECKING: from litellm.caching.redis_cache import RedisCache from litellm.proxy.utils import PrismaClient diff --git a/ui/litellm-dashboard/src/components/CreateUserButton.integration.test.tsx b/ui/litellm-dashboard/src/components/CreateUserButton.integration.test.tsx new file mode 100644 index 00000000000..24059e21ee6 --- /dev/null +++ b/ui/litellm-dashboard/src/components/CreateUserButton.integration.test.tsx @@ -0,0 +1,104 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { CreateUserButton } from "./CreateUserButton"; + +const createUser = vi.fn<(body: Record) => Response>(); + +beforeEach(() => { + createUser.mockReset(); + createUser.mockImplementation((body) => Response.json({ user_id: body.user_id ?? "generated-id" })); + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const path = new URL(input instanceof Request ? input.url : String(input), "http://localhost").pathname; + if (path === "/user/new") return createUser(JSON.parse(String(init?.body))); + if (path === "/models") return Response.json({ data: [] }); + if (path === "/sso/get/ui_settings") return Response.json({ SSO_ENABLED: true }); + if (path === "/v2/team/list") return Response.json({ teams: [], total: 0, total_pages: 0 }); + throw new Error(`Unexpected request ${path}`); + }), + ); +}); + +afterEach(() => vi.unstubAllGlobals()); + +const renderForm = (isEmbedded: boolean, onUserCreated = vi.fn()) => { + const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } }); + render( + + + , + ); + return onUserCreated; +}; + +describe("custom User ID invitation", () => { + it.each([true, false])("sends the custom ID from the form (embedded=%s)", async (embedded) => { + const user = userEvent.setup(); + const onCreated = renderForm(embedded); + if (!embedded) await user.click(screen.getByRole("button", { name: "+ Invite User" })); + await user.click(screen.getByRole("checkbox", { name: "Supply custom User ID" })); + fireEvent.change(screen.getByRole("textbox", { name: "User ID", exact: true }), { + target: { value: " employee-42 " }, + }); + fireEvent.change(screen.getByRole("textbox", { name: "User Email" }), { + target: { value: "employee@example.test" }, + }); + await user.click(screen.getByRole("button", { name: embedded ? "Create User" : "Invite User", exact: true })); + await waitFor(() => + expect(createUser).toHaveBeenCalledWith( + expect.objectContaining({ + user_id: "employee-42", + user_email: "employee@example.test", + auto_create_key: false, + }), + ), + ); + expect(createUser.mock.calls[0][0]).not.toHaveProperty("supply_user_id"); + if (embedded) { + await waitFor(() => expect(onCreated).toHaveBeenCalledWith("employee-42")); + expect(screen.getByRole("checkbox", { name: "Supply custom User ID" })).not.toBeChecked(); + expect(screen.queryByRole("textbox", { name: "User ID", exact: true })).not.toBeInTheDocument(); + } + }); + + it("blocks whitespace and clears the custom ID when automatic generation is selected", async () => { + const user = userEvent.setup(); + renderForm(true); + await user.click(screen.getByRole("checkbox", { name: "Supply custom User ID" })); + fireEvent.change(screen.getByRole("textbox", { name: "User ID", exact: true }), { target: { value: " " } }); + await user.click(screen.getByRole("button", { name: "Create User" })); + expect(await screen.findByText("Enter a User ID")).toBeInTheDocument(); + expect(createUser).not.toHaveBeenCalled(); + fireEvent.change(screen.getByRole("textbox", { name: "User ID", exact: true }), { + target: { value: "discard-me" }, + }); + await user.click(screen.getByRole("checkbox", { name: "Supply custom User ID" })); + await user.click(screen.getByRole("button", { name: "Create User" })); + await waitFor(() => expect(createUser).toHaveBeenCalledWith(expect.objectContaining({ user_id: null }))); + expect(createUser.mock.calls[0][0]).not.toHaveProperty("supply_user_id"); + }); + + it("discards a custom ID when an invitation is cancelled", async () => { + const user = userEvent.setup(); + renderForm(false); + await user.click(screen.getByRole("button", { name: "+ Invite User" })); + await user.click(screen.getByRole("checkbox", { name: "Supply custom User ID" })); + fireEvent.change(screen.getByRole("textbox", { name: "User ID", exact: true }), { target: { value: "cancelled" } }); + await user.click( + within(screen.getByRole("dialog", { name: "Invite User" })).getByRole("button", { name: "Close" }), + ); + await user.click(screen.getByRole("button", { name: "+ Invite User" })); + expect(screen.getByRole("checkbox", { name: "Supply custom User ID" })).not.toBeChecked(); + await user.click(screen.getByRole("checkbox", { name: "Supply custom User ID" })); + expect(screen.getByRole("textbox", { name: "User ID", exact: true })).toHaveValue(""); + }); +}); diff --git a/ui/litellm-dashboard/src/components/CreateUserButton.test.tsx b/ui/litellm-dashboard/src/components/CreateUserButton.test.tsx index 94b3726ede0..d04272cecd3 100644 --- a/ui/litellm-dashboard/src/components/CreateUserButton.test.tsx +++ b/ui/litellm-dashboard/src/components/CreateUserButton.test.tsx @@ -308,7 +308,7 @@ describe("CreateUserButton", () => { const dialog = screen.getByRole("dialog", { name: /invite user/i }); - expectControlBesideLabel(within(dialog).getByRole("checkbox")); + expectControlBesideLabel(within(dialog).getByRole("checkbox", { name: "Send invitation email" })); }); describe("organizations", () => { diff --git a/ui/litellm-dashboard/src/components/CreateUserButton.tsx b/ui/litellm-dashboard/src/components/CreateUserButton.tsx index 83a72e50f5c..dfe1a96c944 100644 --- a/ui/litellm-dashboard/src/components/CreateUserButton.tsx +++ b/ui/litellm-dashboard/src/components/CreateUserButton.tsx @@ -14,7 +14,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/comp import { Alert, AlertDescription, AlertTitle } from "@/components/shared/Alert"; import { ChevronRight, CircleHelp, Info, UserPlus } from "lucide-react"; import React, { useEffect, useState } from "react"; -import { useForm } from "react-hook-form"; +import { useForm, useWatch } from "react-hook-form"; import TeamDropdown from "./common_components/team_dropdown"; import { getModelDisplayName } from "./key_team_helpers/fetch_available_models_team_key"; import { toast } from "@/lib/toast"; @@ -57,6 +57,8 @@ interface UISettings { } interface CreateUserFormValues { + supply_user_id: boolean; + user_id?: string; user_email?: string; user_role: string; team_id?: string | null; @@ -67,6 +69,8 @@ interface CreateUserFormValues { } const EMBEDDED_DEFAULTS: CreateUserFormValues = { + supply_user_id: false, + user_id: "", user_email: undefined, user_role: "internal_user_viewer", team_id: undefined, @@ -75,6 +79,8 @@ const EMBEDDED_DEFAULTS: CreateUserFormValues = { }; const STANDALONE_DEFAULTS: CreateUserFormValues = { + supply_user_id: false, + user_id: "", user_email: undefined, user_role: "internal_user_viewer", team_id: undefined, @@ -94,11 +100,13 @@ const withoutCollapsedModels = (values: CreateUserFormValues, isPersonalKeyOpen: return rest; }; -const buildCreatePayload = (values: CreateUserFormValues): CreateUserFormValues & { organizations?: string[] } => { +const buildCreatePayload = (values: CreateUserFormValues) => { + const { supply_user_id, user_id, ...fields } = values; + const apiValues = supply_user_id ? { ...fields, user_id: user_id?.trim() } : fields; const withModels = (!values.models || values.models.length === 0) && values.user_role !== "proxy_admin" - ? { ...values, models: ["no-default-models"] } - : values; + ? { ...apiValues, models: ["no-default-models"] } + : apiValues; if (!withModels.organization_ids) { return withModels; } @@ -158,6 +166,7 @@ export const CreateUserButton: React.FC = ({ const [uiSettings, setUISettings] = useState(null); const defaultValues = isEmbedded ? EMBEDDED_DEFAULTS : STANDALONE_DEFAULTS; const form = useForm({ defaultValues }); + const supplyUserId = useWatch({ control: form.control, name: "supply_user_id" }); const [isModalVisible, setIsModalVisible] = useState(false); const [apiuser, setApiuser] = useState(false); const [userModels, setUserModels] = useState([]); @@ -200,6 +209,14 @@ export const CreateUserButton: React.FC = ({ }; const handleCreate = async (formValues: CreateUserFormValues) => { + if (formValues.supply_user_id && !formValues.user_id?.trim()) { + form.setError("user_id", { message: "Enter a User ID" }, { shouldFocus: true }); + return; + } + if (formValues.supply_user_id && formValues.user_id?.includes("\u0000")) { + form.setError("user_id", { message: "User ID must not contain NUL characters" }, { shouldFocus: true }); + return; + } try { toast.info("Making API Call"); if (!isEmbedded) { @@ -250,6 +267,34 @@ export const CreateUserButton: React.FC = ({ ); + const userIdField = ( + <> + + {({ id, value, onChange, onBlur }) => ( + { + onChange(checked); + form.resetField("user_id"); + }} + onBlur={onBlur} + /> + )} + + {supplyUserId && ( + + {({ ref, value, ...control }) => } + + )} + + ); + const teamField = ( = ({ {userEmailField} + {userIdField} {roleField("User Role")} {teamField} {metadataField} @@ -341,6 +387,7 @@ export const CreateUserButton: React.FC = ({
{userEmailField} + {userIdField} {roleField( labelWithHint( "Global Proxy Role",