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
feat(ui): add block/unblock key action to key info page (#34116)
ryan-crabbe-berrid2819baf0af3
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useSetKeyBlockedState.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useSetKeyBlockedState.test.tsnew file mode 100644index 00000000000..5eb3bdc105d--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useSetKeyBlockedState.test.ts@@ -0,0 +1,103 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import React, { ReactNode } from "react";+import { useSetKeyBlockedState, setKeyBlockedState } from "./useSetKeyBlockedState";+import { apiClient } from "@/components/networking";++vi.mock("@/components/networking", () => ({+ apiClient: { post: vi.fn() },+}));++const mockUseAuthorized = vi.fn();+vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({+ default: () => mockUseAuthorized(),+}));++const mockPost = vi.mocked(apiClient.post);++const createWrapper = () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ const wrapper = ({ children }: { children: ReactNode }) =>+ React.createElement(QueryClientProvider, { client: queryClient }, children);+ return { queryClient, wrapper };+};++describe("setKeyBlockedState", () => {+ beforeEach(() => {+ mockPost.mockReset();+ });++ it("POSTs the key hash to /key/block when blocking", async () => {+ mockPost.mockResolvedValueOnce({ blocked: true });++ const result = await setKeyBlockedState("sk-access", { keyToken: "hashed-token", blocked: true });++ expect(mockPost).toHaveBeenCalledWith("/key/block", {+ accessToken: "sk-access",+ body: { key: "hashed-token" },+ });+ expect(result).toEqual({ blocked: true });+ });++ it("POSTs the key hash to /key/unblock when unblocking", async () => {+ mockPost.mockResolvedValueOnce({ blocked: false });++ const result = await setKeyBlockedState("sk-access", { keyToken: "hashed-token", blocked: false });++ expect(mockPost).toHaveBeenCalledWith("/key/unblock", {+ accessToken: "sk-access",+ body: { key: "hashed-token" },+ });+ expect(result).toEqual({ blocked: false });+ });++ it("falls back to the requested state when the response has no blocked field", async () => {+ mockPost.mockResolvedValueOnce(null);++ const result = await setKeyBlockedState("sk-access", { keyToken: "hashed-token", blocked: true });++ expect(result).toEqual({ blocked: true });+ });+});++describe("useSetKeyBlockedState", () => {+ beforeEach(() => {+ mockPost.mockReset();+ mockUseAuthorized.mockReturnValue({ accessToken: "sk-access" });+ });++ it("invalidates key queries after a successful mutation", async () => {+ mockPost.mockResolvedValueOnce({ blocked: true });+ const { queryClient, wrapper } = createWrapper();+ const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");++ const { result } = renderHook(() => useSetKeyBlockedState(), { wrapper });+ result.current.mutate({ keyToken: "hashed-token", blocked: true });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ["keys"] });+ });++ it("surfaces request failures as mutation errors", async () => {+ mockPost.mockRejectedValueOnce(new Error("Key not found."));+ const { wrapper } = createWrapper();++ const { result } = renderHook(() => useSetKeyBlockedState(), { wrapper });+ result.current.mutate({ keyToken: "missing", blocked: true });++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(result.current.error?.message).toBe("Key not found.");+ });++ it("errors without an access token", async () => {+ mockUseAuthorized.mockReturnValue({ accessToken: null });+ const { wrapper } = createWrapper();++ const { result } = renderHook(() => useSetKeyBlockedState(), { wrapper });+ result.current.mutate({ keyToken: "hashed-token", blocked: true });++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(mockPost).not.toHaveBeenCalled();+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useSetKeyBlockedState.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useSetKeyBlockedState.tsnew file mode 100644index 00000000000..792ef567f99--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useSetKeyBlockedState.ts@@ -0,0 +1,45 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { apiClient } from "@/components/networking";+import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";+import { keyKeys } from "./useKeys";++export interface SetKeyBlockedStateInput {+ keyToken: string;+ blocked: boolean;+}++export interface SetKeyBlockedStateResult {+ blocked: boolean;+}++interface BlockKeyResponse {+ blocked?: boolean | null;+}++export const setKeyBlockedState = async (+ accessToken: string,+ { keyToken, blocked }: SetKeyBlockedStateInput,+): Promise<SetKeyBlockedStateResult> => {+ const response = await apiClient.post<BlockKeyResponse | null>(blocked ? "/key/block" : "/key/unblock", {+ accessToken,+ body: { key: keyToken },+ });+ return { blocked: response?.blocked ?? blocked };+};++export const useSetKeyBlockedState = () => {+ const { accessToken } = useAuthorized();+ const queryClient = useQueryClient();++ return useMutation<SetKeyBlockedStateResult, Error, SetKeyBlockedStateInput>({+ mutationFn: async (input) => {+ if (!accessToken) {+ throw new Error("Access token is required");+ }+ return setKeyBlockedState(accessToken, input);+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: keyKeys.all });+ },+ });+};diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex d44a491b840..d6e9ba5665c 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -372,7 +372,7 @@ export function getGlobalLitellmHeaderName(): string {return globalLitellmHeaderName;}-const apiClient = createApiClient({+export const apiClient = createApiClient({getBaseUrl: getProxyBaseUrl,getAuthHeaderName: getGlobalLitellmHeaderName,onError: handleError,diff --git a/ui/litellm-dashboard/src/components/templates/KeyInfoHeader.test.tsx b/ui/litellm-dashboard/src/components/templates/KeyInfoHeader.test.tsxindex 14750787609..f67f70e7df9 100644--- a/ui/litellm-dashboard/src/components/templates/KeyInfoHeader.test.tsx+++ b/ui/litellm-dashboard/src/components/templates/KeyInfoHeader.test.tsx@@ -60,22 +60,16 @@ describe("KeyInfoHeader", () => {});describe("action buttons", () => {- it("should show Regenerate and Delete buttons by default", () => {+ it("should show Regenerate button and actions dropdown by default", () => {render(<KeyInfoHeader data={MOCK_DATA} />);expect(screen.getByRole("button", { name: /regenerate key/i })).toBeInTheDocument();- expect(screen.getByRole("button", { name: /delete key/i })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /more key actions/i })).toBeInTheDocument();});- it("should show Regenerate and Delete buttons when canModifyKey is true", () => {- render(<KeyInfoHeader data={MOCK_DATA} canModifyKey={true} />);- expect(screen.getByRole("button", { name: /regenerate key/i })).toBeInTheDocument();- expect(screen.getByRole("button", { name: /delete key/i })).toBeInTheDocument();- });-- it("should hide Regenerate and Delete buttons when canModifyKey is false", () => {+ it("should hide Regenerate button and actions dropdown when canModifyKey is false", () => {render(<KeyInfoHeader data={MOCK_DATA} canModifyKey={false} />);expect(screen.queryByRole("button", { name: /regenerate key/i })).not.toBeInTheDocument();- expect(screen.queryByRole("button", { name: /delete key/i })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /more key actions/i })).not.toBeInTheDocument();});it("should call onRegenerate when Regenerate Key is clicked", async () => {@@ -85,21 +79,87 @@ describe("KeyInfoHeader", () => {expect(onRegenerate).toHaveBeenCalledTimes(1);});+ it("should disable Regenerate button when regenerateDisabled is true", () => {+ render(<KeyInfoHeader data={MOCK_DATA} regenerateDisabled={true} />);+ expect(screen.getByRole("button", { name: /regenerate key/i })).toBeDisabled();+ });++ it("should not disable Regenerate button by default", () => {+ render(<KeyInfoHeader data={MOCK_DATA} />);+ expect(screen.getByRole("button", { name: /regenerate key/i })).not.toBeDisabled();+ });+ });++ describe("destructive actions dropdown", () => {+ const openDropdown = async () => {+ await userEvent.click(screen.getByRole("button", { name: /more key actions/i }));+ };++ it("should list Block Key, Reset Spend, and Delete Key when all handlers are provided", async () => {+ render(<KeyInfoHeader data={MOCK_DATA} onToggleBlocked={vi.fn()} onResetSpend={vi.fn()} onDelete={vi.fn()} />);+ await openDropdown();+ expect(await screen.findByRole("menuitem", { name: /block key/i })).toBeInTheDocument();+ expect(screen.getByRole("menuitem", { name: /reset spend/i })).toBeInTheDocument();+ expect(screen.getByRole("menuitem", { name: /delete key/i })).toBeInTheDocument();+ });++ it("should omit Block Key and Reset Spend when their handlers are not provided", async () => {+ render(<KeyInfoHeader data={MOCK_DATA} onDelete={vi.fn()} />);+ await openDropdown();+ expect(await screen.findByRole("menuitem", { name: /delete key/i })).toBeInTheDocument();+ expect(screen.queryByRole("menuitem", { name: /block key/i })).not.toBeInTheDocument();+ expect(screen.queryByRole("menuitem", { name: /reset spend/i })).not.toBeInTheDocument();+ });++ it("should show Unblock Key instead of Block Key when the key is blocked", async () => {+ render(<KeyInfoHeader data={MOCK_DATA} onToggleBlocked={vi.fn()} isBlocked />);+ await openDropdown();+ expect(await screen.findByRole("menuitem", { name: /unblock key/i })).toBeInTheDocument();+ expect(screen.queryByRole("menuitem", { name: /^block key/i })).not.toBeInTheDocument();+ });++ it("should call onToggleBlocked when Block Key is clicked", async () => {+ const onToggleBlocked = vi.fn();+ render(<KeyInfoHeader data={MOCK_DATA} onToggleBlocked={onToggleBlocked} />);+ await openDropdown();+ await userEvent.click(await screen.findByRole("menuitem", { name: /block key/i }));+ expect(onToggleBlocked).toHaveBeenCalledTimes(1);+ });++ it("should call onToggleBlocked when Unblock Key is clicked", async () => {+ const onToggleBlocked = vi.fn();+ render(<KeyInfoHeader data={MOCK_DATA} onToggleBlocked={onToggleBlocked} isBlocked />);+ await openDropdown();+ await userEvent.click(await screen.findByRole("menuitem", { name: /unblock key/i }));+ expect(onToggleBlocked).toHaveBeenCalledTimes(1);+ });++ it("should call onResetSpend when Reset Spend is clicked", async () => {+ const onResetSpend = vi.fn();+ render(<KeyInfoHeader data={MOCK_DATA} onResetSpend={onResetSpend} />);+ await openDropdown();+ await userEvent.click(await screen.findByRole("menuitem", { name: /reset spend/i }));+ expect(onResetSpend).toHaveBeenCalledTimes(1);+ });+it("should call onDelete when Delete Key is clicked", async () => {const onDelete = vi.fn();render(<KeyInfoHeader data={MOCK_DATA} onDelete={onDelete} />);- await userEvent.click(screen.getByRole("button", { name: /delete key/i }));+ await openDropdown();+ await userEvent.click(await screen.findByRole("menuitem", { name: /delete key/i }));expect(onDelete).toHaveBeenCalledTimes(1);});+ });- it("should disable Regenerate button when regenerateDisabled is true", () => {- render(<KeyInfoHeader data={MOCK_DATA} regenerateDisabled={true} />);- expect(screen.getByRole("button", { name: /regenerate key/i })).toBeDisabled();+ describe("blocked tag", () => {+ it("should show a Blocked tag when isBlocked is true", () => {+ render(<KeyInfoHeader data={MOCK_DATA} isBlocked />);+ expect(screen.getByText("Blocked")).toBeInTheDocument();});- it("should not disable Regenerate button by default", () => {+ it("should not show a Blocked tag by default", () => {render(<KeyInfoHeader data={MOCK_DATA} />);- expect(screen.getByRole("button", { name: /regenerate key/i })).not.toBeDisabled();+ expect(screen.queryByText("Blocked")).not.toBeInTheDocument();});});diff --git a/ui/litellm-dashboard/src/components/templates/KeyInfoHeader.tsx b/ui/litellm-dashboard/src/components/templates/KeyInfoHeader.tsxindex c9c393352cc..d0dd782a697 100644--- a/ui/litellm-dashboard/src/components/templates/KeyInfoHeader.tsx+++ b/ui/litellm-dashboard/src/components/templates/KeyInfoHeader.tsx@@ -1,5 +1,6 @@import React from "react";-import { Button, Typography, Tooltip, Space, Divider, Flex, Popover } from "antd";+import { Button, Typography, Tooltip, Space, Divider, Flex, Popover, Dropdown, Tag } from "antd";+import type { MenuProps } from "antd";import {ArrowLeftOutlined,SyncOutlined,@@ -12,6 +13,9 @@ import {SafetyCertificateOutlined,TransactionOutlined,FieldTimeOutlined,+ MoreOutlined,+ StopOutlined,+ CheckCircleOutlined,} from "@ant-design/icons";import LabeledField from "../common_components/LabeledField";import DefaultProxyAdminTag from "../common_components/DefaultProxyAdminTag";@@ -38,6 +42,8 @@ interface KeyInfoHeaderProps {onRegenerate?: () => void;onDelete?: () => void;onResetSpend?: () => void;+ onToggleBlocked?: () => void;+ isBlocked?: boolean;canModifyKey?: boolean;backButtonText?: string;regenerateDisabled?: boolean;@@ -133,11 +139,33 @@ export function KeyInfoHeader({onRegenerate,onDelete,onResetSpend,+ onToggleBlocked,+ isBlocked = false,canModifyKey = true,backButtonText = "Back to Keys",regenerateDisabled = false,regenerateTooltip,}: KeyInfoHeaderProps) {+ const destructiveActionItems: MenuProps["items"] = [+ ...(onToggleBlocked+ ? [+ isBlocked+ ? { key: "unblock", label: "Unblock Key", icon: <CheckCircleOutlined /> }+ : { key: "block", label: "Block Key", icon: <StopOutlined />, danger: true },+ ]+ : []),+ ...(onResetSpend+ ? [{ key: "reset-spend", label: "Reset Spend", icon: <TransactionOutlined />, danger: true }]+ : []),+ { key: "delete", label: "Delete Key", icon: <DeleteOutlined />, danger: true },+ ];++ const handleDestructiveActionClick: MenuProps["onClick"] = ({ key }) => {+ if (key === "block" || key === "unblock") onToggleBlocked?.();+ if (key === "reset-spend") onResetSpend?.();+ if (key === "delete") onDelete?.();+ };+return (<div>{onCreateNew && (@@ -156,9 +184,16 @@ export function KeyInfoHeader({<Flex justify="space-between" align="start" style={{ marginBottom: 20 }}><div>- <Title level={3} copyable={{ tooltips: ["Copy Key Alias", "Copied!"] }} style={{ margin: 0 }}>- {data.keyName}- </Title>+ <Space align="center">+ <Title level={3} copyable={{ tooltips: ["Copy Key Alias", "Copied!"] }} style={{ margin: 0 }}>+ {data.keyName}+ </Title>+ {isBlocked && (+ <Tag color="red" icon={<StopOutlined />}>+ Blocked+ </Tag>+ )}+ </Space><Text type="secondary" copyable={{ text: data.keyId, tooltips: ["Copy Key ID", "Copied!"] }}>Key ID: {data.keyId}</Text>@@ -172,14 +207,12 @@ export function KeyInfoHeader({</Button></span></Tooltip>- {onResetSpend && (- <Button danger icon={<TransactionOutlined />} onClick={onResetSpend}>- Reset Spend- </Button>- )}- <Button danger icon={<DeleteOutlined />} onClick={onDelete}>- Delete Key- </Button>+ <Dropdown+ menu={{ items: destructiveActionItems, onClick: handleDestructiveActionClick }}+ trigger={["click"]}+ >+ <Button icon={<MoreOutlined />} aria-label="More key actions" />+ </Dropdown></Space>)}</Flex>diff --git a/ui/litellm-dashboard/src/components/templates/key_info_view.tsx b/ui/litellm-dashboard/src/components/templates/key_info_view.tsxindex 23baf024bd1..f3c9423b5d4 100644--- a/ui/litellm-dashboard/src/components/templates/key_info_view.tsx+++ b/ui/litellm-dashboard/src/components/templates/key_info_view.tsx@@ -19,6 +19,7 @@ import LoggingSettingsView from "../logging_settings_view";import NotificationManager from "../molecules/notifications_manager";import { getPolicyInfoWithGuardrails, keyDeleteCall, keyUpdateCall } from "../networking";import { useResetKeySpend } from "@/app/(dashboard)/hooks/keys/useResetKeySpend";+import { useSetKeyBlockedState } from "@/app/(dashboard)/hooks/keys/useSetKeyBlockedState";import { keyKeys } from "@/app/(dashboard)/hooks/keys/useKeys";import { useQueryClient } from "@tanstack/react-query";import ObjectPermissionsView from "../object_permissions_view";@@ -79,7 +80,9 @@ export default function KeyInfoView({const [deleteConfirmInput, setDeleteConfirmInput] = useState("");const [isRegenerateModalOpen, setIsRegenerateModalOpen] = useState(false);const [isResetSpendModalOpen, setIsResetSpendModalOpen] = useState(false);+ const [isBlockModalOpen, setIsBlockModalOpen] = useState(false);const { mutate: resetKeySpend, isPending: resetSpendLoading } = useResetKeySpend();+ const { mutate: setKeyBlockedState, isPending: blockLoading } = useSetKeyBlockedState();// Add local state to maintain key data and track regenerationconst [currentKeyData, setCurrentKeyData] = useState<KeyResponse | undefined>(keyData);const [lastRegeneratedAt, setLastRegeneratedAt] = useState<Date | null>(null);@@ -390,13 +393,18 @@ export default function KeyInfoView({)) ||(userID === currentKeyData.user_id && userRole !== "Internal Viewer");- const canResetSpend =+ const isKeyAdmin =isProxyAdminRole(userRole || "") ||- (teamsData &&- isUserTeamAdminForSingleTeam(- teamsData?.filter((team) => team.team_id === currentKeyData.team_id)[0]?.members_with_roles,- userID || "",- ));+ Boolean(+ teamsData &&+ isUserTeamAdminForSingleTeam(+ teamsData?.filter((team) => team.team_id === currentKeyData.team_id)[0]?.members_with_roles,+ userID || "",+ ),+ );++ const canResetSpend = isKeyAdmin;+ const canBlockKey = isKeyAdmin;const handleResetSpend = () => {resetKeySpend(currentKeyData.token || currentKeyData.token_id, {@@ -415,6 +423,29 @@ export default function KeyInfoView({});};+ const isBlocked = currentKeyData.blocked === true;++ const handleToggleBlocked = () => {+ setKeyBlockedState(+ { keyToken: currentKeyData.token || currentKeyData.token_id, blocked: !isBlocked },+ {+ onSuccess: (response) => {+ const blocked = response.blocked === true;+ setCurrentKeyData((prevData) => (prevData ? { ...prevData, blocked } : undefined));+ if (onKeyDataUpdate) {+ onKeyDataUpdate({ blocked });+ }+ NotificationManager.success(blocked ? "Key blocked" : "Key unblocked");+ setIsBlockModalOpen(false);+ },+ onError: (error) => {+ NotificationManager.fromBackend(parseErrorMessage(error));+ console.error("Error updating key blocked state:", error);+ },+ },+ );+ };+const parentTeam = currentKeyData.team_id ? teamsData?.find((team) => team.team_id === currentKeyData.team_id) : null;const budgetDisplay =@@ -447,6 +478,8 @@ export default function KeyInfoView({onRegenerate={() => setIsRegenerateModalOpen(true)}onDelete={() => setIsDeleteModalOpen(true)}onResetSpend={canResetSpend ? () => setIsResetSpendModalOpen(true) : undefined}+ onToggleBlocked={canBlockKey ? () => setIsBlockModalOpen(true) : undefined}+ isBlocked={isBlocked}canModifyKey={canModifyKey}backButtonText={backButtonText}regenerateDisabled={!premiumUser}@@ -519,6 +552,26 @@ export default function KeyInfoView({</p></Modal>+ <Modal+ title={isBlocked ? "Unblock Key" : "Block Key"}+ open={isBlockModalOpen}+ onOk={handleToggleBlocked}+ onCancel={() => setIsBlockModalOpen(false)}+ okText={isBlocked ? "Unblock" : "Block"}+ okButtonProps={isBlocked ? undefined : { danger: true }}+ confirmLoading={blockLoading}+ >+ <p>+ {isBlocked ? "Unblock" : "Block"}{" "}+ <strong>{currentKeyData?.key_alias || currentKeyData?.token_id || "this key"}</strong>?+ </p>+ <p style={{ color: "#666", fontSize: "0.875rem", marginTop: 8 }}>+ {isBlocked+ ? "Requests using this key will be accepted again."+ : "Requests using this key will be rejected with a 401 error until it is unblocked. The key is not deleted and can be unblocked at any time."}+ </p>+ </Modal>+<TabGroup><TabList className="mb-4"><Tab>Overview</Tab>