Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,145 @@
|
||||
// @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 @toolctrl/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)), "../../../../../..");
|
||||
|
||||
// AK-P4a — FILE RLS GATE PROOF. Companion to R-P2b's rls-tenant-isolation
|
||||
// integration test: proves that once the File RLS block
|
||||
// (local/AK-P4a-merge-migration.sql) is applied, the restricted hivegrid_app role
|
||||
// (NOSUPERUSER, NOBYPASSRLS) is confined to its own tenant's File / FileEntityLink
|
||||
// rows, 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 fileService.server.ts / worker write-backs already set the GUC, so
|
||||
// flipping RLS on cannot break Files.
|
||||
//
|
||||
// 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-file-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("File RLS tenant isolation gate proof (File, FileEntityLink)", () => {
|
||||
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);
|
||||
// 2) File RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the
|
||||
// four Files tables (the deferred P5 activation artifact, applied here).
|
||||
const fileRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/file-isolation.sql"), "utf8");
|
||||
await admin.query(fileRlsSql);
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
// 3) Seed two tenants' files + links as superuser (bypasses RLS). File has no
|
||||
// FK on tenantId/createdByUserId, so no User/Tenant rows are required.
|
||||
await admin.query(`INSERT INTO "File"(id,"updatedAt","tenantId","createdByUserId","displayName","mimeType","sizeBytes","storageKey") VALUES
|
||||
('rls_fileA',now(),'rls_tenantA','rls_userA','a.txt','text/plain',1,'tenants/rls_tenantA/files/rls_fileA/original'),
|
||||
('rls_fileB',now(),'rls_tenantB','rls_userB','b.txt','text/plain',1,'tenants/rls_tenantB/files/rls_fileB/original')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "FileEntityLink"(id,"tenantId","createdByUserId","fileId","entityType","entityId") VALUES
|
||||
('rls_linkA','rls_tenantA','rls_userA','rls_fileA','contact','rls_c1'),
|
||||
('rls_linkB','rls_tenantB','rls_userB','rls_fileB','contact','rls_c2')
|
||||
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 files are visible", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "File" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_fileA"]);
|
||||
});
|
||||
|
||||
it("cannot read another tenant's file even with an explicit WHERE filter", async () => {
|
||||
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "File" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("sees no files at all when no tenant context is set", async () => {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "File"`)).rows[0].c;
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("WITH CHECK blocks inserting a file for a foreign tenant", async () => {
|
||||
await expect(
|
||||
underTenant("rls_tenantA", async () =>
|
||||
app.query(
|
||||
`INSERT INTO "File"(id,"updatedAt","tenantId","createdByUserId","displayName","mimeType","sizeBytes","storageKey")
|
||||
VALUES ('rls_fileX',now(),'rls_tenantB','rls_userB','x.txt','text/plain',1,'tenants/rls_tenantB/files/rls_fileX/original')`,
|
||||
),
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i);
|
||||
});
|
||||
|
||||
it("allows inserting and reading a file for the active tenant", async () => {
|
||||
await underTenant("rls_tenantA", async () => {
|
||||
await app.query(
|
||||
`INSERT INTO "File"(id,"updatedAt","tenantId","createdByUserId","displayName","mimeType","sizeBytes","storageKey")
|
||||
VALUES ('rls_fileA2',now(),'rls_tenantA','rls_userA','a2.txt','text/plain',1,'tenants/rls_tenantA/files/rls_fileA2/original')
|
||||
ON CONFLICT (id) DO NOTHING`,
|
||||
);
|
||||
const ids = (await app.query(`SELECT id FROM "File" ORDER BY id`)).rows.map((r) => r.id);
|
||||
expect(ids).toContain("rls_fileA2");
|
||||
expect(ids).not.toContain("rls_fileB");
|
||||
});
|
||||
});
|
||||
|
||||
it("isolates FileEntityLink rows by tenant as well", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "FileEntityLink" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_linkA"]);
|
||||
const crossCount = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "FileEntityLink" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(crossCount).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
// @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 @toolctrl/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)), "../../../../../..");
|
||||
|
||||
// AK-P4b — TASK RLS GATE PROOF. Companion to R-P2b's rls-tenant-isolation and
|
||||
// AK-P4a's rls-file-isolation integration tests: proves that once the Task RLS
|
||||
// block (prisma/rls/task-isolation.sql) is applied, the restricted hivegrid_app
|
||||
// role (NOSUPERUSER, NOBYPASSRLS) is confined to its own tenant's Task /
|
||||
// TaskWatcher / EntityLink rows, 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 taskService/entityLinkService and worker
|
||||
// crons already set the GUC, so flipping RLS on cannot break Tasks.
|
||||
//
|
||||
// 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-task-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("Task RLS tenant isolation gate proof (Task, TaskWatcher, EntityLink)", () => {
|
||||
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);
|
||||
// 2) Task RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the
|
||||
// three Task tables (the deferred P5 activation artifact, applied here).
|
||||
const taskRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/task-isolation.sql"), "utf8");
|
||||
await admin.query(taskRlsSql);
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
// 3) Seed two tenants' tasks + watchers + links as superuser (bypasses RLS).
|
||||
// Task/TaskWatcher/EntityLink have no FK on tenantId/createdByUserId
|
||||
// (bare scalars, AD-21), so no User/Tenant/Group rows are required. Each
|
||||
// task carries exactly one assignee (single-assignee rule).
|
||||
await admin.query(`INSERT INTO "Task"(id,"updatedAt","tenantId","createdByUserId","title","assignedToUserId") VALUES
|
||||
('rls_taskA',now(),'rls_tenantA','rls_userA','task A','rls_userA'),
|
||||
('rls_taskB',now(),'rls_tenantB','rls_userB','task B','rls_userB')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "TaskWatcher"(id,"tenantId","taskId","userId") VALUES
|
||||
('rls_watchA','rls_tenantA','rls_taskA','rls_userA'),
|
||||
('rls_watchB','rls_tenantB','rls_taskB','rls_userB')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "EntityLink"(id,"tenantId","createdByUserId","sourceType","sourceId","targetType","targetId") VALUES
|
||||
('rls_linkA','rls_tenantA','rls_userA','task','rls_taskA','contact','rls_c1'),
|
||||
('rls_linkB','rls_tenantB','rls_userB','task','rls_taskB','contact','rls_c2')
|
||||
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 tasks are visible", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "Task" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_taskA"]);
|
||||
});
|
||||
|
||||
it("cannot read another tenant's task even with an explicit WHERE filter", async () => {
|
||||
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "Task" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("sees no tasks at all when no tenant context is set", async () => {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "Task"`)).rows[0].c;
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("WITH CHECK blocks inserting a task for a foreign tenant", async () => {
|
||||
await expect(
|
||||
underTenant("rls_tenantA", async () =>
|
||||
app.query(
|
||||
`INSERT INTO "Task"(id,"updatedAt","tenantId","createdByUserId","title","assignedToUserId")
|
||||
VALUES ('rls_taskX',now(),'rls_tenantB','rls_userB','x','rls_userB')`,
|
||||
),
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i);
|
||||
});
|
||||
|
||||
it("allows inserting and reading a task for the active tenant", async () => {
|
||||
await underTenant("rls_tenantA", async () => {
|
||||
await app.query(
|
||||
`INSERT INTO "Task"(id,"updatedAt","tenantId","createdByUserId","title","assignedToUserId")
|
||||
VALUES ('rls_taskA2',now(),'rls_tenantA','rls_userA','a2','rls_userA')
|
||||
ON CONFLICT (id) DO NOTHING`,
|
||||
);
|
||||
const ids = (await app.query(`SELECT id FROM "Task" ORDER BY id`)).rows.map((r) => r.id);
|
||||
expect(ids).toContain("rls_taskA2");
|
||||
expect(ids).not.toContain("rls_taskB");
|
||||
});
|
||||
});
|
||||
|
||||
it("isolates TaskWatcher rows by tenant as well", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "TaskWatcher" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_watchA"]);
|
||||
const crossCount = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "TaskWatcher" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(crossCount).toBe(0);
|
||||
});
|
||||
|
||||
it("isolates EntityLink rows by tenant as well", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EntityLink" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_linkA"]);
|
||||
const crossCount = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "EntityLink" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(crossCount).toBe(0);
|
||||
});
|
||||
});
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
// @vitest-environment node
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import pg from "pg";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
// R-P2b — RLS-GATE-BEWEIS (AD-1): belegt gegen eine echte Postgres, dass mandantenuebergreifender
|
||||
// Zugriff DB-seitig verhindert ist. Laeuft NUR, wenn RLS_TEST_DATABASE_URL gesetzt ist (Superuser-
|
||||
// Verbindung zu einer Wegwerf-DB mit dem gepushten Schema). Ohne die Variable wird der Block
|
||||
// uebersprungen, damit die normale Unit-Suite ohne DB gruen bleibt.
|
||||
//
|
||||
// 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-tenant-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("RLS tenant isolation gate proof (TenantUser)", () => {
|
||||
let admin: pg.Client;
|
||||
let app: pg.Client;
|
||||
|
||||
beforeAll(async () => {
|
||||
admin = new pg.Client({ connectionString: ADMIN_URL });
|
||||
await admin.connect();
|
||||
|
||||
// 1) RLS-Mechanik + restricted Rolle + Policy aus dem committeten SQL anwenden (idempotent).
|
||||
const rlsSql = fs.readFileSync(path.resolve(process.cwd(), "prisma/rls/tenant-isolation.sql"), "utf8");
|
||||
await admin.query(rlsSql);
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
// 2) Zwei Tenants + User + Memberships seeden (als Superuser -> bypasst RLS).
|
||||
await admin.query(`INSERT INTO "Tenant"(id,"updatedAt",slug,name) VALUES
|
||||
('rls_tenantA',now(),'rls-a','A'),('rls_tenantB',now(),'rls-b','B') ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "User"(id,"updatedAt",email,"firstName","lastName") VALUES
|
||||
('rls_userA',now(),'rls-a@example.test','A','A'),('rls_userB',now(),'rls-b@example.test','B','B') ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "TenantUser"(id,"tenantId","userId",type,joined,status) VALUES
|
||||
('rls_tuA','rls_tenantA','rls_userA',0,0,0),('rls_tuB','rls_tenantB','rls_userB',0,0,0) 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 rows are visible", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "TenantUser" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_tuA"]);
|
||||
});
|
||||
|
||||
it("cannot read another tenant's rows even with an explicit WHERE filter", async () => {
|
||||
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "TenantUser" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("sees no rows at all when no tenant context is set", async () => {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "TenantUser"`)).rows[0].c;
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("WITH CHECK blocks inserting a row for a foreign tenant", async () => {
|
||||
await expect(
|
||||
underTenant("rls_tenantA", async () =>
|
||||
app.query(`INSERT INTO "TenantUser"(id,"tenantId","userId",type,joined,status) VALUES ('rls_tuX','rls_tenantB','rls_userB',0,0,0)`)
|
||||
)
|
||||
).rejects.toThrow(/row-level security/i);
|
||||
});
|
||||
|
||||
it("allows inserting and reading a row for the active tenant", async () => {
|
||||
await underTenant("rls_tenantA", async () => {
|
||||
await app.query(`INSERT INTO "TenantUser"(id,"tenantId","userId",type,joined,status) VALUES ('rls_tuA2','rls_tenantA','rls_userA',0,0,0) ON CONFLICT (id) DO NOTHING`);
|
||||
const ids = (await app.query(`SELECT id FROM "TenantUser" ORDER BY id`)).rows.map((r) => r.id);
|
||||
expect(ids).toContain("rls_tuA2");
|
||||
expect(ids).not.toContain("rls_tuB");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const dbMock = vi.hoisted(() => ({ $transaction: vi.fn() }));
|
||||
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
|
||||
|
||||
import { withTenantRLS } from "./tenantRls.server";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("withTenantRLS", () => {
|
||||
it("sets app.tenant_id transaction-locally and runs the callback in the same transaction", async () => {
|
||||
const tx = { $executeRaw: vi.fn().mockResolvedValue(1) };
|
||||
dbMock.$transaction.mockImplementation(async (fn: (tx: unknown) => Promise<unknown>) => fn(tx));
|
||||
|
||||
const result = await withTenantRLS("tenantA", async (handed) => {
|
||||
expect(handed).toBe(tx);
|
||||
return "ok";
|
||||
});
|
||||
|
||||
expect(result).toBe("ok");
|
||||
// Tagged-Template: strings-Array an [0], interpolierter tenantId an [1].
|
||||
const [strings, value] = tx.$executeRaw.mock.calls[0];
|
||||
expect(value).toBe("tenantA");
|
||||
const sql = (strings as string[]).join("?");
|
||||
expect(sql).toContain("set_config");
|
||||
expect(sql).toContain("app.tenant_id");
|
||||
// 3. Argument von set_config ist 'true' (transaktions-lokal) und steht als Literal im SQL.
|
||||
expect(sql).toContain("true");
|
||||
});
|
||||
|
||||
it("rejects an empty tenantId before opening a transaction", async () => {
|
||||
await expect(withTenantRLS("", async () => "x")).rejects.toThrow(/tenantId/);
|
||||
expect(dbMock.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Prisma } from "@toolctrl/db/prisma-browser";
|
||||
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
// R-P2b — App-seitiger RLS-Adoptions-Mechanismus (AD-1). Setzt den Tenant-Kontext
|
||||
// TRANSAKTIONS-LOKAL (set_config(..., true) entspricht SET LOCAL und ist damit PgBouncer-
|
||||
// Transaction-Pooling-kompatibel: der Wert lebt nur bis COMMIT/ROLLBACK auf genau dieser
|
||||
// Verbindung) und fuehrt die Queries innerhalb derselben Transaktion aus, sodass die
|
||||
// RLS-Policies (USING/WITH CHECK auf current_setting('app.tenant_id')) greifen.
|
||||
//
|
||||
// Tenant-bezogene Datenzugriffe eines Moduls laufen ueber diesen Wrapper, sobald die jeweilige
|
||||
// Tabelle RLS-aktiviert ist (siehe prisma/rls/tenant-isolation.sql). Ohne gesetzten Kontext
|
||||
// liefert eine RLS-Tabelle der App-Rolle KEINE Zeile.
|
||||
|
||||
export type TenantRlsClient = Prisma.TransactionClient;
|
||||
|
||||
export async function withTenantRLS<T>(tenantId: string, callback: (tx: TenantRlsClient) => Promise<T>): Promise<T> {
|
||||
if (!tenantId) {
|
||||
throw new Error("withTenantRLS requires a non-empty tenantId");
|
||||
}
|
||||
return db.$transaction(async (tx: TenantRlsClient) => {
|
||||
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
|
||||
return callback(tx);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user