219 lines
11 KiB
TypeScript
219 lines
11 KiB
TypeScript
// @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. 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)), "../../../../../..");
|
|
|
|
// AK-P17a — HR RLS GATE PROOF. Companion to the task/file/tenant isolation tests:
|
|
// proves that once the HR RLS block (prisma/rls/hr-isolation.sql) is applied, the
|
|
// restricted hivegrid_app role (NOSUPERUSER, NOBYPASSRLS) is confined to its own
|
|
// tenant's HR rows (including all three password-safe tables), sees
|
|
// nothing without a tenant context, and is blocked by WITH CHECK from writing
|
|
// cross-tenant rows. This is what makes the P5 activation a pure switch: the
|
|
// wrapped hr*Service helpers already set the GUC, so flipping RLS on cannot break
|
|
// the module.
|
|
//
|
|
// 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-hr-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("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePasswordSafeEntry)", () => {
|
|
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) HR RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the HR
|
|
// tables (the deferred P5 activation artifact, applied here).
|
|
const hrRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/hr-isolation.sql"), "utf8");
|
|
await admin.query(hrRlsSql);
|
|
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
|
|
|
// 3) Seed two tenants' HR rows as superuser (bypasses RLS). The HR models use
|
|
// bare scalars (AD-21), so no User/Tenant rows are required. The vault is
|
|
// seeded for the FK from the entry.
|
|
await admin.query(`INSERT INTO "HrEmployeeProfile"(id,"updatedAt","tenantId","userId","position") VALUES
|
|
('rls_hrpA',now(),'rls_tenantA','rls_userA','Engineer'),
|
|
('rls_hrpB',now(),'rls_tenantB','rls_userB','Engineer')
|
|
ON CONFLICT (id) DO NOTHING`);
|
|
await admin.query(`INSERT INTO "EmployeePasswordSafeVault"(id,"updatedAt","tenantId","name","createdByUserId") VALUES
|
|
('rls_vaultA',now(),'rls_tenantA','Vault A','rls_userA'),
|
|
('rls_vaultB',now(),'rls_tenantB','Vault B','rls_userB')
|
|
ON CONFLICT (id) DO NOTHING`);
|
|
await admin.query(`INSERT INTO "EmployeePasswordSafeEntry"(id,"updatedAt","tenantId","vaultId","title") VALUES
|
|
('rls_entryA',now(),'rls_tenantA','rls_vaultA','Entry A'),
|
|
('rls_entryB',now(),'rls_tenantB','rls_vaultB','Entry B')
|
|
ON CONFLICT (id) DO NOTHING`);
|
|
await admin.query(`INSERT INTO "EmployeePasswordSafeAccess"(id,"updatedAt","tenantId","vaultId","userId","permissionLevel","grantedByUserId") VALUES
|
|
('rls_accessA',now(),'rls_tenantA','rls_vaultA','rls_userA','admin','rls_userA'),
|
|
('rls_accessB',now(),'rls_tenantB','rls_vaultB','rls_userB','admin','rls_userB')
|
|
ON CONFLICT (id) DO NOTHING`);
|
|
await admin.query(`INSERT INTO "HrAnnouncement"(id,"updatedAt","tenantId","authorUserId",title,body,"audienceKind","audienceRef") VALUES
|
|
('rls_announcementA',now(),'rls_tenantA','rls_userA','Team A','Body A','team','team-A'),
|
|
('rls_announcementB',now(),'rls_tenantB','rls_userB','Team B','Body B','team','team-B')
|
|
ON CONFLICT (id) DO NOTHING`);
|
|
await admin.query(`INSERT INTO "HrSurvey"(id,"updatedAt","tenantId","authorUserId",title,"audienceKind","audienceRef") VALUES
|
|
('rls_surveyA',now(),'rls_tenantA','rls_userA','Survey A','location','location-A'),
|
|
('rls_surveyB',now(),'rls_tenantB','rls_userB','Survey B','location','location-B')
|
|
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<T>(tenantId: string, run: () => Promise<T>): Promise<T> {
|
|
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 employee profiles are visible", async () => {
|
|
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "HrEmployeeProfile" ORDER BY id`)).rows.map((r) => r.id));
|
|
expect(ids).toEqual(["rls_hrpA"]);
|
|
});
|
|
|
|
it("cannot read another tenant's profile even with an explicit WHERE filter", async () => {
|
|
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "HrEmployeeProfile" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
|
expect(count).toBe(0);
|
|
});
|
|
|
|
it("isolates audience-targeted announcements and surveys before object gates run", async () => {
|
|
const visible = await underTenant("rls_tenantA", async () => {
|
|
const announcements = (
|
|
await app.query(`SELECT id FROM "HrAnnouncement" ORDER BY id`)
|
|
).rows.map((row) => row.id);
|
|
const surveys = (await app.query(`SELECT id FROM "HrSurvey" ORDER BY id`)).rows.map(
|
|
(row) => row.id,
|
|
);
|
|
return { announcements, surveys };
|
|
});
|
|
|
|
expect(visible).toEqual({
|
|
announcements: ["rls_announcementA"],
|
|
surveys: ["rls_surveyA"],
|
|
});
|
|
});
|
|
|
|
it("sees no HR rows at all when no tenant context is set", async () => {
|
|
const count = (await app.query(`SELECT count(*)::int AS c FROM "HrEmployeeProfile"`)).rows[0].c;
|
|
expect(count).toBe(0);
|
|
});
|
|
|
|
it("WITH CHECK blocks inserting a profile for a foreign tenant", async () => {
|
|
await expect(
|
|
underTenant("rls_tenantA", async () =>
|
|
app.query(`INSERT INTO "HrEmployeeProfile"(id,"updatedAt","tenantId","userId") VALUES ('rls_hrpX',now(),'rls_tenantB','rls_userB')`),
|
|
),
|
|
).rejects.toThrow(/row-level security/i);
|
|
});
|
|
|
|
it("isolates password-safe entries by tenant as well", async () => {
|
|
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmployeePasswordSafeEntry" ORDER BY id`)).rows.map((r) => r.id));
|
|
expect(ids).toEqual(["rls_entryA"]);
|
|
const crossCount = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "EmployeePasswordSafeEntry" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
|
expect(crossCount).toBe(0);
|
|
});
|
|
|
|
it("forces RLS on vault, entry and access rows for the restricted app role", async () => {
|
|
const { rows } = await admin.query(`
|
|
SELECT relname, relrowsecurity, relforcerowsecurity
|
|
FROM pg_class
|
|
WHERE relnamespace = 'public'::regnamespace
|
|
AND relname IN ('EmployeePasswordSafeAccess', 'EmployeePasswordSafeEntry', 'EmployeePasswordSafeVault')
|
|
ORDER BY relname
|
|
`);
|
|
expect(rows).toHaveLength(3);
|
|
expect(rows.every((row) => row.relrowsecurity && row.relforcerowsecurity)).toBe(true);
|
|
});
|
|
|
|
it("isolates vault grants and blocks cross-tenant IDOR writes", async () => {
|
|
const visible = await underTenant("rls_tenantA", async () => {
|
|
const vaults = (await app.query(`SELECT id FROM "EmployeePasswordSafeVault" ORDER BY id`)).rows.map((row) => row.id);
|
|
const access = (await app.query(`SELECT id FROM "EmployeePasswordSafeAccess" ORDER BY id`)).rows.map((row) => row.id);
|
|
return { vaults, access };
|
|
});
|
|
expect(visible).toEqual({ vaults: ["rls_vaultA"], access: ["rls_accessA"] });
|
|
|
|
await expect(
|
|
underTenant("rls_tenantA", () =>
|
|
app.query(`INSERT INTO "EmployeePasswordSafeAccess"(id,"updatedAt","tenantId","vaultId","userId","permissionLevel","grantedByUserId")
|
|
VALUES ('rls_accessX',now(),'rls_tenantB','rls_vaultB','rls_userA','read','rls_userA')`)
|
|
)
|
|
).rejects.toThrow(/row-level security/i);
|
|
});
|
|
|
|
it("returns no vault, entry or access metadata without a bound tenant", async () => {
|
|
for (const table of ["EmployeePasswordSafeVault", "EmployeePasswordSafeEntry", "EmployeePasswordSafeAccess"]) {
|
|
const count = (await app.query(`SELECT count(*)::int AS c FROM "${table}"`)).rows[0].c;
|
|
expect(count, table).toBe(0);
|
|
}
|
|
});
|
|
|
|
it("forces RLS and returns no audience metadata without a bound tenant", async () => {
|
|
for (const table of ["HrAnnouncement", "HrSurvey"]) {
|
|
const count = (await app.query(`SELECT count(*)::int AS c FROM "${table}"`)).rows[0].c;
|
|
expect(count, table).toBe(0);
|
|
}
|
|
|
|
const { rows } = await admin.query(`
|
|
SELECT relname, relrowsecurity, relforcerowsecurity
|
|
FROM pg_class
|
|
WHERE relnamespace = 'public'::regnamespace
|
|
AND relname IN ('HrAnnouncement', 'HrSurvey')
|
|
ORDER BY relname
|
|
`);
|
|
expect(rows).toHaveLength(2);
|
|
expect(rows.every((row) => row.relrowsecurity && row.relforcerowsecurity)).toBe(true);
|
|
});
|
|
});
|