import { describe, it, expect, afterAll } from "vitest"; import { execSync } from "node:child_process"; // Loads .env (DATABASE_URL, provider keys) without printing anything. import "../../scripts/load-env"; const hasDb = (() => { try { execSync(`psql "${process.env.DATABASE_URL ?? "postgres://localhost:5432/polyllm"}" -Atc "select 1"`, { stdio: "ignore" }); return true; } catch { return false; } })(); describe.skipIf(!hasDb)("integration: database + registry + key vault", () => { it("syncs a provider into the registry with a real key and reads it back", async () => { const key = process.env.ANTHROPIC_API_KEY; if (!key) return; // no key → nothing to sync const { syncProvider, listRegistryModels, getModel } = await import("@/lib/ai/registry"); const res = await syncProvider("anthropic", key, "test"); expect(res.ok).toBe(true); expect(res.found).toBeGreaterThan(3); const models = await listRegistryModels({ provider: "anthropic" }); expect(models.some((m) => m.id.startsWith("claude-"))).toBe(true); const m = await getModel(models[0].key); expect(m?.capabilities.text).toBe(true); expect(m?.pricing?.inputPerMillion).toBeGreaterThan(0); }); it("stores provider keys encrypted and never returns them to callers", async () => { process.env.API_KEY_ENCRYPTION_SECRET ??= "integration-secret-0123456789abcdef0123456789abcdef"; const { getDb, users, providerConnections } = await import("@/db"); const { upsertConnection, listConnections, getDecryptedKey, deleteConnection } = await import("@/lib/providers/keys"); const { eq } = await import("drizzle-orm"); const db = getDb(); const id = `it_${Date.now()}`; await db.insert(users).values({ id, name: "Integration", email: `${id}@polyllm.test`, emailVerified: true }); try { const fake = "xai-integration-test-key-0000000000000000"; const res = await upsertConnection(id, "xai", fake, { validate: false }); expect(res.ok).toBe(true); const [row] = await db.select().from(providerConnections).where(eq(providerConnections.userId, id)); expect(row.encryptedKey.startsWith("v1.")).toBe(true); expect(row.encryptedKey).not.toContain("integration-test"); expect(row.keyHint).toMatch(/••••/); const pub = await listConnections(id); expect(JSON.stringify(pub)).not.toContain("integration-test"); expect(await getDecryptedKey(id, "xai")).toBe(fake); await deleteConnection(id, "xai"); expect(await getDecryptedKey(id, "xai")).toBeNull(); } finally { await db.delete(users).where(eq(users.id, id)); } }); afterAll(async () => { const { closeDb } = await import("@/db"); await closeDb(); }); });