Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<RegenerateKeyModal {...defaultProps} selectedToken={makeToken({ expires: previousExpires })} />,
);
renderWithProviders(<RegenerateKeyModal {...defaultProps} />);

const durationField = screen.getByPlaceholderText("e.g. 30s, 30h, 30d");
await user.clear(durationField);
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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(
<RegenerateKeyModal
{...defaultProps}
selectedToken={makeToken({ expires: "2026-06-01T12:00:00Z", duration: "" })}
/>,
);

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(
<RegenerateKeyModal
{...defaultProps}
selectedToken={makeToken({ expires: "2026-06-01T12:00:00Z", duration: "" })}
/>,
);

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({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -21,11 +27,18 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat
const { accessToken } = useAuthorized();
const [form] = Form.useForm();
const [regeneratedKey, setRegeneratedKey] = useState<string | null>(null);
const [regenerateFormData, setRegenerateFormData] = useState<any>(null);
const [newExpiryTime, setNewExpiryTime] = useState<string | null>(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({
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -193,16 +200,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat
</Flex>
</Flex>
) : (
<Form
form={form}
layout="vertical"
style={{ marginTop: 4 }}
onValuesChange={(changedValues) => {
if ("duration" in changedValues) {
setRegenerateFormData((prev: { duration?: string }) => ({ ...prev, duration: changedValues.duration }));
}
}}
>
<Form form={form} layout="vertical" style={{ marginTop: 4 }}>
<Form.Item name="key_alias" label="Key Alias">
<Input disabled />
</Form.Item>
Expand Down Expand Up @@ -230,11 +228,13 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat
<Form.Item
name="duration"
label="Expire Key"
rules={durationRules}
extra={
<Flex vertical gap={2}>
<Text type="secondary" style={{ fontSize: 12 }}>
<Text type={keyIsExpired ? "danger" : "secondary"} style={{ fontSize: 12 }}>
Current expiry:{" "}
{selectedToken?.expires ? new Date(selectedToken.expires).toLocaleString() : "Never"}
{keyIsExpired && " (expired)"}
</Text>
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
{newExpiryTime && (
<Text type="success" style={{ fontSize: 12 }}>
Expand All @@ -257,12 +257,7 @@ export function RegenerateKeyModal({ selectedToken, visible, onClose, onKeyUpdat
Recommended: 24h to 72h for production keys
</Text>
}
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]}
>
<Input placeholder="e.g. 24h, 2d" />
</Form.Item>
Expand Down
30 changes: 30 additions & 0 deletions ui/litellm-dashboard/src/utils/keyExpiryUtils.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
21 changes: 21 additions & 0 deletions ui/litellm-dashboard/src/utils/keyExpiryUtils.ts
Original file line number Diff line number Diff line change
@@ -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();
}
Loading