// @vitest-environment node import pg from "pg"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; // AK-P17a — HR field-crypto END-TO-END proof through the REAL services. // // After the R-P5 per-tenant envelope (getTenantFieldCrypto, AD-8) was bound into // the hrFieldCrypto seam, this drives the actual HR services and asserts that // sensitive values are persisted as ciphertext (never plaintext) and round-trip // on the audited reveal path. The in-memory envelope unit test // (packages/db/src/crypto/tenant-envelope.server.test.ts) proves the primitive in // isolation; this proves the SERVICE WIRING — i.e. that setEmergencyContact / // createEntry / revealEntryValue actually call the bound provider. // // Runs ONLY when HR_CRYPTO_TEST_DATABASE_URL points at a throwaway Postgres with // the schema pushed. Skipped otherwise so the normal unit suite stays green // without a DB. A plain superuser connection is fine: this exercises crypto, not // RLS (the RLS confinement is covered by rls-hr-isolation.integration.test.ts). // // Setup: // docker run -d --name hg-crypto-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=hivegrid -p 5433:5432 pgvector/pgvector:pg16 // DIRECT_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm exec prisma db push // HR_CRYPTO_TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm vitest run hrFieldCrypto.roundtrip const DB_URL = process.env.HR_CRYPTO_TEST_DATABASE_URL; const describeIfDb = DB_URL ? describe : describe.skip; const TENANT = "hrcrypto_tenant"; const OTHER_TENANT = "hrcrypto_other_tenant"; const USER = "hrcrypto_user"; describeIfDb("HR field crypto round-trip through services (getTenantFieldCrypto)", () => { let raw: pg.Client; let hr: typeof import("./hrService.server"); let safe: typeof import("./hrPasswordSafeService.server"); beforeAll(async () => { // Point the app's Prisma client at the throwaway DB and configure the master // key BEFORE importing the services (the db client is constructed on import, // getTenantFieldCrypto wraps the DEK with CRYPTO_SECRET). process.env.DATABASE_URL = DB_URL; process.env.DIRECT_URL = DB_URL; process.env.CRYPTO_SECRET ??= "hr-crypto-it-master-key-0123456789ab"; hr = await import("./hrService.server"); safe = await import("./hrPasswordSafeService.server"); raw = new pg.Client({ connectionString: DB_URL }); await raw.connect(); // Deterministic re-runs: clear this test's tenant rows (FK order). await raw.query(`DELETE FROM "EmployeePasswordSafeEntry" WHERE "tenantId" = ANY($1)`, [[TENANT, OTHER_TENANT]]); await raw.query(`DELETE FROM "EmployeePasswordSafeAccess" WHERE "tenantId" = ANY($1)`, [[TENANT, OTHER_TENANT]]); await raw.query(`DELETE FROM "EmployeePasswordSafeVault" WHERE "tenantId" = ANY($1)`, [[TENANT, OTHER_TENANT]]); await raw.query(`DELETE FROM "HrEmployeeProfile" WHERE "tenantId" = ANY($1)`, [[TENANT, OTHER_TENANT]]); await raw.query(`DELETE FROM "TenantEncryptionKey" WHERE "tenantId" = ANY($1)`, [[TENANT, OTHER_TENANT]]); }); afterAll(async () => { await raw?.end(); }); it("emergency contact: stored as ciphertext, round-trips on reveal", async () => { const contact = { name: "Jamie Doe", phone: "+49 151 23456789", relation: "partner" }; await hr.setEmergencyContact({ tenantId: TENANT, userId: USER, contact }); const { rows } = await raw.query( `SELECT "emergencyContactCiphertext" AS c FROM "HrEmployeeProfile" WHERE "tenantId" = $1 AND "userId" = $2`, [TENANT, USER], ); const stored = rows[0]?.c as string | null; expect(stored).toBeTruthy(); expect(stored).not.toContain("Jamie Doe"); expect(stored).not.toContain(JSON.stringify(contact)); expect(stored!.startsWith("v1:")).toBe(true); const revealed = await hr.revealEmergencyContact({ tenantId: TENANT, userId: USER, revealerUserId: USER }); expect(revealed).toEqual(contact); }); it("password-safe entry: secrets stored as ciphertext, reveal round-trips, list hides values", async () => { const vault = await safe.createVault({ tenantId: TENANT, name: "Ops", createdByUserId: USER }); const secrets = { username: "ops-admin", password: "S3cr3t!pw", notes: "rotate quarterly" }; const { id: entryId } = await safe.createEntry({ tenantId: TENANT, vaultId: vault.id, userId: USER, title: "Router", secrets }); const { rows } = await raw.query( `SELECT "usernameCiphertext" AS u, "passwordCiphertext" AS p, "notesCiphertext" AS n FROM "EmployeePasswordSafeEntry" WHERE id = $1`, [entryId], ); const stored = rows[0] as { u: string; p: string; n: string }; for (const [field, plaintext, column] of [ ["username", secrets.username, stored.u], ["password", secrets.password, stored.p], ["notes", secrets.notes, stored.n], ] as const) { expect(column, `${field} ciphertext present`).toBeTruthy(); expect(column, `${field} is not stored in cleartext`).not.toContain(plaintext); expect(column.startsWith("v1:"), `${field} uses the envelope format`).toBe(true); } expect(await safe.revealEntryValue({ tenantId: TENANT, vaultId: vault.id, entryId, userId: USER, field: "username" })).toBe(secrets.username); expect(await safe.revealEntryValue({ tenantId: TENANT, vaultId: vault.id, entryId, userId: USER, field: "password" })).toBe(secrets.password); expect(await safe.revealEntryValue({ tenantId: TENANT, vaultId: vault.id, entryId, userId: USER, field: "notes" })).toBe(secrets.notes); const list = await safe.listEntries({ tenantId: TENANT, vaultId: vault.id, userId: USER }); const listed = list.find((entry) => entry.id === entryId); expect(listed).toMatchObject({ hasUsername: true, hasPassword: true, hasNotes: true }); // The list view must never carry a secret value. expect(JSON.stringify(list)).not.toContain(secrets.password); }); it("a foreign tenant cannot decrypt this tenant's ciphertext (per-tenant DEK)", async () => { const envelope = await import("@hivegrid/db/crypto/tenant-envelope.server"); const cipher = await envelope.encryptTenantField(TENANT, "tenant-scoped-secret"); // OTHER_TENANT gets its own DEK, so opening TENANT's envelope fails the GCM tag. await expect(envelope.decryptTenantField(OTHER_TENANT, cipher)).rejects.toThrow(); }); });