Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(gateway): add API key expiration (#18561)

Tobias Wochinger9bd9eb5bdba9
diff --git a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts b/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts
index 650beb080d..eb4eda3814 100644
--- a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts
+++ b/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts
@@ -334,17 +334,19 @@ describe("AI gateway control plane", () => {
it("creates, lists, and revokes only associated organization keys", async () => {
const { caller, org } = await prepare();
+ const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
const created = await caller.aiGateway.createApiKey({
orgId: org.id,
name: "Production gateway",
metadata: { environment: "production", costCenter: 42 },
+ expiresAt,
});
expect(created.secretKey).toMatch(/^sk-lf-/);
const listed = await caller.aiGateway.listApiKeys({ orgId: org.id });
expect(listed.data).toHaveLength(1);
expect(listed.data[0]).toMatchObject({
- apiKey: { id: created.id, note: "Production gateway" },
+ apiKey: { id: created.id, note: "Production gateway", expiresAt },
metadata: { environment: "production", costCenter: 42 },
});
expect(JSON.stringify(listed)).not.toContain(created.secretKey);
@@ -370,6 +372,18 @@ describe("AI gateway control plane", () => {
).rejects.toThrow("Gateway API key not found");
});
+ it("rejects gateway API key expiration dates in the past", async () => {
+ const { caller, org } = await prepare();
+
+ await expect(
+ caller.aiGateway.createApiKey({
+ orgId: org.id,
+ metadata: {},
+ expiresAt: new Date(Date.now() - 1_000),
+ }),
+ ).rejects.toThrow("Expiration date must be in the future");
+ });
+
it("owns successful and failed mutation auditing in gateway services", async () => {
const { org, project, session } = await prepare();
const gatewayService = new GatewayConfigService(prisma);
diff --git a/web/src/__tests__/server/unit/gatewayResolveCache.servertest.ts b/web/src/__tests__/server/unit/gatewayResolveCache.servertest.ts
new file mode 100644
index 0000000000..c935496ebc
--- /dev/null
+++ b/web/src/__tests__/server/unit/gatewayResolveCache.servertest.ts
@@ -0,0 +1,75 @@
+import type { Redis } from "ioredis";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ type CachedResolveContext,
+ GatewayResolveCache,
+} from "@/src/features/ai-gateway/server/resolve/gatewayResolveCache";
+
+vi.mock("@/src/env.mjs", () => ({
+ env: {
+ LANGFUSE_AI_GATEWAY_CACHE_RESOLVE_ENABLED: "true",
+ LANGFUSE_AI_GATEWAY_CACHE_RESOLVE_TTL_SECONDS: 300,
+ },
+}));
+
+const context: CachedResolveContext = {
+ organizationId: "org-1",
+ apiKeyId: "key-1",
+ keyMetadata: {},
+ ingestionProjectId: null,
+ ingestionMode: null,
+ connection: null,
+};
+
+describe("GatewayResolveCache", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("does not cache a resolve context beyond the API key expiration", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-10-09T15:00:00.000Z"));
+ const redis = {
+ set: vi.fn().mockResolvedValue("OK"),
+ sadd: vi.fn().mockResolvedValue(1),
+ expire: vi.fn().mockResolvedValue(1),
+ } as unknown as Redis;
+
+ await new GatewayResolveCache(redis).set({
+ fastHashedSecretKey: "hashed-key",
+ apiFormat: "openai.responses",
+ context,
+ expiresAt: new Date("2026-10-09T15:00:10.000Z"),
+ });
+
+ expect(redis.set).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.any(String),
+ "PXAT",
+ new Date("2026-10-09T15:00:10.000Z").getTime(),
+ );
+ expect(redis.expire).toHaveBeenCalledWith(expect.any(String), 600);
+ });
+
+ it("skips caching a context when the API key has expired", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-10-09T15:00:00.000Z"));
+ const redis = {
+ set: vi.fn(),
+ sadd: vi.fn(),
+ expire: vi.fn(),
+ } as unknown as Redis;
+
+ await new GatewayResolveCache(redis).set({
+ fastHashedSecretKey: "hashed-key",
+ apiFormat: "openai.responses",
+ context,
+ expiresAt: new Date("2026-10-09T14:59:59.000Z"),
+ });
+
+ expect(redis.set).not.toHaveBeenCalled();
+ expect(redis.sadd).not.toHaveBeenCalled();
+ expect(redis.expire).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/components/design-system/Input/Input.tsx b/web/src/components/design-system/Input/Input.tsx
index 81472b2426..3b21ccf8a1 100644
--- a/web/src/components/design-system/Input/Input.tsx
+++ b/web/src/components/design-system/Input/Input.tsx
@@ -17,6 +17,7 @@ type InputProps = Pick<
| "id"
| "inputMode"
| "maxLength"
+ | "min"
| "minLength"
| "name"
| "onBlur"
diff --git a/web/src/components/design-system/SelectDropdown/SelectDropdown.tsx b/web/src/components/design-system/SelectDropdown/SelectDropdown.tsx
index 03156aea98..d722fd65e2 100644
--- a/web/src/components/design-system/SelectDropdown/SelectDropdown.tsx
+++ b/web/src/components/design-system/SelectDropdown/SelectDropdown.tsx
@@ -79,7 +79,7 @@ export function SelectDropdown<V extends string>({
...triggerProps
}: {
value: V;
- options: SelectNode<V>[];
+ options: readonly SelectNode<V>[];
onValueChange: (value: V) => void;
emptyMessage?: string;
children: (
diff --git a/web/src/components/design-system/table/columns/createDateTableColumn.stories.tsx b/web/src/components/design-system/table/columns/createDateTableColumn.stories.tsx
index 6d8133c92b..75c9043886 100644
--- a/web/src/components/design-system/table/columns/createDateTableColumn.stories.tsx
+++ b/web/src/components/design-system/table/columns/createDateTableColumn.stories.tsx
@@ -1,3 +1,5 @@
+import type { ReactNode } from "react";
+
import preview from "../../../../../.storybook/preview";
import {
@@ -10,15 +12,22 @@ type Row = {
timestamp: Date | null;
};
-const columns = [
- createDateTableColumn<Row>({
- id: "timestamp",
- accessorFn: (row) => row.timestamp,
- header: "Date",
- }),
-];
+function DateTableColumnStory({
+ data,
+ getPrefix,
+}: {
+ data: AsyncTableData<Row[]>;
+ getPrefix?: (value: Date) => ReactNode;
+}) {
+ const columns = [
+ createDateTableColumn<Row>({
+ id: "timestamp",
+ accessorFn: (row) => row.timestamp,
+ header: "Date",
+ getPrefix,
+ }),
+ ];
-function DateTableColumnStory({ data }: { data: AsyncTableData<Row[]> }) {
return (
<DataTable
tableName="date-column-story"
@@ -58,6 +67,18 @@ export const EmptyValue = meta.story({
},
});
+export const WithPrefix = meta.story({
+ name: "With Prefix",
+ args: {
+ data: {
+ isLoading: false,
+ isError: false,
+ data: [{ timestamp: new Date("2026-01-15T10:30:00.000Z") }],
+ },
+ getPrefix: () => "Started on ",
+ },
+});
+
export const Loading = meta.story({
args: {
data: {
diff --git a/web/src/components/design-system/table/columns/createDateTableColumn.tsx b/web/src/components/design-system/table/columns/createDateTableColumn.tsx
index 45858aadfb..759afb94ea 100644
--- a/web/src/components/design-system/table/columns/createDateTableColumn.tsx
+++ b/web/src/components/design-system/table/columns/createDateTableColumn.tsx
@@ -1,6 +1,7 @@
/* eslint-disable boundaries/dependencies */
import { type CellContext, type RowData } from "@tanstack/react-table";
import { formatDistanceToNow } from "date-fns";
+import type { ReactNode } from "react";
import { buildLocalIsoDatePresentation } from "@/src/utils/dates";
import { Skeleton } from "@/src/components/ui/skeleton";
@@ -13,6 +14,7 @@ export function createDateTableColumn<TData extends RowData>({
getValue,
mode = "absolute",
emptyValue,
+ getPrefix,
...options
}: TableColumnOptions<TData, Date> & {
getValue?: (
@@ -21,6 +23,7 @@ export function createDateTableColumn<TData extends RowData>({
) => Date | { type: "loading" } | undefined;
mode?: "absolute" | "relative";
emptyValue?: string;
+ getPrefix?: (value: Date) => ReactNode;
}) {
return createTableColumn<TData, Date>({
...options,
@@ -44,6 +47,7 @@ export function createDateTableColumn<TData extends RowData>({
return preparedDate ? (
<span className="block w-full truncate" title={preparedDate.title}>
+ {getPrefix?.(resolvedValue)}
{mode === "relative"
? formatDistanceToNow(resolvedValue, { addSuffix: true })
: preparedDate.display}
diff --git a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx
index 99355cd6f3..a77f295a0f 100644
--- a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx
+++ b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx
@@ -18,6 +18,11 @@ import {
import { InfoTooltip } from "@/src/components/ui/InfoTooltip/InfoTooltip";
import { Input } from "@/src/components/ui/input";
import { Label } from "@/src/components/ui/label";
+import {
+ ApiKeyExpirationInput,
+ type ApiKeyExpirationPreset,
+ resolveApiKeyExpiration,
+} from "@/src/features/apiKey";
import { GeneratedKeyContent } from "@/src/features/ai-gateway/components/GatewayApiKeysPage/components/GeneratedKeyContent";
import {
api,
@@ -39,6 +44,9 @@ export function CreateGatewayApiKeyDialogController({
children: (control: { openDialog: () => void }) => ReactNode;
}) {
const [name, setName] = useState("");
+ const [expiryPreset, setExpiryPreset] =
+ useState<ApiKeyExpirationPreset>("never");
+ const [customExpiry, setCustomExpiry] = useState("");
const [metadata, setMetadata] = useState<MetadataField[]>(() => [
{ id: 1, key: "", value: "" },
]);
@@ -56,6 +64,8 @@ export function CreateGatewayApiKeyDialogController({
const reset = () => {
setName("");
+ setExpiryPreset("never");
+ setCustomExpiry("");
setMetadata([{ id: 1, key: "", value: "" }]);
setIsMetadataOpen(false);
setGeneratedKeys(null);
@@ -63,8 +73,10 @@ export function CreateGatewayApiKeyDialogController({
};
const metadataCount = metadata.filter((field) => field.key.trim()).length;
+ const expiresAt = resolveApiKeyExpiration(expiryPreset, customExpiry);
const submit = async () => {
+ if (expiresAt === undefined) return;
const metadataObject = Object.fromEntries(
metadata
.filter((field) => field.key.trim())
@@ -75,6 +87,7 @@ export function CreateGatewayApiKeyDialogController({
orgId: organizationId,
name: name.trim() || undefined,
metadata: metadataObject,
+ expiresAt,
});
setGeneratedKeys({
publicKey: created.publicKey,
@@ -126,6 +139,13 @@ export function CreateGatewayApiKeyDialogController({
onChange={(event) => setName(event.target.value)}
/>
</div>
+ <ApiKeyExpirationInput
+ id="gateway-key-expiry"
+ expiryPreset={expiryPreset}
+ customExpiry={customExpiry}
+ onExpiryPresetChange={setExpiryPreset}
+ onCustomExpiryChange={setCustomExpiry}
+ />
<Collapsible
open={isMetadataOpen}
onOpenChange={setIsMetadataOpen}
@@ -231,7 +251,7 @@ export function CreateGatewayApiKeyDialogController({
</Button>
<Button
loading={create.isPending}
- disabled={create.isPending}
+ disabled={create.isPending || expiresAt === undefined}
onClick={submit}
>
Create key
diff --git a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.stories.tsx b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.stories.tsx
index a7ef89adbf..121c1d2924 100644
--- a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.stories.tsx
+++ b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.stories.tsx
@@ -19,6 +19,7 @@ const apiKeys = [
displaySecretKey: "sk-lf-gw-...91bc",
note: "Production application",
createdAt: new Date("2026-09-04T12:00:00.000Z"),
+ expiresAt: new Date("2027-09-04T23:59:59.999Z"),
},
},
] satisfies Extract<
@@ -37,6 +38,7 @@ const manyApiKeys = Array.from({ length: 30 }, (_, index) => ({
displaySecretKey: `sk-lf-gw-...${String(index + 1).padStart(4, "0")}`,
note: `Application ${index + 1}`,
createdAt: new Date(Date.UTC(2026, 8, 4 - (index % 28))),
+ expiresAt: null,
},
})) satisfies Extract<
ComponentProps<typeof GatewayApiKeysTable>["data"],
@@ -67,7 +69,7 @@ export const PopulatedMetadata = meta.story({
play: async ({ canvas }) => {
const cells = canvas.getAllByRole("row")[1]!.querySelectorAll("td");
await expect(cells[1]).toHaveClass("ph-no-capture");
- await expect(cells[3]).toHaveClass("ph-no-capture");
+ await expect(cells[4]).toHaveClass("ph-no-capture");
},
});
@@ -98,7 +100,7 @@ export const OverflowingMetadata = meta.story({
play: async ({ canvas }) => {
const metadataCell = canvas
.getAllByRole("row")[1]!
- .querySelectorAll("td")[3]!;
+ .querySelectorAll("td")[4]!;
await waitFor(() => {
expect(metadataCell).toHaveTextContent(/\+\d+/);
});
diff --git a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsx b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsx
index 9483a5f631..75e327e7cb 100644
--- a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsx
+++ b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsx
@@ -7,6 +7,7 @@ import { createBadgeListTableColumn } from "@/src/components/design-system/table
import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";
import type { AsyncTableData } from "@/src/components/design-system/table/Table";
import type { LangfuseColumnDef } from "@/src/components/table/types";
+import { isApiKeyExpired } from "@/src/features/apiKey";
type GatewayApiKey = {
metadata: unknown;
@@ -16,6 +17,7 @@ type GatewayApiKey = {
displaySecretKey: string;
note: string | null;
createdAt: Date;
+ expiresAt: Date | null;
};
};
@@ -51,6 +53,16 @@ export function GatewayApiKeysTable({
nullValue: "-",
enableResizing: false,
}),
+ createDateTableColumn<GatewayApiKey>({
+ accessorFn: (row) => row.apiKey.expiresAt,
+ id: "expiresAt",
+ header: "Expiration",
+ hideBelowMd: true,
+ enableResizing: false,
+ emptyValue: "No expiration",
+ getPrefix: (expiresAt) =>
+ isApiKeyExpired(expiresAt) ? "Expired on " : null,
+ }),
createBadgeListTableColumn<GatewayApiKey>({
accessorFn: (row) => getMetadataEntries(row.metadata),
id: "metadata",
diff --git a/web/src/features/ai-gateway/components/gatewayMutationErrors.clienttest.tsx b/web/src/features/ai-gateway/components/gatewayMutationErrors.clienttest.tsx
index 510a0c2579..684c64dbfb 100644
--- a/web/src/features/ai-gateway/components/gatewayMutationErrors.clienttest.tsx
+++ b/web/src/features/ai-gateway/components/gatewayMutationErrors.clienttest.tsx
@@ -371,8 +371,9 @@ describe("gateway mutation local error handling", () => {
).toBeInTheDocument();
expect(createApiKeyMutateAsync).toHaveBeenCalledWith({
orgId: "org-1",
- note: undefined,
+ name: undefined,
metadata: {},
+ expiresAt: null,
});
});
});
diff --git a/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts b/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts
index 468e996d85..62ba613aec 100644
--- a/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts
+++ b/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts
@@ -31,6 +31,7 @@ export class GatewayApiKeyService {
organizationId: string;
name?: string;
metadata: GatewayMetadata;
+ expiresAt?: Date | null;
session: OrgAuthedContext["session"];
}) {
const key = await this.prisma.$transaction(async (tx) => {
@@ -39,6 +40,7 @@ export class GatewayApiKeyService {
role: SystemRoleId("AI_GATEWAY"),
createdBy: UserId(params.session.user.id),
name: params.name,
+ expiresAt: params.expiresAt,
});
await tx.gatewayApiKeyAssociation.create({
data: {
@@ -59,6 +61,7 @@ export class GatewayApiKeyService {
publicKey: key.publicKey,
displaySecretKey: key.displaySecretKey,
note: key.note,
+ expiresAt: params.expiresAt ?? null,
},
},
this.prisma,
diff --git a/web/src/features/ai-gateway/server/auth/gatewayApiKeyAuthenticator.ts b/web/src/features/ai-gateway/server/auth/gatewayApiKeyAuthenticator.ts
index 44e22d1a30..ff88a662b7 100644
--- a/web/src/features/ai-gateway/server/auth/gatewayApiKeyAuthenticator.ts
+++ b/web/src/features/ai-gateway/server/auth/gatewayApiKeyAuthenticator.ts
@@ -101,7 +101,11 @@ export class GatewayApiKeyAuthenticator {
: null,
};
- await this.cache.set({ ...params, context });
+ await this.cache.set({
+ ...params,
+ context,
+ expiresAt: row.apiKey.expiresAt,
+ });
return context;
}
}
diff --git a/web/src/features/ai-gateway/server/availability.servertest.ts b/web/src/features/ai-gateway/server/availability.servertest.ts
index 8c1d73daa2..38e75f1326 100644
--- a/web/src/features/ai-gateway/server/availability.servertest.ts
+++ b/web/src/features/ai-gateway/server/availability.servertest.ts
@@ -30,4 +30,13 @@ describe("gateway organization allowlist", () => {
}),
).toThrow(ForbiddenError);
});
+
+ it("enables the gateway in preview deployments", () => {
+ expect(
+ isGatewayEnabledForOrganization("org-not-allowed", [], {
+ nodeEnv: "production",
+ previewPrUrl: "https://github.com/langfuse/langfuse/pull/18561",
+ }),
+ ).toBe(true);
+ });
});
diff --git a/web/src/features/ai-gateway/server/availability.ts b/web/src/features/ai-gateway/server/availability.ts
index 10ca3b1385..7b00fcae3d 100644
--- a/web/src/features/ai-gateway/server/availability.ts
+++ b/web/src/features/ai-gateway/server/availability.ts
@@ -4,11 +4,13 @@ import { env } from "@/src/env.mjs";
type GatewayAvailabilityEnvironment = {
nodeEnv: string | undefined;
+ previewPrUrl?: string;
};
const getGatewayAvailabilityEnvironment =
(): GatewayAvailabilityEnvironment => ({
nodeEnv: env.NODE_ENV,
+ previewPrUrl: env.NEXT_PUBLIC_PREVIEW_PR_URL,
});
export const isGatewayEnabledForOrganization = (
@@ -18,6 +20,7 @@ export const isGatewayEnabledForOrganization = (
environment = getGatewayAvailabilityEnvironment(),
): boolean =>
environment.nodeEnv === "development" ||
+ environment.previewPrUrl !== undefined ||
allowedOrganizationIds.includes(organizationId);
export const requireGatewayEnabledForOrganization = (
diff --git a/web/src/features/ai-gateway/server/resolve/gatewayResolveCache.ts b/web/src/features/ai-gateway/server/resolve/gatewayResolveCache.ts
index 5186f1ce98..f905c1be27 100644
--- a/web/src/features/ai-gateway/server/resolve/gatewayResolveCache.ts
+++ b/web/src/features/ai-gateway/server/resolve/gatewayResolveCache.ts
@@ -104,14 +104,26 @@ export class GatewayResolveCache {
fastHashedSecretKey: string;
apiFormat: string;
context: CachedResolveContext | typeof GATEWAY_RESOLVE_KEY_NON_EXISTENT;
+ expiresAt?: Date | null;
}) {
if (!this.enabled) return;
const key = contextCacheKey(params.fastHashedSecretKey, params.apiFormat);
- const ttl = env.LANGFUSE_AI_GATEWAY_CACHE_RESOLVE_TTL_SECONDS;
+ const configuredTtl = env.LANGFUSE_AI_GATEWAY_CACHE_RESOLVE_TTL_SECONDS;
+ const now = Date.now();
+ const expirationTimestamp = Math.min(
+ now + configuredTtl * 1000,
+ params.expiresAt?.getTime() ?? Number.POSITIVE_INFINITY,
+ );
+ if (expirationTimestamp <= now) return;
try {
if (params.context === GATEWAY_RESOLVE_KEY_NON_EXISTENT) {
- await this.redis!.set(key, JSON.stringify(params.context), "EX", ttl);
+ await this.redis!.set(
+ key,
+ JSON.stringify(params.context),
+ "PXAT",
+ expirationTimestamp,
+ );
return;
}
@@ -119,11 +131,16 @@ export class GatewayResolveCache {
// commands separately instead of wrapping them in one transaction.
const index = organizationIndexKey(params.context.organizationId);
await Promise.all([
- this.redis!.set(key, JSON.stringify(params.context), "EX", ttl),
+ this.redis!.set(
+ key,
+ JSON.stringify(params.context),
+ "PXAT",
+ expirationTimestamp,
+ ),
this.redis!.sadd(index, key),
// The index must outlive its entries, otherwise invalidation can miss a
// cached key that is still live.
- this.redis!.expire(index, ttl * 2),
+ this.redis!.expire(index, configuredTtl * 2),
]);
} catch (error) {
logger.error("Error writing gateway resolve cache", error);
diff --git a/web/src/features/ai-gateway/server/resolve/gatewayResolveRepository.ts b/web/src/features/ai-gateway/server/resolve/gatewayResolveRepository.ts
index 0351dde840..22360c2897 100644
--- a/web/src/features/ai-gateway/server/resolve/gatewayResolveRepository.ts
+++ b/web/src/features/ai-gateway/server/resolve/gatewayResolveRepository.ts
@@ -24,6 +24,7 @@ export class GatewayResolveRepository {
apiKey: {
select: {
orgId: true,
+ expiresAt: true,
organization: {
select: {
gatewayConfig: {
diff --git a/web/src/features/ai-gateway/server/router.ts b/web/src/features/ai-gateway/server/router.ts
index 7cbd80b446..fd40068614 100644
--- a/web/src/features/ai-gateway/server/router.ts
+++ b/web/src/features/ai-gateway/server/router.ts
@@ -217,6 +217,12 @@ export const aiGatewayRouter = createTRPCRouter({
organizationInput.extend({
name: z.string().max(500).optional(),
metadata: GatewayMetadataSchema.default({}),
+ expiresAt: z
+ .date()
+ .nullish()
+ .refine((date) => date == null || date.getTime() > Date.now(), {
+ message: "Expiration date must be in the future",
+ }),
}),
)
.mutation(async ({ input, ctx }) => {
@@ -225,6 +231,7 @@ export const aiGatewayRouter = createTRPCRouter({
organizationId: input.orgId,
name: input.name,
metadata: input.metadata,
+ expiresAt: input.expiresAt,
session: ctx.session,
});
return key;
diff --git a/web/src/features/apiKey/components/ApiKeyExpirationInput/ApiKeyExpirationInput.stories.tsx b/web/src/features/apiKey/components/ApiKeyExpirationInput/ApiKeyExpirationInput.stories.tsx
new file mode 100644
index 0000000000..ec41db312b
--- /dev/null
+++ b/web/src/features/apiKey/components/ApiKeyExpirationInput/ApiKeyExpirationInput.stories.tsx
@@ -0,0 +1,73 @@
+import { useState } from "react";
+import { expect, fn, userEvent, within } from "storybook/test";
+
+import preview from "../../../../../.storybook/preview";
+import { ApiKeyExpirationInput } from "./ApiKeyExpirationInput";
+import type { ApiKeyExpirationPreset } from "@/src/features/apiKey/constants/apiKeyExpirationOptions";
+
+const meta = preview.meta({
+ component: ApiKeyExpirationInput,
+});
+
+export const Default = meta.story({
+ args: {
+ id: "api-key-expiration-default",
+ expiryPreset: "never",
+ customExpiry: "",
+ onExpiryPresetChange: fn(),
+ onCustomExpiryChange: fn(),
+ },
+});
+
+export const CustomDate = meta.story({
+ args: {
+ id: "api-key-expiration-custom",
+ expiryPreset: "custom",
+ customExpiry: "2026-12-31",
+ onExpiryPresetChange: fn(),
+ onCustomExpiryChange: fn(),
+ },
+});
+
+export const SelectsCustomDate = meta.story({
+ name: "(Test) Selects Custom Date",
+ args: {
+ id: "api-key-expiration-interactive",
+ expiryPreset: "never",
+ customExpiry: "",
+ onExpiryPresetChange: fn(),
+ onCustomExpiryChange: fn(),
+ },
+ render: (args) => {
+ const [expiryPreset, setExpiryPreset] =
+ useState<ApiKeyExpirationPreset>("never");
+ const [customExpiry, setCustomExpiry] = useState("");
+
+ const handleExpiryPresetChange = (value: ApiKeyExpirationPreset) => {
+ setExpiryPreset(value);
+ args.onExpiryPresetChange(value);
+ };
+ const handleCustomExpiryChange = (value: string) => {
+ setCustomExpiry(value);
+ args.onCustomExpiryChange(value);
+ };
+
+ return (
+ <ApiKeyExpirationInput
+ {...args}
+ expiryPreset={expiryPreset}
+ customExpiry={customExpiry}
+ onExpiryPresetChange={handleExpiryPresetChange}
+ onCustomExpiryChange={handleCustomExpiryChange}
+ />
+ );
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(canvas.getByRole("combobox"));
+ await userEvent.click(body.getByRole("option", { name: "Custom date…" }));
+ await expect(canvas.getByLabelText("Custom expiration date")).toBeVisible();
+ },
+});
diff --git a/web/src/features/apiKey/components/ApiKeyExpirationInput/ApiKeyExpirationInput.tsx b/web/src/features/apiKey/components/ApiKeyExpirationInput/ApiKeyExpirationInput.tsx
new file mode 100644
index 0000000000..91ed9cbe2a
--- /dev/null
+++ b/web/src/features/apiKey/components/ApiKeyExpirationInput/ApiKeyExpirationInput.tsx
@@ -0,0 +1,54 @@
+import type { ChangeEvent } from "react";
+
+import { Input } from "@/src/components/design-system/Input/Input";
+import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";
+import { Label } from "@/src/components/ui/label";
+import {
+ apiKeyExpirationOptions,
+ type ApiKeyExpirationPreset,
+} from "@/src/features/apiKey/constants/apiKeyExpirationOptions";
+import { localDateInputValue } from "@/src/features/apiKey/fns/localDateInputValue";
+
+type ApiKeyExpirationInputProps = {
+ id: string;
+ expiryPreset: ApiKeyExpirationPreset;
+ customExpiry: string;
+ onExpiryPresetChange: (value: ApiKeyExpirationPreset) => void;
+ onCustomExpiryChange: (value: string) => void;
+};
+
+export function ApiKeyExpirationInput({
+ id,
+ expiryPreset,
+ customExpiry,
+ onExpiryPresetChange,
+ onCustomExpiryChange,
+}: ApiKeyExpirationInputProps) {
+ const handleCustomExpiryChange = (event: ChangeEvent<HTMLInputElement>) => {
+ onCustomExpiryChange(event.target.value);
+ };
+
+ return (
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor={id}>Expiration</Label>
+ <div className="flex gap-2">
+ <SelectInput
+ id={id}
+ value={expiryPreset}
+ options={apiKeyExpirationOptions}
+ placeholder="Select expiration"
+ onValueChange={onExpiryPresetChange}
+ />
+ {expiryPreset === "custom" ? (
+ <Input
+ type="date"
+ aria-label="Custom expiration date"
+ min={localDateInputValue(new Date())}
+ value={customExpiry}
+ onChange={handleCustomExpiryChange}
+ />
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/features/apiKey/constants/apiKeyExpirationOptions.ts b/web/src/features/apiKey/constants/apiKeyExpirationOptions.ts
new file mode 100644
index 0000000000..db8cf7f5ce
--- /dev/null
+++ b/web/src/features/apiKey/constants/apiKeyExpirationOptions.ts
@@ -0,0 +1,11 @@
+export const apiKeyExpirationOptions = [
+ { value: "never", label: "No expiration", days: null },
+ { value: "30d", label: "30 days", days: 30 },
+ { value: "60d", label: "60 days", days: 60 },
+ { value: "90d", label: "90 days", days: 90 },
+ { value: "1y", label: "1 year", days: 365 },
+ { value: "custom", label: "Custom date…", days: null },
+] as const;
+
+export type ApiKeyExpirationPreset =
+ (typeof apiKeyExpirationOptions)[number]["value"];
diff --git a/web/src/features/apiKey/fns/localDateInputValue.ts b/web/src/features/apiKey/fns/localDateInputValue.ts
new file mode 100644
index 0000000000..39f06e5236
--- /dev/null
+++ b/web/src/features/apiKey/fns/localDateInputValue.ts
@@ -0,0 +1,6 @@
+export const localDateInputValue = (date: Date) =>
+ [
+ date.getFullYear(),
+ String(date.getMonth() + 1).padStart(2, "0"),
+ String(date.getDate()).padStart(2, "0"),
+ ].join("-");
diff --git a/web/src/features/apiKey/fns/resolveApiKeyExpiration.clienttest.ts b/web/src/features/apiKey/fns/resolveApiKeyExpiration.clienttest.ts
new file mode 100644
index 0000000000..abf9d2bcc4
--- /dev/null
+++ b/web/src/features/apiKey/fns/resolveApiKeyExpiration.clienttest.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+
+import { resolveApiKeyExpiration } from "./resolveApiKeyExpiration";
+
+describe("resolveApiKeyExpiration", () => {
+ const now = new Date("2026-01-01T00:00:00.000Z");
+
+ it("returns null when the key never expires", () => {
+ expect(resolveApiKeyExpiration("never", "", now)).toBeNull();
+ });
+
+ it("offsets a preset by its day count from now", () => {
+ expect(resolveApiKeyExpiration("30d", "", now)).toEqual(
+ new Date("2026-01-31T00:00:00.000Z"),
+ );
+ expect(resolveApiKeyExpiration("1y", "", now)).toEqual(
+ new Date("2027-01-01T00:00:00.000Z"),
+ );
+ });
+
+ it("expires a custom date at the end of that local day", () => {
+ expect(resolveApiKeyExpiration("custom", "2026-06-15", now)).toEqual(
+ new Date(2026, 5, 15, 23, 59, 59, 999),
+ );
+ });
+
+ it("leaves a missing, invalid, or past custom date unresolved", () => {
+ expect(resolveApiKeyExpiration("custom", "", now)).toBeUndefined();
+ expect(
+ resolveApiKeyExpiration("custom", "not-a-date", now),
+ ).toBeUndefined();
+ expect(
+ resolveApiKeyExpiration("custom", "2026-02-30", now),
+ ).toBeUndefined();
+ expect(
+ resolveApiKeyExpiration("custom", "2025-12-01", now),
+ ).toBeUndefined();
+ });
+});
diff --git a/web/src/features/apiKey/fns/resolveApiKeyExpiration.ts b/web/src/features/apiKey/fns/resolveApiKeyExpiration.ts
new file mode 100644
index 0000000000..35be4e1308
--- /dev/null
+++ b/web/src/features/apiKey/fns/resolveApiKeyExpiration.ts
@@ -0,0 +1,30 @@
+import {
+ apiKeyExpirationOptions,
+ type ApiKeyExpirationPreset,
+} from "@/src/features/apiKey/constants/apiKeyExpirationOptions";
+
+const MS_PER_DAY = 24 * 60 * 60 * 1000;
+
+/** Resolves an expiration preset to an absolute date, null for no expiration, or undefined for an invalid custom date. */
+export const resolveApiKeyExpiration = (
+ preset: ApiKeyExpirationPreset,
+ customDate: string,
+ now: Date = new Date(),
+): Date | null | undefined => {
+ if (preset === "custom") return parseCustomExpiry(customDate, now);
+ const days =
+ apiKeyExpirationOptions.find((option) => option.value === preset)?.days ??
+ null;
+ if (days === null) return null;
+ return new Date(now.getTime() + days * MS_PER_DAY);
+};
+
+const parseCustomExpiry = (customDate: string, now: Date): Date | undefined => {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(customDate);
+ if (!match) return undefined;
+ const [year, month, day] = [match[1], match[2], match[3]].map(Number);
+ const endOfDay = new Date(year, month - 1, day, 23, 59, 59, 999);
+ const isRealDate =
+ endOfDay.getMonth() === month - 1 && endOfDay.getDate() === day;
+ return isRealDate && endOfDay > now ? endOfDay : undefined;
+};
diff --git a/web/src/features/apiKey/index.ts b/web/src/features/apiKey/index.ts
new file mode 100644
index 0000000000..128b8c90eb
--- /dev/null
+++ b/web/src/features/apiKey/index.ts
@@ -0,0 +1,4 @@
+export { ApiKeyExpirationInput } from "@/src/features/apiKey/components/ApiKeyExpirationInput/ApiKeyExpirationInput";
+export type { ApiKeyExpirationPreset } from "@/src/features/apiKey/constants/apiKeyExpirationOptions";
+export { resolveApiKeyExpiration } from "@/src/features/apiKey/fns/resolveApiKeyExpiration";
+export { isApiKeyExpired } from "@/src/features/apiKey/helpers/isApiKeyExpired";
diff --git a/web/src/features/organizations/OrganizationSettingsPage.tsx b/web/src/features/organizations/OrganizationSettingsPage.tsx
index 5b7002054a..5bc6ee3a4a 100644
--- a/web/src/features/organizations/OrganizationSettingsPage.tsx
+++ b/web/src/features/organizations/OrganizationSettingsPage.tsx
@@ -300,7 +300,7 @@ export const getOrganizationSettingsPages = ({
show: showAiGateway,
},
{
- title: "Gateway API keys",
+ title: "Gateway keys",
slug: "ai-gateway-api-keys",
section: "AI Gateway",
cmdKKeywords: ["gateway", "api", "keys", "metadata", "credentials"],
diff --git a/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx b/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx
index 8e95861898..46cb3f2648 100644
--- a/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx
+++ b/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx
@@ -21,21 +21,18 @@ import { Label } from "@/src/components/ui/label";
import {
Select,
SelectContent,
- SelectItem,
SelectTrigger,
- SelectValue,
} from "@/src/components/ui/select";
+import {
+ ApiKeyExpirationInput,
+ type ApiKeyExpirationPreset,
+ resolveApiKeyExpiration,
+} from "@/src/features/apiKey";
import { ApiKeyDetailContent } from "@/src/features/public-api/components/ApiKeyDetailContent";
import { rolePermissionCountLabel } from "@/src/features/rbac/components/RolePermissionList";
import { RolePermissionPopup } from "@/src/features/rbac/components/RolePermissionPopup";
import { RoleSelectItem } from "@/src/features/rbac/components/RoleSelectItem";
import { roleIcons } from "@/src/features/rbac/components/roleIcons";
-import {
- expiryPresetOptions,
- localDateInputValue,
- resolveExpiresAt,
- type ExpiryPreset,
-} from "@/src/features/public-api/components/apiKeyFormOptions";
type ApiKeyScope = "project" | "organization";
@@ -105,7 +102,8 @@ function ApiKeyCreateForm({
const [name, setName] = useState("");
const [role, setRole] = useState<SystemRole>(DEFAULT_ROLE);
- const [expiryPreset, setExpiryPreset] = useState<ExpiryPreset>("never");
+ const [expiryPreset, setExpiryPreset] =
+ useState<ApiKeyExpirationPreset>("never");
const [customExpiry, setCustomExpiry] = useState("");
const [roleSelectOpen, setRoleSelectOpen] = useState(false);
const [permissionsOpen, setPermissionsOpen] = useState(false);
@@ -113,7 +111,7 @@ function ApiKeyCreateForm({
null,
);
- const expiresAt = resolveExpiresAt(expiryPreset, customExpiry);
+ const expiresAt = resolveApiKeyExpiration(expiryPreset, customExpiry);
const submitDisabled = name.trim() === "" || expiresAt === undefined;
const openPermissions = (target: SystemRole) => {
@@ -154,37 +152,13 @@ function ApiKeyCreateForm({
/>
</div>
- <div className="flex flex-col gap-1.5">
- <Label htmlFor="apiKeyExpiry">Expiration</Label>
- <div className={expiryPreset === "custom" ? "flex gap-2" : ""}>
- <Select
- value={expiryPreset}
- onValueChange={(value) =>
- setExpiryPreset(value as ExpiryPreset)
- }
- >
- <SelectTrigger id="apiKeyExpiry" className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {expiryPresetOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {expiryPreset === "custom" && (
- <Input
- type="date"
- aria-label="Custom expiration date"
- min={localDateInputValue(new Date())}
- value={customExpiry}
- onChange={(e) => setCustomExpiry(e.target.value)}
- />
- )}
- </div>
- </div>
+ <ApiKeyExpirationInput
+ id="apiKeyExpiry"
+ expiryPreset={expiryPreset}
+ customExpiry={customExpiry}
+ onExpiryPresetChange={setExpiryPreset}
+ onCustomExpiryChange={setCustomExpiry}
+ />
{roleSelectionEnabled && (
<div className="flex flex-col gap-1.5">
diff --git a/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx b/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx
index ec6fafebab..7696551b2d 100644
--- a/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx
+++ b/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx
@@ -5,12 +5,9 @@ import { type TableProps } from "@/src/components/design-system/table/Table";
import { createDateTableColumn } from "@/src/components/design-system/table/columns/createDateTableColumn";
import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";
import { createUserTableColumn } from "@/src/components/design-system/table/columns/createUserTableColumn";
-import { createTableColumn } from "@/src/components/design-system/table/columns/utils/createTableColumn";
import { SettingsTable } from "@/src/components/SettingsTable/SettingsTable";
import { type LangfuseColumnDef } from "@/src/components/table/types";
-import { Skeleton } from "@/src/components/ui/skeleton";
-import { isApiKeyExpired } from "@/src/features/apiKey/helpers/isApiKeyExpired";
-import { buildLocalIsoDatePresentation } from "@/src/utils/dates";
+import { isApiKeyExpired } from "@/src/features/apiKey";
import { type RouterOutput } from "@/src/utils/types";
export type ApiKeySettingsTableRow =
@@ -85,26 +82,14 @@ export function ApiKeySettingsTable({
header: "Secret Key",
enableResizing: false,
}),
- createTableColumn<ApiKeySettingsTableRow, Date>({
+ createDateTableColumn<ApiKeySettingsTableRow>({
accessorKey: "expiresAt",
header: "Expiration",
hideBelowMd: true,
enableResizing: false,
- loadingCell: <Skeleton className="h-4 w-1/2" />,
- renderCell: (expiresAt) => {
- if (!expiresAt) {
- return <span className="text-muted-foreground">No expiration</span>;
- }
- const date = buildLocalIsoDatePresentation({ date: expiresAt });
- if (!date) return null;
-
- return (
- <span className="block w-full truncate" title={date.title}>
- {isApiKeyExpired(expiresAt) ? "Expired on " : ""}
- {date.display}
- </span>
- );
- },
+ emptyValue: "No expiration",
+ getPrefix: (expiresAt) =>
+ isApiKeyExpired(expiresAt) ? "Expired on " : null,
}),
createDateTableColumn<ApiKeySettingsTableRow>({
accessorKey: "createdAt",
diff --git a/web/src/features/public-api/components/apiKeyFormOptions.clienttest.ts b/web/src/features/public-api/components/apiKeyFormOptions.clienttest.ts
deleted file mode 100644
index 2f617b634a..0000000000
--- a/web/src/features/public-api/components/apiKeyFormOptions.clienttest.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { resolveExpiresAt } from "./apiKeyFormOptions";
-
-describe("resolveExpiresAt", () => {
- const now = new Date("2026-01-01T00:00:00.000Z");
-
- it("returns null when the key never expires", () => {
- expect(resolveExpiresAt("never", "", now)).toBeNull();
- });
-
- it("offsets a preset by its day count from now", () => {
- expect(resolveExpiresAt("30d", "", now)).toEqual(
- new Date("2026-01-31T00:00:00.000Z"),
- );
- expect(resolveExpiresAt("1y", "", now)).toEqual(
- new Date("2027-01-01T00:00:00.000Z"),
- );
- });
-
- it("expires a custom date at the end of that local day", () => {
- expect(resolveExpiresAt("custom", "2026-06-15", now)).toEqual(
- new Date(2026, 5, 15, 23, 59, 59, 999),
- );
- });
-
- it("leaves a missing, invalid, or past custom date unresolved", () => {
- expect(resolveExpiresAt("custom", "", now)).toBeUndefined();
- expect(resolveExpiresAt("custom", "not-a-date", now)).toBeUndefined();
- expect(resolveExpiresAt("custom", "2026-02-30", now)).toBeUndefined();
- expect(resolveExpiresAt("custom", "2025-12-01", now)).toBeUndefined();
- });
-});
diff --git a/web/src/features/public-api/components/apiKeyFormOptions.ts b/web/src/features/public-api/components/apiKeyFormOptions.ts
deleted file mode 100644
index 91a030f6ce..0000000000
--- a/web/src/features/public-api/components/apiKeyFormOptions.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-/** ExpiryPreset is a selectable key-lifetime option; `custom` defers to a picked date. */
-export type ExpiryPreset = "never" | "30d" | "60d" | "90d" | "1y" | "custom";
-
-/** expiryPresetOptions lists the lifetime presets in display order; `days` is null when the choice carries no fixed offset. */
-export const expiryPresetOptions: {
- value: ExpiryPreset;
- label: string;
- days: number | null;
-}[] = [
- { value: "never", label: "No expiration", days: null },
- { value: "30d", label: "30 days", days: 30 },
- { value: "60d", label: "60 days", days: 60 },
- { value: "90d", label: "90 days", days: 90 },
- { value: "1y", label: "1 year", days: 365 },
- { value: "custom", label: "Custom date…", days: null },
-];
-
-const MS_PER_DAY = 24 * 60 * 60 * 1000;
-
-/** resolveExpiresAt turns an expiry preset into an absolute date, null when the key never expires, or undefined when the custom date is missing, invalid, or not in the future. */
-export const resolveExpiresAt = (
- preset: ExpiryPreset,
- customDate: string,
- now: Date = new Date(),
-): Date | null | undefined => {
- if (preset === "custom") return parseCustomExpiry(customDate, now);
- const days =
- expiryPresetOptions.find((o) => o.value === preset)?.days ?? null;
- if (days === null) return null;
- return new Date(now.getTime() + days * MS_PER_DAY);
-};
-
-/** localDateInputValue formats a date as the local `yyyy-mm-dd` value a date input expects. */
-export const localDateInputValue = (date: Date): string =>
- [
- date.getFullYear(),
- String(date.getMonth() + 1).padStart(2, "0"),
- String(date.getDate()).padStart(2, "0"),
- ].join("-");
-
-/** parseCustomExpiry resolves a `yyyy-mm-dd` value to the end of that local day, or undefined unless it is a real date after now. */
-const parseCustomExpiry = (customDate: string, now: Date): Date | undefined => {
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(customDate);
- if (!match) return undefined;
- const [year, month, day] = [match[1], match[2], match[3]].map(Number);
- const endOfDay = new Date(year, month - 1, day, 23, 59, 59, 999);
- const isRealDate =
- endOfDay.getMonth() === month - 1 && endOfDay.getDate() === day;
- return isRealDate && endOfDay > now ? endOfDay : undefined;
-};