// @vitest-environment node import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import pg from "pg"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; // Resolve the repo root from this file's location so the SQL artifacts load // regardless of the cwd vitest runs under (root vs the @hivegrid/web package dir). // This file lives at apps/web/app/utils/db/.server/ → six segments below root. const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../../.."); // VA-P23 — EMAIL-INBOX RLS GATE PROOF. Companion to rls-file-isolation: proves // that once the email-inbox RLS block (prisma/rls/email-inbox-isolation.sql) is // applied, the restricted hivegrid_app role (NOSUPERUSER, NOBYPASSRLS) is // confined to its own tenant's EmailIntegrationMailbox / -Message rows, sees // nothing without a tenant context, and is blocked by WITH CHECK from writing // cross-tenant rows. This makes the P5 activation a pure switch: the wrapped // emailInbox db layer already runs inside withTenantRLS(). // // Runs ONLY when RLS_TEST_DATABASE_URL is set (a SUPERUSER connection to a // throwaway DB with the schema pushed). Without it the block is skipped so the // normal unit suite stays green without a DB. // // Setup: // docker run -d --name hg-rls-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 // RLS_TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm vitest run rls-email-inbox-isolation const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL; const APP_ROLE = "hivegrid_app"; const APP_PASSWORD = "hivegrid_app_pw"; function appUrlFrom(adminUrl: string): string { const url = new URL(adminUrl); url.username = APP_ROLE; url.password = APP_PASSWORD; return url.toString(); } const describeIfDb = ADMIN_URL ? describe : describe.skip; describeIfDb("Email-inbox RLS tenant isolation gate proof (EmailIntegrationMailbox, EmailIntegrationMessage)", () => { let admin: pg.Client; let app: pg.Client; beforeAll(async () => { admin = new pg.Client({ connectionString: ADMIN_URL }); await admin.connect(); // 1) Base RLS mechanic + restricted role (creates hivegrid_app, NOBYPASSRLS). const baseSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8"); await admin.query(baseSql); // Production credentials are intentionally not part of the rollout SQL. // Set a disposable password only inside this throwaway integration database. await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`); // 2) Email-inbox RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs // on the four VA-P23 tables (the deferred P5 activation artifact). const emailInboxRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/email-inbox-isolation.sql"), "utf8"); await admin.query(emailInboxRlsSql); await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`); // 3) Seed two tenants' mailboxes + messages as superuser (bypasses RLS). // Mailbox has no FK on tenantId/ownerUserId, so no User/Tenant rows needed. await admin.query(`INSERT INTO "EmailIntegrationMailbox"(id,"updatedAt","tenantId","ownerUserId",provider,"emailAddress","externalAccountId") VALUES ('rls_mboxA',now(),'rls_tenantA','rls_userA','gmail','a@example.com','extA'), ('rls_mboxB',now(),'rls_tenantB','rls_userB','microsoft','b@example.com','extB') ON CONFLICT (id) DO NOTHING`); await admin.query(`INSERT INTO "EmailIntegrationMessage"(id,"updatedAt","tenantId","mailboxId","providerMessageId",direction,"fromAddress","sentAt") VALUES ('rls_msgA',now(),'rls_tenantA','rls_mboxA','pmA','inbound','x@example.com',now()), ('rls_msgB',now(),'rls_tenantB','rls_mboxB','pmB','inbound','y@example.com',now()) ON CONFLICT (id) DO NOTHING`); app = new pg.Client({ connectionString: appUrlFrom(ADMIN_URL!) }); await app.connect(); }); afterAll(async () => { await app?.end(); await admin?.end(); }); async function underTenant(tenantId: string, run: () => Promise): Promise { await app.query("BEGIN"); try { await app.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]); const result = await run(); await app.query("COMMIT"); return result; } catch (error) { await app.query("ROLLBACK"); throw error; } } it("confirms the app role is neither superuser nor BYPASSRLS", async () => { const { rows } = await admin.query(`SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = $1`, [APP_ROLE]); expect(rows[0]).toMatchObject({ rolsuper: false, rolbypassrls: false }); }); it("under tenant A context, only tenant A mailboxes are visible", async () => { const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmailIntegrationMailbox" ORDER BY id`)).rows.map((r) => r.id)); expect(ids).toEqual(["rls_mboxA"]); }); it("cannot read another tenant's messages even with an explicit WHERE filter", async () => { const count = await underTenant( "rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "EmailIntegrationMessage" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c, ); expect(count).toBe(0); }); it("sees no mailboxes at all when no tenant context is set", async () => { const count = (await app.query(`SELECT count(*)::int AS c FROM "EmailIntegrationMailbox"`)).rows[0].c; expect(count).toBe(0); }); it("WITH CHECK blocks inserting a message for a foreign tenant", async () => { await expect( underTenant("rls_tenantA", async () => app.query( `INSERT INTO "EmailIntegrationMessage"(id,"updatedAt","tenantId","mailboxId","providerMessageId",direction,"fromAddress","sentAt") VALUES ('rls_msgX',now(),'rls_tenantB','rls_mboxB','pmX','inbound','z@example.com',now())`, ), ), ).rejects.toThrow(/row-level security/i); }); it("allows inserting and reading a message for the active tenant", async () => { await underTenant("rls_tenantA", async () => { await app.query( `INSERT INTO "EmailIntegrationMessage"(id,"updatedAt","tenantId","mailboxId","providerMessageId",direction,"fromAddress","sentAt") VALUES ('rls_msgA2',now(),'rls_tenantA','rls_mboxA','pmA2','outbound','a@example.com',now()) ON CONFLICT (id) DO NOTHING`, ); const ids = (await app.query(`SELECT id FROM "EmailIntegrationMessage" ORDER BY id`)).rows.map((r) => r.id); expect(ids).toContain("rls_msgA2"); expect(ids).not.toContain("rls_msgB"); }); }); it("isolates sync cursors and webhook events by tenant as well", async () => { await admin.query(`INSERT INTO "EmailIntegrationSyncCursor"(id,"updatedAt","tenantId","mailboxId","externalFolderId") VALUES ('rls_curA',now(),'rls_tenantA','rls_mboxA','*'), ('rls_curB',now(),'rls_tenantB','rls_mboxB','inbox') ON CONFLICT (id) DO NOTHING`); await admin.query(`INSERT INTO "EmailIntegrationWebhookEvent"(id,"tenantId","mailboxId",provider,"notificationPayload") VALUES ('rls_whA','rls_tenantA','rls_mboxA','gmail','{}'), ('rls_whB','rls_tenantB','rls_mboxB','microsoft','{}') ON CONFLICT (id) DO NOTHING`); const cursorIds = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmailIntegrationSyncCursor" ORDER BY id`)).rows.map((r) => r.id)); expect(cursorIds).toEqual(["rls_curA"]); const eventIds = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmailIntegrationWebhookEvent" ORDER BY id`)).rows.map((r) => r.id)); expect(eventIds).toEqual(["rls_whA"]); }); });