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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
test(ui): characterize the create key form payload contract (#37405)
yuneng-jiangcb5f15802355
diff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.jsonindex dfaa417cae3..355835eb87c 100644--- a/ui/litellm-dashboard/eslint-suppressions.json+++ b/ui/litellm-dashboard/eslint-suppressions.json@@ -2328,14 +2328,6 @@"count": 1}},- "src/components/organisms/create_key_button.test.tsx": {- "@typescript-eslint/no-require-imports": {- "count": 1- },- "react/display-name": {- "count": 8- }- },"src/components/organisms/create_key_button.tsx": {"local/filename-pascal-case": {"count": 1@@ -3031,4 +3023,4 @@"count": 1}}-}\ No newline at end of file+}diff --git a/ui/litellm-dashboard/src/components/organisms/create_key_button.integration.test.tsx b/ui/litellm-dashboard/src/components/organisms/create_key_button.integration.test.tsxindex feea216e4ff..9788d365fd0 100644--- a/ui/litellm-dashboard/src/components/organisms/create_key_button.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/organisms/create_key_button.integration.test.tsx@@ -1,70 +1,114 @@import userEvent from "@testing-library/user-event";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { renderWithProviders, screen, waitFor } from "../../../tests/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { renderWithProviders, screen, testQueryClient, waitFor } from "../../../tests/test-utils";+import type { Team } from "../key_team_helpers/key_list";+import { keyCreateCall, keyCreateServiceAccountCall, modelAvailableCall, userFilterUICall } from "../networking";import CreateKey from "./create_key_button";-const { mockKeyCreateCall } = vi.hoisted(() => ({- mockKeyCreateCall: vi.fn().mockResolvedValue({ key: "sk-created", soft_budget: null }),+const state = vi.hoisted(() => ({+ authorized: {+ accessToken: "test-token",+ userId: "test-user-id",+ userRole: "Admin",+ premiumUser: false,+ },+ can: {} as Record<string, boolean>,+ uiSettings: {} as Record<string, unknown>,+ tags: {} as Record<string, { name: string }>,+ teams: [] as { team_id: string; team_alias: string; models: string[] }[],+ organizations: [] as { organization_id: string; organization_alias: string }[],+ accessGroups: [] as { access_group_id: string; access_group_name: string }[],+ projects: [] as { project_id: string; project_alias: string; team_id?: string; models?: string[] }[],}));-vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({- default: () => ({ accessToken: "test-token", userId: "test-user-id", userRole: "Admin", premiumUser: true }),+vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({ default: () => state.authorized }));+vi.mock("@/app/(dashboard)/hooks/useCan", () => ({+ default: (capability: string) => state.can[capability] ?? true,}));--vi.mock("@/app/(dashboard)/hooks/useCan", () => ({ default: () => false }));--vi.mock("@/app/(dashboard)/hooks/keys/useKeys", () => ({ keyKeys: { lists: () => ["keys"] } }));-vi.mock("@/app/(dashboard)/hooks/organizations/useOrganizations", () => ({- useOrganizations: () => ({ data: [], isLoading: false }),+ useOrganizations: () => ({ data: state.organizations, isLoading: false }),}));-vi.mock("@/app/(dashboard)/hooks/projects/useProjects", () => ({- useProjects: () => ({ data: [], isLoading: false }),+ useProjects: () => ({ data: state.projects, isLoading: false }),}));-vi.mock("@/app/(dashboard)/hooks/uiSettings/useUISettings", () => ({- useUISettings: () => ({ data: { values: {} } }),+ useUISettings: () => ({ data: { values: state.uiSettings } }),+}));+vi.mock("@/app/(dashboard)/hooks/tags/useTags", () => ({+ useTags: () => ({ data: state.tags, isLoading: false }),}));--vi.mock("@/app/(dashboard)/hooks/tags/useTags", () => ({ useTags: () => ({ data: {} }) }));-vi.mock("@/app/(dashboard)/hooks/teams/useTeams", () => ({- useInfiniteTeams: () => ({ data: { pages: [{ teams: [] }] }, fetchNextPage: vi.fn(), hasNextPage: false }),+ useInfiniteTeams: () => ({+ data: { pages: [{ teams: state.teams, total: state.teams.length, page: 1, page_size: 50, total_pages: 1 }] },+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ isFetchingNextPage: false,+ isLoading: false,+ }),}));-vi.mock("@/app/(dashboard)/hooks/accessGroups/useAccessGroups", () => ({- useAccessGroups: () => ({ data: [], isLoading: false, isError: false }),+ useAccessGroups: () => ({ data: state.accessGroups, isLoading: false, isError: false }),}));--vi.mock("../networking", () => ({- keyCreateCall: mockKeyCreateCall,- keyCreateServiceAccountCall: vi.fn().mockResolvedValue({ key: "sk-sa", soft_budget: null }),- modelAvailableCall: vi.fn().mockResolvedValue({ data: [{ id: "gpt-4" }] }),- getGuardrailsList: vi.fn().mockResolvedValue({ guardrails: [] }),- getPoliciesList: vi.fn().mockResolvedValue({ policies: [] }),- getPromptsList: vi.fn().mockResolvedValue({ prompts: [] }),- getPossibleUserRoles: vi.fn().mockResolvedValue({}),- userFilterUICall: vi.fn().mockResolvedValue([]),- fetchMCPAccessGroups: vi.fn().mockResolvedValue([]),- getAgentsList: vi.fn().mockResolvedValue({ agents: [] }),- getPassThroughEndpointsCall: vi.fn().mockResolvedValue({ endpoints: [] }),- proxyBaseUrl: "http://localhost:4000",+vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPServers", () => ({+ useMCPServers: () => ({ data: [], isLoading: false }),+}));+vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPAccessGroups", () => ({+ useMCPAccessGroups: () => ({ data: [], isLoading: false }),}));+vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPToolsets", () => ({+ useMCPToolsets: () => ({ data: [], isLoading: false }),+}));++vi.mock("../networking", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../networking")>();+ const emptyMcpTools = { tools: [], error: null, message: null, stack_trace: null };+ return {+ ...actual,+ keyCreateCall: vi.fn().mockResolvedValue({ key: "sk-created", soft_budget: null }),+ keyCreateServiceAccountCall: vi.fn().mockResolvedValue({ key: "sk-service-account", soft_budget: null }),+ modelAvailableCall: vi.fn().mockResolvedValue({ data: [{ id: "gpt-4" }] }),+ getGuardrailsList: vi.fn().mockResolvedValue({ guardrails: [] }),+ getPoliciesList: vi.fn().mockResolvedValue({ policies: [] }),+ getPromptsList: vi.fn().mockResolvedValue({ prompts: [] }),+ getPossibleUserRoles: vi.fn().mockResolvedValue({}),+ userFilterUICall: vi.fn().mockResolvedValue([]),+ getAgentsList: vi.fn().mockResolvedValue({ agents: [] }),+ getPassThroughEndpointsCall: vi.fn().mockResolvedValue({ endpoints: [] }),+ vectorStoreListCall: vi.fn().mockResolvedValue({ data: [] }),+ listMCPTools: vi.fn().mockResolvedValue(emptyMcpTools),+ getRouterSettingsCall: vi.fn().mockResolvedValue({ router_settings: {} }),+ };+});-vi.mock("../agent_management/AgentSelector", () => ({ default: () => null }));-vi.mock("../common_components/check_openapi_schema", () => ({ default: () => null }));-vi.mock("../common_components/PremiumLoggingSettings", () => ({ default: () => null }));-vi.mock("../common_components/RouterSettingsAccordion", () => ({ default: () => null }));-vi.mock("../mcp_server_management/MCPServerSelector", () => ({ default: () => null }));-vi.mock("../mcp_server_management/MCPToolPermissions", () => ({ default: () => null }));-vi.mock("../vector_store_management/VectorStoreSelector", () => ({ default: () => null }));-vi.mock("../CreateUserButton", () => ({ CreateUserButton: () => null }));+const OPENAPI_SCHEMA = {+ components: {+ schemas: {+ GenerateKeyRequest: {+ properties: {+ key: { type: "string", title: "Key" },+ soft_budget: { type: "number", title: "Soft Budget" },+ blocked: { type: "boolean", title: "Blocked" },+ max_budget: { type: "number", title: "Max Budget" },+ },+ },+ },+ },+};-const MINIMAL_CREATE_PAYLOAD = {+const SECTIONS = {+ mcp: /MCP Settings/i,+ agent: /Agent Settings/i,+ logging: /Logging Settings/i,+ router: /Router Settings/i,+ aliases: /Model Aliases/i,+ lifecycle: /Key Lifecycle/i,+ advanced: /Advanced Settings/i,+} as const;++const ALL_CLOSED_PAYLOAD = {organization_id: undefined,team_id: null,- key_alias: "probe-key",+ key_alias: "contract-key",models: [],key_type: "llm_api",user_id: "test-user-id",@@ -72,100 +116,763 @@ const MINIMAL_CREATE_PAYLOAD = {metadata: "{}",};-describe("CreateKey submit payload contract", () => {+const OPTIONAL_OPEN_PAYLOAD = {+ ...ALL_CLOSED_PAYLOAD,+ max_budget: undefined,+ budget_duration: undefined,+ tpm_limit: undefined,+ tpm_limit_type: null,+ rpm_limit: undefined,+ rpm_limit_type: null,+ throttle_on_budget_exceeded: undefined,+ enable_prompt_caching: undefined,+ guardrails: undefined,+ policies: undefined,+ prompts: undefined,+ access_group_ids: undefined,+ allowed_passthrough_routes: undefined,+ allowed_vector_store_ids: undefined,+ tags: undefined,+};++const ROUTER_SETTINGS_DEFAULT = {+ routing_strategy: null,+ allowed_fails: null,+ cooldown_time: null,+ num_retries: null,+ timeout: null,+ retry_after: null,+ fallbacks: null,+ context_window_fallbacks: null,+ retry_policy: null,+ model_group_alias: null,+ enable_tag_filtering: false,+ routing_strategy_args: null,+};++const SECTION_PAYLOAD_ADDITIONS: Record<keyof typeof SECTIONS, Record<string, unknown>> = {+ mcp: { allowed_mcp_servers_and_groups: { servers: [], accessGroups: [] } },+ agent: { allowed_agents_and_groups: undefined },+ logging: {},+ router: { router_settings: ROUTER_SETTINGS_DEFAULT },+ aliases: {},+ lifecycle: {},+ advanced: { key: undefined, soft_budget: undefined, blocked: undefined },+};++const ALL_OPEN_PAYLOAD = {+ ...OPTIONAL_OPEN_PAYLOAD,+ ...SECTION_PAYLOAD_ADDITIONS.mcp,+ ...SECTION_PAYLOAD_ADDITIONS.agent,+ ...SECTION_PAYLOAD_ADDITIONS.router,+ ...SECTION_PAYLOAD_ADDITIONS.advanced,+};++const renderCreateKey = (props: Partial<React.ComponentProps<typeof CreateKey>> = {}) =>+ renderWithProviders(<CreateKey team={null} teams={[]} data={[]} addKey={vi.fn()} {...props} />);++const openModal = async (props: Partial<React.ComponentProps<typeof CreateKey>> = {}) => {+ const view = renderCreateKey(props);+ await userEvent.click(screen.getByTestId("create-key-button"));+ await screen.findByRole("button", { name: /^create key$/i });+ return view;+};++const antdSearchInput = (placeholder: HTMLElement): HTMLInputElement => {+ const input = placeholder.parentElement?.querySelector("input");+ if (input == null) {+ throw new Error("no antd search input next to the placeholder");+ }+ return input;+};++const openAntdSelect = async (placeholder: HTMLElement) => {+ await userEvent.click(antdSearchInput(placeholder));+};++const openSection = async (name: RegExp) => {+ await userEvent.click(await screen.findByRole("button", { name }));+};++const nameTheKey = async (alias = "contract-key") => {+ await userEvent.type(await screen.findByLabelText(/Key Name/), alias);+};++const submit = async () => {+ await userEvent.click(screen.getByRole("button", { name: /^create key$/i }));+};++const createdPayload = async () => {+ await waitFor(() => {+ expect(vi.mocked(keyCreateCall)).toHaveBeenCalled();+ });+ return vi.mocked(keyCreateCall).mock.calls[0][2] as Record<string, unknown>;+};++describe("CreateKey", () => {beforeEach(() => {- mockKeyCreateCall.mockClear();+ testQueryClient.clear();+ state.authorized = { accessToken: "test-token", userId: "test-user-id", userRole: "Admin", premiumUser: false };+ state.can = {};+ state.uiSettings = {};+ state.tags = {};+ state.teams = [];+ state.organizations = [];+ state.projects = [];+ state.accessGroups = [];+ vi.mocked(keyCreateCall).mockClear().mockResolvedValue({ key: "sk-created", soft_budget: null });+ vi.mocked(keyCreateServiceAccountCall)+ .mockClear()+ .mockResolvedValue({ key: "sk-service-account", soft_budget: null });+ vi.mocked(userFilterUICall).mockClear().mockResolvedValue([]);+ vi.mocked(modelAvailableCall)+ .mockClear()+ .mockResolvedValue({ data: [{ id: "gpt-4" }] });+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes("openapi.json")) {+ return { ok: true, status: 200, json: async () => OPENAPI_SCHEMA } as unknown as Response;+ }+ return { ok: true, status: 200, json: async () => ({}) } as unknown as Response;+ }),+ );});- const openModal = async () => {- renderWithProviders(<CreateKey team={null} teams={[]} data={[]} addKey={() => {}} />);- await userEvent.click(screen.getAllByTestId("create-key-button")[0]);- await screen.findByRole("button", { name: /create key/i });- };+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ describe("submit payload contract", () => {+ it("sends only the always-mounted fields when every collapsible section is closed", async () => {+ await openModal();+ await nameTheKey();+ await submit();++ expect(await createdPayload()).toStrictEqual(ALL_CLOSED_PAYLOAD);+ });++ it("registers the Optional Settings fields as undefined-valued keys once that section is open", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await submit();++ expect(await createdPayload()).toStrictEqual(OPTIONAL_OPEN_PAYLOAD);+ });++ it("sends the full mounted field set when every section is open", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ for (const trigger of Object.values(SECTIONS)) {+ await openSection(trigger);+ }+ await screen.findByLabelText("Soft Budget");+ await submit();++ expect(await createdPayload()).toStrictEqual(ALL_OPEN_PAYLOAD);+ });++ it.each(Object.keys(SECTIONS) as (keyof typeof SECTIONS)[])(+ "adds exactly the %s section's own keys when it is the only nested section open",+ async (section) => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await openSection(SECTIONS[section]);+ if (section === "advanced") {+ await screen.findByLabelText("Soft Budget");+ }+ await submit();++ expect(await createdPayload()).toStrictEqual({+ ...OPTIONAL_OPEN_PAYLOAD,+ ...SECTION_PAYLOAD_ADDITIONS[section],+ });+ },+ );++ it.each([+ [+ "every section closed",+ false,+ ["team_id", "key_alias", "models", "key_type", "user_id", "duration", "metadata"],+ ],+ [+ "Optional Settings open",+ true,+ [+ "team_id",+ "key_alias",+ "models",+ "key_type",+ "tpm_limit_type",+ "rpm_limit_type",+ "user_id",+ "duration",+ "metadata",+ ],+ ],+ ])("serialises to exactly the wire keys with %s", async (_label, openOptional, wireKeys) => {+ await openModal();+ await nameTheKey();+ if (openOptional) {+ await openSection(/Optional Settings/i);+ }+ await submit();++ const serialised = JSON.parse(JSON.stringify(await createdPayload())) as Record<string, unknown>;+ expect(Object.keys(serialised).sort()).toStrictEqual([...wireKeys].sort());+ });++ it("omits a budget typed into a section the user closed again, rather than sending it as null", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.type(await screen.findByLabelText(/Max Budget \(USD\)/), "150.75");+ await openSection(/Optional Settings/i);+ await submit();++ const payload = await createdPayload();+ expect(payload).not.toHaveProperty("max_budget");+ expect(payload).toStrictEqual(ALL_CLOSED_PAYLOAD);+ });++ it("restores the typed budget when the closed section is expanded again before submit", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.type(await screen.findByLabelText(/Max Budget \(USD\)/), "150.75");+ await openSection(/Optional Settings/i);+ await openSection(/Optional Settings/i);++ expect(await screen.findByLabelText(/Max Budget \(USD\)/)).toHaveValue(150.75);++ await submit();++ expect(await createdPayload()).toStrictEqual({ ...OPTIONAL_OPEN_PAYLOAD, max_budget: "150.75" });+ });++ it("sends a typed max budget as a string, not a number", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.type(await screen.findByLabelText(/Max Budget \(USD\)/), "150.75");+ await submit();++ const payload = await createdPayload();+ expect(payload.max_budget).toBe("150.75");+ });++ it.each([+ ["Tokens per minute Limit (TPM)", "tpm_limit"],+ ["Requests per minute Limit (RPM)", "rpm_limit"],+ ])("routes a typed %s into the %s payload key", async (label, key) => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.type(await screen.findByLabelText(label), "42");+ await submit();++ expect((await createdPayload())[key]).toBe("42");+ });++ it("routes the shared rate-limit-type control into its own payload key", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.click(await screen.findByLabelText(/TPM Rate Limit Type/));+ await userEvent.click(await screen.findByRole("option", { name: /Guaranteed throughput/ }));+ await submit();++ const payload = await createdPayload();+ expect(payload.tpm_limit_type).toBe("guaranteed_throughput");+ expect(payload.rpm_limit_type).toBeNull();+ });++ it("routes a typed expiry into duration, which is otherwise coalesced to null", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await openSection(SECTIONS.lifecycle);+ await userEvent.type(await screen.findByLabelText("Expire Key"), "45d");+ await submit();++ expect((await createdPayload()).duration).toBe("45d");+ });++ it("drops a typed expiry back to null when its section is collapsed before submit", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await openSection(SECTIONS.lifecycle);+ await userEvent.type(await screen.findByLabelText("Expire Key"), "45d");+ await openSection(SECTIONS.lifecycle);+ await submit();++ expect((await createdPayload()).duration).toBeNull();+ });++ it("routes a selected budget reset window into budget_duration", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.click(await screen.findByLabelText("Reset Budget"));+ await userEvent.click(await screen.findByRole("option", { name: "daily" }));+ await submit();++ expect((await createdPayload()).budget_duration).toBe("24h");+ });++ it("sends an explicit null budget_duration when the never-resets window is chosen", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.click(await screen.findByLabelText("Reset Budget"));+ await userEvent.click(await screen.findByRole("option", { name: /never resets/i }));+ await submit();++ const payload = await createdPayload();+ expect("budget_duration" in payload).toBe(true);+ expect(payload.budget_duration).toBeNull();+ });++ it("routes typed tags into the tags key", async () => {+ state.tags = { production: { name: "production" } };+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.type(await screen.findByLabelText("Tags"), "production{Enter}");+ await submit();++ expect((await createdPayload()).tags).toStrictEqual(["production"]);+ });++ it("routes a chosen access group into access_group_ids", async () => {+ state.accessGroups = [{ access_group_id: "ag-1", access_group_name: "Group One" }];+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);++ await openAntdSelect(await screen.findByText("Select access groups (optional)"));+ await userEvent.click(await screen.findByText("Group One"));+ await submit();++ expect((await createdPayload()).access_group_ids).toStrictEqual(["ag-1"]);+ });++ it("moves the schema-driven Advanced Settings fields onto the payload under their own keys", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await openSection(SECTIONS.advanced);+ await userEvent.type(await screen.findByLabelText("Soft Budget"), "12");+ await submit();++ const payload = await createdPayload();+ expect(payload.soft_budget).toBe(12);+ expect(payload).toHaveProperty("key");+ });++ it("drops the schema-driven custom key field when the proxy disables custom API keys", async () => {+ state.uiSettings = { disable_custom_api_keys: true };+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await openSection(SECTIONS.advanced);+ await screen.findByLabelText("Soft Budget");+ await submit();++ const payload = await createdPayload();+ expect(payload).not.toHaveProperty("key");+ expect(payload).toHaveProperty("soft_budget");+ });- it("sends exactly the bound form fields for a minimal create", async () => {- await openModal();+ it("drops the policy and prompt keys entirely for a role that cannot see those fields", async () => {+ state.can = { viewPolicies: false, viewPrompts: false };+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await submit();++ const payload = await createdPayload();+ expect(payload).not.toHaveProperty("policies");+ expect(payload).not.toHaveProperty("prompts");+ expect(payload).toHaveProperty("guardrails");+ });++ it("adds project_id only when the projects UI is enabled", async () => {+ state.uiSettings = { enable_projects_ui: true };+ await openModal();+ await nameTheKey();+ await submit();++ expect(await createdPayload()).toStrictEqual({ ...ALL_CLOSED_PAYLOAD, project_id: undefined });+ });++ it("keeps disable_global_guardrails out of the payload while the switch is off", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await submit();++ expect(await createdPayload()).not.toHaveProperty("disable_global_guardrails");+ });++ it("sends disable_global_guardrails once the switch is on", async () => {+ state.authorized = { ...state.authorized, premiumUser: true };+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.click(await screen.findByLabelText("Disable Global Guardrails"));+ await submit();++ expect((await createdPayload()).disable_global_guardrails).toBe(true);+ });++ it("folds a metadata JSON string back through JSON.stringify", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.type(await screen.findByLabelText("Metadata"), '{{"team":"research"}');+ await submit();++ expect((await createdPayload()).metadata).toBe('{"team":"research"}');+ });+ });++ describe("key ownership", () => {+ it("stamps the signed-in user onto user_id when the key is owned by you", async () => {+ await openModal();+ await nameTheKey();+ await submit();++ expect((await createdPayload()).user_id).toBe("test-user-id");+ });++ it("mounts the user search control only once Another User is chosen", async () => {+ await openModal();+ expect(screen.queryByText("Type email to search for users")).not.toBeInTheDocument();++ await userEvent.click(screen.getByRole("radio", { name: "Another User" }));++ expect(await screen.findByText("Type email to search for users")).toBeInTheDocument();+ });++ it("hides the Another User option from a non-admin", async () => {+ state.authorized = { ...state.authorized, userRole: "Internal User" };+ await openModal();++ expect(screen.queryByRole("radio", { name: "Another User" })).not.toBeInTheDocument();+ });++ it("routes a service account through the service account endpoint and stamps the alias into metadata", async () => {+ state.teams = [{ team_id: "team-1", team_alias: "Team One", models: [] }];+ await openModal({ teams: state.teams as unknown as Team[] });+ await userEvent.click(screen.getByRole("radio", { name: "Service Account" }));+ await userEvent.type(await screen.findByLabelText(/Service Account ID/), "svc-account-1");++ await userEvent.click(await screen.findByLabelText("Team"));+ await userEvent.click(await screen.findByRole("option", { name: /Team One/ }));++ await submit();++ await waitFor(() => {+ expect(vi.mocked(keyCreateServiceAccountCall)).toHaveBeenCalled();+ });+ expect(vi.mocked(keyCreateCall)).not.toHaveBeenCalled();+ const payload = vi.mocked(keyCreateServiceAccountCall).mock.calls[0][1] as Record<string, unknown>;+ expect(JSON.parse(String(payload.metadata))).toStrictEqual({ service_account_id: "svc-account-1" });+ expect(payload).not.toHaveProperty("user_id");+ });+ });++ describe("required field validation", () => {+ it("blocks the submit and marks the alias invalid when it is blank", async () => {+ await openModal();+ await submit();++ await waitFor(() => {+ expect(screen.getByLabelText(/Key Name/)).toHaveAttribute("aria-invalid", "true");+ });+ expect(vi.mocked(keyCreateCall)).not.toHaveBeenCalled();+ });++ it("suppresses the required message behind the always-visible help text", async () => {+ await openModal();+ await submit();++ await waitFor(() => {+ expect(screen.getByLabelText(/Key Name/)).toHaveAttribute("aria-invalid", "true");+ });+ expect(screen.queryByText("Please input a key name")).not.toBeInTheDocument();+ expect(screen.getByText("required")).toBeInTheDocument();+ });++ it("blocks a service account submit until a team is chosen, then lets it through", async () => {+ state.teams = [{ team_id: "team-1", team_alias: "Team One", models: [] }];+ await openModal({ teams: state.teams as unknown as Team[] });+ await userEvent.click(screen.getByRole("radio", { name: "Service Account" }));+ await userEvent.type(await screen.findByLabelText(/Service Account ID/), "svc-account-1");+ await submit();++ await waitFor(() => {+ expect(vi.mocked(keyCreateServiceAccountCall)).not.toHaveBeenCalled();+ });++ await userEvent.click(await screen.findByLabelText("Team"));+ await userEvent.click(await screen.findByRole("option", { name: /Team One/ }));+ await submit();++ await waitFor(() => {+ expect(vi.mocked(keyCreateServiceAccountCall)).toHaveBeenCalledTimes(1);+ });+ });++ it("blocks the submit when the budget exceeds the team ceiling", async () => {+ await openModal({ team: { team_id: "team-1", max_budget: 10 } as unknown as Team });+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await userEvent.type(await screen.findByLabelText(/Max Budget \(USD\)/), "50");+ await submit();++ await waitFor(() => {+ expect(screen.getByLabelText(/Max Budget \(USD\)/)).toHaveAttribute("aria-invalid", "true");+ });+ expect(vi.mocked(keyCreateCall)).not.toHaveBeenCalled();+ });+ });- await userEvent.type(screen.getByLabelText(/Key Name/), "probe-key");- await userEvent.click(screen.getByRole("button", { name: /create key/i }));+ describe("deep link prefill", () => {+ it("prefills the key alias", async () => {+ renderCreateKey({ autoOpenCreate: true, prefillData: { key_alias: "prefilled-key" } });- await waitFor(() => {- expect(mockKeyCreateCall).toHaveBeenCalled();+ expect(await screen.findByLabelText(/Key Name/)).toHaveValue("prefilled-key");+ });++ it("prefills models once the available model list arrives", async () => {+ renderCreateKey({ autoOpenCreate: true, prefillData: { models: ["gpt-4"] } });++ expect(await screen.findByTitle("gpt-4")).toBeInTheDocument();+ });++ it("ignores a team the user has no access to", async () => {+ renderCreateKey({+ teams: [{ team_id: "team-1", models: [] } as unknown as Team],+ autoOpenCreate: true,+ prefillData: { team_id: "team-404", key_alias: "example-key" },+ });++ await userEvent.type(await screen.findByLabelText(/Key Name/), "-suffix");+ await submit();++ const payload = await createdPayload();+ expect(payload.team_id).toBeNull();+ expect(payload.key_alias).toBe("example-key-suffix");+ });++ it("falls back to you when another_user is requested by a non-admin", async () => {+ state.authorized = { ...state.authorized, userRole: "Internal User" };+ renderCreateKey({ autoOpenCreate: true, prefillData: { owned_by: "another_user", key_alias: "example-key" } });++ expect(await screen.findByRole("radio", { name: "You" })).toBeChecked();+ });++ it("applies another_user for an admin", async () => {+ renderCreateKey({ autoOpenCreate: true, prefillData: { owned_by: "another_user" } });++ expect(await screen.findByRole("radio", { name: "Another User" })).toBeChecked();+ });++ it("prefills the key type", async () => {+ renderCreateKey({ autoOpenCreate: true, prefillData: { key_type: "management" } });++ await screen.findByLabelText(/Key Name/);+ await userEvent.type(await screen.findByLabelText(/Key Name/), "prefilled-type");+ await submit();++ expect((await createdPayload()).key_type).toBe("management");});- expect(mockKeyCreateCall.mock.calls[0][2]).toStrictEqual(MINIMAL_CREATE_PAYLOAD);});- it("keeps a collapsed Optional Settings section out of the payload entirely", async () => {- await openModal();+ describe("models dropdown team gating", () => {+ it("offers all-proxy-models but not all-team-models when no team is selected", async () => {+ await openModal();+ await userEvent.click(await screen.findByLabelText("Models"));- await userEvent.type(screen.getByLabelText(/Key Name/), "probe-key");- await userEvent.click(screen.getByRole("button", { name: /create key/i }));+ expect(await screen.findByTitle("All Proxy Models")).toBeInTheDocument();+ expect(screen.queryByTitle("All Team Models")).not.toBeInTheDocument();+ });++ it("offers all-team-models but hides all-proxy-models once a team is selected", async () => {+ state.teams = [{ team_id: "team-1", team_alias: "Team One", models: ["team-model-1"] }];+ await openModal({ teams: state.teams as unknown as Team[] });++ await userEvent.click(await screen.findByLabelText("Team"));+ await userEvent.click(await screen.findByRole("option", { name: /Team One/ }));- await waitFor(() => {- expect(mockKeyCreateCall).toHaveBeenCalled();+ await userEvent.click(await screen.findByLabelText("Models"));++ expect(await screen.findByTitle("All Team Models")).toBeInTheDocument();+ expect(screen.queryByTitle("All Proxy Models")).not.toBeInTheDocument();});- const payload = mockKeyCreateCall.mock.calls[0][2];- expect(payload).not.toHaveProperty("tpm_limit_type");- expect(payload).not.toHaveProperty("rpm_limit_type");- expect(payload).not.toHaveProperty("max_budget");});- it("carries the shared rate-limit-type control into the payload once its section is open", async () => {- await openModal();+ describe("organization dropdown", () => {+ it("is editable for an admin", async () => {+ state.organizations = [{ organization_id: "org-1", organization_alias: "Engineering" }];+ await openModal();++ expect(await screen.findByLabelText("Organization")).not.toHaveAttribute("data-disabled");+ });++ it("is read-only for a non-admin", async () => {+ state.authorized = { ...state.authorized, userRole: "Internal User" };+ state.organizations = [{ organization_id: "org-1", organization_alias: "Engineering" }];+ await openModal();- await userEvent.type(screen.getByLabelText(/Key Name/), "probe-key");- await userEvent.click(screen.getByText("Optional Settings"));+ expect(await screen.findByLabelText("Organization")).toHaveAttribute("data-disabled", "");+ });- await userEvent.click(await screen.findByLabelText(/TPM Rate Limit Type/));- await userEvent.click(await screen.findByText("Guaranteed throughput"));+ it("routes a chosen organization into organization_id", async () => {+ state.organizations = [{ organization_id: "org-1", organization_alias: "Engineering" }];+ await openModal();+ await nameTheKey();- await userEvent.click(screen.getByRole("button", { name: /create key/i }));+ await userEvent.click(await screen.findByLabelText("Organization"));+ await userEvent.click(await screen.findByRole("option", { name: /Engineering/ }));+ await submit();- await waitFor(() => {- expect(mockKeyCreateCall).toHaveBeenCalled();+ expect((await createdPayload()).organization_id).toBe("org-1");});- expect(mockKeyCreateCall.mock.calls[0][2]).toMatchObject({- tpm_limit_type: "guaranteed_throughput",- rpm_limit_type: null,+ });++ describe("policy and prompt fields", () => {+ it("loads and offers both selectors for a role that can see them", async () => {+ await openModal();+ await openSection(/Optional Settings/i);++ expect(await screen.findByLabelText("Policies")).toBeInTheDocument();+ expect(await screen.findByLabelText("Prompts")).toBeInTheDocument();+ });++ it("omits both selectors for a role that cannot see them", async () => {+ state.can = { viewPolicies: false, viewPrompts: false };+ await openModal();+ await openSection(/Optional Settings/i);++ await screen.findByLabelText("Guardrails");+ expect(screen.queryByLabelText("Policies")).not.toBeInTheDocument();+ expect(screen.queryByLabelText("Prompts")).not.toBeInTheDocument();+ });+ });++ describe("tags dropdown", () => {+ it("offers the tags returned by the tags hook", async () => {+ state.tags = { production: { name: "production" }, staging: { name: "staging" } };+ await openModal();+ await openSection(/Optional Settings/i);++ await userEvent.click(await screen.findByLabelText("Tags"));++ expect(await screen.findByTitle("production")).toBeInTheDocument();+ expect(await screen.findByTitle("staging")).toBeInTheDocument();});});- it("carries the shared lifecycle expiry into the payload once its section is open", async () => {- await openModal();+ describe("user search debounce", () => {+ it("fires exactly one search carrying the last typed value", async () => {+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ renderCreateKey({ autoOpenCreate: true, prefillData: { owned_by: "another_user" } });+ const search = antdSearchInput(await screen.findByText("Type email to search for users"));++ await user.type(search, "ali");+ expect(vi.mocked(userFilterUICall)).not.toHaveBeenCalled();++ await user.type(search, "ce");+ await vi.advanceTimersByTimeAsync(400);++ expect(vi.mocked(userFilterUICall)).toHaveBeenCalledTimes(1);+ const params = vi.mocked(userFilterUICall).mock.calls[0][1] as URLSearchParams;+ expect(params.get("user_email")).toBe("alice");+ } finally {+ vi.useRealTimers();+ }+ });+ });- await userEvent.type(screen.getByLabelText(/Key Name/), "probe-key");- await userEvent.click(screen.getByText("Optional Settings"));- await userEvent.click(await screen.findByText("Key Lifecycle"));+ describe("created key display", () => {+ it("surfaces the generated key after a successful create", async () => {+ await openModal();+ await nameTheKey();+ await submit();+ await createdPayload();- await userEvent.type(await screen.findByLabelText("Expire Key"), "45d");+ expect(await screen.findByText("Save your Key")).toBeInTheDocument();+ });- await userEvent.click(screen.getByRole("button", { name: /create key/i }));+ it("rejects a duplicate alias within the same team without calling the API", async () => {+ await openModal({ data: [{ team_id: null, key_alias: "contract-key" }] });+ await nameTheKey();+ await submit();- await waitFor(() => {- expect(mockKeyCreateCall).toHaveBeenCalled();+ await waitFor(() => {+ expect(screen.getByRole("button", { name: /^create key$/i })).toBeInTheDocument();+ });+ expect(vi.mocked(keyCreateCall)).not.toHaveBeenCalled();});- expect(mockKeyCreateCall.mock.calls[0][2]).toMatchObject({ duration: "45d" });});- it("preserves a value typed in a section that is collapsed and reopened before submit", async () => {- await openModal();+ describe("key type gating", () => {+ it("labels the llm_api option AI APIs", async () => {+ await openModal();+ await userEvent.click(await screen.findByLabelText("Key Type"));- await userEvent.type(screen.getByLabelText(/Key Name/), "probe-key");- await userEvent.click(screen.getByText("Optional Settings"));+ expect(+ await screen.findByText("Can call only AI API routes (chat/completions, embeddings, etc.)"),+ ).toBeInTheDocument();+ expect(screen.queryByText("LLM API")).not.toBeInTheDocument();+ });- const maxBudget = await screen.findByLabelText(/Max Budget/);- await userEvent.type(maxBudget, "150.75");+ it("clears and disables models when a management key type is chosen", async () => {+ await openModal();+ await nameTheKey();- await userEvent.click(screen.getByText("Optional Settings"));- await userEvent.click(screen.getByText("Optional Settings"));+ await userEvent.click(await screen.findByLabelText("Key Type"));+ await userEvent.click(await screen.findByText("Management"));+ await submit();- expect(await screen.findByLabelText(/Max Budget/)).toHaveValue(150.75);+ const payload = await createdPayload();+ expect(payload.key_type).toBe("management");+ expect(payload.models).toStrictEqual([]);+ });+ });++ describe("mount-gate liveness", () => {+ it("keeps the MCP tool permissions key out of the payload even with its section open", async () => {+ await openModal();+ await nameTheKey();+ await openSection(/Optional Settings/i);+ await openSection(SECTIONS.mcp);+ await submit();++ const payload = await createdPayload();+ expect(payload).not.toHaveProperty("mcp_tool_permissions");+ expect(payload).toHaveProperty("allowed_mcp_servers_and_groups");+ });- await userEvent.click(screen.getByRole("button", { name: /create key/i }));+ it("registers no Optional Settings field while a team choice is still required", async () => {+ vi.mocked(modelAvailableCall).mockResolvedValue({ data: [{ id: "no-default-models" }] });+ renderCreateKey();+ await userEvent.click(screen.getByTestId("create-key-button"));- await waitFor(() => {- expect(mockKeyCreateCall).toHaveBeenCalled();+ expect(await screen.findByText(/Please select a team to continue/)).toBeInTheDocument();+ expect(screen.queryByLabelText(/Key Name/)).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /Optional Settings/i })).not.toBeInTheDocument();});- expect(mockKeyCreateCall.mock.calls[0][2]).toMatchObject({ max_budget: "150.75" });});});diff --git a/ui/litellm-dashboard/src/components/organisms/create_key_button.test.tsx b/ui/litellm-dashboard/src/components/organisms/create_key_button.test.tsxindex 7c9eed62c89..e6bd6cddd38 100644--- a/ui/litellm-dashboard/src/components/organisms/create_key_button.test.tsx+++ b/ui/litellm-dashboard/src/components/organisms/create_key_button.test.tsx@@ -1,891 +1,76 @@-import { act, fireEvent, within } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { renderWithProviders, screen, waitFor } from "../../../tests/test-utils";-import { Team } from "../key_team_helpers/key_list";-import { getPoliciesList, getPromptsList, userFilterUICall } from "../networking";-import CreateKey from "./create_key_button";--const { formMock, setFieldsValueMock, radioGroupValueRef, formStateRef, mockKeyCreateCall, teamDropdownTeamsRef } =- vi.hoisted(() => {- const formStateRef = { current: {} as Record<string, any> };- const teamDropdownTeamsRef = { current: [] as Array<{ team_id: string; team_alias: string; models: string[] }> };- const mockKeyCreateCall = vi.fn().mockResolvedValue({- key: "test-api-key",- soft_budget: null,- });- const formMock = {- setFieldsValue: vi.fn((values: Record<string, any>) => {- Object.assign(formStateRef.current, values);- }),- setFieldValue: vi.fn((name: string, value: any) => {- formStateRef.current[name] = value;- }),- getFieldValue: vi.fn((name: string) => formStateRef.current[name]),- resetFields: vi.fn(() => {- formStateRef.current = {};- }),- };- const radioGroupValueRef = { current: null as string | null };- return {- formMock,- setFieldsValueMock: formMock.setFieldsValue,- radioGroupValueRef,- formStateRef,- mockKeyCreateCall,- teamDropdownTeamsRef,- };- });--const defaultAuthorizedState = {- accessToken: "test-token",- userId: "test-user-id",- userRole: "Admin",- premiumUser: false,-};--let authorizedState = { ...defaultAuthorizedState };--vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({- default: () => authorizedState,-}));--vi.mock("@/app/(dashboard)/hooks/keys/useKeys", () => ({- keyKeys: {- lists: () => ["keys"],- },-}));--vi.mock("@ant-design/icons", () => ({- InfoCircleOutlined: () => null,-}));--vi.mock("react-copy-to-clipboard", () => ({- CopyToClipboard: ({ children }: { children: any }) => children,-}));--vi.mock("antd", () => {- const React = require("react");-- const getValueFromEvent = (event: any) => {- if (event?.target) {- if (event.target.type === "checkbox") {- return event.target.checked;- }- return event.target.value;- }- return event;- };-- const Form = ({- children,- onFinish,- ...props- }: {- children?: any;- onFinish?: (values: Record<string, any>) => void;- }) =>- React.createElement(- "form",- {- ...props,- onSubmit: (event: Event) => {- event.preventDefault();- onFinish?.({ ...formStateRef.current });- },- },- children,- );-- Form.Item = ({ children, name }: { children?: any; name?: string }) => {- if (!name || !React.isValidElement(children)) {- return React.createElement(React.Fragment, null, children);- }-- return React.cloneElement(children, {- value: formStateRef.current[name],- onChange: (event: any) => {- formStateRef.current[name] = getValueFromEvent(event);- },- });- };-- Form.useForm = () => [formMock];-- Form.useWatch = (name: string) => formStateRef.current[name];-- const Select = ({- children,- onChange,- onSearch,- options,- ...props- }: {- children?: any;- onChange?: (value: string) => void;- onSearch?: (value: string) => void;- options?: Array<{ value: string; label: string }>;- }) => {- const select = React.createElement(- "select",- {- ...props,- onChange: (event: any) => onChange?.(event.target.value),- },- children,- options?.map((opt: any) => React.createElement("option", { key: opt.value, value: opt.value }, opt.label)),- );-- if (!onSearch) {- return select;- }-- return React.createElement(- React.Fragment,- null,- React.createElement("input", {- "data-testid": "select-search-input",- onChange: (event: React.ChangeEvent<HTMLInputElement>) => onSearch(event.target.value),- }),- select,- );- };-- Select.Option = ({ children, ...props }: { children?: any }) => React.createElement("option", props, children);-- const Input = (props: any) => React.createElement("input", props);- Input.Password = (props: any) => React.createElement("input", { ...props, type: "password" });- Input.TextArea = (props: any) => React.createElement("textarea", props);-- const Modal = ({ children, open }: { children?: any; open?: boolean }) =>- open ? React.createElement("div", null, children) : null;-- const Radio = ({ children, ...props }: { children?: any }) => React.createElement("div", props, children);-- Radio.Group = ({ children, value }: { children?: any; value?: string }) => {- radioGroupValueRef.current = value ?? null;- return React.createElement("div", null, children);- };-- const Switch = (props: any) => React.createElement("input", { ...props, type: "checkbox" });- const Tag = ({ children }: { children?: any }) => React.createElement("span", null, children);- const Tooltip = ({ children }: { children?: any }) => React.createElement(React.Fragment, null, children);-- const Button = ({ children, htmlType, ...props }: { children?: any; htmlType?: string }) =>- React.createElement("button", { ...props, type: htmlType ?? props.type }, children);-- const Typography = ({ children, ...props }: { children?: any }) => React.createElement("div", props, children);- Typography.Text = ({ children, ...props }: { children?: any }) => React.createElement("span", props, children);- Typography.Paragraph = ({ children, ...props }: { children?: any }) => React.createElement("p", props, children);- Typography.Title = ({ children, ...props }: { children?: any }) => React.createElement("h1", props, children);-- return {- Button,- Form,- Input,- message: {- success: vi.fn(),- error: vi.fn(),- warning: vi.fn(),- info: vi.fn(),- },- Modal,- Radio,- Select,- Switch,- Tag,- Tooltip,- Typography,- };-});+import { beforeEach, describe, expect, it, vi } from "vitest";+import { modelAvailableCall } from "../networking";+import { fetchTeamModels, fetchUserModels } from "./create_key_button";vi.mock("../networking", () => ({- keyCreateCall: mockKeyCreateCall,- modelAvailableCall: vi.fn().mockResolvedValue({ data: [{ id: "gpt-4" }] }),- getGuardrailsList: vi.fn().mockResolvedValue({ guardrails: [] }),- getPoliciesList: vi.fn().mockResolvedValue({ policies: [] }),- getPromptsList: vi.fn().mockResolvedValue({ prompts: [] }),- proxyBaseUrl: "http://localhost:4000",- getPossibleUserRoles: vi.fn().mockResolvedValue({- Admin: { ui_label: "Admin" },- User: { ui_label: "User" },- }),- userFilterUICall: vi.fn().mockResolvedValue([]),- keyCreateServiceAccountCall: vi.fn().mockResolvedValue({- key: "test-service-account-key",- soft_budget: null,- }),- fetchMCPAccessGroups: vi.fn().mockResolvedValue([]),- getAgentsList: vi.fn().mockResolvedValue({ agents: [] }),-}));--vi.mock("../agent_management/AgentSelector", () => ({ default: () => null }));-vi.mock("../common_components/budget_duration_dropdown", () => ({- NEVER_RESETS_BUDGET_DURATION: "none",- default: ({- showNeverResets,- placeholder,- onChange,- }: {- showNeverResets?: boolean;- placeholder?: string;- onChange?: (value: string) => void;- }) => (- <select data-testid="budget-duration-dropdown" onChange={(event) => onChange?.(event.target.value)}>- <option value="">{placeholder ?? "n/a"}</option>- {showNeverResets ? <option value="none">Never resets</option> : null}- <option value="30d">monthly</option>- </select>- ),-}));-vi.mock("../common_components/check_openapi_schema", () => ({ default: () => null }));-vi.mock("../common_components/KeyLifecycleSettings", () => ({ default: () => null }));-vi.mock("../common_components/ModelAliasManager", () => ({ default: () => null }));-vi.mock("../common_components/PassThroughRoutesSelector", () => ({ default: () => null }));-vi.mock("../common_components/PremiumLoggingSettings", () => ({ default: () => null }));-vi.mock("../common_components/RateLimitTypeFormItem", () => ({ default: () => null }));-vi.mock("../common_components/RouterSettingsAccordion", () => ({ default: () => null }));-vi.mock("@/app/(dashboard)/hooks/teams/useTeams", () => ({- useInfiniteTeams: () => ({- data: {- pages: [- {- teams: [- { team_id: "team-1", team_alias: "Team One" },- { team_id: "team-2", team_alias: "Team Two" },- ],- total: 2,- page: 1,- page_size: 50,- total_pages: 1,- },- ],- },- fetchNextPage: vi.fn(),- hasNextPage: false,- isFetchingNextPage: false,- isLoading: false,- }),-}));-vi.mock("../common_components/team_dropdown", () => ({- default: ({- onTeamSelect,- disabled,- }: {- onTeamSelect?: (team: { team_id: string; team_alias: string; models: string[] } | null) => void;- disabled?: boolean;- }) => (- <select- data-testid="team-dropdown"- disabled={disabled}- onChange={(e) =>- onTeamSelect?.(teamDropdownTeamsRef.current.find((team) => team.team_id === e.target.value) ?? null)- }- >- <option value="">Select team</option>- {teamDropdownTeamsRef.current.map((team) => (- <option key={team.team_id} value={team.team_id}>- {team.team_alias}- </option>- ))}- </select>- ),-}));-vi.mock("../CreateUserButton", () => ({ CreateUserButton: () => null }));-vi.mock("../mcp_server_management/MCPServerSelector", () => ({ default: () => null }));-vi.mock("../mcp_server_management/MCPToolPermissions", () => ({ default: () => null }));-vi.mock("../shared/numerical_input", () => ({ default: () => null }));-vi.mock("../vector_store_management/VectorStoreSelector", () => ({ default: () => null }));-vi.mock("../key_team_helpers/fetch_available_models_team_key", async () => {- const actual = await vi.importActual("../key_team_helpers/fetch_available_models_team_key");- return {- ...actual,- getModelDisplayName: (model: string) => model,- };-});--vi.mock("@/app/(dashboard)/hooks/tags/useTags", () => ({- useTags: vi.fn().mockReturnValue({- data: [- { name: "production", description: "Prod tag", models: [], created_at: "2026-01-01", updated_at: "2026-01-01" },- { name: "staging", description: "Staging tag", models: [], created_at: "2026-01-01", updated_at: "2026-01-01" },- ],- isLoading: false,- }),-}));--vi.mock("@/app/(dashboard)/hooks/projects/useProjects", () => ({- useProjects: vi.fn().mockReturnValue({ data: [], isLoading: false }),-}));--vi.mock("@/app/(dashboard)/hooks/organizations/useOrganizations", () => ({- useOrganizations: vi.fn().mockReturnValue({- data: [- { organization_id: "org-1", organization_alias: "Engineering" },- { organization_id: "org-2", organization_alias: "Sales" },- ],- isLoading: false,- }),-}));--vi.mock("../common_components/OrganizationDropdown", () => ({- default: ({ value, onChange, disabled }: { value?: string; onChange?: (v: string) => void; disabled?: boolean }) => (- <select- data-testid="org-dropdown"- disabled={disabled}- value={value || ""}- onChange={(e) => onChange?.(e.target.value)}- >- <option value="">Select org</option>- <option value="org-1">Engineering</option>- <option value="org-2">Sales</option>- </select>- ),+ modelAvailableCall: vi.fn(),}));-vi.mock("../common_components/ProjectDropdown", () => ({- default: ({ value, onChange }: { value?: string; onChange?: (v: string) => void }) => (- <input data-testid="project-dropdown" value={value || ""} onChange={(e) => onChange?.(e.target.value)} />- ),-}));--vi.mock("../common_components/AccessGroupSelector", () => ({- default: ({ value = [], onChange }: { value?: string[]; onChange?: (v: string[]) => void }) => (- <input- data-testid="access-group-selector"- value={Array.isArray(value) ? value.join(",") : ""}- onChange={(event) => onChange?.(event.target.value ? event.target.value.split(",").map((v) => v.trim()) : [])}- />- ),-}));--describe("CreateKey", () => {- const defaultProps = {- team: null,- teams: [],- data: [],- addKey: vi.fn(),- };-- const openOptionalSettings = async () => {- const trigger = await screen.findByRole("button", { name: /optional settings/i });- act(() => {- fireEvent.click(trigger);- });- };-+describe("fetchTeamModels", () => {beforeEach(() => {- vi.clearAllMocks();- if (typeof window !== "undefined" && window.localStorage && typeof window.localStorage.clear === "function") {- window.localStorage.clear();- }- authorizedState = { ...defaultAuthorizedState };- radioGroupValueRef.current = null;- formStateRef.current = {};- teamDropdownTeamsRef.current = [- { team_id: "team-1", team_alias: "Team One", models: [] },- { team_id: "team-2", team_alias: "Team Two", models: [] },- ];- mockKeyCreateCall.mockResolvedValue({- key: "test-api-key",- soft_budget: null,- });- });-- it("should render the CreateKey component", () => {- renderWithProviders(<CreateKey {...defaultProps} />);- expect(screen.getByRole("button", { name: /create new key/i })).toBeInTheDocument();- });-- it("should display 'AI APIs' label for the llm_api key type option", async () => {- renderWithProviders(<CreateKey {...defaultProps} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- await waitFor(() => {- expect(screen.getByText("AI APIs")).toBeInTheDocument();- expect(screen.queryByText("LLM API")).not.toBeInTheDocument();- });- });-- it("should include access_group_ids in keyCreateCall payload when access groups are selected", async () => {- renderWithProviders(<CreateKey {...defaultProps} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- await openOptionalSettings();-- await waitFor(() => {- expect(screen.getByTestId("access-group-selector")).toBeInTheDocument();- });-- act(() => {- fireEvent.change(screen.getByTestId("access-group-selector"), { target: { value: "ag-1,ag-2" } });- formMock.setFieldValue("key_alias", "Test Key");- });-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create key/i }));- });-- await waitFor(() => {- expect(mockKeyCreateCall).toHaveBeenCalled();- const formValues = mockKeyCreateCall.mock.calls[0][2];- expect(formValues).toHaveProperty("access_group_ids");- expect(formValues.access_group_ids).toEqual(["ag-1", "ag-2"]);- });- });-- it("should include mcp_toolsets in keyCreateCall payload when only toolsets are selected", async () => {- renderWithProviders(<CreateKey {...defaultProps} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- await waitFor(() => {- expect(screen.getByRole("button", { name: /create key/i })).toBeInTheDocument();- });-- act(() => {- formMock.setFieldValue("key_alias", "Test Key");- formMock.setFieldValue("allowed_mcp_servers_and_groups", {- servers: [],- accessGroups: [],- toolsets: ["ts-1"],- });- });-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create key/i }));- });-- await waitFor(() => {- expect(mockKeyCreateCall).toHaveBeenCalled();- });- expect(mockKeyCreateCall.mock.calls[0][2].object_permission?.mcp_toolsets).toEqual(["ts-1"]);- });-- it("should prefill models when provided without team_id", async () => {- renderWithProviders(- <CreateKey- {...defaultProps}- autoOpenCreate={true}- prefillData={{- models: ["gpt-4"],- }}- />,- );-- await waitFor(() => {- expect(setFieldsValueMock).toHaveBeenCalledWith({ models: ["gpt-4"] });- });- });-- it("should prefill team_id when it exists in teams", async () => {- renderWithProviders(- <CreateKey- {...defaultProps}- teams={[{ team_id: "team-1", models: [] } as any]}- autoOpenCreate={true}- prefillData={{ team_id: "team-1" }}- />,- );-- await waitFor(() => {- expect(setFieldsValueMock).toHaveBeenCalledWith({ team_id: "team-1" });- });- });-- it("should ignore team_id when it does not exist in teams", async () => {- renderWithProviders(- <CreateKey- {...defaultProps}- teams={[{ team_id: "team-1", models: [] } as any]}- autoOpenCreate={true}- prefillData={{ team_id: "team-404", key_alias: "example-key" }}- />,- );-- await waitFor(() => {- expect(setFieldsValueMock).toHaveBeenCalledWith({ key_alias: "example-key" });- });-- expect(setFieldsValueMock).not.toHaveBeenCalledWith({ team_id: "team-404" });+ vi.mocked(modelAvailableCall).mockReset();});- it('should fall back to "you" when owned_by is another_user for non-admin', async () => {- authorizedState = { ...defaultAuthorizedState, userRole: "Internal User" };-- renderWithProviders(- <CreateKey- {...defaultProps}- autoOpenCreate={true}- prefillData={{ owned_by: "another_user", key_alias: "example-key" }}- />,- );+ it("asks the proxy for the team-scoped model list and returns the ids", async () => {+ vi.mocked(modelAvailableCall).mockResolvedValue({ data: [{ id: "gpt-4" }, { id: "claude-opus-4" }] });- await waitFor(() => {- expect(setFieldsValueMock).toHaveBeenCalledWith({ key_alias: "example-key" });- });-- expect(radioGroupValueRef.current).toBe("you");+ await expect(fetchTeamModels("user-1", "Admin", "token-1", "team-1")).resolves.toStrictEqual([+ "gpt-4",+ "claude-opus-4",+ ]);+ expect(modelAvailableCall).toHaveBeenCalledWith("token-1", "user-1", "Admin", true, "team-1", true);});- it("should apply owned_by another_user for admin", async () => {- renderWithProviders(- <CreateKey {...defaultProps} autoOpenCreate={true} prefillData={{ owned_by: "another_user" }} />,- );-- await waitFor(() => {- expect(radioGroupValueRef.current).toBe("another_user");- });- });+ it("passes a null team through rather than dropping the argument", async () => {+ vi.mocked(modelAvailableCall).mockResolvedValue({ data: [] });- it("should prefill key_type when provided", async () => {- renderWithProviders(<CreateKey {...defaultProps} autoOpenCreate={true} prefillData={{ key_type: "management" }} />);+ await fetchTeamModels("user-1", "Admin", "token-1", null);- await waitFor(() => {- expect(setFieldsValueMock).toHaveBeenCalledWith({ key_type: "management" });- });+ expect(modelAvailableCall).toHaveBeenCalledWith("token-1", "user-1", "Admin", true, null, true);});- describe("organization dropdown", () => {- it("should render the organization dropdown when modal is open", async () => {- renderWithProviders(<CreateKey {...defaultProps} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- await waitFor(() => {- expect(screen.getByTestId("org-dropdown")).toBeInTheDocument();- });- });-- it("should disable the organization dropdown for non-admin users", async () => {- authorizedState = { ...defaultAuthorizedState, userRole: "Internal User" };-- renderWithProviders(<CreateKey {...defaultProps} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- await waitFor(() => {- expect(screen.getByTestId("org-dropdown")).toBeDisabled();- });- });-- it("should enable the organization dropdown for admin users", async () => {- authorizedState = { ...defaultAuthorizedState, userRole: "Admin" };-- renderWithProviders(<CreateKey {...defaultProps} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- await waitFor(() => {- expect(screen.getByTestId("org-dropdown")).toBeEnabled();- });- });-- it("should render team dropdown alongside organization dropdown", async () => {- const teamsWithOrg = [{ team_id: "team-1", team_alias: "Team Alpha", organization_id: "org-1", models: [] }];-- renderWithProviders(<CreateKey {...defaultProps} teams={teamsWithOrg as any} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- await waitFor(() => {- expect(screen.getByTestId("org-dropdown")).toBeInTheDocument();- expect(screen.getByTestId("team-dropdown")).toBeInTheDocument();- });- });-- it("should set organization_id in form state when org is selected", async () => {- renderWithProviders(<CreateKey {...defaultProps} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- await waitFor(() => {- expect(screen.getByTestId("org-dropdown")).toBeInTheDocument();- });-- act(() => {- fireEvent.change(screen.getByTestId("org-dropdown"), { target: { value: "org-1" } });- });-- expect(formStateRef.current["organization_id"]).toBe("org-1");- });+ it("returns an empty list and makes no call when the user id is null", async () => {+ await expect(fetchTeamModels(null as unknown as string, "Admin", "token-1", "team-1")).resolves.toStrictEqual([]);+ expect(modelAvailableCall).not.toHaveBeenCalled();});- describe("models dropdown team gating", () => {- const getModelsSelect = async (): Promise<HTMLElement> => {- return waitFor(() => {- const element = document.querySelector('select[placeholder="Select models"]');- expect(element).toBeTruthy();- return element as HTMLElement;- });- };-- it("should offer all-proxy-models but not all-team-models when no team is selected", async () => {- renderWithProviders(<CreateKey {...defaultProps} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- const modelsSelect = await getModelsSelect();-- await waitFor(() => {- expect(within(modelsSelect).getByText("gpt-4")).toBeInTheDocument();- });-- expect(within(modelsSelect).getByText("All Proxy Models")).toBeInTheDocument();- expect(within(modelsSelect).queryByText("All Team Models")).not.toBeInTheDocument();- });+ it("swallows a failed lookup and returns an empty list", async () => {+ vi.mocked(modelAvailableCall).mockRejectedValue(new Error("proxy down"));- it("should offer all-team-models but hide all-proxy-models when a team is selected", async () => {- teamDropdownTeamsRef.current = [- { team_id: "team-1", team_alias: "Team One", models: ["all-proxy-models", "team-model-1"] },- ];-- renderWithProviders(<CreateKey {...defaultProps} teams={teamDropdownTeamsRef.current as unknown as Team[]} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- await waitFor(() => {- expect(screen.getByTestId("team-dropdown")).toBeInTheDocument();- });-- act(() => {- fireEvent.change(screen.getByTestId("team-dropdown"), { target: { value: "team-1" } });- });-- const modelsSelect = await getModelsSelect();-- await waitFor(() => {- expect(within(modelsSelect).getByText("team-model-1")).toBeInTheDocument();- });-- expect(within(modelsSelect).getByText("All Team Models")).toBeInTheDocument();- expect(within(modelsSelect).queryByText("All Proxy Models")).not.toBeInTheDocument();- expect(within(modelsSelect).queryByText("all-proxy-models")).not.toBeInTheDocument();- });+ await expect(fetchTeamModels("user-1", "Admin", "token-1", "team-1")).resolves.toStrictEqual([]);});+});- describe("user search debounce", () => {- const mockUserFilterUICall = vi.mocked(userFilterUICall);-- beforeEach(() => {- vi.useFakeTimers();- });-- afterEach(() => {- vi.runOnlyPendingTimers();- vi.useRealTimers();- });-- const renderUserSearch = () => {- const view = renderWithProviders(- <CreateKey {...defaultProps} autoOpenCreate={true} prefillData={{ owned_by: "another_user" }} />,- );- return { input: screen.getByTestId("select-search-input"), unmount: view.unmount };- };-- it("should not fire the search before the wait elapses", () => {- const { input } = renderUserSearch();-- act(() => {- fireEvent.change(input, { target: { value: "alice" } });- });-- expect(mockUserFilterUICall).not.toHaveBeenCalled();-- act(() => {- vi.advanceTimersByTime(299);- });-- expect(mockUserFilterUICall).not.toHaveBeenCalled();- });-- it("should fire exactly one search carrying the last value after the wait", async () => {- const { input } = renderUserSearch();-- act(() => {- fireEvent.change(input, { target: { value: "a" } });- vi.advanceTimersByTime(100);- fireEvent.change(input, { target: { value: "al" } });- vi.advanceTimersByTime(100);- fireEvent.change(input, { target: { value: "alice" } });- });-- expect(mockUserFilterUICall).not.toHaveBeenCalled();-- await act(async () => {- vi.advanceTimersByTime(300);- });-- expect(mockUserFilterUICall).toHaveBeenCalledTimes(1);- const params = mockUserFilterUICall.mock.calls[0][1] as URLSearchParams;- expect(params.get("user_email")).toBe("alice");- });-- it("should fire nothing when unmounted mid-wait", () => {- const { input, unmount } = renderUserSearch();-- act(() => {- fireEvent.change(input, { target: { value: "alice" } });- });-- unmount();-- act(() => {- vi.advanceTimersByTime(1000);- });-- expect(mockUserFilterUICall).not.toHaveBeenCalled();- });+describe("fetchUserModels", () => {+ beforeEach(() => {+ vi.mocked(modelAvailableCall).mockReset();});- describe("tags dropdown", () => {- it("should populate tags dropdown with options from useTags hook", async () => {- renderWithProviders(<CreateKey {...defaultProps} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });+ it("hands the returned ids to the setter without the team-scoped arguments", async () => {+ vi.mocked(modelAvailableCall).mockResolvedValue({ data: [{ id: "gpt-4" }] });+ const setUserModels = vi.fn();- await openOptionalSettings();+ await fetchUserModels("user-1", "Admin", "token-1", setUserModels);- await waitFor(() => {- expect(screen.getByText("production")).toBeInTheDocument();- expect(screen.getByText("staging")).toBeInTheDocument();- });- });+ expect(modelAvailableCall).toHaveBeenCalledWith("token-1", "user-1", "Admin");+ expect(setUserModels).toHaveBeenCalledWith(["gpt-4"]);});- describe("policy and prompt fields", () => {- const POLICIES_PLACEHOLDER = "Premium feature - Upgrade to set policies by key";- const PROMPTS_PLACEHOLDER = "Premium feature - Upgrade to set prompts by key";-- const openModal = async () => {- renderWithProviders(<CreateKey {...defaultProps} />);- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });- await openOptionalSettings();- };-- beforeEach(() => {- vi.mocked(getPoliciesList).mockResolvedValue({ policies: [{ policy_name: "policy-a" }] });- vi.mocked(getPromptsList).mockResolvedValue({ prompts: [{ prompt_id: "prompt-a" }] } as any);- });+ it("leaves the setter untouched when the lookup fails", async () => {+ vi.mocked(modelAvailableCall).mockRejectedValue(new Error("proxy down"));+ const setUserModels = vi.fn();- it("should load and offer both selectors for an admin", async () => {- await openModal();+ await fetchUserModels("user-1", "Admin", "token-1", setUserModels);- await waitFor(() => {- expect(screen.getByRole("option", { name: "policy-a" })).toBeInTheDocument();- expect(screen.getByRole("option", { name: "prompt-a" })).toBeInTheDocument();- });- expect(getPoliciesList).toHaveBeenCalledWith("test-token");- expect(getPromptsList).toHaveBeenCalledWith("test-token");- expect(screen.getByPlaceholderText(POLICIES_PLACEHOLDER)).toBeInTheDocument();- expect(screen.getByPlaceholderText(PROMPTS_PLACEHOLDER)).toBeInTheDocument();- });-- it("should omit both selectors and fire neither admin-only request for an internal user", async () => {- authorizedState = { ...defaultAuthorizedState, userRole: "Internal User" };-- await openModal();-- expect(await screen.findByTestId("org-dropdown")).toBeInTheDocument();-- expect(getPoliciesList).not.toHaveBeenCalled();- expect(getPromptsList).not.toHaveBeenCalled();- expect(screen.queryByPlaceholderText(POLICIES_PLACEHOLDER)).not.toBeInTheDocument();- expect(screen.queryByPlaceholderText(PROMPTS_PLACEHOLDER)).not.toBeInTheDocument();- });+ expect(setUserModels).not.toHaveBeenCalled();});- describe("budget reset", () => {- const openModal = async () => {- renderWithProviders(<CreateKey {...defaultProps} />);-- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create new key/i }));- });-- await openOptionalSettings();-- await waitFor(() => {- expect(screen.getByTestId("budget-duration-dropdown")).toBeInTheDocument();- });- };-- const submit = async () => {- act(() => {- fireEvent.click(screen.getByRole("button", { name: /create key/i }));- });-- await waitFor(() => {- expect(mockKeyCreateCall).toHaveBeenCalled();- });-- return mockKeyCreateCall.mock.calls[0][2];- };-- it("should send an explicit null budget_duration when 'Never resets' is selected", async () => {- await openModal();-- expect(screen.getByRole("option", { name: "Never resets" })).toBeInTheDocument();-- act(() => {- fireEvent.change(screen.getByTestId("budget-duration-dropdown"), { target: { value: "none" } });- formMock.setFieldValue("key_alias", "Never Resets Key");- });-- const formValues = await submit();-- expect("budget_duration" in formValues).toBe(true);- expect(formValues.budget_duration).toBeNull();- });-- it("should label the omit option distinctly from 'Never resets'", async () => {- await openModal();-- const optionLabels = Array.from(- screen.getByTestId("budget-duration-dropdown").querySelectorAll("option"),- (option) => option.textContent,- );-- expect(optionLabels).toContain("Never resets");- expect(new Set(optionLabels).size).toBe(optionLabels.length);- expect(screen.getByRole("option", { name: "Never resets" })).toHaveValue("none");- });-- it("should omit budget_duration entirely when the reset dropdown is untouched", async () => {- await openModal();-- act(() => {- formMock.setFieldValue("key_alias", "Inherits Default Key");- });+ it("makes no call when the user role is null", async () => {+ const setUserModels = vi.fn();- const formValues = await submit();+ await fetchUserModels("user-1", null as unknown as string, "token-1", setUserModels);- expect("budget_duration" in formValues).toBe(false);- });+ expect(modelAvailableCall).not.toHaveBeenCalled();+ expect(setUserModels).not.toHaveBeenCalled();});});