Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion src/lib/utils/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const API_KEY_VERIFY_CACHE_KEY_PROMISE = webcrypto.subtle.importKey(
// The proxy still loads the active key row before calling verifyApiKey, so this
// cache only removes repeated bcrypt work; revocation, expiry, ownership, and
// authorization changes remain database-authoritative on every request.
const API_KEY_VERIFY_CACHE_TTL_MS = 10_000;
const API_KEY_VERIFY_CACHE_TTL_MS = 120_000;
const API_KEY_VERIFY_CACHE_MAX_ENTRIES = 2_048;
const apiKeyVerificationCache = new Map<string, number>();

Expand Down
24 changes: 24 additions & 0 deletions tests/unit/utils/auth.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import bcryptjs from "bcryptjs";
import {
hashApiKey,
verifyApiKey,
Expand Down Expand Up @@ -60,6 +61,29 @@ describe("auth utilities", () => {
const otherHash = await hashApiKey(otherKey);
expect(await verifyApiKey(key, otherHash)).toBe(false);
});
it("should expire cached verification after the two-minute TTL", async () => {
const key = "sk-auto-cache-expiring-key12345678901234567890";
const hash = await hashApiKey(key);
const compareSpy = vi.spyOn(bcryptjs, "compare");
const baseTime = Date.now();
const dateNowSpy = vi.spyOn(Date, "now").mockReturnValue(baseTime);

try {
expect(await verifyApiKey(key, hash)).toBe(true);
expect(compareSpy).toHaveBeenCalledTimes(1);

dateNowSpy.mockReturnValue(baseTime + 119_999);
expect(await verifyApiKey(key, hash)).toBe(true);
expect(compareSpy).toHaveBeenCalledTimes(1);

dateNowSpy.mockReturnValue(baseTime + 120_000);
expect(await verifyApiKey(key, hash)).toBe(true);
expect(compareSpy).toHaveBeenCalledTimes(2);
} finally {
dateNowSpy.mockRestore();
compareSpy.mockRestore();
}
});
it("should handle invalid hash gracefully", async () => {
const key = "sk-auto-testkey123456789012345678901234";

Expand Down
Loading