Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+3
@@ -43,6 +43,9 @@ describeIfDb("Apps-Engine RLS tenant isolation gate proof (DataConnection, AppSy
|
||||
await admin.connect();
|
||||
|
||||
await admin.query(fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8"));
|
||||
// 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}'`);
|
||||
await admin.query(fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/apps-engine-isolation.sql"), "utf8"));
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync, readdirSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const repoRoot = path.resolve(process.cwd());
|
||||
const rlsDirectory = path.join(repoRoot, "prisma", "rls");
|
||||
|
||||
function executableSql(relativePath: string): string {
|
||||
return readFileSync(path.join(rlsDirectory, relativePath), "utf8").replace(/--.*$/gm, "");
|
||||
}
|
||||
|
||||
describe("RLS rollout artifacts", () => {
|
||||
it("never provisions a reusable database password from repository SQL", () => {
|
||||
const violations = readdirSync(rlsDirectory)
|
||||
.filter((file) => file.endsWith(".sql"))
|
||||
.filter((file) => /\b(?:CREATE|ALTER)\s+(?:ROLE|USER)\b[^;]*\bPASSWORD\b/is.test(executableSql(file)));
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the canonical transaction-local tenant context name in every isolation policy", () => {
|
||||
const isolationFiles = readdirSync(rlsDirectory).filter((file) => file.endsWith("-isolation.sql"));
|
||||
const violations = isolationFiles.filter((file) => {
|
||||
const sql = executableSql(file);
|
||||
return !sql.includes("app.tenant_id") || sql.includes("app.current_tenant_id");
|
||||
});
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps global automation templates read-only for the tenant runtime role", () => {
|
||||
const sql = executableSql("automation-isolation.sql");
|
||||
const selectPolicy = /CREATE POLICY "tenant_isolation_automation_template_select"[\s\S]*?;/i.exec(sql)?.[0];
|
||||
const mutablePolicies = [...sql.matchAll(/CREATE POLICY "tenant_isolation_automation_template_(?:insert|update|delete)"[\s\S]*?;/gi)].map(
|
||||
(match) => match[0],
|
||||
);
|
||||
|
||||
expect(selectPolicy).toContain('"tenantId" IS NULL OR');
|
||||
expect(mutablePolicies).toHaveLength(3);
|
||||
for (const policy of mutablePolicies) {
|
||||
expect(policy).toContain("current_setting('app.tenant_id', true)");
|
||||
expect(policy).not.toContain('"tenantId" IS NULL');
|
||||
}
|
||||
});
|
||||
});
|
||||
+3
@@ -52,6 +52,9 @@ describeIfDb("Email-inbox RLS tenant isolation gate proof (EmailIntegrationMailb
|
||||
// 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");
|
||||
|
||||
+3
@@ -53,6 +53,9 @@ describeIfDb("File RLS tenant isolation gate proof (File, FileEntityLink)", () =
|
||||
// 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) 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");
|
||||
|
||||
+85
-1
@@ -14,7 +14,7 @@ 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 (here: HrEmployeeProfile + EmployeePasswordSafeEntry), sees
|
||||
// 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
|
||||
@@ -53,6 +53,9 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
|
||||
// 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");
|
||||
@@ -74,6 +77,18 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
|
||||
('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();
|
||||
@@ -112,6 +127,23 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
|
||||
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);
|
||||
@@ -131,4 +163,56 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
|
||||
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);
|
||||
});
|
||||
});
|
||||
+3
@@ -53,6 +53,9 @@ describeIfDb("Task RLS tenant isolation gate proof (Task, TaskWatcher, EntityLin
|
||||
// 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) 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");
|
||||
|
||||
+3
@@ -39,6 +39,9 @@ describeIfDb("RLS tenant isolation gate proof (TenantUser)", () => {
|
||||
// 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);
|
||||
// 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}'`);
|
||||
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).
|
||||
|
||||
+7
-4
@@ -1,4 +1,5 @@
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
@@ -18,8 +19,10 @@ export async function withTenantRLS<T>(tenantId: string, callback: (tx: TenantRl
|
||||
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);
|
||||
});
|
||||
return runWithRlsContext({ tenantId }, () =>
|
||||
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