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
+231
@@ -0,0 +1,231 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
PORTAL_APP_WORKER_DELTA_TABLES,
|
||||
assertPortalAppWorkerPolicyParity,
|
||||
normalizePolicyExpression,
|
||||
parsePortalAppWorkerPolicyContract,
|
||||
readPortalAppWorkerPolicyState,
|
||||
type PortalAppWorkerPolicyContract,
|
||||
type PortalAppWorkerPolicyState,
|
||||
} from "./portal-app-worker-policy-parity.js";
|
||||
|
||||
const CANONICAL_ARTIFACT = join(process.cwd(), "prisma/rls/tenant-policy-contract-isolation.sql");
|
||||
const APP_WORKER_ROLES = ["hivegrid_app", "hivegrid_worker"] as const;
|
||||
const PRIVILEGES = ["SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER"] as const;
|
||||
|
||||
let canonicalSql: string;
|
||||
let contract: PortalAppWorkerPolicyContract;
|
||||
|
||||
beforeAll(async () => {
|
||||
canonicalSql = await readFile(CANONICAL_ARTIFACT, "utf8");
|
||||
contract = parsePortalAppWorkerPolicyContract(canonicalSql);
|
||||
});
|
||||
|
||||
describe("portal app/worker policy contract parser", () => {
|
||||
it("derives the complete portal delta contract from the generated artifact", () => {
|
||||
expect(contract.tables.map(({ table }) => table)).toEqual(PORTAL_APP_WORKER_DELTA_TABLES);
|
||||
expect(contract.policies).toHaveLength(69);
|
||||
expect(contract.grants).toHaveLength(144);
|
||||
expect(contract.tables).toEqual(
|
||||
PORTAL_APP_WORKER_DELTA_TABLES.map((table) => ({
|
||||
table,
|
||||
rowSecurity: true,
|
||||
forceRowSecurity: true,
|
||||
}))
|
||||
);
|
||||
|
||||
const portalPolicy = contract.policies.find(({ table, policy }) => table === "Portal" && policy === "hg_Portal_all");
|
||||
expect(portalPolicy).toMatchObject({
|
||||
permissive: true,
|
||||
command: "*",
|
||||
roles: ["hivegrid_app", "hivegrid_worker"],
|
||||
});
|
||||
expect(portalPolicy?.usingExpression).not.toBeNull();
|
||||
expect(portalPolicy?.usingExpression).toBe(portalPolicy?.withCheckExpression);
|
||||
});
|
||||
|
||||
it("fails closed when ENABLE/FORCE, grants, or SQL structure are malformed", () => {
|
||||
expect(() => parsePortalAppWorkerPolicyContract(canonicalSql.replace('ALTER TABLE "Portal" FORCE ROW LEVEL SECURITY;', ""))).toThrow(
|
||||
"must ENABLE and FORCE RLS exactly once for Portal"
|
||||
);
|
||||
|
||||
expect(() => parsePortalAppWorkerPolicyContract(`${canonicalSql}\nGRANT SELECT ON "Portal" TO hivegrid_app;`)).toThrow(
|
||||
"duplicates SELECT on Portal to hivegrid_app"
|
||||
);
|
||||
|
||||
expect(() => parsePortalAppWorkerPolicyContract(`${canonicalSql}\nGRANT TRUNCATE ON "Portal" TO hivegrid_app;`)).toThrow(
|
||||
"grants forbidden TRUNCATE on Portal to hivegrid_app"
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
parsePortalAppWorkerPolicyContract(
|
||||
canonicalSql.replace('CREATE POLICY "hg_Portal_all" ON "Portal"', 'CREATE POLICY "hg_Portal_all" ON "Portal" AS MAYBE')
|
||||
)
|
||||
).toThrow("invalid AS mode");
|
||||
});
|
||||
|
||||
it("normalizes PostgreSQL deparser casts and aliases without erasing subquery boundaries", () => {
|
||||
const artifactExpression = "\"tenantId\" = NULLIF(current_setting('app.tenant_id', true), '')";
|
||||
const postgresExpression = "(\"tenantId\" = NULLIF(current_setting('app.tenant_id'::text, true), ''::text))";
|
||||
expect(normalizePolicyExpression(postgresExpression)).toBe(normalizePolicyExpression(artifactExpression));
|
||||
|
||||
const artifactExistsExpression =
|
||||
'("tenantId" = NULLIF(current_setting(\'app.tenant_id\', true), \'\') AND EXISTS (SELECT 1 FROM "Portal" AS "owner_0" WHERE "owner_0"."id" = "PortalUser"."portalId" AND "owner_0"."tenantId" = NULLIF(current_setting(\'app.tenant_id\', true), \'\')))';
|
||||
const postgresExistsExpression =
|
||||
'(("tenantId" = NULLIF(current_setting(\'app.tenant_id\'::text, true), \'\'::text)) AND (EXISTS ( SELECT 1 FROM "Portal" owner_0 WHERE ((owner_0.id = "PortalUser"."portalId") AND (owner_0."tenantId" = NULLIF(current_setting(\'app.tenant_id\'::text, true), \'\'::text))))))';
|
||||
expect(normalizePolicyExpression(postgresExistsExpression)).toBe(normalizePolicyExpression(artifactExistsExpression));
|
||||
|
||||
const artifactNullableRelation =
|
||||
'"PortalServiceInboxItem"."routingRuleId" IS NULL OR EXISTS (SELECT 1 FROM "PortalActivityRoutingRule" AS "owner_0" WHERE "owner_0"."id" = "PortalServiceInboxItem"."routingRuleId")';
|
||||
const postgresNullableRelation =
|
||||
'"routingRuleId" IS NULL OR EXISTS (SELECT 1 FROM "PortalActivityRoutingRule" owner_0 WHERE owner_0.id = "PortalServiceInboxItem"."routingRuleId")';
|
||||
expect(normalizePolicyExpression(postgresNullableRelation, "PortalServiceInboxItem")).toBe(
|
||||
normalizePolicyExpression(artifactNullableRelation, "PortalServiceInboxItem")
|
||||
);
|
||||
expect(normalizePolicyExpression('"wrong_alias"."routingRuleId" IS NULL', "PortalServiceInboxItem")).not.toBe(
|
||||
normalizePolicyExpression('"routingRuleId" IS NULL', "PortalServiceInboxItem")
|
||||
);
|
||||
|
||||
const siblingSubqueries =
|
||||
'EXISTS (SELECT 1 FROM "Portal" AS "owner_0" WHERE "owner_0"."id" = "PortalUser"."portalId") AND EXISTS (SELECT 1 FROM "Portal" AS "owner_1" WHERE "owner_1"."id" = "PortalUser"."portalId")';
|
||||
const nestedSubquery =
|
||||
'EXISTS (SELECT 1 FROM "Portal" AS "owner_0" WHERE "owner_0"."id" = "PortalUser"."portalId" AND EXISTS (SELECT 1 FROM "Portal" AS "owner_1" WHERE "owner_1"."id" = "PortalUser"."portalId"))';
|
||||
expect(normalizePolicyExpression(siblingSubqueries)).not.toBe(normalizePolicyExpression(nestedSubquery));
|
||||
});
|
||||
});
|
||||
|
||||
describe("portal app/worker exact database-state parity", () => {
|
||||
it("accepts only the exact state derived from the canonical artifact", () => {
|
||||
expect(() => assertPortalAppWorkerPolicyParity(contract, stateFromContract(contract))).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects permissive true expressions, missing/extra policies, and role or command drift", () => {
|
||||
const state = stateFromContract(contract);
|
||||
const policy = state.policies.find(({ table, policy: name }) => table === "PortalEmailTemplate" && name === "hg_PortalEmailTemplate_update");
|
||||
if (!policy) throw new Error("test fixture policy missing");
|
||||
policy.usingExpression = normalizePolicyExpression("true");
|
||||
policy.command = "*";
|
||||
policy.roles = ["PUBLIC"];
|
||||
state.policies.pop();
|
||||
state.policies.push({
|
||||
table: "Portal",
|
||||
policy: "allow_everything",
|
||||
permissive: true,
|
||||
command: "*",
|
||||
roles: ["hivegrid_app", "hivegrid_worker"],
|
||||
usingExpression: normalizePolicyExpression("true"),
|
||||
withCheckExpression: normalizePolicyExpression("true"),
|
||||
});
|
||||
|
||||
expect(() => assertPortalAppWorkerPolicyParity(contract, state)).toThrow(
|
||||
/using_expression_mismatch.*command_mismatch|command_mismatch.*using_expression_mismatch/
|
||||
);
|
||||
expect(() => assertPortalAppWorkerPolicyParity(contract, state)).toThrow("roles_mismatch");
|
||||
expect(() => assertPortalAppWorkerPolicyParity(contract, state)).toThrow("unexpected_policy");
|
||||
expect(() => assertPortalAppWorkerPolicyParity(contract, state)).toThrow("policy_missing");
|
||||
});
|
||||
|
||||
it("rejects missing FORCE RLS, a missing required grant, and every extra table privilege", () => {
|
||||
const state = stateFromContract(contract);
|
||||
const portal = state.tables.find(({ table }) => table === "Portal");
|
||||
if (!portal) throw new Error("test fixture table missing");
|
||||
portal.forceRowSecurity = false;
|
||||
state.grants = state.grants.filter(({ table, role, privilege }) => !(table === "Portal" && role === "hivegrid_app" && privilege === "DELETE"));
|
||||
state.grants.push({
|
||||
table: "Portal",
|
||||
role: "hivegrid_worker",
|
||||
privilege: "TRUNCATE",
|
||||
});
|
||||
state.columnGrants.push({
|
||||
table: "PortalUser",
|
||||
column: "passwordHash",
|
||||
role: "hivegrid_app",
|
||||
privilege: "UPDATE",
|
||||
});
|
||||
|
||||
expect(() => assertPortalAppWorkerPolicyParity(contract, state)).toThrow("Portal:rls_not_forced");
|
||||
expect(() => assertPortalAppWorkerPolicyParity(contract, state)).toThrow("Portal:hivegrid_app:DELETE:grant_missing");
|
||||
expect(() => assertPortalAppWorkerPolicyParity(contract, state)).toThrow("Portal:hivegrid_worker:TRUNCATE:unexpected_grant");
|
||||
expect(() => assertPortalAppWorkerPolicyParity(contract, state)).toThrow("PortalUser.passwordHash:hivegrid_app:UPDATE:unexpected_column_grant");
|
||||
});
|
||||
|
||||
it("reads table flags, all app/worker-affecting policies, and the full effective privilege matrix", async () => {
|
||||
const queries: string[] = [];
|
||||
const queryRawUnsafe = vi.fn(async (query: string): Promise<unknown[]> => {
|
||||
queries.push(query);
|
||||
if (query.includes(":tables */")) {
|
||||
return PORTAL_APP_WORKER_DELTA_TABLES.map((table) => ({
|
||||
table_name: table,
|
||||
row_security: true,
|
||||
force_row_security: true,
|
||||
}));
|
||||
}
|
||||
if (query.includes(":policies */")) {
|
||||
return [
|
||||
{
|
||||
table_name: "Portal",
|
||||
policy_name: "hg_Portal_all",
|
||||
permissive: true,
|
||||
command: "*",
|
||||
roles: ["hivegrid_app", "hivegrid_worker"],
|
||||
using_expression: "(\"tenantId\" = NULLIF(current_setting('app.tenant_id'::text, true), ''::text))",
|
||||
with_check_expression: "(\"tenantId\" = NULLIF(current_setting('app.tenant_id'::text, true), ''::text))",
|
||||
},
|
||||
];
|
||||
}
|
||||
if (query.includes(":privileges */")) {
|
||||
return PORTAL_APP_WORKER_DELTA_TABLES.flatMap((table) =>
|
||||
APP_WORKER_ROLES.flatMap((role) =>
|
||||
PRIVILEGES.map((privilege) => ({
|
||||
table_name: table,
|
||||
role_name: role,
|
||||
privilege_type: privilege,
|
||||
granted: ["SELECT", "INSERT", "UPDATE", "DELETE"].includes(privilege),
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
if (query.includes(":column-grants */")) return [];
|
||||
throw new Error("unexpected test query");
|
||||
});
|
||||
|
||||
const state = await readPortalAppWorkerPolicyState({ $queryRawUnsafe: queryRawUnsafe });
|
||||
|
||||
expect(queryRawUnsafe).toHaveBeenCalledTimes(4);
|
||||
expect(queries[0]).toContain("class.relrowsecurity");
|
||||
expect(queries[0]).toContain("class.relforcerowsecurity");
|
||||
expect(queries[1]).toContain("pg_get_expr(policy.polqual");
|
||||
expect(queries[1]).toContain("policy_role.role_oid = 0");
|
||||
expect(queries[1]).toContain("pg_has_role(runtime_role.oid, role.oid, 'MEMBER')");
|
||||
expect(queries[1]).toContain("hivegrid_app");
|
||||
expect(queries[1]).toContain("hivegrid_worker");
|
||||
expect(queries[2]).toContain("has_table_privilege");
|
||||
expect(queries[2]).toContain("TRUNCATE");
|
||||
expect(queries[2]).toContain("REFERENCES");
|
||||
expect(queries[2]).toContain("TRIGGER");
|
||||
expect(queries[3]).toContain("attribute.attacl");
|
||||
expect(queries[3]).toContain("aclexplode");
|
||||
expect(queries[3]).toContain("access.grantee = 0");
|
||||
expect(state.tables).toHaveLength(18);
|
||||
expect(state.policies).toHaveLength(1);
|
||||
expect(state.grants).toHaveLength(144);
|
||||
expect(state.columnGrants).toEqual([]);
|
||||
expect(state.policies[0]?.usingExpression).toBe(contract.policies.find(({ policy }) => policy === "hg_Portal_all")?.usingExpression);
|
||||
});
|
||||
});
|
||||
|
||||
function stateFromContract(source: PortalAppWorkerPolicyContract): PortalAppWorkerPolicyState {
|
||||
return {
|
||||
tables: source.tables.map((table) => ({ ...table })),
|
||||
policies: source.policies.map((policy) => ({
|
||||
...policy,
|
||||
roles: [...policy.roles],
|
||||
})),
|
||||
grants: source.grants.map((grant) => ({ ...grant })),
|
||||
columnGrants: [],
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user