import { test, expect } from "bun:test"; import { parseKV, type Role } from "../scripts/kv-secrets"; function fixture(role: Role) { return { status: 200, data: { request_id: "synthetic-request", data: { data: { database_url: `postgresql://${role}@127.0.0.1:15432/messenger?sslmode=disable`, cache_url: `redis://${role}:synthetic-password@127.0.0.1:16379/0`, s3_json: JSON.stringify({ Endpoint: "127.0.0.1:19000", Access: "vp7" + role, Secret: "synthetic-s3-secret", Bucket: "messenger-attachments", }), ...(role === "worker" ? { publisher_url: "redis://publisher:synthetic-password@127.0.0.1:16379/0", } : {}), }, metadata: { version: 1 }, }, }, }; } test.each(["api", "worker"] as const)( "reads the native KVv2 envelope for %s", (role) => { const result = parseKV(fixture(role), role); expect(result.version).toBe(1); expect(new URL(result.secrets.database_url).username).toBe(role); }, ); test("rejects missing KVv2 nesting and required fields", () => { expect(() => parseKV({ status: 200, data: { data: {} } }, "api")).toThrow(); const f = fixture("api"); delete (f.data.data.data as any).s3_json; expect(() => parseKV(f, "api")).toThrow(); }); test("rejects credentials for another role", () => { expect(() => parseKV(fixture("worker"), "api")).toThrow("BAO_ROLE_MISMATCH"); }); test("rejects invalid metadata and denied responses", () => { const f = fixture("api"); f.data.data.metadata.version = -1; expect(() => parseKV(f, "api")).toThrow(); const denied = fixture("api"); denied.status = 403; expect(() => parseKV(denied, "api")).toThrow(); });