mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-17 09:34:48 +00:00
feat(ui): add bulk actions for virtual keys (#52138)
This commit is contained in:
parent
43fc7d5cd3
commit
f33dcfd1dd
16 changed files with 1225 additions and 19 deletions
|
|
@ -3412,6 +3412,7 @@ async def _process_single_key_update(
|
|||
"""
|
||||
# Validate max_budget
|
||||
_validate_max_budget(update_key_request.max_budget)
|
||||
validate_budget_duration(update_key_request.budget_duration)
|
||||
|
||||
check_permissions_caller_permission(
|
||||
data=update_key_request,
|
||||
|
|
@ -4468,6 +4469,8 @@ async def bulk_update_keys(
|
|||
- key: str - The key identifier (token) to update
|
||||
- budget_id: Optional[str] - Budget ID associated with the key
|
||||
- max_budget: Optional[float] - Max budget for key
|
||||
- budget_duration: Optional[str] - Budget reset period, or null to stop resetting
|
||||
- user_id: Optional[str] - Owner user ID, or null to remove the owner
|
||||
- team_id: Optional[str] - Team ID associated with key
|
||||
- tags: Optional[List[str]] - Tags for organizing keys
|
||||
- object_permission: Optional[LiteLLM_ObjectPermissionBase] - key-specific object permission, as on /key/update
|
||||
|
|
|
|||
|
|
@ -35,6 +35,8 @@ class BulkUpdateKeyRequestItem(LiteLLMBaseModel):
|
|||
key: str # Key identifier (token)
|
||||
budget_id: str | None = None # Budget ID associated with the key
|
||||
max_budget: float | None = None # Max budget for key
|
||||
budget_duration: str | None = None
|
||||
user_id: str | None = None
|
||||
team_id: str | None = None # Team ID associated with key
|
||||
tags: list[str] | None = None # Tags for organizing keys
|
||||
object_permission: LiteLLM_ObjectPermissionBase | None = None
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import {
|
||||
keepPreviousData,
|
||||
type QueryClient,
|
||||
useInfiniteQuery,
|
||||
useQuery,
|
||||
UseQueryResult,
|
||||
|
|
@ -145,6 +146,12 @@ export const useInfiniteKeys = (pageSize: number, options: KeyListCallOptions =
|
|||
};
|
||||
|
||||
export const deletedKeyKeys = createQueryKeys("deletedKeys");
|
||||
|
||||
export const invalidateKeyQueries = (queryClient: QueryClient) =>
|
||||
Promise.allSettled(
|
||||
[keyKeys, deletedKeyKeys, infiniteKeyKeys].map((keys) => queryClient.invalidateQueries({ queryKey: keys.all })),
|
||||
);
|
||||
|
||||
export const useDeletedKeys = (
|
||||
page: number,
|
||||
pageSize: number,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,253 @@
|
|||
"use client";
|
||||
|
||||
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import type { TFunction } from "i18next";
|
||||
import { ChevronDown, DollarSign, ListChecks, Trash2, UserRound, UsersRound } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { invalidateKeyQueries } from "@/app/(dashboard)/hooks/keys/useKeys";
|
||||
import DeleteResourceModal from "@/components/common_components/DeleteResourceModal";
|
||||
import type { KeyResponse } from "@/components/key_team_helpers/key_list";
|
||||
import { keyBulkUpdateCall, keyDeleteCall, type BulkKeyUpdateResponse } from "@/components/networking";
|
||||
import { parseErrorMessage } from "@/components/shared/errorUtils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { VirtualKeysBulkEditDialog, type BulkKeyEditAction, type BulkKeyEditValues } from "./VirtualKeysBulkEditDialog";
|
||||
|
||||
const BULK_MUTATION_KEY = ["keys", "bulkAction"] as const;
|
||||
type KeyTarget = Readonly<Pick<KeyResponse, "token" | "key_alias">>;
|
||||
type BulkDialog = {
|
||||
action: BulkKeyEditAction | "delete";
|
||||
targets: readonly KeyTarget[];
|
||||
failures?: BulkKeyUpdateResponse["failed_updates"];
|
||||
};
|
||||
|
||||
interface VirtualKeysBulkActionsProps {
|
||||
table: Table<KeyResponse>;
|
||||
accessToken: string;
|
||||
disabled: boolean;
|
||||
canEdit: boolean;
|
||||
selectionMode: boolean;
|
||||
onSelectionModeChange: (enabled: boolean) => void;
|
||||
}
|
||||
|
||||
function targetsAreEligible(table: Table<KeyResponse>, dialog: BulkDialog | null): boolean {
|
||||
if (!dialog || dialog.targets.length === 0) return false;
|
||||
return dialog.targets.every((target) => {
|
||||
const row = table.getRowModel().rows.find((row) => row.original.token === target.token);
|
||||
if (!row) return dialog.action !== "delete";
|
||||
if (!row.getCanSelect()) return false;
|
||||
return dialog.action !== "team" || !row.original.project_id;
|
||||
});
|
||||
}
|
||||
|
||||
function bulkActionError(error: unknown, selectionChanged: boolean, isDelete: boolean, t: TFunction): string | null {
|
||||
if (error) return parseErrorMessage(error);
|
||||
if (!selectionChanged) return null;
|
||||
return t(
|
||||
isDelete
|
||||
? "apiKeys.virtualKeysTable.bulkDelete.selectionChanged"
|
||||
: "apiKeys.virtualKeysTable.bulkEdit.selectionChanged",
|
||||
);
|
||||
}
|
||||
|
||||
export function VirtualKeysBulkActions({
|
||||
table,
|
||||
accessToken,
|
||||
disabled,
|
||||
canEdit,
|
||||
selectionMode,
|
||||
onSelectionModeChange,
|
||||
}: VirtualKeysBulkActionsProps) {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [dialog, setDialog] = useState<BulkDialog | null>(null);
|
||||
const targets = dialog?.targets ?? [];
|
||||
const isDelete = dialog?.action === "delete";
|
||||
const isPending = useIsMutating({ mutationKey: BULK_MUTATION_KEY }) > 0;
|
||||
const deleteOptions = {
|
||||
mutationKey: [...BULK_MUTATION_KEY, "delete"],
|
||||
mutationFn: (keys: readonly KeyTarget[]) =>
|
||||
keyDeleteCall(
|
||||
accessToken,
|
||||
keys.map((key) => key.token),
|
||||
),
|
||||
retry: false,
|
||||
onSuccess: (_: unknown, keys: readonly KeyTarget[]) =>
|
||||
toast.success(t("apiKeys.virtualKeysTable.bulkDelete.success", { count: keys.length })),
|
||||
onSettled: () => invalidateKeyQueries(queryClient),
|
||||
};
|
||||
const deletion = useMutation(deleteOptions);
|
||||
const updateOptions = {
|
||||
mutationKey: [...BULK_MUTATION_KEY, "update"],
|
||||
mutationFn: ({ keys, values }: { keys: readonly KeyTarget[]; values: BulkKeyEditValues }) =>
|
||||
keyBulkUpdateCall(
|
||||
accessToken,
|
||||
keys.map((key) => ({ key: key.token, ...values })),
|
||||
),
|
||||
retry: false,
|
||||
onSuccess: (result: BulkKeyUpdateResponse) => {
|
||||
if (result.successful_updates.length > 0) {
|
||||
toast.success(t("apiKeys.virtualKeysTable.bulkEdit.success", { count: result.successful_updates.length }));
|
||||
}
|
||||
},
|
||||
onSettled: () => invalidateKeyQueries(queryClient),
|
||||
};
|
||||
const update = useMutation(updateOptions);
|
||||
|
||||
const selectedRows = table.getSelectedRowModel().rows;
|
||||
const canOpen = !disabled && selectedRows.length > 0 && selectedRows.every((row) => row.getCanSelect());
|
||||
const canMoveToTeam = selectedRows.every(({ original }) => !original.project_id);
|
||||
const actionAllowed = isDelete || canEdit;
|
||||
const canConfirm = !disabled && actionAllowed && targetsAreEligible(table, dialog);
|
||||
|
||||
const openDialog = (action: BulkDialog["action"]) => {
|
||||
if (!canOpen || isPending) return;
|
||||
if (action !== "delete" && !canEdit) return;
|
||||
if (action === "team" && !canMoveToTeam) return;
|
||||
deletion.reset();
|
||||
update.reset();
|
||||
setDialog({
|
||||
action,
|
||||
targets: selectedRows.map(({ original }) => ({ token: original.token, key_alias: original.key_alias })),
|
||||
});
|
||||
};
|
||||
|
||||
const closeDialog = () => {
|
||||
if (queryClient.isMutating({ mutationKey: BULK_MUTATION_KEY }) > 0) return;
|
||||
setDialog(null);
|
||||
deletion.reset();
|
||||
update.reset();
|
||||
};
|
||||
|
||||
const confirmDelete = () => {
|
||||
if (!canConfirm || queryClient.isMutating({ mutationKey: BULK_MUTATION_KEY }) > 0) return;
|
||||
deletion.mutate(targets, {
|
||||
onSuccess: () => {
|
||||
table.resetRowSelection();
|
||||
setDialog(null);
|
||||
},
|
||||
});
|
||||
};
|
||||
const confirmUpdate = (values: BulkKeyEditValues) => {
|
||||
if (!dialog || !canConfirm) return;
|
||||
if (!canEdit || queryClient.isMutating({ mutationKey: BULK_MUTATION_KEY }) > 0) return;
|
||||
update.mutate(
|
||||
{ keys: dialog.targets, values },
|
||||
{
|
||||
onSuccess: (result) => {
|
||||
const succeeded = new Set(result.successful_updates.map((key) => key.key));
|
||||
table.setRowSelection((current) =>
|
||||
Object.fromEntries(Object.entries(current).filter(([token]) => !succeeded.has(token))),
|
||||
);
|
||||
const remaining = dialog.targets.filter((target) => !succeeded.has(target.token));
|
||||
setDialog(remaining.length > 0 ? { ...dialog, targets: remaining, failures: result.failed_updates } : null);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const mutationError = isDelete ? deletion.error : update.error;
|
||||
const selectionChanged = Boolean(dialog) && !disabled && !canConfirm;
|
||||
const displayError = bulkActionError(mutationError, selectionChanged, isDelete, t);
|
||||
|
||||
if (!selectionMode) {
|
||||
return (
|
||||
<Button variant="outline" size="sm" onClick={() => onSelectionModeChange(true)} disabled={disabled || isPending}>
|
||||
<ListChecks />
|
||||
{t("apiKeys.virtualKeysTable.bulkActions.select")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<span className="text-sm text-muted-foreground" role="status">
|
||||
{t("apiKeys.virtualKeysTable.bulkDelete.selected", { count: selectedRows.length })}
|
||||
</span>
|
||||
<Button variant="ghost" size="sm" onClick={() => onSelectionModeChange(false)} disabled={isPending}>
|
||||
{t("apiKeys.virtualKeysTable.bulkActions.cancel")}
|
||||
</Button>
|
||||
{selectedRows.length > 0 && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button variant="outline" size="sm" />} disabled={!canOpen || isPending}>
|
||||
{t("apiKeys.virtualKeysTable.bulkActions.menu")}
|
||||
<ChevronDown />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="min-w-44">
|
||||
{canEdit && (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
onClick={() => openDialog("team")}
|
||||
disabled={!canMoveToTeam}
|
||||
title={!canMoveToTeam ? t("apiKeys.virtualKeysTable.bulkEdit.projectTeamLocked") : undefined}
|
||||
>
|
||||
<UsersRound />
|
||||
{t("apiKeys.virtualKeysTable.bulkEdit.team")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => openDialog("user")}>
|
||||
<UserRound />
|
||||
{t("apiKeys.virtualKeysTable.bulkEdit.user")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => openDialog("budget")}>
|
||||
<DollarSign />
|
||||
{t("apiKeys.virtualKeysTable.bulkEdit.budget")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuItem variant="destructive" onClick={() => openDialog("delete")}>
|
||||
<Trash2 />
|
||||
{t("apiKeys.virtualKeysTable.bulkDelete.action", { count: selectedRows.length })}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
<DeleteResourceModal
|
||||
isOpen={isDelete}
|
||||
title={t("apiKeys.virtualKeysTable.bulkDelete.title", { count: targets.length })}
|
||||
alertMessage={t("apiKeys.virtualKeysTable.bulkDelete.warning")}
|
||||
message={t("apiKeys.virtualKeysTable.bulkDelete.message")}
|
||||
resourceInformationTitle={t("apiKeys.virtualKeysTable.bulkDelete.selected", { count: targets.length })}
|
||||
resourceInformation={targets.flatMap((target, index) => [
|
||||
{
|
||||
label: t("apiKeys.virtualKeysTable.bulkDelete.keyAlias", { number: index + 1 }),
|
||||
value: target.key_alias || t("apiKeys.virtualKeysTable.bulkDelete.noAlias"),
|
||||
},
|
||||
{
|
||||
label: t("apiKeys.virtualKeysTable.bulkDelete.keyId", { number: index + 1 }),
|
||||
value: target.token,
|
||||
code: true,
|
||||
},
|
||||
])}
|
||||
onCancel={closeDialog}
|
||||
onOk={confirmDelete}
|
||||
confirmLoading={isPending}
|
||||
confirmDisabled={!canConfirm}
|
||||
requiredConfirmation={t("apiKeys.virtualKeysTable.bulkDelete.requiredConfirmation")}
|
||||
errorMessage={displayError}
|
||||
/>
|
||||
{dialog && dialog.action !== "delete" && (
|
||||
<VirtualKeysBulkEditDialog
|
||||
action={dialog.action}
|
||||
targets={dialog.targets}
|
||||
pending={isPending}
|
||||
disabled={!canConfirm}
|
||||
errorMessage={displayError}
|
||||
failures={dialog.failures}
|
||||
onCancel={closeDialog}
|
||||
onConfirm={confirmUpdate}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,198 @@
|
|||
"use client";
|
||||
|
||||
import { useId, useState, type FormEvent } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import BudgetDurationDropdown from "@/components/common_components/budget_duration_dropdown";
|
||||
import TeamDropdown from "@/components/common_components/team_dropdown";
|
||||
import UserDropdown from "@/components/common_components/UserDropdown";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Field, FieldError, FieldLabel, FieldSet } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
export type BulkKeyEditAction = "team" | "user" | "budget";
|
||||
export type BulkKeyEditValues =
|
||||
| { team_id: string }
|
||||
| { user_id: string }
|
||||
| { max_budget: number; budget_duration: string };
|
||||
|
||||
interface VirtualKeysBulkEditDialogProps {
|
||||
action: BulkKeyEditAction;
|
||||
targets: readonly { token: string; key_alias?: string | null }[];
|
||||
pending: boolean;
|
||||
disabled: boolean;
|
||||
errorMessage?: string | null;
|
||||
failures?: readonly { key: string; failed_reason: string }[];
|
||||
onCancel: () => void;
|
||||
onConfirm: (values: BulkKeyEditValues) => void;
|
||||
}
|
||||
|
||||
const parseBudget = (input: string): number | null => {
|
||||
if (input.trim() === "") return null;
|
||||
const amount = Number(input);
|
||||
return Number.isFinite(amount) && amount >= 0 ? amount : null;
|
||||
};
|
||||
|
||||
export function VirtualKeysBulkEditDialog({
|
||||
action,
|
||||
targets,
|
||||
pending,
|
||||
disabled,
|
||||
errorMessage,
|
||||
failures = [],
|
||||
onCancel,
|
||||
onConfirm,
|
||||
}: VirtualKeysBulkEditDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const fieldId = useId();
|
||||
const [teamId, setTeamId] = useState<string | null>(null);
|
||||
const [userId, setUserId] = useState<string | null>(null);
|
||||
const [budgetInput, setBudgetInput] = useState("");
|
||||
const [duration, setDuration] = useState<string | null>("30d");
|
||||
const locked = pending || disabled;
|
||||
const budget = parseBudget(budgetInput);
|
||||
const invalidBudget = budgetInput !== "" && budget === null;
|
||||
const valuesByAction: Record<BulkKeyEditAction, BulkKeyEditValues | null> = {
|
||||
team: teamId ? { team_id: teamId } : null,
|
||||
user: userId ? { user_id: userId } : null,
|
||||
budget: budget !== null && duration ? { max_budget: budget, budget_duration: duration } : null,
|
||||
};
|
||||
const values = valuesByAction[action];
|
||||
const canApply = !locked && values !== null && targets.length > 0;
|
||||
|
||||
const cancel = () => {
|
||||
if (!pending) onCancel();
|
||||
};
|
||||
|
||||
const submit = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!canApply || !values) return;
|
||||
onConfirm(values);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && cancel()}>
|
||||
<DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto" showCloseButton={!pending}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t(`apiKeys.virtualKeysTable.bulkEdit.${action}`)}</DialogTitle>
|
||||
<DialogDescription>{t(`apiKeys.virtualKeysTable.bulkEdit.descriptions.${action}`)}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-2 rounded-lg border border-border bg-muted/30 p-3">
|
||||
<p className="font-medium">{t("apiKeys.virtualKeysTable.bulkEdit.selected", { count: targets.length })}</p>
|
||||
<ul className="max-h-28 space-y-1 overflow-y-auto text-sm text-muted-foreground">
|
||||
{targets.map((target) => (
|
||||
<li key={target.token} className="break-all">
|
||||
{target.key_alias || target.token}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
<form onSubmit={submit} className="space-y-6" aria-busy={pending}>
|
||||
<FieldSet disabled={locked} inert={locked}>
|
||||
{action === "team" && (
|
||||
<Field>
|
||||
<FieldLabel htmlFor={`${fieldId}-team`}>
|
||||
{t("apiKeys.virtualKeysTable.bulkEdit.fields.team")}
|
||||
</FieldLabel>
|
||||
<TeamDropdown
|
||||
id={`${fieldId}-team`}
|
||||
value={teamId}
|
||||
onChange={(value) => !locked && setTeamId(value)}
|
||||
disabled={locked}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{action === "user" && (
|
||||
<Field>
|
||||
<FieldLabel htmlFor={`${fieldId}-user`}>
|
||||
{t("apiKeys.virtualKeysTable.bulkEdit.fields.user")}
|
||||
</FieldLabel>
|
||||
<UserDropdown
|
||||
id={`${fieldId}-user`}
|
||||
value={userId}
|
||||
onChange={(value) => !locked && setUserId(value)}
|
||||
disabled={locked}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{action === "budget" && (
|
||||
<>
|
||||
<Field data-invalid={invalidBudget}>
|
||||
<FieldLabel htmlFor={`${fieldId}-budget`}>
|
||||
{t("apiKeys.virtualKeysTable.bulkEdit.fields.budget")}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id={`${fieldId}-budget`}
|
||||
type="number"
|
||||
min={0}
|
||||
step="any"
|
||||
required
|
||||
value={budgetInput}
|
||||
onChange={(event) => !locked && setBudgetInput(event.target.value)}
|
||||
disabled={locked}
|
||||
aria-invalid={invalidBudget}
|
||||
aria-describedby={invalidBudget ? `${fieldId}-budget-error` : undefined}
|
||||
/>
|
||||
{invalidBudget && (
|
||||
<FieldError id={`${fieldId}-budget-error`}>
|
||||
{t("apiKeys.virtualKeysTable.bulkEdit.invalidBudget")}
|
||||
</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
<Field data-invalid={duration === null}>
|
||||
<FieldLabel htmlFor={`${fieldId}-duration`}>
|
||||
{t("apiKeys.virtualKeysTable.bulkEdit.fields.resetPeriod")}
|
||||
</FieldLabel>
|
||||
<BudgetDurationDropdown
|
||||
key={locked ? "locked" : "editable"}
|
||||
id={`${fieldId}-duration`}
|
||||
value={duration}
|
||||
onChange={(value) => !locked && setDuration(value)}
|
||||
placeholder={t("apiKeys.virtualKeysTable.bulkEdit.resetPeriodPlaceholder")}
|
||||
/>
|
||||
{duration === null && (
|
||||
<FieldError>{t("apiKeys.virtualKeysTable.bulkEdit.resetPeriodRequired")}</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
</FieldSet>
|
||||
{errorMessage && <FieldError>{errorMessage}</FieldError>}
|
||||
{failures.length > 0 && (
|
||||
<div role="alert" className="space-y-2 text-sm text-destructive">
|
||||
<p>{t("apiKeys.virtualKeysTable.bulkEdit.partialFailure", { count: failures.length })}</p>
|
||||
<ul className="max-h-40 space-y-3 overflow-y-auto">
|
||||
{failures.map((failure) => (
|
||||
<li key={failure.key} className="space-y-1 break-words">
|
||||
<p className="font-medium">
|
||||
{targets.find((target) => target.token === failure.key)?.key_alias || failure.key}
|
||||
</p>
|
||||
<p className="whitespace-pre-wrap">{failure.failed_reason}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={cancel} disabled={pending}>
|
||||
{t("apiKeys.virtualKeysTable.bulkEdit.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={!canApply}>
|
||||
{pending
|
||||
? t("apiKeys.virtualKeysTable.bulkEdit.pending")
|
||||
: t("apiKeys.virtualKeysTable.bulkEdit.apply", { count: targets.length })}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,323 @@
|
|||
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { KeyResponse } from "../key_team_helpers/key_list";
|
||||
import { chooseSelectOption, renderWithProviders, testQueryClient } from "../../../tests/test-utils";
|
||||
import { VirtualKeysTable } from "./VirtualKeysTable";
|
||||
|
||||
vi.unmock("@/app/(dashboard)/hooks/useAuthorized");
|
||||
vi.mock("next/navigation", () => ({
|
||||
usePathname: () => "/ui/api-keys/",
|
||||
useRouter: () => ({ push: vi.fn() }),
|
||||
}));
|
||||
|
||||
const keys = ["First key", "Second key", "Keep key"].map((key_alias, index) => ({
|
||||
token: `hashed-token-${index}`,
|
||||
key_alias,
|
||||
user_id: "user-1",
|
||||
models: [],
|
||||
spend: 0,
|
||||
max_budget: 100,
|
||||
})) satisfies Partial<KeyResponse>[];
|
||||
|
||||
const keyPage = (rows: readonly Partial<KeyResponse>[] = keys, total = rows.length, page = 1, size = 50) => {
|
||||
const response = { keys: rows, total_count: total, current_page: page, total_pages: Math.ceil(total / size) };
|
||||
return Response.json(response);
|
||||
};
|
||||
|
||||
const updatedKeysResponse = (rows = keys.slice(0, 2)) =>
|
||||
Response.json({
|
||||
total_requested: rows.length,
|
||||
successful_updates: rows.map(({ token }) => ({ key: token, key_info: {} })),
|
||||
failed_updates: [],
|
||||
});
|
||||
|
||||
const installApi = (rows: readonly Partial<KeyResponse>[] = keys, role = "proxy_admin") => {
|
||||
const list = vi.fn<() => Response | Promise<Response>>(() => keyPage(rows));
|
||||
const remove = vi.fn<() => Promise<Response>>(async () => Response.json({ deleted_keys: [] }));
|
||||
const update = vi.fn<(request: Request) => Promise<Response>>(async () => updatedKeysResponse());
|
||||
const responses: Record<string, unknown> = {
|
||||
"/ui/litellm-runtime-config.json": {},
|
||||
"/litellm/.well-known/litellm-ui-config": {
|
||||
server_root_path: "/",
|
||||
proxy_base_url: null,
|
||||
gateway_base_url: null,
|
||||
admin_ui_disabled: false,
|
||||
},
|
||||
"/management/v1/users/me": { user_id: "user-1", user_email: "user@example.com", user_role: role },
|
||||
"/get/ui_settings": { values: {} },
|
||||
"/organization/list": [],
|
||||
"/v2/team/list": { teams: [], total: 0, page: 1, page_size: 100, total_pages: 1 },
|
||||
};
|
||||
const fetch: typeof globalThis.fetch = async (input, init) => {
|
||||
const request =
|
||||
input instanceof Request ? input : new Request(new URL(String(input), window.location.origin), init);
|
||||
const path = new URL(request.url).pathname;
|
||||
if (path === "/key/list") return list();
|
||||
if (path === "/key/delete") return remove();
|
||||
if (path === "/key/bulk_update") return update(request);
|
||||
if (path in responses) return Response.json(responses[path]);
|
||||
throw new Error(`Unexpected request: ${request.method} ${path}`);
|
||||
};
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
return { list, remove, update, responses };
|
||||
};
|
||||
|
||||
const rowCheckbox = (alias: string) =>
|
||||
within(screen.getByRole("row", { name: new RegExp(alias) })).getByRole("checkbox");
|
||||
|
||||
const selectFirstTwo = async () => {
|
||||
await screen.findByRole("row", { name: /First key/ }, { timeout: 5000 });
|
||||
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Select keys", exact: true }));
|
||||
expect(screen.queryByRole("button", { name: "Actions", exact: true })).not.toBeInTheDocument();
|
||||
await waitFor(() => expect(rowCheckbox("First key")).not.toHaveAttribute("aria-disabled", "true"));
|
||||
fireEvent.click(rowCheckbox("First key"));
|
||||
fireEvent.click(rowCheckbox("Second key"));
|
||||
};
|
||||
|
||||
const openAction = async (user: ReturnType<typeof userEvent.setup>, action: "delete" | "budget") => {
|
||||
const option = action === "delete" ? "Delete selected (2)" : "Set budget";
|
||||
await chooseSelectOption(user, screen.getByRole("button", { name: "Actions", exact: true }), option, "menuitem");
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
if (action === "budget") {
|
||||
fireEvent.change(within(dialog).getByRole("spinbutton", { name: "Budget per key (USD)" }), {
|
||||
target: { value: "25" },
|
||||
});
|
||||
}
|
||||
return dialog;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
testQueryClient.clear();
|
||||
localStorage.clear();
|
||||
const token = `${btoa("{}")}.${btoa(JSON.stringify({ key: "test-token", premium_user: true }))}.test`;
|
||||
document.cookie = `token=${token}; path=/`;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
testQueryClient.clear();
|
||||
document.cookie = "token=; Max-Age=0; path=/";
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("Virtual Keys bulk actions", () => {
|
||||
it("keeps selection unavailable when the initial key request fails", async () => {
|
||||
const api = installApi();
|
||||
api.list.mockRejectedValue(new TypeError("Key list unavailable"));
|
||||
renderWithProviders(<VirtualKeysTable />);
|
||||
expect(await screen.findByRole("alert", {}, { timeout: 5000 })).toHaveTextContent("Failed to load");
|
||||
expect(await screen.findByRole("button", { name: "Select keys", exact: true })).toBeDisabled();
|
||||
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("requires exact delete confirmation and clears it on cancel and reopen without losing selection", async () => {
|
||||
const api = installApi();
|
||||
const user = userEvent.setup();
|
||||
renderWithProviders(<VirtualKeysTable />);
|
||||
await selectFirstTwo();
|
||||
const dialog = await openAction(user, "delete");
|
||||
const submit = within(dialog).getByRole("button", { name: "Delete", exact: true });
|
||||
expect(submit).toBeDisabled();
|
||||
for (const value of ["delete", "Confirm delete", "confirm delete "]) {
|
||||
fireEvent.change(within(dialog).getByRole("textbox"), { target: { value } });
|
||||
expect(submit).toBeDisabled();
|
||||
}
|
||||
fireEvent.change(within(dialog).getByRole("textbox"), { target: { value: "confirm delete" } });
|
||||
expect(submit).toBeEnabled();
|
||||
await user.click(within(dialog).getByRole("button", { name: "Cancel", exact: true }));
|
||||
expect(rowCheckbox("First key")).toBeChecked();
|
||||
expect(rowCheckbox("Second key")).toBeChecked();
|
||||
const reopened = await openAction(user, "delete");
|
||||
expect(within(reopened).getByRole("textbox")).toHaveValue("");
|
||||
expect(within(reopened).getByRole("button", { name: "Delete", exact: true })).toBeDisabled();
|
||||
await user.click(within(reopened).getByRole("button", { name: "Cancel", exact: true }));
|
||||
await user.click(screen.getByRole("button", { name: "Cancel selection" }));
|
||||
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
|
||||
await user.click(await screen.findByRole("button", { name: "Select keys", exact: true }));
|
||||
expect(screen.queryAllByRole("checkbox", { checked: true })).toHaveLength(0);
|
||||
expect(screen.queryByRole("button", { name: "Actions", exact: true })).not.toBeInTheDocument();
|
||||
expect(api.remove).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("blocks a confirmed deletion if selected rows disappear on refetch", async () => {
|
||||
const api = installApi();
|
||||
const user = userEvent.setup();
|
||||
renderWithProviders(<VirtualKeysTable />);
|
||||
await selectFirstTwo();
|
||||
const dialog = await openAction(user, "delete");
|
||||
fireEvent.change(within(dialog).getByRole("textbox"), { target: { value: "confirm delete" } });
|
||||
const submit = within(dialog).getByRole("button", { name: "Delete", exact: true });
|
||||
expect(submit).toBeEnabled();
|
||||
api.list.mockReturnValue(keyPage([keys[2]]));
|
||||
await act(async () => testQueryClient.invalidateQueries({ queryKey: ["keys"] }));
|
||||
await waitFor(() => expect(submit).toBeDisabled());
|
||||
expect(api.remove).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["delete", "budget"] as const)(
|
||||
"preserves selection after mutation and list errors and locks pending %s retries",
|
||||
async (action) => {
|
||||
const api = installApi();
|
||||
const pending = Promise.withResolvers<Response>();
|
||||
const mutation = action === "delete" ? api.remove : api.update;
|
||||
mutation.mockRejectedValueOnce(new TypeError("Network connection lost")).mockReturnValueOnce(pending.promise);
|
||||
const user = userEvent.setup();
|
||||
renderWithProviders(<VirtualKeysTable />);
|
||||
await selectFirstTwo();
|
||||
const firstCheckbox = rowCheckbox("First key");
|
||||
const secondCheckbox = rowCheckbox("Second key");
|
||||
const cancelSelection = screen.getByRole("button", { name: "Cancel selection" });
|
||||
const dialog = await openAction(user, action);
|
||||
if (action === "delete") {
|
||||
fireEvent.change(within(dialog).getByRole("textbox"), { target: { value: "confirm delete" } });
|
||||
}
|
||||
const submit = within(dialog).getByRole("button", {
|
||||
name: action === "delete" ? "Delete" : "Apply to 2 keys",
|
||||
exact: true,
|
||||
});
|
||||
api.list.mockRejectedValueOnce(new TypeError("Key list unavailable"));
|
||||
await user.click(submit);
|
||||
expect(await within(dialog).findByText("Network connection lost")).toBeVisible();
|
||||
expect(api.list).toHaveBeenCalledTimes(2);
|
||||
expect(firstCheckbox).toBeInTheDocument();
|
||||
expect(firstCheckbox).toBeChecked();
|
||||
expect(secondCheckbox).toBeInTheDocument();
|
||||
expect(secondCheckbox).toBeChecked();
|
||||
expect(submit).toBeEnabled();
|
||||
expect(mutation).toHaveBeenCalledOnce();
|
||||
|
||||
await user.dblClick(submit);
|
||||
expect(submit).toBeDisabled();
|
||||
expect(cancelSelection).toBeDisabled();
|
||||
const cancel = within(dialog).getByRole("button", { name: "Cancel", exact: true });
|
||||
expect(cancel).toBeDisabled();
|
||||
await user.click(cancel);
|
||||
await user.keyboard("{Escape}");
|
||||
expect(dialog).toBeInTheDocument();
|
||||
expect(mutation).toHaveBeenCalledTimes(2);
|
||||
await act(async () =>
|
||||
pending.resolve(action === "delete" ? Response.json({ deleted_keys: [] }) : updatedKeysResponse()),
|
||||
);
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(screen.getByText("0 keys selected")).toBeVisible();
|
||||
expect(rowCheckbox("First key")).not.toBeChecked();
|
||||
expect(screen.queryByRole("button", { name: "Actions", exact: true })).not.toBeInTheDocument();
|
||||
expect(mutation).toHaveBeenCalledTimes(2);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["off-page", "failed"])("retries only the failed key snapshot after %s refetch", async (refetch) => {
|
||||
const api = installApi();
|
||||
api.list.mockReturnValue(keyPage(keys.slice(0, 2), 3, 1, 2));
|
||||
const response = {
|
||||
total_requested: 2,
|
||||
successful_updates: [{ key: keys[0].token, key_info: {} }],
|
||||
failed_updates: [{ key: keys[1].token, key_info: null, failed_reason: "Budget exceeds team limit" }],
|
||||
};
|
||||
api.update.mockResolvedValueOnce(Response.json(response)).mockResolvedValueOnce(updatedKeysResponse([keys[1]]));
|
||||
const user = userEvent.setup();
|
||||
renderWithProviders(<VirtualKeysTable />, { searchParams: "?page_size=2&sort_by=max_budget&sort_order=asc" });
|
||||
await selectFirstTwo();
|
||||
const firstCheckbox = rowCheckbox("First key");
|
||||
const secondCheckbox = rowCheckbox("Second key");
|
||||
const dialog = await openAction(user, "budget");
|
||||
if (refetch === "failed") {
|
||||
api.list.mockRejectedValue(new TypeError("Key list unavailable"));
|
||||
} else {
|
||||
api.list.mockImplementation(() => keyPage([{ ...keys[0], max_budget: 25 }, keys[2]], 3, 1, 2));
|
||||
}
|
||||
await user.click(within(dialog).getByRole("button", { name: "Apply to 2 keys" }));
|
||||
|
||||
await waitFor(() => expect(firstCheckbox).not.toBeChecked());
|
||||
if (refetch === "failed") expect(secondCheckbox).toBeChecked();
|
||||
else expect(secondCheckbox).not.toBeInTheDocument();
|
||||
expect(firstCheckbox).toBeInTheDocument();
|
||||
expect(within(dialog).getByText("Budget exceeds team limit")).toBeInTheDocument();
|
||||
expect(dialog).toHaveTextContent("Second key");
|
||||
expect(within(dialog).queryByText("First key")).not.toBeInTheDocument();
|
||||
const retry = within(dialog).getByRole("button", { name: /Apply to 1 key/ });
|
||||
expect(retry).toBeEnabled();
|
||||
await user.click(retry);
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(api.update).toHaveBeenCalledTimes(2);
|
||||
const body: { keys: { key: string }[] } = await api.update.mock.calls[1][0].clone().json();
|
||||
expect(body.keys.map(({ key }) => key)).toEqual([keys[1].token]);
|
||||
});
|
||||
|
||||
it.each(["internal_user", "proxy_admin_viewer", "internal_user_viewer"])(
|
||||
"restricts bulk actions for %s",
|
||||
async (role) => {
|
||||
installApi(keys, role);
|
||||
const user = userEvent.setup();
|
||||
renderWithProviders(<VirtualKeysTable />);
|
||||
await screen.findByRole("row", { name: /First key/ });
|
||||
if (role === "internal_user") {
|
||||
await selectFirstTwo();
|
||||
await user.click(screen.getByRole("button", { name: "Actions", exact: true }));
|
||||
expect(await screen.findByRole("menuitem", { name: "Delete selected (2)" })).not.toHaveAttribute(
|
||||
"aria-disabled",
|
||||
"true",
|
||||
);
|
||||
} else {
|
||||
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Select keys", exact: true })).not.toBeInTheDocument();
|
||||
}
|
||||
expect(
|
||||
screen.queryByRole("menuitem", { name: /Move to team|Assign to user|Set budget/ }),
|
||||
).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it("excludes deleted rows from select-all and prevents moving selected project keys to a team", async () => {
|
||||
installApi([{ ...keys[0], project_id: "project-1" }, keys[1], { ...keys[2], deleted_at: "2026-01-02T00:00:00Z" }]);
|
||||
const user = userEvent.setup();
|
||||
renderWithProviders(<VirtualKeysTable />);
|
||||
await screen.findByRole("row", { name: /First key/ });
|
||||
await user.click(await screen.findByRole("button", { name: "Select keys", exact: true }));
|
||||
await waitFor(() => expect(rowCheckbox("First key")).not.toHaveAttribute("aria-disabled", "true"));
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Select all rows" }));
|
||||
expect(rowCheckbox("First key")).toBeChecked();
|
||||
expect(rowCheckbox("Keep key")).toHaveAttribute("aria-disabled", "true");
|
||||
expect(rowCheckbox("Keep key")).not.toBeChecked();
|
||||
await user.click(screen.getByRole("button", { name: "Actions", exact: true }));
|
||||
expect(await screen.findByRole("menuitem", { name: "Move to team" })).toHaveAttribute("aria-disabled", "true");
|
||||
expect(screen.getByRole("menuitem", { name: "Assign to user" })).not.toHaveAttribute("aria-disabled", "true");
|
||||
expect(screen.getByRole("menuitem", { name: "Set budget" })).not.toHaveAttribute("aria-disabled", "true");
|
||||
});
|
||||
|
||||
it.each(["search", "page", "status", "auth"] as const)("exits selection when the %s scope changes", async (scope) => {
|
||||
const api = installApi();
|
||||
api.list.mockReturnValue(keyPage(keys, 51));
|
||||
const user = userEvent.setup();
|
||||
renderWithProviders(<VirtualKeysTable />);
|
||||
await selectFirstTwo();
|
||||
const pending = Promise.withResolvers<Response>();
|
||||
api.list.mockReturnValueOnce(pending.promise);
|
||||
if (scope === "search") {
|
||||
fireEvent.change(screen.getByTestId("datatable-search"), { target: { value: "Keep" } });
|
||||
expect(screen.getByRole("button", { name: "Select keys", exact: true })).toBeDisabled();
|
||||
} else if (scope === "page") {
|
||||
await user.click(screen.getByRole("button", { name: "Go to next page" }));
|
||||
} else if (scope === "auth") {
|
||||
api.responses["/management/v1/users/me"] = { user_id: "user-2", user_role: "proxy_admin" };
|
||||
await act(async () => testQueryClient.invalidateQueries({ queryKey: ["currentUser"] }));
|
||||
} else {
|
||||
await user.click(screen.getByRole("button", { name: "Filters" }));
|
||||
await chooseSelectOption(user, screen.getByRole("combobox", { name: "Status" }), "Deleted");
|
||||
await user.click(screen.getByTestId("filter-drawer-apply"));
|
||||
}
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Cancel selection" })).not.toBeInTheDocument());
|
||||
expect(screen.queryByRole("button", { name: "Actions", exact: true })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
|
||||
expect(api.update).not.toHaveBeenCalled();
|
||||
expect(api.remove).not.toHaveBeenCalled();
|
||||
if (scope === "auth") return;
|
||||
await waitFor(() => expect(api.list).toHaveBeenCalledTimes(2));
|
||||
const nextRow = scope === "status" ? { ...keys[2], deleted_at: "2026-01-02T00:00:00Z" } : keys[2];
|
||||
await act(async () => pending.resolve(keyPage([nextRow], scope === "page" ? 51 : 1, scope === "page" ? 2 : 1)));
|
||||
await screen.findByRole("row", { name: /Keep key/ });
|
||||
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
@ -2,12 +2,14 @@
|
|||
|
||||
import { useKeyInfo } from "@/app/(dashboard)/hooks/keys/useKeyInfo";
|
||||
import { useKeys } from "@/app/(dashboard)/hooks/keys/useKeys";
|
||||
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
|
||||
import { useOrganizations } from "@/app/(dashboard)/hooks/organizations/useOrganizations";
|
||||
import { useTeamMemberBudgets } from "@/app/(dashboard)/hooks/teams/useTeamMemberBudgets";
|
||||
import { useApplyUserBudgetToTeamKeys } from "@/app/(dashboard)/hooks/uiSettings/useApplyUserBudgetToTeamKeys";
|
||||
import { useAllTeams } from "@/app/(dashboard)/hooks/teams/useTeams";
|
||||
import { DEBOUNCE_WAIT_MS } from "@/utils/debounceConstants";
|
||||
import {
|
||||
createSelectionColumn,
|
||||
DataTable,
|
||||
DataTableFilterDrawer,
|
||||
DataTableFilterField,
|
||||
|
|
@ -23,17 +25,26 @@ import { PageHeader, PageHeaderControls, PageHeaderDescription, PageHeaderTitle
|
|||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { useDebouncedValue } from "@tanstack/react-pacer/debouncer";
|
||||
import { ColumnFiltersState, functionalUpdate, OnChangeFn } from "@tanstack/react-table";
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
functionalUpdate,
|
||||
OnChangeFn,
|
||||
type Row,
|
||||
type RowSelectionState,
|
||||
} from "@tanstack/react-table";
|
||||
import { KeyRound } from "lucide-react";
|
||||
import { parseAsString, useQueryState } from "nuqs";
|
||||
import { useResetDetailState } from "@/hooks/useUrlTab";
|
||||
import React, { useCallback, useMemo, useState } from "react";
|
||||
import type { ParseKeys } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { canModifyKey } from "@/utils/keyPermissions";
|
||||
import { isProxyAdminRole } from "@/utils/roles";
|
||||
|
||||
import { KeyResponse, Team } from "../key_team_helpers/key_list";
|
||||
import KeyInfoView from "../templates/key_info_view";
|
||||
import { getKeyTableColumns, KEY_TABLE_HIDDEN_COLUMNS, KEY_TABLE_SORT_FIELDS } from "./keyTableColumns";
|
||||
import { VirtualKeysBulkActions } from "./VirtualKeysBulkActions";
|
||||
|
||||
interface VirtualKeysTableProps {
|
||||
headerActions?: React.ReactNode;
|
||||
|
|
@ -92,8 +103,30 @@ const appliedFilter = (filters: ColumnFiltersState, column: FilterColumn): strin
|
|||
return typeof value === "string" ? value : undefined;
|
||||
};
|
||||
|
||||
function useScopedRowSelection(scope: string) {
|
||||
const [selection, setSelection] = useState<{ scope: string; enabled: boolean; rows: RowSelectionState }>({
|
||||
scope,
|
||||
enabled: false,
|
||||
rows: {},
|
||||
});
|
||||
if (selection.scope !== scope) {
|
||||
setSelection({ scope, enabled: false, rows: {} });
|
||||
}
|
||||
const selectionMode = selection.scope === scope && selection.enabled;
|
||||
const rowSelection = selection.scope === scope ? selection.rows : {};
|
||||
const setSelectionMode = (enabled: boolean) => setSelection({ scope, enabled, rows: {} });
|
||||
const onRowSelectionChange: OnChangeFn<RowSelectionState> = (updater) =>
|
||||
setSelection((current) => ({
|
||||
scope,
|
||||
enabled: current.scope === scope && current.enabled,
|
||||
rows: functionalUpdate(updater, current.scope === scope ? current.rows : {}),
|
||||
}));
|
||||
return { rowSelection, onRowSelectionChange, selectionMode, setSelectionMode };
|
||||
}
|
||||
|
||||
export function VirtualKeysTable({ headerActions }: VirtualKeysTableProps) {
|
||||
const { t } = useTranslation();
|
||||
const { accessToken, token, userId, userRole, isViewOnly, isAuthorized, isLoading: isAuthLoading } = useAuthorized();
|
||||
const { data: fetchedOrganizations } = useOrganizations();
|
||||
const organizations = useMemo(() => fetchedOrganizations ?? [], [fetchedOrganizations]);
|
||||
const { data: fetchedTeams } = useAllTeams();
|
||||
|
|
@ -171,7 +204,41 @@ export function VirtualKeysTable({ headerActions }: VirtualKeysTableProps) {
|
|||
}),
|
||||
[allTeams, organizations, teamMemberBudgets, setSelectedKeyId, applyUserBudgetToTeamKeys, resetDetailState],
|
||||
);
|
||||
const columns = useMemo(() => getKeyTableColumns(columnDeps, t), [columnDeps, t]);
|
||||
const isReadOnly = isViewOnly || !isAuthorized || isAuthLoading;
|
||||
const bulkSelectionAllowed = Boolean(accessToken && userId) && !isReadOnly && keyListOptions.status !== "deleted";
|
||||
const hasCurrentRows = !isPending && !isPlaceholderData && keys !== undefined;
|
||||
const selectionReady = bulkSelectionAllowed && hasCurrentRows && searchInput === searchQuery;
|
||||
const selectionScope = JSON.stringify([
|
||||
token,
|
||||
accessToken,
|
||||
userId,
|
||||
userRole,
|
||||
isViewOnly,
|
||||
isAuthorized,
|
||||
isAuthLoading,
|
||||
pagination,
|
||||
sorting,
|
||||
searchInput,
|
||||
searchQuery,
|
||||
columnFilters,
|
||||
selectedKeyId,
|
||||
]);
|
||||
const { rowSelection, onRowSelectionChange, selectionMode, setSelectionMode } = useScopedRowSelection(selectionScope);
|
||||
const isRowSelectable = (row: Row<KeyResponse>) => {
|
||||
if (!selectionMode || !selectionReady || !row.original.token || row.original.deleted_at) return false;
|
||||
return canModifyKey(row.original, allTeams, userId, userRole);
|
||||
};
|
||||
const columns = useMemo(() => {
|
||||
const keyColumns = getKeyTableColumns(columnDeps, t);
|
||||
if (!bulkSelectionAllowed || !selectionMode) return keyColumns;
|
||||
return [
|
||||
createSelectionColumn<KeyResponse>({
|
||||
rowAriaLabel: ({ original }) =>
|
||||
t("apiKeys.virtualKeysTable.bulkDelete.selectKey", { key: original.key_alias || original.token }),
|
||||
}),
|
||||
...keyColumns,
|
||||
];
|
||||
}, [columnDeps, t, bulkSelectionAllowed, selectionMode]);
|
||||
|
||||
const selectedKeyFromList = useMemo(
|
||||
() => keyList.find((key) => key.token === selectedKeyId),
|
||||
|
|
@ -267,6 +334,9 @@ export function VirtualKeysTable({ headerActions }: VirtualKeysTableProps) {
|
|||
data={keyList}
|
||||
columns={columns}
|
||||
getRowId={(row) => row.token}
|
||||
enableRowSelection={isRowSelectable}
|
||||
rowSelection={rowSelection}
|
||||
onRowSelectionChange={onRowSelectionChange}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={onColumnVisibilityChange}
|
||||
sortingMode="server"
|
||||
|
|
@ -299,7 +369,19 @@ export function VirtualKeysTable({ headerActions }: VirtualKeysTableProps) {
|
|||
onOpenFilters={() => setFiltersOpen(true)}
|
||||
filterLabels={filterLabels}
|
||||
formatFilterValue={formatFilterValue}
|
||||
/>
|
||||
>
|
||||
{bulkSelectionAllowed && accessToken && (
|
||||
<VirtualKeysBulkActions
|
||||
key={selectionScope}
|
||||
table={table}
|
||||
accessToken={accessToken}
|
||||
disabled={!selectionReady}
|
||||
canEdit={isProxyAdminRole(userRole ?? "")}
|
||||
selectionMode={selectionMode}
|
||||
onSelectionModeChange={setSelectionMode}
|
||||
/>
|
||||
)}
|
||||
</DataTableToolbar>
|
||||
<DataTableFilterDrawer
|
||||
table={table}
|
||||
open={filtersOpen}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ interface DeleteResourceModalProps {
|
|||
onCancel: () => void;
|
||||
onOk: () => void;
|
||||
confirmLoading: boolean;
|
||||
confirmDisabled?: boolean;
|
||||
requiredConfirmation?: string;
|
||||
errorMessage?: string | null;
|
||||
}
|
||||
|
|
@ -35,11 +36,13 @@ export default function DeleteResourceModal({
|
|||
onCancel,
|
||||
onOk,
|
||||
confirmLoading,
|
||||
confirmDisabled = false,
|
||||
requiredConfirmation,
|
||||
errorMessage,
|
||||
}: DeleteResourceModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [requiredConfirmationInput, setRequiredConfirmationInput] = useState("");
|
||||
const confirmationMissing = Boolean(requiredConfirmation && requiredConfirmationInput !== requiredConfirmation);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
|
|
@ -115,7 +118,7 @@ export default function DeleteResourceModal({
|
|||
<Button
|
||||
variant="destructive"
|
||||
onClick={onOk}
|
||||
disabled={(!!requiredConfirmation && requiredConfirmationInput !== requiredConfirmation) || confirmLoading}
|
||||
disabled={confirmationMissing || confirmLoading || confirmDisabled}
|
||||
>
|
||||
{confirmLoading
|
||||
? t("commonComponents.deleteResourceModal.deleting")
|
||||
|
|
|
|||
|
|
@ -1079,15 +1079,25 @@ export const userCreateCall = async (
|
|||
}
|
||||
};
|
||||
|
||||
export const keyDeleteCall = async (accessToken: string, user_key: string) => {
|
||||
export const keyDeleteCall = async (accessToken: string, user_key: string | string[]) => {
|
||||
try {
|
||||
return await apiClient.post(`/key/delete`, { accessToken, body: { keys: [user_key] } });
|
||||
return await apiClient.post(`/key/delete`, {
|
||||
accessToken,
|
||||
body: { keys: typeof user_key === "string" ? [user_key] : user_key },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to create key:", error);
|
||||
console.error("Failed to delete key:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export type BulkKeyUpdateResponse = components["schemas"]["BulkUpdateKeyResponse"];
|
||||
|
||||
export const keyBulkUpdateCall = (
|
||||
accessToken: string,
|
||||
keys: components["schemas"]["BulkUpdateKeyRequestItem"][],
|
||||
): Promise<BulkKeyUpdateResponse> => apiClient.post("/key/bulk_update", { accessToken, body: { keys } });
|
||||
|
||||
export const userDeleteCall = async (accessToken: string, userIds: string[]) => {
|
||||
try {
|
||||
return await apiClient.post(`/user/delete`, { accessToken, body: { user_ids: userIds } });
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import { useOrganizations } from "@/app/(dashboard)/hooks/organizations/useOrgan
|
|||
import { formatBudgetResetTime } from "@/utils/budgetUtils";
|
||||
import { formatNumberWithCommas } from "@/utils/dataUtils";
|
||||
import { mapEmptyStringToNull } from "@/utils/keyUpdateUtils";
|
||||
import { canModifyKey as canModifyVirtualKey } from "@/utils/keyPermissions";
|
||||
import { ArrowLeft, Info } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
|
@ -519,14 +520,7 @@ export default function KeyInfoView({
|
|||
return t("keyDetail.keyInfoView.timestamp", { date: dateStr, time: timeStr });
|
||||
};
|
||||
|
||||
const canModifyKey =
|
||||
isProxyAdminRole(userRole || "") ||
|
||||
(teamsData &&
|
||||
isUserTeamAdminForSingleTeam(
|
||||
teamsData?.filter((team) => team.team_id === currentKeyData.team_id)[0]?.members_with_roles,
|
||||
userID || "",
|
||||
)) ||
|
||||
(userID === currentKeyData.user_id && userRole !== "Internal Viewer");
|
||||
const canModifyKey = canModifyVirtualKey(currentKeyData, teamsData, userID, userRole);
|
||||
|
||||
const isKeyAdmin =
|
||||
isProxyAdminRole(userRole || "") ||
|
||||
|
|
|
|||
|
|
@ -2496,6 +2496,59 @@
|
|||
"loading": "Loading keys...",
|
||||
"empty": "No keys found",
|
||||
"searchPlaceholder": "Search by key alias or ID…",
|
||||
"bulkActions": {
|
||||
"select": "Select keys",
|
||||
"cancel": "Cancel selection",
|
||||
"menu": "Actions"
|
||||
},
|
||||
"bulkDelete": {
|
||||
"selectKey": "Select {{key}}",
|
||||
"selected_one": "{{count}} key selected",
|
||||
"selected_other": "{{count}} keys selected",
|
||||
"action": "Delete selected ({{count}})",
|
||||
"title_one": "Delete {{count}} Virtual Key",
|
||||
"title_other": "Delete {{count}} Virtual Keys",
|
||||
"warning": "Deleted keys immediately stop authenticating requests. This action cannot be undone.",
|
||||
"message": "Confirm deletion of only the keys listed above.",
|
||||
"requiredConfirmation": "confirm delete",
|
||||
"keyAlias": "Key {{number}} alias",
|
||||
"keyId": "Key {{number}} ID",
|
||||
"noAlias": "No alias",
|
||||
"selectionChanged": "Some selected keys are no longer available to delete. Close this dialog and review your selection.",
|
||||
"success_one": "{{count}} Virtual Key deleted",
|
||||
"success_other": "{{count}} Virtual Keys deleted"
|
||||
},
|
||||
"bulkEdit": {
|
||||
"team": "Move to team",
|
||||
"user": "Assign to user",
|
||||
"budget": "Set budget",
|
||||
"selected_one": "{{count}} key selected",
|
||||
"selected_other": "{{count}} keys selected",
|
||||
"apply_one": "Apply to {{count}} key",
|
||||
"apply_other": "Apply to {{count}} keys",
|
||||
"pending": "Applying...",
|
||||
"cancel": "Cancel",
|
||||
"success_one": "{{count}} Virtual Key updated",
|
||||
"success_other": "{{count}} Virtual Keys updated",
|
||||
"partialFailure_one": "{{count}} key could not be updated. Review the reason below and try again.",
|
||||
"partialFailure_other": "{{count}} keys could not be updated. Review the reasons below and try again.",
|
||||
"selectionChanged": "Some selected keys are no longer available to edit. Close this dialog and review your selection.",
|
||||
"projectTeamLocked": "Project keys keep their project’s team",
|
||||
"descriptions": {
|
||||
"team": "Only the team will be updated. User, model, and budget settings stay unchanged.",
|
||||
"user": "Only the assigned user will be updated. Team, model, and budget settings stay unchanged.",
|
||||
"budget": "Apply the same budget and reset period to each key separately. Existing spend stays unchanged."
|
||||
},
|
||||
"fields": {
|
||||
"team": "Team",
|
||||
"user": "User",
|
||||
"budget": "Budget per key (USD)",
|
||||
"resetPeriod": "Reset period"
|
||||
},
|
||||
"invalidBudget": "Enter a finite amount of 0 or more.",
|
||||
"resetPeriodPlaceholder": "Select a reset period",
|
||||
"resetPeriodRequired": "Select a reset period."
|
||||
},
|
||||
"filters": {
|
||||
"title": "Filters",
|
||||
"description": "Narrow down virtual keys",
|
||||
|
|
|
|||
6
litellm/ui/litellm-dashboard/src/lib/http/schema.d.ts
generated
vendored
6
litellm/ui/litellm-dashboard/src/lib/http/schema.d.ts
generated
vendored
|
|
@ -8645,6 +8645,8 @@ export interface paths {
|
|||
* - key: str - The key identifier (token) to update
|
||||
* - budget_id: Optional[str] - Budget ID associated with the key
|
||||
* - max_budget: Optional[float] - Max budget for key
|
||||
* - budget_duration: Optional[str] - Budget reset period, or null to stop resetting
|
||||
* - user_id: Optional[str] - Owner user ID, or null to remove the owner
|
||||
* - team_id: Optional[str] - Team ID associated with key
|
||||
* - tags: Optional[List[str]] - Tags for organizing keys
|
||||
* - object_permission: Optional[LiteLLM_ObjectPermissionBase] - key-specific object permission, as on /key/update
|
||||
|
|
@ -30259,6 +30261,8 @@ export interface components {
|
|||
* @description One /key/bulk_update item; only the fields it carries are written.
|
||||
*/
|
||||
BulkUpdateKeyRequestItem: {
|
||||
/** Budget Duration */
|
||||
budget_duration?: string | null;
|
||||
/** Budget Id */
|
||||
budget_id?: string | null;
|
||||
/** Key */
|
||||
|
|
@ -30270,6 +30274,8 @@ export interface components {
|
|||
tags?: string[] | null;
|
||||
/** Team Id */
|
||||
team_id?: string | null;
|
||||
/** User Id */
|
||||
user_id?: string | null;
|
||||
};
|
||||
/**
|
||||
* BulkUpdateKeyResponse
|
||||
|
|
|
|||
|
|
@ -0,0 +1,41 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { canModifyKey } from "./keyPermissions";
|
||||
|
||||
const key = { user_id: "owner", team_id: "key-team" };
|
||||
|
||||
describe("canModifyKey", () => {
|
||||
it.each(["Admin", "proxy_admin"])("allows %s to modify another user's key", (role) => {
|
||||
expect(canModifyKey(key, [], "administrator", role)).toBe(true);
|
||||
});
|
||||
|
||||
it("allows an internal user to modify their own key but not another user's key", () => {
|
||||
expect(canModifyKey(key, [], "owner", "Internal User")).toBe(true);
|
||||
expect(canModifyKey(key, [], "another-user", "Internal User")).toBe(false);
|
||||
});
|
||||
|
||||
it("denies an internal viewer even when they own the key", () => {
|
||||
expect(canModifyKey(key, [], "owner", "Internal Viewer")).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ teamId: "key-team", memberRole: "admin", allowed: true },
|
||||
{ teamId: "other-team", memberRole: "admin", allowed: false },
|
||||
{ teamId: "key-team", memberRole: "user", allowed: false },
|
||||
] as const)(
|
||||
"checks the $memberRole membership on $teamId before allowing a team key change",
|
||||
({ teamId, memberRole, allowed }) => {
|
||||
const teams = [
|
||||
{
|
||||
team_id: teamId,
|
||||
members_with_roles: [{ user_id: "member", user_email: "member@example.com", role: memberRole }],
|
||||
},
|
||||
];
|
||||
expect(canModifyKey(key, teams, "member", "Internal User")).toBe(allowed);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not grant access through missing teams or a missing session", () => {
|
||||
expect(canModifyKey(key, undefined, "another-user", "Internal User")).toBe(false);
|
||||
expect(canModifyKey(key, null, null, null)).toBe(false);
|
||||
});
|
||||
});
|
||||
19
litellm/ui/litellm-dashboard/src/utils/keyPermissions.ts
Normal file
19
litellm/ui/litellm-dashboard/src/utils/keyPermissions.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import type { KeyResponse, Team } from "@/components/key_team_helpers/key_list";
|
||||
import { isProxyAdminRole, isUserTeamAdminForSingleTeam } from "@/utils/roles";
|
||||
|
||||
export const canModifyKey = (
|
||||
key: Pick<KeyResponse, "user_id" | "team_id">,
|
||||
teams: readonly Pick<Team, "team_id" | "members_with_roles">[] | null | undefined,
|
||||
userId: string | null,
|
||||
userRole: string | null,
|
||||
): boolean => {
|
||||
const canModifyOwnKey = userId === key.user_id && userRole !== "Internal Viewer";
|
||||
return (
|
||||
isProxyAdminRole(userRole ?? "") ||
|
||||
isUserTeamAdminForSingleTeam(
|
||||
teams?.find((team) => team.team_id === key.team_id)?.members_with_roles ?? null,
|
||||
userId ?? "",
|
||||
) ||
|
||||
canModifyOwnKey
|
||||
);
|
||||
};
|
||||
|
|
@ -6,10 +6,13 @@ import {
|
|||
E2E_INTERNAL_USER_KEY_ALIAS,
|
||||
E2E_TEAM_CRUD_ALIAS,
|
||||
E2E_TEAM_CRUD_ID,
|
||||
E2E_TEAM_ADMIN_USER_ID,
|
||||
E2E_INTERNAL_USER_ID,
|
||||
E2E_INTERNAL_USER_EMAIL,
|
||||
} from "../../constants";
|
||||
import { Page } from "../../fixtures/pages";
|
||||
import { navigateToPage, dismissFeedbackPopup } from "../../helpers/navigation";
|
||||
import { captureRequestBody, readBack } from "../../helpers/roundTrip";
|
||||
import { captureRequestBody, readBack, runWithCleanup } from "../../helpers/roundTrip";
|
||||
import { masterKey } from "../../helpers/traffic";
|
||||
import { proxyIsPremium } from "../../helpers/premium";
|
||||
|
||||
|
|
@ -36,6 +39,67 @@ async function createDeletableKey(page: PlaywrightPage): Promise<string> {
|
|||
return alias;
|
||||
}
|
||||
|
||||
async function readKeyStates(page: PlaywrightPage, aliases: string[]) {
|
||||
const keys = await Promise.all(aliases.map((alias) => findKeyByAlias(page, alias)));
|
||||
return keys.map(
|
||||
(key) =>
|
||||
key && {
|
||||
token: key.token,
|
||||
key_alias: key.key_alias,
|
||||
team_id: key.team_id,
|
||||
user_id: key.user_id,
|
||||
max_budget: key.max_budget,
|
||||
budget_duration: key.budget_duration,
|
||||
models: key.models,
|
||||
metadata: key.metadata,
|
||||
tpm_limit: key.tpm_limit,
|
||||
rpm_limit: key.rpm_limit,
|
||||
expires: key.expires,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function withBulkKeys(page: PlaywrightPage, action: (aliases: string[]) => Promise<void>) {
|
||||
const prefix = `e2e-bulk-${test.info().workerIndex}-${Date.now()}`;
|
||||
const aliases = [`${prefix}-first`, `${prefix}-second`, `${prefix}-keep`];
|
||||
const headers = { Authorization: `Bearer ${masterKey()}` };
|
||||
await runWithCleanup(
|
||||
async () => {
|
||||
for (const key_alias of aliases) {
|
||||
const response = await page.request.post("/key/generate", {
|
||||
headers,
|
||||
data: {
|
||||
key_alias,
|
||||
user_id: E2E_TEAM_ADMIN_USER_ID,
|
||||
max_budget: 100,
|
||||
budget_duration: "30d",
|
||||
tpm_limit: 123,
|
||||
rpm_limit: 45,
|
||||
metadata: { bulk_edit_test: prefix },
|
||||
},
|
||||
});
|
||||
expect(response.ok(), `create disposable key ${key_alias}`).toBe(true);
|
||||
}
|
||||
const initial = await readKeyStates(page, aliases);
|
||||
expect(initial.map((key) => key?.token)).toEqual(aliases.map(() => expect.any(String)));
|
||||
await navigateToPage(page, Page.ApiKeys);
|
||||
await page.getByTestId("datatable-search").fill(prefix);
|
||||
await expect(page.getByRole("row").filter({ hasText: aliases[0] })).toBeVisible();
|
||||
await expect(page.getByRole("checkbox")).toHaveCount(0);
|
||||
await page.getByRole("button", { name: "Select keys", exact: true }).click();
|
||||
await expect(page.getByRole("button", { name: "Actions", exact: true })).toHaveCount(0);
|
||||
await action(aliases);
|
||||
},
|
||||
async () => {
|
||||
const remaining = await readKeyStates(page, aliases);
|
||||
const tokens = remaining.flatMap((key) => (typeof key?.token === "string" ? [key.token] : []));
|
||||
if (tokens.length === 0) return true;
|
||||
const response = await page.request.post("/key/delete", { headers, data: { keys: tokens } });
|
||||
return response.ok();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test.describe("Proxy Admin - Keys", () => {
|
||||
test.use({ storageState: ADMIN_STORAGE_PATH });
|
||||
|
||||
|
|
@ -194,6 +258,95 @@ test.describe("Proxy Admin - Keys", () => {
|
|||
.toBeUndefined();
|
||||
});
|
||||
|
||||
test("Bulk delete only selected keys after confirmation", async ({ page }) => {
|
||||
await withBulkKeys(page, async (aliases) => {
|
||||
const before = await readKeyStates(page, aliases);
|
||||
for (const alias of aliases.slice(0, 2)) {
|
||||
await page.getByRole("row").filter({ hasText: alias }).getByRole("checkbox").check();
|
||||
}
|
||||
await page.getByRole("button", { name: "Actions", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Delete selected (2)" }).click();
|
||||
const modal = page.getByRole("dialog", { name: /Delete/ });
|
||||
await expect(modal.getByText(aliases[0], { exact: true })).toBeVisible();
|
||||
await expect(modal.getByText(aliases[1], { exact: true })).toBeVisible();
|
||||
await expect(modal.getByText(aliases[2], { exact: true })).toHaveCount(0);
|
||||
const deleteButton = modal.getByRole("button", { name: "Delete", exact: true });
|
||||
await expect(deleteButton).toBeDisabled();
|
||||
await modal.getByRole("textbox").fill("Confirm delete");
|
||||
await expect(deleteButton).toBeDisabled();
|
||||
await modal.getByRole("textbox").fill("confirm delete");
|
||||
await expect(deleteButton).toBeEnabled();
|
||||
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
expect(await readKeyStates(page, aliases)).toEqual(before);
|
||||
|
||||
await page.getByRole("button", { name: "Actions", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Delete selected (2)" }).click();
|
||||
await expect(modal.getByRole("textbox")).toHaveValue("");
|
||||
await expect(deleteButton).toBeDisabled();
|
||||
await modal.getByRole("textbox").fill("confirm delete");
|
||||
const body = await captureRequestBody<{ keys: string[] }>(
|
||||
page,
|
||||
{ method: "POST", urlIncludes: "/key/delete" },
|
||||
() => deleteButton.click(),
|
||||
);
|
||||
expect(body.keys).toEqual(expect.arrayContaining(before.slice(0, 2).map((key) => key?.token)));
|
||||
expect(body.keys).toHaveLength(2);
|
||||
await expect.poll(() => readKeyStates(page, aliases)).toEqual([undefined, undefined, before[2]]);
|
||||
for (const alias of aliases.slice(0, 2)) {
|
||||
await expect(page.getByRole("row").filter({ hasText: alias })).toHaveCount(0);
|
||||
}
|
||||
await page.reload();
|
||||
await expect(page.getByRole("row").filter({ hasText: aliases[2] })).toBeVisible();
|
||||
await expect(page.getByRole("checkbox")).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
test("Bulk edit team, user, and budget only for selected keys", async ({ page }) => {
|
||||
await withBulkKeys(page, async (aliases) => {
|
||||
for (const [action, changes] of [
|
||||
["Move to team", { team_id: E2E_TEAM_CRUD_ID }],
|
||||
["Assign to user", { user_id: E2E_INTERNAL_USER_ID }],
|
||||
["Set budget", { max_budget: 25.5, budget_duration: "7d" }],
|
||||
] as const) {
|
||||
await test.step(action, async () => {
|
||||
const before = await readKeyStates(page, aliases);
|
||||
for (const alias of aliases.slice(0, 2)) {
|
||||
await page.getByRole("row").filter({ hasText: alias }).getByRole("checkbox").check();
|
||||
}
|
||||
await page.getByRole("button", { name: "Actions", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: action, exact: true }).click();
|
||||
const dialog = page.getByRole("dialog", { name: action, exact: true });
|
||||
if ("team_id" in changes) {
|
||||
await dialog.getByRole("combobox", { name: "Team", exact: true }).fill(E2E_TEAM_CRUD_ALIAS);
|
||||
await page.getByRole("option", { name: new RegExp(E2E_TEAM_CRUD_ALIAS) }).click();
|
||||
} else if ("user_id" in changes) {
|
||||
await dialog.getByRole("combobox", { name: "User", exact: true }).fill(E2E_INTERNAL_USER_EMAIL);
|
||||
await page.getByRole("option", { name: new RegExp(E2E_INTERNAL_USER_ID) }).click();
|
||||
} else {
|
||||
await expect(dialog.getByRole("button", { name: "Apply to 2 keys" })).toBeDisabled();
|
||||
await dialog.getByRole("spinbutton", { name: "Budget per key (USD)" }).fill("25.5");
|
||||
const period = dialog.getByRole("combobox", { name: "Reset period" });
|
||||
await expect(period).toContainText(/monthly/i);
|
||||
await period.click();
|
||||
await page.getByRole("option", { name: /^weekly$/i }).click();
|
||||
}
|
||||
await dialog.getByRole("button", { name: "Apply to 2 keys" }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
const expected = before.map((key, index) => (index < 2 ? { ...key, ...changes } : key));
|
||||
await expect.poll(() => readKeyStates(page, aliases)).toEqual(expected);
|
||||
await expect(page.getByText("0 keys selected", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Actions", exact: true })).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
await page.getByRole("button", { name: "Cancel selection" }).click();
|
||||
await expect(page.getByRole("checkbox")).toHaveCount(0);
|
||||
await page.reload();
|
||||
for (const alias of aliases) {
|
||||
await expect(page.getByRole("row").filter({ hasText: alias })).toBeVisible();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test("See internal user keys in team", async ({ page }) => {
|
||||
await navigateToPage(page, Page.ApiKeys);
|
||||
await dismissFeedbackPopup(page);
|
||||
|
|
@ -254,7 +407,9 @@ test.describe("Proxy Admin - Keys", () => {
|
|||
// verify it can call /chat/completions for the model it was scoped to.
|
||||
// The mock LLM server (fixtures/mock_llm_server/server.py) replies with
|
||||
// a fixed "This is a mock response." body.
|
||||
const apiKey = (await page.getByRole("dialog", { name: "Save your Key" }).locator("pre").filter({ hasText: /^sk-/ }).innerText()).trim();
|
||||
const apiKey = (
|
||||
await page.getByRole("dialog", { name: "Save your Key" }).locator("pre").filter({ hasText: /^sk-/ }).innerText()
|
||||
).trim();
|
||||
expect(apiKey).toMatch(/^sk-/);
|
||||
|
||||
const response = await page.request.post("/chat/completions", {
|
||||
|
|
|
|||
|
|
@ -7674,7 +7674,14 @@ async def _run_bulk_update_on_one_key(
|
|||
from litellm.proxy.management_endpoints.key_management_endpoints import bulk_update_keys
|
||||
|
||||
key_in_db = LiteLLM_VerificationToken(
|
||||
token=_BULK_UPDATE_TOKEN, user_id="test-user", team_id="team-1", max_budget=100.0, budget_id="budget-1"
|
||||
token=_BULK_UPDATE_TOKEN,
|
||||
user_id="test-user",
|
||||
team_id="team-1",
|
||||
max_budget=100.0,
|
||||
budget_id="budget-1",
|
||||
budget_duration="30d",
|
||||
budget_reset_at=datetime(2025, 1, 1, tzinfo=timezone.utc),
|
||||
metadata={"purpose": "unchanged"},
|
||||
)
|
||||
mock_prisma_client = AsyncMock()
|
||||
mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=key_in_db)
|
||||
|
|
@ -7733,7 +7740,7 @@ async def test_bulk_update_keys_item_without_a_field_leaves_that_column_alone(mo
|
|||
written = _written_key_row(await _bulk_update_one_key(monkeypatch, {"tags": ["team-a"]}))
|
||||
|
||||
assert written["metadata"]["tags"] == ["team-a"]
|
||||
assert not {"max_budget", "team_id", "budget_id"} & written.keys()
|
||||
assert not {"max_budget", "team_id", "budget_id", "user_id", "budget_duration", "budget_reset_at"} & written.keys()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -7745,6 +7752,56 @@ async def test_bulk_update_keys_explicit_null_still_clears_the_field(monkeypatch
|
|||
assert not {"team_id", "budget_id"} & written.keys()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("item_payload", "expected_changes"),
|
||||
[
|
||||
({"user_id": "new-owner"}, {"user_id": "new-owner"}),
|
||||
({"user_id": None}, {"user_id": None}),
|
||||
({"budget_duration": None}, {"budget_duration": None, "budget_reset_at": None}),
|
||||
],
|
||||
)
|
||||
async def test_bulk_update_keys_applies_owner_and_period_changes_without_overwriting_other_fields(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
item_payload: Mapping[str, object],
|
||||
expected_changes: Mapping[str, object],
|
||||
) -> None:
|
||||
written: Final = _written_key_row(await _bulk_update_one_key(monkeypatch, item_payload))
|
||||
|
||||
assert written == {"token": _BULK_UPDATE_TOKEN, "metadata": {"purpose": "unchanged"}, **expected_changes}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_update_keys_new_period_reschedules_the_budget_without_changing_its_limit(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
written: Final = _written_key_row(await _bulk_update_one_key(monkeypatch, {"budget_duration": "7d"}))
|
||||
|
||||
assert isinstance(written["budget_reset_at"], datetime)
|
||||
assert {field: value for field, value in written.items() if field != "budget_reset_at"} == {
|
||||
"token": _BULK_UPDATE_TOKEN,
|
||||
"budget_duration": "7d",
|
||||
"metadata": {"purpose": "unchanged"},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("bad_duration", ["0s", "-5m", "invalid"])
|
||||
async def test_bulk_update_keys_rejects_invalid_period_without_writing_the_key(
|
||||
monkeypatch: pytest.MonkeyPatch, bad_duration: str
|
||||
) -> None:
|
||||
response, prisma = await _run_bulk_update_on_one_key(monkeypatch, {"budget_duration": bad_duration})
|
||||
|
||||
assert response.successful_updates == []
|
||||
assert [(update.key, update.failed_reason) for update in response.failed_updates] == [
|
||||
(
|
||||
_BULK_UPDATE_TOKEN,
|
||||
f"Invalid budget_duration '{bad_duration}'. Use a format like '1h', '24h', '7d', or '30d'.",
|
||||
)
|
||||
]
|
||||
prisma.update_data.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_update_keys_object_permission_is_granted_not_dropped(monkeypatch):
|
||||
"""`object_permission` used to be accepted with 200 and dropped, leaving an item that carried
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue