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
+299
@@ -0,0 +1,299 @@
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { getDbClient, type DbClient } from "./client.server.js";
|
||||
import {
|
||||
defaultAdminRoleSeeds,
|
||||
defaultAppRoleSeeds,
|
||||
defaultPermissionSeedDescriptors,
|
||||
defaultPermissionSeeds,
|
||||
syncDefaultRolesAndPermissions,
|
||||
type PermissionCatalogSyncClient,
|
||||
} from "./permissions-seed.server.js";
|
||||
import type { DbTransactionClient } from "./transactions.server.js";
|
||||
|
||||
const CATALOG_TABLE_NAMES = ["Permission", "Role", "RolePermission"] as const;
|
||||
const CATALOG_SYNC_TRANSACTION_OPTIONS = { maxWait: 5_000, timeout: 45_000 } as const;
|
||||
|
||||
const TEMPORARY_DML_GRANTS = [
|
||||
'GRANT INSERT, UPDATE ON "Permission" TO hivegrid_rls_definer',
|
||||
'GRANT INSERT, UPDATE, DELETE ON "Role" TO hivegrid_rls_definer',
|
||||
'GRANT INSERT, DELETE ON "RolePermission" TO hivegrid_rls_definer',
|
||||
] as const;
|
||||
|
||||
const TEMPORARY_DML_REVOKES = [
|
||||
'REVOKE INSERT, UPDATE ON "Permission" FROM hivegrid_rls_definer',
|
||||
'REVOKE INSERT, UPDATE, DELETE ON "Role" FROM hivegrid_rls_definer',
|
||||
'REVOKE INSERT, DELETE ON "RolePermission" FROM hivegrid_rls_definer',
|
||||
] as const;
|
||||
|
||||
type DeployPermissionCatalogTransaction = PermissionCatalogSyncClient & Pick<DbTransactionClient, "$executeRawUnsafe" | "$queryRawUnsafe">;
|
||||
|
||||
type DeployPermissionCatalogClient = Pick<DbClient, "$transaction">;
|
||||
|
||||
type CatalogBoundaryRow = {
|
||||
tableName: string;
|
||||
ownerName: string;
|
||||
currentUser: string;
|
||||
sessionUser: string;
|
||||
rlsEnabled: boolean;
|
||||
forceRls: boolean;
|
||||
definerCanLogin: boolean;
|
||||
definerIsSuperuser: boolean;
|
||||
definerCanCreateDatabase: boolean;
|
||||
definerCanCreateRole: boolean;
|
||||
definerInherits: boolean;
|
||||
definerCanReplicate: boolean;
|
||||
definerBypassesRls: boolean;
|
||||
currentUserCanSetDefinerRole: boolean;
|
||||
runtimeRoleHasDefinerMembership: boolean;
|
||||
definerHasSchemaUsage: boolean;
|
||||
definerHasSchemaCreate: boolean;
|
||||
definerHasSelect: boolean;
|
||||
definerHasInsert: boolean;
|
||||
definerHasUpdate: boolean;
|
||||
definerHasDelete: boolean;
|
||||
definerHasTruncate: boolean;
|
||||
definerHasReferences: boolean;
|
||||
definerHasTrigger: boolean;
|
||||
definerHasColumnInsert: boolean;
|
||||
definerHasColumnUpdate: boolean;
|
||||
definerHasColumnReferences: boolean;
|
||||
userContextIsEmpty: boolean;
|
||||
tenantContextIsEmpty: boolean;
|
||||
};
|
||||
|
||||
export type DeployPermissionCatalogSyncResult = Awaited<ReturnType<typeof syncDefaultRolesAndPermissions>>;
|
||||
|
||||
async function assertCatalogBoundary(transaction: DeployPermissionCatalogTransaction) {
|
||||
const rows = await transaction.$queryRawUnsafe<CatalogBoundaryRow[]>(`
|
||||
SELECT
|
||||
relation.relname AS "tableName",
|
||||
pg_get_userbyid(relation.relowner) AS "ownerName",
|
||||
current_user AS "currentUser",
|
||||
session_user AS "sessionUser",
|
||||
relation.relrowsecurity AS "rlsEnabled",
|
||||
relation.relforcerowsecurity AS "forceRls",
|
||||
definer.rolcanlogin AS "definerCanLogin",
|
||||
definer.rolsuper AS "definerIsSuperuser",
|
||||
definer.rolcreatedb AS "definerCanCreateDatabase",
|
||||
definer.rolcreaterole AS "definerCanCreateRole",
|
||||
definer.rolinherit AS "definerInherits",
|
||||
definer.rolreplication AS "definerCanReplicate",
|
||||
definer.rolbypassrls AS "definerBypassesRls",
|
||||
(current_setting('is_superuser')::boolean OR pg_has_role(current_user, 'hivegrid_rls_definer', 'MEMBER')) AS "currentUserCanSetDefinerRole",
|
||||
(
|
||||
pg_has_role('hivegrid_app', 'hivegrid_rls_definer', 'MEMBER')
|
||||
OR pg_has_role('hivegrid_worker', 'hivegrid_rls_definer', 'MEMBER')
|
||||
OR pg_has_role('hivegrid_authentik_jit', 'hivegrid_rls_definer', 'MEMBER')
|
||||
) AS "runtimeRoleHasDefinerMembership",
|
||||
has_schema_privilege('hivegrid_rls_definer', 'public', 'USAGE') AS "definerHasSchemaUsage",
|
||||
has_schema_privilege('hivegrid_rls_definer', 'public', 'CREATE') AS "definerHasSchemaCreate",
|
||||
has_table_privilege('hivegrid_rls_definer', format('%I.%I', namespace.nspname, relation.relname), 'SELECT') AS "definerHasSelect",
|
||||
has_table_privilege('hivegrid_rls_definer', format('%I.%I', namespace.nspname, relation.relname), 'INSERT') AS "definerHasInsert",
|
||||
has_table_privilege('hivegrid_rls_definer', format('%I.%I', namespace.nspname, relation.relname), 'UPDATE') AS "definerHasUpdate",
|
||||
has_table_privilege('hivegrid_rls_definer', format('%I.%I', namespace.nspname, relation.relname), 'DELETE') AS "definerHasDelete",
|
||||
has_table_privilege('hivegrid_rls_definer', format('%I.%I', namespace.nspname, relation.relname), 'TRUNCATE') AS "definerHasTruncate",
|
||||
has_table_privilege('hivegrid_rls_definer', format('%I.%I', namespace.nspname, relation.relname), 'REFERENCES') AS "definerHasReferences",
|
||||
has_table_privilege('hivegrid_rls_definer', format('%I.%I', namespace.nspname, relation.relname), 'TRIGGER') AS "definerHasTrigger",
|
||||
has_any_column_privilege('hivegrid_rls_definer', format('%I.%I', namespace.nspname, relation.relname), 'INSERT') AS "definerHasColumnInsert",
|
||||
has_any_column_privilege('hivegrid_rls_definer', format('%I.%I', namespace.nspname, relation.relname), 'UPDATE') AS "definerHasColumnUpdate",
|
||||
has_any_column_privilege('hivegrid_rls_definer', format('%I.%I', namespace.nspname, relation.relname), 'REFERENCES') AS "definerHasColumnReferences",
|
||||
NULLIF(current_setting('app.user_id', true), '') IS NULL AS "userContextIsEmpty",
|
||||
NULLIF(current_setting('app.tenant_id', true), '') IS NULL AS "tenantContextIsEmpty"
|
||||
FROM pg_class AS relation
|
||||
JOIN pg_namespace AS namespace ON namespace.oid = relation.relnamespace
|
||||
CROSS JOIN pg_roles AS definer
|
||||
WHERE namespace.nspname = 'public'
|
||||
AND relation.relname IN ('Permission', 'Role', 'RolePermission')
|
||||
AND definer.rolname = 'hivegrid_rls_definer'
|
||||
ORDER BY relation.relname
|
||||
`);
|
||||
|
||||
const rowByTableName = new Map(rows.map((row) => [row.tableName, row]));
|
||||
if (rows.length !== CATALOG_TABLE_NAMES.length || CATALOG_TABLE_NAMES.some((tableName) => !rowByTableName.has(tableName))) {
|
||||
throw new Error("Permission catalog sync requires the complete reviewed table boundary");
|
||||
}
|
||||
|
||||
for (const tableName of CATALOG_TABLE_NAMES) {
|
||||
const row = rowByTableName.get(tableName);
|
||||
if (
|
||||
!row ||
|
||||
row.ownerName !== "hivegrid_migrator" ||
|
||||
row.currentUser !== "hivegrid_migrator" ||
|
||||
row.sessionUser !== "hivegrid_migrator" ||
|
||||
!row.rlsEnabled ||
|
||||
!row.forceRls ||
|
||||
row.definerCanLogin ||
|
||||
row.definerIsSuperuser ||
|
||||
row.definerCanCreateDatabase ||
|
||||
row.definerCanCreateRole ||
|
||||
row.definerInherits ||
|
||||
row.definerCanReplicate ||
|
||||
!row.definerBypassesRls ||
|
||||
!row.currentUserCanSetDefinerRole ||
|
||||
row.runtimeRoleHasDefinerMembership ||
|
||||
!row.definerHasSchemaUsage ||
|
||||
row.definerHasSchemaCreate ||
|
||||
!row.definerHasSelect ||
|
||||
row.definerHasInsert ||
|
||||
row.definerHasUpdate ||
|
||||
row.definerHasDelete ||
|
||||
row.definerHasTruncate ||
|
||||
row.definerHasReferences ||
|
||||
row.definerHasTrigger ||
|
||||
row.definerHasColumnInsert ||
|
||||
row.definerHasColumnUpdate ||
|
||||
row.definerHasColumnReferences ||
|
||||
!row.userContextIsEmpty ||
|
||||
!row.tenantContextIsEmpty
|
||||
) {
|
||||
throw new Error(`Permission catalog sync refuses changed security boundary for ${tableName}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function assertGlobalCatalogData(transaction: DeployPermissionCatalogTransaction) {
|
||||
const expectedRoles = [...defaultAdminRoleSeeds, ...defaultAppRoleSeeds];
|
||||
const roles = await transaction.role.findMany({
|
||||
where: { tenantId: null, name: { in: expectedRoles.map((role) => role.name) } },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
type: true,
|
||||
assignToNewUsers: true,
|
||||
isDefault: true,
|
||||
order: true,
|
||||
isTemplateOrigin: true,
|
||||
},
|
||||
});
|
||||
const permissions = await transaction.permission.findMany({
|
||||
where: { name: { in: [...defaultPermissionSeeds] } },
|
||||
select: { id: true, name: true, description: true, type: true, isDefault: true, order: true },
|
||||
});
|
||||
|
||||
const roleDescriptorByName = new Map(expectedRoles.map((descriptor, index) => [descriptor.name, { ...descriptor, order: index + 1 }] as const));
|
||||
const permissionDescriptorByName = new Map<string, (typeof defaultPermissionSeedDescriptors)[number] & { order: number }>(
|
||||
defaultPermissionSeedDescriptors.map((descriptor, index) => [descriptor.name, { ...descriptor, order: index + 1 }] as const)
|
||||
);
|
||||
|
||||
if (
|
||||
roles.length !== expectedRoles.length ||
|
||||
new Set(roles.map((role) => role.name)).size !== expectedRoles.length ||
|
||||
roles.some((role) => {
|
||||
const descriptor = roleDescriptorByName.get(role.name);
|
||||
return (
|
||||
!descriptor ||
|
||||
role.description !== descriptor.description ||
|
||||
role.type !== descriptor.type ||
|
||||
role.assignToNewUsers !== descriptor.assignToNewUsers ||
|
||||
!role.isDefault ||
|
||||
role.order !== descriptor.order ||
|
||||
role.isTemplateOrigin
|
||||
);
|
||||
}) ||
|
||||
permissions.length !== defaultPermissionSeeds.length ||
|
||||
new Set(permissions.map((permission) => permission.name)).size !== defaultPermissionSeeds.length ||
|
||||
permissions.some((permission) => {
|
||||
const descriptor = permissionDescriptorByName.get(permission.name);
|
||||
return (
|
||||
!descriptor ||
|
||||
permission.description !== descriptor.description ||
|
||||
permission.type !== descriptor.type ||
|
||||
!permission.isDefault ||
|
||||
permission.order !== descriptor.order
|
||||
);
|
||||
})
|
||||
) {
|
||||
throw new Error("Permission catalog sync did not produce the complete global catalog");
|
||||
}
|
||||
|
||||
const roleIdByName = new Map(roles.map((role) => [role.name, role.id]));
|
||||
const permissionIdByName = new Map(permissions.map((permission) => [permission.name, permission.id]));
|
||||
const desiredKeys = new Set<string>();
|
||||
for (const descriptor of defaultPermissionSeedDescriptors) {
|
||||
const permissionId = permissionIdByName.get(descriptor.name);
|
||||
if (!permissionId) {
|
||||
throw new Error("Permission catalog sync left an unresolved global permission");
|
||||
}
|
||||
for (const roleName of descriptor.inRoles) {
|
||||
const roleId = roleIdByName.get(roleName);
|
||||
if (!roleId) {
|
||||
throw new Error("Permission catalog sync left an unresolved global default role");
|
||||
}
|
||||
desiredKeys.add(`${roleId}:${permissionId}`);
|
||||
}
|
||||
}
|
||||
|
||||
const rolePermissions = await transaction.rolePermission.findMany({
|
||||
where: {
|
||||
roleId: { in: roles.map((role) => role.id) },
|
||||
permissionId: { in: permissions.map((permission) => permission.id) },
|
||||
},
|
||||
select: { roleId: true, permissionId: true },
|
||||
});
|
||||
const actualKeys = new Set(rolePermissions.map(({ roleId, permissionId }) => `${roleId}:${permissionId}`));
|
||||
if (rolePermissions.length !== desiredKeys.size || actualKeys.size !== desiredKeys.size || [...desiredKeys].some((key) => !actualKeys.has(key))) {
|
||||
throw new Error("Permission catalog sync did not produce the complete global default-role matrix");
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncDeployPermissionCatalog({
|
||||
client = getDbClient(),
|
||||
}: { client?: DeployPermissionCatalogClient } = {}): Promise<DeployPermissionCatalogSyncResult> {
|
||||
return client.$transaction(async (transaction) => {
|
||||
const catalogTransaction = transaction as DeployPermissionCatalogTransaction;
|
||||
|
||||
await catalogTransaction.$executeRawUnsafe("SET LOCAL lock_timeout = '5s'");
|
||||
await catalogTransaction.$executeRawUnsafe("SET LOCAL statement_timeout = '30s'");
|
||||
await catalogTransaction.$executeRawUnsafe("SET LOCAL idle_in_transaction_session_timeout = '30s'");
|
||||
await catalogTransaction.$executeRawUnsafe("SELECT pg_advisory_xact_lock(1212765778, 1347375955)");
|
||||
await catalogTransaction.$executeRawUnsafe('LOCK TABLE "Permission", "Role", "RolePermission" IN SHARE ROW EXCLUSIVE MODE');
|
||||
await assertCatalogBoundary(catalogTransaction);
|
||||
|
||||
for (const statement of TEMPORARY_DML_GRANTS) {
|
||||
await catalogTransaction.$executeRawUnsafe(statement);
|
||||
}
|
||||
await catalogTransaction.$executeRawUnsafe("SET LOCAL ROLE hivegrid_rls_definer");
|
||||
|
||||
const result = await syncDefaultRolesAndPermissions({ client: catalogTransaction });
|
||||
await assertGlobalCatalogData(catalogTransaction);
|
||||
|
||||
await catalogTransaction.$executeRawUnsafe("RESET ROLE");
|
||||
for (const statement of TEMPORARY_DML_REVOKES) {
|
||||
await catalogTransaction.$executeRawUnsafe(statement);
|
||||
}
|
||||
await assertCatalogBoundary(catalogTransaction);
|
||||
|
||||
return result;
|
||||
}, CATALOG_SYNC_TRANSACTION_OPTIONS);
|
||||
}
|
||||
|
||||
export function isDeployPermissionCatalogSyncDirectExecution(entrypoint = process.argv[1], moduleUrl = import.meta.url) {
|
||||
if (!entrypoint) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const modulePath = fileURLToPath(moduleUrl);
|
||||
const moduleFilename = path.basename(modulePath);
|
||||
return (
|
||||
(moduleFilename === "deploy-permission-catalog-sync.server.ts" || moduleFilename === "deploy-permission-catalog-sync.server.js") &&
|
||||
path.resolve(entrypoint) === modulePath
|
||||
);
|
||||
}
|
||||
|
||||
if (isDeployPermissionCatalogSyncDirectExecution()) {
|
||||
const client = getDbClient();
|
||||
syncDeployPermissionCatalog({ client })
|
||||
.then((result) => {
|
||||
process.stdout.write(`${JSON.stringify({ event: "permission-catalog-sync-complete", ...result })}\n`);
|
||||
})
|
||||
.catch((error) => {
|
||||
process.stderr.write(`${JSON.stringify({ event: "permission-catalog-sync-failed", error: { name: error instanceof Error ? error.name : "Error" } })}\n`);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(async () => {
|
||||
await client.$disconnect();
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user