From b00f81ab38fcf3368aa575862940f475ba2eab53 Mon Sep 17 00:00:00 2001 From: Milan Date: Sat, 6 Jun 2026 12:55:11 +0300 Subject: [PATCH 1/5] fix(ui): require new expiration when regenerating an expired key Regenerating an already-expired virtual key without setting a new duration produced a key that inherited the past expiry and was immediately unusable. The regenerate modal now marks the duration as required for expired keys, labels the current expiry as "(expired)" in red, and validates timezone-correctly so naive DB timestamps are compared in UTC. Adds keyExpiryUtils (isKeyExpired / parseExpiresUtc) with tests and covers the expired-key regenerate flow in RegenerateKeyModal tests. Co-authored-by: Cursor --- .../organisms/RegenerateKeyModal.test.tsx | 54 +++++++++++++------ .../organisms/RegenerateKeyModal.tsx | 47 ++++++++-------- .../src/utils/keyExpiryUtils.test.ts | 30 +++++++++++ .../src/utils/keyExpiryUtils.ts | 21 ++++++++ 4 files changed, 111 insertions(+), 41 deletions(-) create mode 100644 ui/litellm-dashboard/src/utils/keyExpiryUtils.test.ts create mode 100644 ui/litellm-dashboard/src/utils/keyExpiryUtils.ts diff --git a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx index a69ae7792496..2bfde5076506 100644 --- a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx +++ b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx @@ -239,19 +239,10 @@ describe("RegenerateKeyModal", () => { }); }); - it("should fall back to the previous expiry when duration is unparseable", async () => { - // Regression: if calculateNewExpiryTime returns null (unrecognised suffix), - // the payload should fall back to the previous expires rather than null. + it("should reject unparseable duration values before calling regenerate", async () => { const user = userEvent.setup(); - const previousExpires = "2026-12-31T00:00:00Z"; - mockRegenerateKeyCall.mockResolvedValue({ - key: "sk-new-regenerated-key", - token: "new-token-hash", - }); - renderWithProviders( - , - ); + renderWithProviders(); const durationField = screen.getByPlaceholderText("e.g. 30s, 30h, 30d"); await user.clear(durationField); @@ -260,11 +251,11 @@ describe("RegenerateKeyModal", () => { await user.click(screen.getByRole("button", { name: /Regenerate/ })); await waitFor(() => { - expect(mockOnKeyUpdate).toHaveBeenCalledOnce(); + expect( + screen.getByText("Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo"), + ).toBeInTheDocument(); }); - - const updateCall = mockOnKeyUpdate.mock.calls[0][0]; - expect(updateCall.expires).toBe(previousExpires); + expect(mockRegenerateKeyCall).not.toHaveBeenCalled(); }); it("should pass form values to onKeyUpdate even when the API echoes back different limits", async () => { @@ -338,6 +329,39 @@ describe("RegenerateKeyModal", () => { expect(mockRegenerateKeyCall).not.toHaveBeenCalled(); }); + it("should mark expiry as expired without pre-filling a duration", async () => { + vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-06-06T12:00:00Z")); + + renderWithProviders( + , + ); + + expect(screen.getByText(/\(expired\)/)).toBeInTheDocument(); + expect(screen.getByPlaceholderText("e.g. 30s, 30h, 30d")).toHaveValue(""); + }); + + it("should require a new expiration before regenerating an expired key", async () => { + vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-06-06T12:00:00Z")); + const user = userEvent.setup(); + + renderWithProviders( + , + ); + + await user.click(screen.getByRole("button", { name: /Regenerate/ })); + + await waitFor(() => { + expect(screen.getByText("Expiration is required for expired keys")).toBeInTheDocument(); + }); + expect(mockRegenerateKeyCall).not.toHaveBeenCalled(); + }); + it("should pass the correct token identifier to regenerateKeyCall", async () => { const user = userEvent.setup(); mockRegenerateKeyCall.mockResolvedValue({ diff --git a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx index b27642efa5aa..60accc7e50fc 100644 --- a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx +++ b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx @@ -7,9 +7,15 @@ import { CopyToClipboard } from "react-copy-to-clipboard"; import { KeyResponse } from "../key_team_helpers/key_list"; import NotificationManager from "../molecules/notifications_manager"; import { regenerateKeyCall } from "../networking"; +import { isKeyExpired } from "@/utils/keyExpiryUtils"; const { Text } = Typography; +const DURATION_RULE = { + pattern: /^(\d+(s|m|h|d|w|mo))?$/, + message: "Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo", +}; + interface RegenerateKeyModalProps { selectedToken: KeyResponse | null; visible: boolean; @@ -21,11 +27,18 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat const { accessToken } = useAuthorized(); const [form] = Form.useForm(); const [regeneratedKey, setRegeneratedKey] = useState(null); - const [regenerateFormData, setRegenerateFormData] = useState(null); - const [newExpiryTime, setNewExpiryTime] = useState(null); const [isRegenerating, setIsRegenerating] = useState(false); const [copied, setCopied] = useState(false); + const keyIsExpired = isKeyExpired(selectedToken?.expires); + const durationValue = Form.useWatch("duration", form); + + // Expired keys must get a new duration, otherwise regeneration produces a key + // that inherits the old (past) expiry and is immediately unusable. + const durationRules = keyIsExpired + ? [{ required: true, message: "Expiration is required for expired keys" }, DURATION_RULE] + : [DURATION_RULE]; + useEffect(() => { if (visible && selectedToken && accessToken) { form.setFieldsValue({ @@ -72,13 +85,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat } }; - useEffect(() => { - if (regenerateFormData?.duration) { - setNewExpiryTime(calculateNewExpiryTime(regenerateFormData.duration)); - } else { - setNewExpiryTime(null); - } - }, [regenerateFormData?.duration]); + const newExpiryTime = durationValue ? calculateNewExpiryTime(durationValue) : null; const handleRegenerateKey = async () => { if (!selectedToken || !accessToken) return; @@ -193,16 +200,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat ) : ( -
{ - if ("duration" in changedValues) { - setRegenerateFormData((prev: { duration?: string }) => ({ ...prev, duration: changedValues.duration })); - } - }} - > + @@ -230,11 +228,13 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat - + Current expiry:{" "} {selectedToken?.expires ? new Date(selectedToken.expires).toLocaleString() : "Never"} + {keyIsExpired && " (expired)"} {newExpiryTime && ( @@ -257,12 +257,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat Recommended: 24h to 72h for production keys } - rules={[ - { - pattern: /^(\d+(s|m|h|d|w|mo))?$/, - message: "Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo", - }, - ]} + rules={[DURATION_RULE]} > diff --git a/ui/litellm-dashboard/src/utils/keyExpiryUtils.test.ts b/ui/litellm-dashboard/src/utils/keyExpiryUtils.test.ts new file mode 100644 index 000000000000..a995fe06d0e2 --- /dev/null +++ b/ui/litellm-dashboard/src/utils/keyExpiryUtils.test.ts @@ -0,0 +1,30 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { isKeyExpired, parseExpiresUtc } from "./keyExpiryUtils"; + +describe("keyExpiryUtils", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("treats naive ISO strings as UTC", () => { + const ms = parseExpiresUtc("2020-01-01T12:00:00"); + expect(ms).toBe(Date.parse("2020-01-01T12:00:00Z")); + }); + + it("parses Z-suffixed ISO strings unchanged", () => { + const iso = "2020-01-01T12:00:00.000Z"; + expect(parseExpiresUtc(iso)).toBe(Date.parse(iso)); + }); + + it("returns false when expires is missing", () => { + expect(isKeyExpired(undefined)).toBe(false); + expect(isKeyExpired(null)).toBe(false); + }); + + it("detects expired keys using UTC comparison", () => { + vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-06-06T12:00:00Z")); + expect(isKeyExpired("2026-06-05T12:00:00Z")).toBe(true); + expect(isKeyExpired("2026-06-06T12:00:00")).toBe(false); + expect(isKeyExpired("2026-06-07T12:00:00Z")).toBe(false); + }); +}); diff --git a/ui/litellm-dashboard/src/utils/keyExpiryUtils.ts b/ui/litellm-dashboard/src/utils/keyExpiryUtils.ts new file mode 100644 index 000000000000..297656f1355c --- /dev/null +++ b/ui/litellm-dashboard/src/utils/keyExpiryUtils.ts @@ -0,0 +1,21 @@ +const HAS_TIMEZONE_SUFFIX = /[zZ]$|[+-]\d{2}:?\d{2}$/; + +/** + * Parse a key expires timestamp as UTC, matching proxy auth behavior for naive DB values. + */ +export function parseExpiresUtc(expires: string): number { + const normalized = HAS_TIMEZONE_SUFFIX.test(expires) ? expires : `${expires}Z`; + return Date.parse(normalized); +} + +/** + * Returns true when the key has an expires value in the past (UTC). + */ +export function isKeyExpired(expires?: string | null): boolean { + if (!expires) { + return false; + } + + const expiryMs = parseExpiresUtc(expires); + return !Number.isNaN(expiryMs) && expiryMs < Date.now(); +} From 5399e05b5c791b93e23d0ff9ead717bd8745e278 Mon Sep 17 00:00:00 2001 From: Milan Date: Sat, 6 Jun 2026 13:49:06 +0300 Subject: [PATCH 2/5] style(ui): fix prettier formatting in RegenerateKeyModal tests Co-authored-by: Cursor --- .../src/components/organisms/RegenerateKeyModal.test.tsx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx index 2bfde5076506..159ca9fdea3c 100644 --- a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx +++ b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx @@ -251,9 +251,7 @@ describe("RegenerateKeyModal", () => { await user.click(screen.getByRole("button", { name: /Regenerate/ })); await waitFor(() => { - expect( - screen.getByText("Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo"), - ).toBeInTheDocument(); + expect(screen.getByText("Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo")).toBeInTheDocument(); }); expect(mockRegenerateKeyCall).not.toHaveBeenCalled(); }); From 9559cb13f4e9cd6278cdba470cafa2fbbb4e0ac1 Mon Sep 17 00:00:00 2001 From: Milan Date: Sat, 6 Jun 2026 13:56:08 +0300 Subject: [PATCH 3/5] refactor(ui): address review feedback on expired-key regenerate - Display the current expiry via formatExpiresUtc so the shown time and the (expired) badge both use UTC parsing, fixing a possible mismatch for naive DB timestamps in non-UTC browsers. - Extract the expiry-preview logic into keyExpiryUtils (calculateExpiryPreviewFromDuration) so it is unit-tested directly. - Restore coverage for the "preview returns null -> keep previous expiry" fallback branch in RegenerateKeyModal. Co-authored-by: Cursor --- .../organisms/RegenerateKeyModal.test.tsx | 23 ++++++++ .../organisms/RegenerateKeyModal.tsx | 43 ++------------- .../src/utils/keyExpiryUtils.test.ts | 17 +++++- .../src/utils/keyExpiryUtils.ts | 54 +++++++++++++++++++ 4 files changed, 97 insertions(+), 40 deletions(-) diff --git a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx index 159ca9fdea3c..ec818a5a3d27 100644 --- a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx +++ b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx @@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event"; import { renderWithProviders, screen, waitFor } from "../../../tests/test-utils"; import { RegenerateKeyModal } from "./RegenerateKeyModal"; import { KeyResponse } from "../key_team_helpers/key_list"; +import * as keyExpiryUtils from "@/utils/keyExpiryUtils"; // Mock the networking call const mockRegenerateKeyCall = vi.fn(); @@ -239,6 +240,28 @@ describe("RegenerateKeyModal", () => { }); }); + it("should fall back to the previous expiry when preview calculation returns null", async () => { + const user = userEvent.setup(); + const previousExpires = "2026-12-31T00:00:00Z"; + vi.spyOn(keyExpiryUtils, "calculateExpiryPreviewFromDuration").mockReturnValue(null); + mockRegenerateKeyCall.mockResolvedValue({ + key: "sk-new-regenerated-key", + token: "new-token-hash", + }); + + renderWithProviders( + , + ); + + await user.click(screen.getByRole("button", { name: /Regenerate/ })); + + await waitFor(() => { + expect(mockOnKeyUpdate).toHaveBeenCalledOnce(); + }); + + expect(mockOnKeyUpdate.mock.calls[0][0].expires).toBe(previousExpires); + }); + it("should reject unparseable duration values before calling regenerate", async () => { const user = userEvent.setup(); diff --git a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx index 60accc7e50fc..9cbf6ef7a3d7 100644 --- a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx +++ b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx @@ -1,13 +1,12 @@ import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized"; import { CheckOutlined, CopyOutlined, SyncOutlined } from "@ant-design/icons"; import { Alert, Button, Col, Flex, Form, Input, InputNumber, Modal, Row, Space, Typography } from "antd"; -import { add } from "date-fns"; import { useEffect, useState } from "react"; import { CopyToClipboard } from "react-copy-to-clipboard"; import { KeyResponse } from "../key_team_helpers/key_list"; import NotificationManager from "../molecules/notifications_manager"; import { regenerateKeyCall } from "../networking"; -import { isKeyExpired } from "@/utils/keyExpiryUtils"; +import { calculateExpiryPreviewFromDuration, formatExpiresUtc, isKeyExpired } from "@/utils/keyExpiryUtils"; const { Text } = Typography; @@ -52,40 +51,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat } }, [visible, selectedToken, form, accessToken]); - const calculateNewExpiryTime = (duration: string | undefined): string | null => { - if (!duration) return null; - - try { - const amount = parseInt(duration); - if (Number.isNaN(amount)) { - throw new Error("Invalid duration format"); - } - const now = new Date(); - // Check "mo" before "m" to avoid a false prefix match (e.g. "1mo" → minutes). - let newExpiry: Date; - if (duration.endsWith("mo")) { - newExpiry = add(now, { months: amount }); - } else if (duration.endsWith("s")) { - newExpiry = add(now, { seconds: amount }); - } else if (duration.endsWith("m")) { - newExpiry = add(now, { minutes: amount }); - } else if (duration.endsWith("h")) { - newExpiry = add(now, { hours: amount }); - } else if (duration.endsWith("d")) { - newExpiry = add(now, { days: amount }); - } else if (duration.endsWith("w")) { - newExpiry = add(now, { weeks: amount }); - } else { - throw new Error("Invalid duration format"); - } - - return newExpiry.toLocaleString(); - } catch (error) { - return null; - } - }; - - const newExpiryTime = durationValue ? calculateNewExpiryTime(durationValue) : null; + const newExpiryTime = durationValue ? calculateExpiryPreviewFromDuration(durationValue) : null; const handleRegenerateKey = async () => { if (!selectedToken || !accessToken) return; @@ -110,7 +76,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat tpm_limit: formValues.tpm_limit, rpm_limit: formValues.rpm_limit, expires: formValues.duration - ? calculateNewExpiryTime(formValues.duration) ?? selectedToken.expires + ? calculateExpiryPreviewFromDuration(formValues.duration) ?? selectedToken.expires : selectedToken.expires, }; @@ -232,8 +198,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat extra={ - Current expiry:{" "} - {selectedToken?.expires ? new Date(selectedToken.expires).toLocaleString() : "Never"} + Current expiry: {selectedToken?.expires ? formatExpiresUtc(selectedToken.expires) : "Never"} {keyIsExpired && " (expired)"} {newExpiryTime && ( diff --git a/ui/litellm-dashboard/src/utils/keyExpiryUtils.test.ts b/ui/litellm-dashboard/src/utils/keyExpiryUtils.test.ts index a995fe06d0e2..b485346ff10f 100644 --- a/ui/litellm-dashboard/src/utils/keyExpiryUtils.test.ts +++ b/ui/litellm-dashboard/src/utils/keyExpiryUtils.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { isKeyExpired, parseExpiresUtc } from "./keyExpiryUtils"; +import { calculateExpiryPreviewFromDuration, formatExpiresUtc, isKeyExpired, parseExpiresUtc } from "./keyExpiryUtils"; describe("keyExpiryUtils", () => { afterEach(() => { @@ -16,6 +16,11 @@ describe("keyExpiryUtils", () => { expect(parseExpiresUtc(iso)).toBe(Date.parse(iso)); }); + it("formats naive ISO strings as UTC before localizing", () => { + const naive = "2026-06-05T10:00:00"; + expect(formatExpiresUtc(naive)).toBe(new Date(Date.parse(`${naive}Z`)).toLocaleString()); + }); + it("returns false when expires is missing", () => { expect(isKeyExpired(undefined)).toBe(false); expect(isKeyExpired(null)).toBe(false); @@ -27,4 +32,14 @@ describe("keyExpiryUtils", () => { expect(isKeyExpired("2026-06-06T12:00:00")).toBe(false); expect(isKeyExpired("2026-06-07T12:00:00Z")).toBe(false); }); + + it("returns a preview for supported duration strings", () => { + vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-06-06T12:00:00Z")); + expect(calculateExpiryPreviewFromDuration("30d")).toBeTruthy(); + }); + + it("returns null for unparseable duration strings", () => { + expect(calculateExpiryPreviewFromDuration("bogus")).toBeNull(); + expect(calculateExpiryPreviewFromDuration(undefined)).toBeNull(); + }); }); diff --git a/ui/litellm-dashboard/src/utils/keyExpiryUtils.ts b/ui/litellm-dashboard/src/utils/keyExpiryUtils.ts index 297656f1355c..bc42d60e17dd 100644 --- a/ui/litellm-dashboard/src/utils/keyExpiryUtils.ts +++ b/ui/litellm-dashboard/src/utils/keyExpiryUtils.ts @@ -1,3 +1,5 @@ +import { add } from "date-fns"; + const HAS_TIMEZONE_SUFFIX = /[zZ]$|[+-]\d{2}:?\d{2}$/; /** @@ -8,6 +10,18 @@ export function parseExpiresUtc(expires: string): number { return Date.parse(normalized); } +/** + * Format an expires timestamp for display, treating naive DB values as UTC. + */ +export function formatExpiresUtc(expires: string): string { + const expiryMs = parseExpiresUtc(expires); + if (Number.isNaN(expiryMs)) { + return expires; + } + + return new Date(expiryMs).toLocaleString(); +} + /** * Returns true when the key has an expires value in the past (UTC). */ @@ -19,3 +33,43 @@ export function isKeyExpired(expires?: string | null): boolean { const expiryMs = parseExpiresUtc(expires); return !Number.isNaN(expiryMs) && expiryMs < Date.now(); } + +/** + * Compute a human-readable preview of the new expiry from a duration string. + * Returns null when the duration cannot be parsed. + */ +export function calculateExpiryPreviewFromDuration(duration: string | undefined): string | null { + if (!duration) { + return null; + } + + try { + const amount = parseInt(duration); + if (Number.isNaN(amount)) { + throw new Error("Invalid duration format"); + } + + const now = new Date(); + // Check "mo" before "m" to avoid a false prefix match (e.g. "1mo" → minutes). + let newExpiry: Date; + if (duration.endsWith("mo")) { + newExpiry = add(now, { months: amount }); + } else if (duration.endsWith("s")) { + newExpiry = add(now, { seconds: amount }); + } else if (duration.endsWith("m")) { + newExpiry = add(now, { minutes: amount }); + } else if (duration.endsWith("h")) { + newExpiry = add(now, { hours: amount }); + } else if (duration.endsWith("d")) { + newExpiry = add(now, { days: amount }); + } else if (duration.endsWith("w")) { + newExpiry = add(now, { weeks: amount }); + } else { + throw new Error("Invalid duration format"); + } + + return newExpiry.toLocaleString(); + } catch { + return null; + } +} From 27674aa93a7cb76150c8d18e600a34b5c35ec47c Mon Sep 17 00:00:00 2001 From: Milan Date: Sat, 6 Jun 2026 14:09:52 +0300 Subject: [PATCH 4/5] fix(ui): use API ISO expires for regenerate optimistic update The regenerate optimistic update wrote calculateExpiryPreviewFromDuration's locale-formatted string into expires, which broke parseExpiresUtc/isKeyExpired/ formatExpiresUtc on subsequent renders. Use the authoritative ISO expires from the regenerate API response (falling back to the prior expiry only when absent). The preview helper now feeds the display preview only. Co-authored-by: Cursor --- .../organisms/RegenerateKeyModal.test.tsx | 28 ++++++++++++++++--- .../organisms/RegenerateKeyModal.tsx | 6 ++-- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx index ec818a5a3d27..06089ffac6c3 100644 --- a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx +++ b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx @@ -3,7 +3,6 @@ import userEvent from "@testing-library/user-event"; import { renderWithProviders, screen, waitFor } from "../../../tests/test-utils"; import { RegenerateKeyModal } from "./RegenerateKeyModal"; import { KeyResponse } from "../key_team_helpers/key_list"; -import * as keyExpiryUtils from "@/utils/keyExpiryUtils"; // Mock the networking call const mockRegenerateKeyCall = vi.fn(); @@ -240,17 +239,38 @@ describe("RegenerateKeyModal", () => { }); }); - it("should fall back to the previous expiry when preview calculation returns null", async () => { + it("should use the API response's ISO expires for the optimistic update", async () => { + const user = userEvent.setup(); + const apiExpires = "2026-06-13T11:08:16.783000Z"; + mockRegenerateKeyCall.mockResolvedValue({ + key: "sk-new-regenerated-key", + token: "new-token-hash", + expires: apiExpires, + }); + + renderWithProviders( + , + ); + + await user.click(screen.getByRole("button", { name: /Regenerate/ })); + + await waitFor(() => { + expect(mockOnKeyUpdate).toHaveBeenCalledOnce(); + }); + + expect(mockOnKeyUpdate.mock.calls[0][0].expires).toBe(apiExpires); + }); + + it("should fall back to the previous expiry when the API response omits expires", async () => { const user = userEvent.setup(); const previousExpires = "2026-12-31T00:00:00Z"; - vi.spyOn(keyExpiryUtils, "calculateExpiryPreviewFromDuration").mockReturnValue(null); mockRegenerateKeyCall.mockResolvedValue({ key: "sk-new-regenerated-key", token: "new-token-hash", }); renderWithProviders( - , + , ); await user.click(screen.getByRole("button", { name: /Regenerate/ })); diff --git a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx index 9cbf6ef7a3d7..056ded2af555 100644 --- a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx +++ b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx @@ -68,6 +68,8 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat // fields it returns (new token, timestamps, etc.) are captured, then // override with the explicit form values — the user's just-submitted // edits must win over whatever the API echoes back. + // expires must come from the API (an ISO string), never the locale- + // formatted preview, otherwise downstream expiry parsing breaks. const updatedKeyData: Partial = { ...response, token: response.token || response.key_id || selectedToken.token, @@ -75,9 +77,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat max_budget: formValues.max_budget, tpm_limit: formValues.tpm_limit, rpm_limit: formValues.rpm_limit, - expires: formValues.duration - ? calculateExpiryPreviewFromDuration(formValues.duration) ?? selectedToken.expires - : selectedToken.expires, + expires: response.expires ?? selectedToken.expires, }; // Update the parent component with new key data From f527f5b8c00183e229c59166481aa092dcaca982 Mon Sep 17 00:00:00 2001 From: Milan Date: Sat, 6 Jun 2026 14:21:13 +0300 Subject: [PATCH 5/5] fix(ui): don't toast Ant form validation errors on regenerate Making the duration field required for expired keys means form.validateFields() now rejects client-side with a ValidateErrorEntity. That hit the catch block and produced a spurious Info toast (stringified object) alongside the correct inline message. Skip the backend toast for validation rejections, matching the error?.errorFields convention used elsewhere in the dashboard. Co-authored-by: Cursor --- .../components/organisms/RegenerateKeyModal.test.tsx | 12 ++++++++++++ .../src/components/organisms/RegenerateKeyModal.tsx | 7 ++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx index 06089ffac6c3..98ce38271512 100644 --- a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx +++ b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.test.tsx @@ -10,6 +10,15 @@ vi.mock("../networking", () => ({ regenerateKeyCall: (...args: unknown[]) => mockRegenerateKeyCall(...args), })); +const mockNotificationFromBackend = vi.fn(); +const mockNotificationSuccess = vi.fn(); +vi.mock("../molecules/notifications_manager", () => ({ + default: { + fromBackend: (...args: unknown[]) => mockNotificationFromBackend(...args), + success: (...args: unknown[]) => mockNotificationSuccess(...args), + }, +})); + const makeToken = (overrides: Partial = {}): KeyResponse => ({ token: "token-hash-123", @@ -297,6 +306,7 @@ describe("RegenerateKeyModal", () => { expect(screen.getByText("Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo")).toBeInTheDocument(); }); expect(mockRegenerateKeyCall).not.toHaveBeenCalled(); + expect(mockNotificationFromBackend).not.toHaveBeenCalled(); }); it("should pass form values to onKeyUpdate even when the API echoes back different limits", async () => { @@ -401,6 +411,8 @@ describe("RegenerateKeyModal", () => { expect(screen.getByText("Expiration is required for expired keys")).toBeInTheDocument(); }); expect(mockRegenerateKeyCall).not.toHaveBeenCalled(); + // Form validation rejections must not surface a backend-style toast. + expect(mockNotificationFromBackend).not.toHaveBeenCalled(); }); it("should pass the correct token identifier to regenerateKeyCall", async () => { diff --git a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx index 056ded2af555..8138614982a3 100644 --- a/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx +++ b/ui/litellm-dashboard/src/components/organisms/RegenerateKeyModal.tsx @@ -87,9 +87,14 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat setIsRegenerating(false); } catch (error) { + setIsRegenerating(false); // Reset regenerating state on error + // Ant Design form validation rejections surface inline under the field; + // don't also raise a backend-style toast for them. + if (error && typeof error === "object" && "errorFields" in error) { + return; + } console.error("Error regenerating key:", error); NotificationManager.fromBackend(error); - setIsRegenerating(false); // Reset regenerating state on error } };