import { describe, expect, test } from "bun:test"; import { MemoryCacheStore } from "@/external/storage/cache/MemoryCacheStore.js"; import { clearSecretKeyCache, getCachedSecretKeyVerification, setCachedSecretKeyVerification, } from "@/internal/dev/api-keys/cacheApiKeyUtils.js"; import { hashApiKey, verifyKey } from "@/internal/dev/api-keys/apiKeyUtils.js"; describe("cacheApiKeyUtils", () => { test("uses the provided cache store for secret key verification cache", async () => { const store = new MemoryCacheStore(); const hashedKey = "hashed_key_123"; const data = { orgId: "org_123", env: "sandbox" }; await setCachedSecretKeyVerification({ cacheStore: store, hashedKey, data, ttl: 60, }); await expect( getCachedSecretKeyVerification({ cacheStore: store, hashedKey, }), ).resolves.toEqual(data); await clearSecretKeyCache({ cacheStore: store, hashedKey, }); await expect( getCachedSecretKeyVerification({ cacheStore: store, hashedKey, }), ).resolves.toBeNull(); }); test("verifyKey reads from the provided cache store without Redis", async () => { const store = new MemoryCacheStore(); const key = "am_sk_test_123"; const pendingMigrations: unknown[] = []; const cachedVerification = { pendingMigrations, org: { id: "org_123", pendingMigrations }, }; await setCachedSecretKeyVerification({ cacheStore: store, hashedKey: await hashApiKey(key), data: cachedVerification, }); await expect( verifyKey({ cacheStore: store, db: {} as never, key, }), ).resolves.toMatchObject({ valid: true, data: cachedVerification, }); }); test("secret key cache helpers miss and no-op when no cache store is provided", async () => { const hashedKey = "hashed_key_without_store"; await expect( getCachedSecretKeyVerification({ hashedKey, }), ).resolves.toBeNull(); await expect( setCachedSecretKeyVerification({ hashedKey, data: { orgId: "org_123" }, }), ).resolves.toBeUndefined(); await expect( clearSecretKeyCache({ hashedKey, }), ).resolves.toBeUndefined(); }); });