4183 lines
206 KiB
JavaScript
4183 lines
206 KiB
JavaScript
#!/usr/bin/env node
|
|
import { createHash } from "node:crypto";
|
|
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
import {
|
|
APPEND_ONLY_TENANT_MODEL_CONTRACT,
|
|
DERIVED_OWNERSHIP_CONTRACT,
|
|
DIRECT_SCALAR_TENANT_REFERENCE_CONTRACT,
|
|
DIRECT_WORKER_POLICY_CONTRACT,
|
|
DIRECT_RELATION_GLOBAL_PARENT_CONTRACT,
|
|
GLOBAL_GUARDED_EXTRA_MODELS,
|
|
GLOBAL_GUARDED_MODEL_CONTRACT,
|
|
GLOBAL_SHARED_POLICY_CONTRACT,
|
|
MIXED_POLICY_CONTRACT,
|
|
PLATFORM_ADMIN_POLICY_CONTRACT,
|
|
TENANT_RESOLVER_CONTRACT,
|
|
TENANT_ROOT_POLICY_CONTRACT,
|
|
} from "../prisma/tenant-policy-contract.mjs";
|
|
import { GLOBAL_IMPLICIT_TABLES, TENANT_SCOPED_IMPLICIT_TABLES, TENANT_SCOPE_MANIFEST } from "../prisma/tenant-scope-manifest.mjs";
|
|
import { modelRequiresTenantRls, parsePrismaSchemaDirectory, validateTenantScopeManifest } from "./lib/prisma-tenant-scope.mjs";
|
|
|
|
export const GENERATED_POLICY_PATH = "prisma/rls/tenant-policy-contract-isolation.sql";
|
|
// The reviewed baseline is immutable. Later policy additions are rendered as
|
|
// additive SQL via renderPostCutoverPolicyDeltaSql().
|
|
export const GENERATED_MIGRATION_PATH = "prisma/migrations/00000000000000_hivegrid_baseline/migration.sql";
|
|
export const GENERATED_RUNTIME_CONTRACT_PATH = "packages/db/src/rls-runtime-contract.generated.ts";
|
|
export const FROZEN_BASELINE_MIGRATION_SHA256 = "f39a3e6800356d3199b1274a492721217c12c0c5cafcf3f648b3050868c3abbe";
|
|
export const EXPECTED_POLICY_DEFINITION_COUNT = 377;
|
|
export const EXPECTED_FORCED_RLS_COUNT = 377;
|
|
export const EXPECTED_TENANT_RESOLVER_NAMES = Object.freeze([
|
|
"hivegrid_resolve_admin_sso_identity_v2",
|
|
"hivegrid_resolve_admin_session_identity",
|
|
"hivegrid_resolve_user_email",
|
|
"hivegrid_resolve_user_session",
|
|
"hivegrid_resolve_trusted_device",
|
|
"hivegrid_resolve_public_form_key",
|
|
"hivegrid_resolve_public_form_slug",
|
|
"hivegrid_resolve_public_booking_page",
|
|
"hivegrid_resolve_admin_booking_page",
|
|
"hivegrid_resolve_calendar_webhook",
|
|
"hivegrid_resolve_aircall_webhook",
|
|
"hivegrid_resolve_hallopetra_webhook",
|
|
"hivegrid_resolve_admin_aircall_webhook",
|
|
"hivegrid_resolve_gmail_mailboxes",
|
|
"hivegrid_resolve_microsoft_mailbox",
|
|
"hivegrid_resolve_signature_signer",
|
|
"hivegrid_resolve_outbound_email_click",
|
|
"hivegrid_resolve_outbound_email_open",
|
|
"hivegrid_resolve_public_knowledge_base",
|
|
"hivegrid_resolve_workspace_invite",
|
|
"hivegrid_resolve_api_key",
|
|
"hivegrid_resolve_public_webhook",
|
|
"hivegrid_resolve_mcp_oauth_access_token",
|
|
"hivegrid_resolve_mcp_oauth_refresh_token",
|
|
"hivegrid_resolve_mcp_oauth_authorization_code",
|
|
"hivegrid_resolve_tenant_inbound_address",
|
|
"hivegrid_resolve_email_sequence_provider_message",
|
|
"hivegrid_resolve_event_webhook_attempt",
|
|
"hivegrid_resolve_email_sequence_delivery",
|
|
]);
|
|
|
|
const TENANT_CONTEXT_SQL = "NULLIF(current_setting('app.tenant_id', true), '')";
|
|
const USER_CONTEXT_SQL = "NULLIF(current_setting('app.user_id', true), '')";
|
|
const PUBLIC_KNOWLEDGE_BASE_CONTEXT_SQL = "NULLIF(current_setting('app.public_knowledge_base_id', true), '')";
|
|
const OPERATOR_CONTEXT_SQL = "public.hivegrid_is_operator()";
|
|
const APP_CONTEXT_SQL = "current_user = 'hivegrid_app'";
|
|
const WORKER_CONTEXT_SQL = "current_user = 'hivegrid_worker'";
|
|
const PLATFORM_ANALYTICS_CONTEXT_SQL = `(${APP_CONTEXT_SQL} AND NULLIF(current_setting('app.platform_analytics', true), '') = 'true' AND ${TENANT_CONTEXT_SQL} IS NULL AND ${USER_CONTEXT_SQL} IS NULL)`;
|
|
const TENANT_POLICY_ROLES = Object.freeze(["hivegrid_app", "hivegrid_worker"]);
|
|
const APP_ROLE = "hivegrid_app";
|
|
const WORKER_ROLE = "hivegrid_worker";
|
|
const AUTHENTIK_JIT_ROLE = "hivegrid_authentik_jit";
|
|
const EXPECTED_APPEND_ONLY_TENANT_MODELS = Object.freeze(["TeamChatEvent"]);
|
|
const ADMIN_SALES_OWNER_FIELDS = Object.freeze({
|
|
AdminLead: "assignedToAdminUserId",
|
|
AdminDeal: "ownerAdminUserId",
|
|
AdminTask: "assignedToAdminUserId",
|
|
AdminTaskRecurrence: "createdByAdminUserId",
|
|
});
|
|
const ADMIN_EMAIL_MODELS = new Set([
|
|
"AdminMailbox",
|
|
"AdminMailboxSyncCursor",
|
|
"AdminMailboxWebhookEvent",
|
|
"AdminEmailThread",
|
|
"AdminEmailMessage",
|
|
"AdminEmailParticipant",
|
|
"AdminEmailAttachment",
|
|
"AdminEmailEvent",
|
|
"AdminEmailLink",
|
|
"AdminEmailTemplate",
|
|
"AdminEmailSnippet",
|
|
"AdminEmailSignature",
|
|
"AdminEmailOutboundPolicy",
|
|
"AdminScheduledEmail",
|
|
"AdminNoReplyReminder",
|
|
"AdminBulkEmailRun",
|
|
"AdminSendingDomain",
|
|
"AdminBccAddress",
|
|
]);
|
|
const ADMIN_PHONE_MODELS = new Set([
|
|
"AdminPhoneConnection",
|
|
"AdminPhoneNumber",
|
|
"AdminTelephonyPolicy",
|
|
"AdminCallSession",
|
|
"AdminCallParticipant",
|
|
"AdminCallEvent",
|
|
"AdminCallMatchCandidate",
|
|
"AdminCallRecording",
|
|
"AdminDialerList",
|
|
"AdminDialerEntry",
|
|
"AdminOutboundCallRequest",
|
|
]);
|
|
const ADMIN_BOOKING_MODELS = new Set([
|
|
"AdminAvailabilityRule",
|
|
"AdminAvailabilityOverride",
|
|
"AdminBooking",
|
|
"AdminBookingParticipant",
|
|
"AdminBookingAssignment",
|
|
"AdminBookingReminder",
|
|
]);
|
|
|
|
function quoteIdentifier(identifier) {
|
|
return `"${identifier.replaceAll('"', '""')}"`;
|
|
}
|
|
|
|
function quoteLiteral(value) {
|
|
return `'${value.replaceAll("'", "''")}'`;
|
|
}
|
|
|
|
function renderScalarLiteral(value) {
|
|
if (typeof value === "string") return quoteLiteral(value);
|
|
if (typeof value === "boolean") return value ? "true" : "false";
|
|
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
if (value === null) return "NULL";
|
|
throw new TypeError(`Unsupported policy literal ${String(value)}`);
|
|
}
|
|
|
|
function renderFieldPredicates(alias, fields) {
|
|
return Object.entries(fields ?? {}).map(([field, value]) => {
|
|
const column = `${alias}.${quoteIdentifier(field)}`;
|
|
if (value && typeof value === "object" && value.notNull === true && Object.keys(value).length === 1) {
|
|
return `${column} IS NOT NULL`;
|
|
}
|
|
if (value && typeof value === "object" && Array.isArray(value.oneOf) && Object.keys(value).length === 1) {
|
|
if (value.oneOf.length === 0) throw new TypeError(`Policy oneOf predicate for ${field} must not be empty`);
|
|
return `${column} IN (${value.oneOf.map(renderScalarLiteral).join(", ")})`;
|
|
}
|
|
return value === null ? `${column} IS NULL` : `${column} = ${renderScalarLiteral(value)}`;
|
|
});
|
|
}
|
|
|
|
function compareContractKeys(label, expected, actual, errors) {
|
|
const expectedNames = new Set(expected);
|
|
const actualNames = new Set(Object.keys(actual));
|
|
for (const model of expectedNames) {
|
|
if (!actualNames.has(model)) errors.push(`${label} is missing ${model}`);
|
|
}
|
|
for (const model of actualNames) {
|
|
if (!expectedNames.has(model)) errors.push(`${label} contains unexpected model ${model}`);
|
|
}
|
|
}
|
|
|
|
function inspectTenantResolvers(resolverContract, modelsByName, errors) {
|
|
compareContractKeys("tenant resolver contract", EXPECTED_TENANT_RESOLVER_NAMES, resolverContract, errors);
|
|
const resolvers = [];
|
|
for (const [name, contract] of Object.entries(resolverContract)) {
|
|
if (!/^hivegrid_resolve_[a-z0-9_]+$/.test(name)) {
|
|
errors.push(`tenant resolver has unsafe function name ${name}`);
|
|
}
|
|
if (!Array.isArray(contract.parameters) || contract.parameters.length === 0) {
|
|
errors.push(`${name} must declare at least one parameter`);
|
|
continue;
|
|
}
|
|
const parameterNames = new Set();
|
|
let sawDefault = false;
|
|
for (const parameter of contract.parameters) {
|
|
if (!/^p_[a-z0-9_]+$/.test(parameter.name)) {
|
|
errors.push(`${name} has unsafe parameter name ${String(parameter.name)}`);
|
|
}
|
|
if (parameterNames.has(parameter.name)) errors.push(`${name} repeats parameter ${parameter.name}`);
|
|
parameterNames.add(parameter.name);
|
|
if (!new Set(["text", "text[]"]).has(parameter.type)) {
|
|
errors.push(`${name}.${parameter.name} uses unsupported SQL type ${String(parameter.type)}`);
|
|
}
|
|
if (parameter.defaultSql !== undefined) {
|
|
sawDefault = true;
|
|
if (parameter.defaultSql !== "NULL") {
|
|
errors.push(`${name}.${parameter.name} uses unsupported default ${String(parameter.defaultSql)}`);
|
|
}
|
|
} else if (sawDefault) {
|
|
errors.push(`${name} has a required parameter after a defaulted parameter`);
|
|
}
|
|
}
|
|
const query = typeof contract.query === "string" ? contract.query.trim() : "";
|
|
if (!/^(SELECT|WITH)\b/.test(query)) errors.push(`${name} resolver query must start with SELECT or WITH`);
|
|
if (/;|\b(?:INSERT|UPDATE|DELETE|MERGE|GRANT|REVOKE|ALTER|DROP|CREATE|CALL|COPY)\b/i.test(query)) {
|
|
errors.push(`${name} resolver query must be read-only and contain no statement separator`);
|
|
}
|
|
for (const outputColumn of ["tenant_id", "resource_id", "user_id"]) {
|
|
if (!new RegExp(`\\bAS\\s+${outputColumn}\\b`, "i").test(query)) {
|
|
errors.push(`${name} resolver query does not project ${outputColumn}`);
|
|
}
|
|
}
|
|
const readModels = contract.readModels ?? [];
|
|
if (!Array.isArray(readModels) || readModels.some((model) => typeof model !== "string" || !modelsByName.has(model))) {
|
|
errors.push(`${name} declares an unknown resolver read model`);
|
|
}
|
|
resolvers.push({ name, parameters: contract.parameters, query, readModels: [...readModels] });
|
|
}
|
|
return resolvers;
|
|
}
|
|
|
|
function platformAccessSpec(model, access, errors) {
|
|
const table = quoteIdentifier(model);
|
|
const tenant = `"tenantId" = ${TENANT_CONTEXT_SQL}`;
|
|
const identity = `"userId" = ${USER_CONTEXT_SQL}`;
|
|
const optionalTenant = `("tenantId" IS NULL OR ${tenant})`;
|
|
const optionalIdentity = `("userId" IS NULL OR ${identity})`;
|
|
const tenantMember = `EXISTS (SELECT 1 FROM "TenantUser" AS "platform_target_membership" WHERE "platform_target_membership"."tenantId" = ${table}."tenantId" AND "platform_target_membership"."userId" = ${table}."userId")`;
|
|
const tenantMemberOrPretenantIdentity = `(("tenantId" IS NULL AND ${optionalIdentity}) OR (${tenant} AND ("userId" IS NULL OR ${tenantMember})))`;
|
|
const ticketTenant = `EXISTS (SELECT 1 FROM "SupportTicket" AS "platform_ticket" WHERE "platform_ticket"."id" = "SupportTicketMessage"."supportTicketId" AND "platform_ticket"."tenantId" = ${TENANT_CONTEXT_SQL})`;
|
|
const hasPermission = (permission) => `public.hivegrid_admin_has_permission(${quoteLiteral(permission)})`;
|
|
const operatorWithPermission = (permission) => `(${OPERATOR_CONTEXT_SQL} AND ${hasPermission(permission)})`;
|
|
const salesOwnerField = ADMIN_SALES_OWNER_FIELDS[model];
|
|
const salesRead = operatorWithPermission("admin_sales.crm.read");
|
|
const salesWrite = operatorWithPermission("admin_sales.crm.write");
|
|
const salesOwnerRead = (owner) => `(${salesRead} AND (${owner} = ${USER_CONTEXT_SQL} OR ${hasPermission("admin_sales.crm.read_all")}))`;
|
|
const salesOwnerWrite = (owner) => `(${salesWrite} AND (${owner} = ${USER_CONTEXT_SQL} OR ${hasPermission("admin_sales.crm.write_all")}))`;
|
|
const salesOwnedRead = salesOwnerRead(salesOwnerField ? `${table}.${quoteIdentifier(salesOwnerField)}` : "NULL");
|
|
const salesOwnedWrite = salesOwnerWrite(salesOwnerField ? `${table}.${quoteIdentifier(salesOwnerField)}` : "NULL");
|
|
const emailPermission =
|
|
"(public.hivegrid_admin_has_permission('admin_sales.email.connect') OR public.hivegrid_admin_has_permission('admin_sales.email.send') OR public.hivegrid_admin_has_permission('admin_sales.email.track') OR public.hivegrid_admin_has_permission('admin_sales.email.bulk_send'))";
|
|
const phonePermission =
|
|
"(public.hivegrid_admin_has_permission('admin_sales.phone.call') OR public.hivegrid_admin_has_permission('admin_sales.phone.recording'))";
|
|
const bookingPermission = "public.hivegrid_admin_has_permission('admin_sales.booking.manage')";
|
|
const communicationPermission = ADMIN_EMAIL_MODELS.has(model)
|
|
? emailPermission
|
|
: ADMIN_PHONE_MODELS.has(model)
|
|
? phonePermission
|
|
: ADMIN_BOOKING_MODELS.has(model)
|
|
? bookingPermission
|
|
: "false";
|
|
const communicationOwn = `${table}."adminUserId" = ${USER_CONTEXT_SQL}`;
|
|
const communicationRead = `(${OPERATOR_CONTEXT_SQL} AND ((${communicationOwn} AND ${communicationPermission}) OR ${hasPermission("admin_sales.communication.read_all")}))`;
|
|
const communicationWrite = `(${OPERATOR_CONTEXT_SQL} AND ${communicationOwn} AND ${communicationPermission})`;
|
|
const relatedOwnerAccess = (relatedTable, relationField, ownerField, access) => {
|
|
const alias = quoteIdentifier(`admin_scope_${relatedTable.toLowerCase()}`);
|
|
const owner = `${alias}.${quoteIdentifier(ownerField)}`;
|
|
const permission = access === "read" ? salesOwnerRead(owner) : salesOwnerWrite(owner);
|
|
return `EXISTS (SELECT 1 FROM ${quoteIdentifier(relatedTable)} AS ${alias} WHERE ${alias}."id" = ${table}.${quoteIdentifier(relationField)} AND ${permission})`;
|
|
};
|
|
const relatedCommunicationAccess = (relatedTable, relationField, permission, access) => {
|
|
const alias = quoteIdentifier(`admin_scope_${relatedTable.toLowerCase()}`);
|
|
const own = `${alias}."adminUserId" = ${USER_CONTEXT_SQL}`;
|
|
const allowed = access === "read" ? `((${own} AND ${permission}) OR ${hasPermission("admin_sales.communication.read_all")})` : `(${own} AND ${permission})`;
|
|
return `EXISTS (SELECT 1 FROM ${quoteIdentifier(relatedTable)} AS ${alias} WHERE ${alias}."id" = ${table}.${quoteIdentifier(relationField)} AND ${OPERATOR_CONTEXT_SQL} AND ${allowed})`;
|
|
};
|
|
const leadAccess = (field, access) => relatedOwnerAccess("AdminLead", field, "assignedToAdminUserId", access);
|
|
const dealAccess = (field, access) => relatedOwnerAccess("AdminDeal", field, "ownerAdminUserId", access);
|
|
const taskAccess = (field, access) => relatedOwnerAccess("AdminTask", field, "assignedToAdminUserId", access);
|
|
const nullableRelation = (field, expression) => `(${table}.${quoteIdentifier(field)} IS NULL OR ${expression})`;
|
|
const leadChildRead = leadAccess("leadId", "read");
|
|
const leadChildWrite = leadAccess("leadId", "write");
|
|
const dealChildRead = dealAccess("dealId", "read");
|
|
const dealChildWrite = dealAccess("dealId", "write");
|
|
const dealHistoryWrite = `(${dealChildWrite} AND ${table}."actorAdminUserId" = ${USER_CONTEXT_SQL})`;
|
|
const pairedLeadRead = `(${leadAccess("primaryLeadId", "read")} AND ${leadAccess("duplicateLeadId", "read")})`;
|
|
const pairedLeadWrite = `(${leadAccess("primaryLeadId", "write")} AND ${leadAccess("duplicateLeadId", "write")})`;
|
|
const mergedLeadRead = `(${leadAccess("survivorLeadId", "read")} AND ${leadAccess("mergedLeadId", "read")})`;
|
|
const mergedLeadWrite = `(${leadAccess("survivorLeadId", "write")} AND ${leadAccess("mergedLeadId", "write")})`;
|
|
const mergeRecordWrite = `(${mergedLeadWrite} AND ${table}."actorAdminUserId" = ${USER_CONTEXT_SQL})`;
|
|
const customValueRead = `(${salesRead} AND ${nullableRelation("dealId", dealAccess("dealId", "read"))})`;
|
|
const customValueWrite = `(${salesWrite} AND ${nullableRelation("dealId", dealAccess("dealId", "write"))})`;
|
|
const activityRead = `(${salesRead} AND ${nullableRelation("leadId", leadAccess("leadId", "read"))} AND ${nullableRelation("dealId", dealAccess("dealId", "read"))} AND ${nullableRelation("taskId", taskAccess("taskId", "read"))} AND ${nullableRelation("emailMessageId", relatedCommunicationAccess("AdminEmailMessage", "emailMessageId", emailPermission, "read"))} AND ${nullableRelation("callSessionId", relatedCommunicationAccess("AdminCallSession", "callSessionId", phonePermission, "read"))} AND ${nullableRelation("bookingId", relatedCommunicationAccess("AdminBooking", "bookingId", bookingPermission, "read"))})`;
|
|
const activityWrite = `(${table}."actorAdminUserId" = ${USER_CONTEXT_SQL} AND ${salesWrite} AND ${nullableRelation("leadId", leadAccess("leadId", "write"))} AND ${nullableRelation("dealId", dealAccess("dealId", "write"))} AND ${nullableRelation("taskId", taskAccess("taskId", "write"))} AND ${nullableRelation("emailMessageId", relatedCommunicationAccess("AdminEmailMessage", "emailMessageId", emailPermission, "write"))} AND ${nullableRelation("callSessionId", relatedCommunicationAccess("AdminCallSession", "callSessionId", phonePermission, "write"))} AND ${nullableRelation("bookingId", relatedCommunicationAccess("AdminBooking", "bookingId", bookingPermission, "write"))})`;
|
|
const leadActivityWrite = `(${leadChildWrite} AND ((${table}."actorAdminUserId" = ${USER_CONTEXT_SQL}) OR (${table}."actorAdminUserId" IS NULL AND ${table}."id" LIKE 'legacy-activity:%' AND EXISTS (SELECT 1 FROM "AdminLead" AS "legacy_import_parent" WHERE "legacy_import_parent"."id" = ${table}."leadId" AND "legacy_import_parent"."externalId" LIKE 'legacy:%'))))`;
|
|
const specs = {
|
|
none: { expression: "false", roles: [] },
|
|
operator: { expression: OPERATOR_CONTEXT_SQL, roles: [APP_ROLE] },
|
|
"operator-actor": {
|
|
expression: `("actorAdminUserId" = ${USER_CONTEXT_SQL} AND ${OPERATOR_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"operator-created-by": {
|
|
expression: `("createdByAdminUserId" = ${USER_CONTEXT_SQL} AND ${OPERATOR_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"operator-actor-or-worker": {
|
|
expression: `((${table}."actorAdminUserId" = ${USER_CONTEXT_SQL} AND ${OPERATOR_CONTEXT_SQL}) OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"operator-created-by-or-worker": {
|
|
expression: `((${table}."createdByAdminUserId" = ${USER_CONTEXT_SQL} AND ${OPERATOR_CONTEXT_SQL}) OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"operator-admin-user": {
|
|
expression: `(${table}."adminUserId" = ${USER_CONTEXT_SQL} AND ${OPERATOR_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"operator-admin-user-or-worker": {
|
|
expression: `((${table}."adminUserId" = ${USER_CONTEXT_SQL} AND ${OPERATOR_CONTEXT_SQL}) OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"admin-sales-shared-read": {
|
|
expression: salesRead,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-shared-read-or-worker": {
|
|
expression: `(${salesRead} OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"admin-sales-shared-write": {
|
|
expression: salesWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-shared-write-or-worker": {
|
|
expression: `(${salesWrite} OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"admin-sales-owned-read": {
|
|
expression: salesOwnedRead,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-owned-read-or-worker": {
|
|
expression: `(${salesOwnedRead} OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"admin-sales-owned-write": {
|
|
expression: salesOwnedWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-owned-write-or-worker": {
|
|
expression: `(${salesOwnedWrite} OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"admin-sales-lead-child-read": {
|
|
expression: leadChildRead,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-lead-child-write": {
|
|
expression: leadChildWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-lead-activity-write": {
|
|
expression: leadActivityWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-paired-lead-read": {
|
|
expression: pairedLeadRead,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-paired-lead-write": {
|
|
expression: pairedLeadWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-merged-lead-read": {
|
|
expression: mergedLeadRead,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-merged-lead-write": {
|
|
expression: mergedLeadWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-deal-child-read": {
|
|
expression: dealChildRead,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-deal-child-write": {
|
|
expression: dealChildWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-deal-history-write": {
|
|
expression: dealHistoryWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-custom-value-read": {
|
|
expression: customValueRead,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-custom-value-write": {
|
|
expression: customValueWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-activity-read": {
|
|
expression: activityRead,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-sales-activity-write-or-worker": {
|
|
expression: `(${activityWrite} OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"admin-sales-merge-record-write": {
|
|
expression: mergeRecordWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-communication-read": {
|
|
expression: communicationRead,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-communication-read-or-worker": {
|
|
expression: `(${communicationRead} OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"admin-communication-write": {
|
|
expression: communicationWrite,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"admin-communication-write-or-worker": {
|
|
expression: `(${communicationWrite} OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"operator-requested-by-or-worker": {
|
|
expression: `((${table}."requestedByAdminUserId" = ${USER_CONTEXT_SQL} AND ${OPERATOR_CONTEXT_SQL}) OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"operator-actor-or-legacy-import": {
|
|
expression: `((${OPERATOR_CONTEXT_SQL}) AND (("actorAdminUserId" = ${USER_CONTEXT_SQL}) OR ("actorAdminUserId" IS NULL AND ${table}."id" LIKE 'legacy-activity:%' AND EXISTS (SELECT 1 FROM "AdminLead" AS "legacy_import_parent" WHERE "legacy_import_parent"."id" = ${table}."leadId" AND "legacy_import_parent"."externalId" LIKE 'legacy:%'))))`,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"operator-tenant": {
|
|
expression: `(${tenant} AND ${OPERATOR_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"tenant-or-identity-or-operator": {
|
|
expression: `(${tenant} OR ${identity} OR ${OPERATOR_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"scoped-or-anonymous-or-operator": {
|
|
expression: `((${optionalTenant} AND ${optionalIdentity}) OR ${OPERATOR_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE],
|
|
},
|
|
"tenant-member-or-pretenant-identity-or-operator": {
|
|
expression: `(${tenantMemberOrPretenantIdentity} OR ${OPERATOR_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE],
|
|
},
|
|
app: { expression: "true", roles: [APP_ROLE] },
|
|
worker: { expression: "true", roles: [WORKER_ROLE] },
|
|
"operator-or-worker": {
|
|
expression: `(${OPERATOR_CONTEXT_SQL} OR ${WORKER_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE, WORKER_ROLE],
|
|
},
|
|
"public-ticket-tenant-or-operator": {
|
|
expression: `(("internalNote" = false AND ${ticketTenant}) OR ${OPERATOR_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE],
|
|
},
|
|
};
|
|
const spec = specs[access];
|
|
if (!spec) {
|
|
errors.push(`${model} has unsupported platform access ${String(access)}`);
|
|
return { expression: "false", roles: [APP_ROLE] };
|
|
}
|
|
return spec;
|
|
}
|
|
|
|
function compilePlatformPolicy(model, contract, errors) {
|
|
const expectedCommands = ["select", "insert", "update", "delete"];
|
|
compareContractKeys(`${model.model} platform commands`, expectedCommands, contract.commands ?? {}, errors);
|
|
const compiled = Object.fromEntries(expectedCommands.map((command) => [command, platformAccessSpec(model.model, contract.commands?.[command], errors)]));
|
|
const updateCheck = platformAccessSpec(model.model, contract.updateCheck ?? contract.commands?.update, errors);
|
|
return {
|
|
model: model.model,
|
|
schema: model.schema,
|
|
table: model.table,
|
|
scope: "platform-admin",
|
|
enforcement: "platform-policy",
|
|
readExpression: compiled.select.expression,
|
|
writeExpression: updateCheck.expression,
|
|
commandExpressions: Object.fromEntries(expectedCommands.map((command) => [command, compiled[command].expression])),
|
|
commandRoles: Object.fromEntries(expectedCommands.map((command) => [command, compiled[command].roles])),
|
|
updateCheckExpression: updateCheck.expression,
|
|
integrityChecks: [],
|
|
paths: [
|
|
`reviewed platform policy: ${Object.values(contract.commands ?? {}).join(" / ")}`,
|
|
...(contract.updateCheck ? [`UPDATE WITH CHECK: ${contract.updateCheck}`] : []),
|
|
],
|
|
policyNames: commandPolicyNames(model.model),
|
|
forceRls: true,
|
|
};
|
|
}
|
|
|
|
function globalSharedAccessSpec(model, access, errors) {
|
|
const table = quoteIdentifier(model);
|
|
const userOwned = `${table}."userId" = ${USER_CONTEXT_SQL}`;
|
|
const currentUser = `${table}."id" = ${USER_CONTEXT_SQL}`;
|
|
const userVisibleInTenant = `(${currentUser} OR ${OPERATOR_CONTEXT_SQL} OR (${TENANT_CONTEXT_SQL} IS NOT NULL AND EXISTS (SELECT 1 FROM "TenantUser" AS "visible_membership" WHERE "visible_membership"."userId" = ${table}."id" AND "visible_membership"."tenantId" = ${TENANT_CONTEXT_SQL})))`;
|
|
const specs = {
|
|
none: { expression: "false", roles: [] },
|
|
operator: { expression: OPERATOR_CONTEXT_SQL, roles: [APP_ROLE] },
|
|
"runtime-read": { expression: "true", roles: TENANT_POLICY_ROLES },
|
|
"user-visible": { expression: userVisibleInTenant, roles: TENANT_POLICY_ROLES },
|
|
"current-user": { expression: `(${currentUser} OR ${OPERATOR_CONTEXT_SQL})`, roles: TENANT_POLICY_ROLES },
|
|
"user-owned": { expression: `(${userOwned} OR ${OPERATOR_CONTEXT_SQL})`, roles: TENANT_POLICY_ROLES },
|
|
"active-or-operator": {
|
|
expression: `("active" = true OR ${OPERATOR_CONTEXT_SQL})`,
|
|
roles: [APP_ROLE],
|
|
},
|
|
};
|
|
const spec = specs[access];
|
|
if (!spec) {
|
|
errors.push(`${model} has unsupported global-shared access ${String(access)}`);
|
|
return specs.none;
|
|
}
|
|
return spec;
|
|
}
|
|
|
|
function compileGlobalSharedPolicy(model, contract, errors) {
|
|
const expectedCommands = ["select", "insert", "update", "delete"];
|
|
compareContractKeys(`${model.model} global-shared commands`, expectedCommands, contract.commands ?? {}, errors);
|
|
if (!new Set(["reviewed", "pending-runtime-contract"]).has(contract.status)) {
|
|
errors.push(`${model.model} has invalid global-shared contract status ${String(contract.status)}`);
|
|
}
|
|
const compiled = Object.fromEntries(expectedCommands.map((command) => [command, globalSharedAccessSpec(model.model, contract.commands?.[command], errors)]));
|
|
if (contract.status === "pending-runtime-contract" && expectedCommands.some((command) => contract.commands?.[command] !== "none")) {
|
|
errors.push(`${model.model} pending global-shared contract must deny every command`);
|
|
}
|
|
return {
|
|
model: model.model,
|
|
schema: model.schema,
|
|
table: model.table,
|
|
scope: "global-shared",
|
|
enforcement: contract.status === "pending-runtime-contract" ? "deny-pending-review" : "global-command-policy",
|
|
readExpression: compiled.select.expression,
|
|
writeExpression: compiled.update.expression,
|
|
commandExpressions: Object.fromEntries(expectedCommands.map((command) => [command, compiled[command].expression])),
|
|
commandRoles: Object.fromEntries(expectedCommands.map((command) => [command, compiled[command].roles])),
|
|
integrityChecks: [],
|
|
paths: [`reviewed global-shared policy: ${Object.values(contract.commands ?? {}).join(" / ")}`],
|
|
policyNames: commandPolicyNames(model.model),
|
|
forceRls: true,
|
|
};
|
|
}
|
|
|
|
function resolveOwnershipPath(startModel, pathContract, modelsByName, errors, terminalKind = "tenant") {
|
|
const steps = [];
|
|
let current = modelsByName.get(startModel);
|
|
if (!current) return null;
|
|
|
|
for (const relationName of pathContract.relations) {
|
|
const relation = current.owningRelations.find((candidate) => candidate.field === relationName);
|
|
if (!relation) {
|
|
errors.push(`${startModel} ownership path references missing relation ${current.model}.${relationName}`);
|
|
return null;
|
|
}
|
|
if (relation.fields.length !== relation.references.length) {
|
|
errors.push(`${current.model}.${relationName} has mismatched FK/reference arity`);
|
|
return null;
|
|
}
|
|
const target = modelsByName.get(relation.target);
|
|
if (!target) {
|
|
errors.push(`${current.model}.${relationName} targets unknown model ${relation.target}`);
|
|
return null;
|
|
}
|
|
steps.push({ from: current, relation, target });
|
|
current = target;
|
|
}
|
|
|
|
if (steps.length === 0) {
|
|
errors.push(`${startModel} ownership path must contain at least one relation`);
|
|
return null;
|
|
}
|
|
if (terminalKind === "tenant" && !current.tenantField) {
|
|
errors.push(`${startModel} ownership path ends at ${current.model}, which has no tenantId field`);
|
|
return null;
|
|
}
|
|
if (terminalKind === "identity" && current.model !== "User") {
|
|
errors.push(`${startModel} identity path ends at ${current.model}, expected User`);
|
|
return null;
|
|
}
|
|
if (terminalKind === "tenant" && pathContract.allowGlobalRead === true && current.tenantField.nullable !== true) {
|
|
errors.push(`${startModel} allows global reads through non-nullable terminal ${current.model}`);
|
|
}
|
|
if (terminalKind === "tenant" && pathContract.allowGlobalWrite === true && current.tenantField.nullable !== true) {
|
|
errors.push(`${startModel} allows global writes through non-nullable terminal ${current.model}`);
|
|
}
|
|
if (terminalKind === "tenant" && pathContract.workerReadGlobal === true && current.tenantField.nullable !== true) {
|
|
errors.push(`${startModel} allows global worker reads through non-nullable terminal ${current.model}`);
|
|
}
|
|
if (terminalKind === "tenant" && pathContract.workerWriteGlobal === true && current.tenantField.nullable !== true) {
|
|
errors.push(`${startModel} allows global worker writes through non-nullable terminal ${current.model}`);
|
|
}
|
|
if (terminalKind === "tenant" && pathContract.operatorReadGlobal === true && current.tenantField.nullable !== true) {
|
|
errors.push(`${startModel} allows global operator reads through non-nullable terminal ${current.model}`);
|
|
}
|
|
if (terminalKind === "tenant" && pathContract.operatorWriteGlobal === true && current.tenantField.nullable !== true) {
|
|
errors.push(`${startModel} allows global operator writes through non-nullable terminal ${current.model}`);
|
|
}
|
|
if (pathContract.globalReadFields && pathContract.allowGlobalRead !== true) {
|
|
errors.push(`${startModel} declares globalReadFields without allowGlobalRead`);
|
|
}
|
|
if (pathContract.globalWriteFields && pathContract.allowGlobalWrite !== true) {
|
|
errors.push(`${startModel} declares globalWriteFields without allowGlobalWrite`);
|
|
}
|
|
if ((pathContract.publicReadGlobal === true || pathContract.publicWriteGlobal === true) && current.model !== "KnowledgeBase") {
|
|
errors.push(`${startModel} public knowledge-base path ends at ${current.model}`);
|
|
}
|
|
if (pathContract.publicWriteGlobal === true && pathContract.publicReadGlobal !== true) {
|
|
errors.push(`${startModel} allows public knowledge-base writes without public reads`);
|
|
}
|
|
if (
|
|
(pathContract.publicTerminalFields || pathContract.publicRowFields || pathContract.publicPathFields) &&
|
|
pathContract.publicReadGlobal !== true &&
|
|
pathContract.publicWriteGlobal !== true
|
|
) {
|
|
errors.push(`${startModel} declares public knowledge-base fields without public access`);
|
|
}
|
|
for (const modelName of Object.keys(pathContract.publicPathFields ?? {})) {
|
|
if (!steps.some((step) => step.target.model === modelName)) {
|
|
errors.push(`${startModel} public knowledge-base path fields reference absent model ${modelName}`);
|
|
}
|
|
}
|
|
|
|
return { steps, terminal: current, contract: pathContract };
|
|
}
|
|
|
|
function describeResolvedPath(resolved) {
|
|
return resolved.steps.map((step) => `${step.from.model}.${step.relation.field}->${step.target.model}`).join(" -> ");
|
|
}
|
|
|
|
function compileResolvedPath(startModel, resolved, mode, tenantExpression = TENANT_CONTEXT_SQL) {
|
|
const outerTable = quoteIdentifier(resolved.steps[0].from.table);
|
|
const aliases = resolved.steps.map((_, index) => quoteIdentifier(`owner_${index}`));
|
|
const first = resolved.steps[0];
|
|
const from = `${quoteIdentifier(first.target.table)} AS ${aliases[0]}`;
|
|
const joins = [];
|
|
const predicates = first.relation.fields.map(
|
|
(field, index) => `${aliases[0]}.${quoteIdentifier(first.relation.references[index])} = ${outerTable}.${quoteIdentifier(field)}`
|
|
);
|
|
|
|
for (let index = 1; index < resolved.steps.length; index += 1) {
|
|
const step = resolved.steps[index];
|
|
const previousAlias = aliases[index - 1];
|
|
const alias = aliases[index];
|
|
const on = step.relation.fields.map(
|
|
(field, fieldIndex) => `${alias}.${quoteIdentifier(step.relation.references[fieldIndex])} = ${previousAlias}.${quoteIdentifier(field)}`
|
|
);
|
|
joins.push(`JOIN ${quoteIdentifier(step.target.table)} AS ${alias} ON ${on.join(" AND ")}`);
|
|
}
|
|
|
|
const terminalAlias = aliases.at(-1);
|
|
const allowGlobal = mode === "read" ? resolved.contract.allowGlobalRead === true : resolved.contract.allowGlobalWrite === true;
|
|
const tenantPredicate = `${terminalAlias}."tenantId" = ${tenantExpression}`;
|
|
const globalFields = mode === "read" ? resolved.contract.globalReadFields : resolved.contract.globalWriteFields;
|
|
const workerGlobal = mode === "read" ? resolved.contract.workerReadGlobal === true : resolved.contract.workerWriteGlobal === true;
|
|
const operatorGlobal = mode === "read" ? resolved.contract.operatorReadGlobal === true : resolved.contract.operatorWriteGlobal === true;
|
|
const operatorAllTenants = mode === "read" && resolved.contract.operatorReadAllTenants === true;
|
|
const publicGlobal = mode === "read" ? resolved.contract.publicReadGlobal === true : resolved.contract.publicWriteGlobal === true;
|
|
const accessPredicates = [tenantPredicate];
|
|
if (allowGlobal) {
|
|
accessPredicates.push(`(${[`${terminalAlias}."tenantId" IS NULL`, ...renderFieldPredicates(terminalAlias, globalFields)].join(" AND ")})`);
|
|
}
|
|
if (workerGlobal) {
|
|
accessPredicates.push(`(${WORKER_CONTEXT_SQL} AND ${terminalAlias}."tenantId" IS NULL)`);
|
|
}
|
|
if (operatorGlobal) {
|
|
accessPredicates.push(`(${OPERATOR_CONTEXT_SQL} AND ${terminalAlias}."tenantId" IS NULL)`);
|
|
}
|
|
if (operatorAllTenants) {
|
|
accessPredicates.push(OPERATOR_CONTEXT_SQL);
|
|
}
|
|
if (publicGlobal) {
|
|
const publicPredicates = [
|
|
APP_CONTEXT_SQL,
|
|
`${terminalAlias}."tenantId" IS NULL`,
|
|
`${terminalAlias}."id" = ${PUBLIC_KNOWLEDGE_BASE_CONTEXT_SQL}`,
|
|
...renderFieldPredicates(terminalAlias, resolved.contract.publicTerminalFields),
|
|
...renderFieldPredicates(outerTable, resolved.contract.publicRowFields),
|
|
];
|
|
for (let index = 0; index < resolved.steps.length; index += 1) {
|
|
const fields = resolved.contract.publicPathFields?.[resolved.steps[index].target.model];
|
|
publicPredicates.push(...renderFieldPredicates(aliases[index], fields));
|
|
}
|
|
accessPredicates.push(`(${publicPredicates.join(" AND ")})`);
|
|
}
|
|
predicates.push(accessPredicates.length === 1 ? tenantPredicate : `(${accessPredicates.join(" OR ")})`);
|
|
|
|
return `EXISTS (SELECT 1 FROM ${from}${joins.length > 0 ? ` ${joins.join(" ")}` : ""} WHERE ${predicates.join(" AND ")})`;
|
|
}
|
|
|
|
function compileResolvedIdentityPath(startModel, resolved) {
|
|
const outerTable = quoteIdentifier(resolved.steps[0].from.table);
|
|
const aliases = resolved.steps.map((_, index) => quoteIdentifier(`identity_${index}`));
|
|
const first = resolved.steps[0];
|
|
const from = `${quoteIdentifier(first.target.table)} AS ${aliases[0]}`;
|
|
const joins = [];
|
|
const predicates = first.relation.fields.map(
|
|
(field, index) => `${aliases[0]}.${quoteIdentifier(first.relation.references[index])} = ${outerTable}.${quoteIdentifier(field)}`
|
|
);
|
|
|
|
for (let index = 1; index < resolved.steps.length; index += 1) {
|
|
const step = resolved.steps[index];
|
|
const previousAlias = aliases[index - 1];
|
|
const alias = aliases[index];
|
|
const on = step.relation.fields.map(
|
|
(field, fieldIndex) => `${alias}.${quoteIdentifier(step.relation.references[fieldIndex])} = ${previousAlias}.${quoteIdentifier(field)}`
|
|
);
|
|
joins.push(`JOIN ${quoteIdentifier(step.target.table)} AS ${alias} ON ${on.join(" AND ")}`);
|
|
}
|
|
|
|
if (resolved.terminal.model !== "User") {
|
|
throw new Error(`${startModel} identity path must terminate at User, found ${resolved.terminal.model}`);
|
|
}
|
|
predicates.push(`${aliases.at(-1)}."id" = ${USER_CONTEXT_SQL}`);
|
|
return `EXISTS (SELECT 1 FROM ${from}${joins.length > 0 ? ` ${joins.join(" ")}` : ""} WHERE ${predicates.join(" AND ")})`;
|
|
}
|
|
|
|
function optionalPathPredicate(startModel, resolved, expression) {
|
|
const outerTable = quoteIdentifier(resolved.steps[0].from.table);
|
|
const firstFields = resolved.steps[0].relation.fields;
|
|
const emptyReference = firstFields.map((field) => `${outerTable}.${quoteIdentifier(field)} IS NULL`).join(" AND ");
|
|
return `((${emptyReference}) OR ${expression})`;
|
|
}
|
|
|
|
function compileOwnershipExpression(model, ownershipContract, modelsByName, mode, errors, tenantExpression = TENANT_CONTEXT_SQL) {
|
|
const resolveGroup = (paths, optional) =>
|
|
paths
|
|
.map((pathContract) => resolveOwnershipPath(model.model, pathContract, modelsByName, errors))
|
|
.filter(Boolean)
|
|
.map((resolved) => {
|
|
const pathMode =
|
|
mode === "read" && ownershipContract.readGlobal === true && resolved.contract.allowGlobalRead === undefined
|
|
? { ...resolved, contract: { ...resolved.contract, allowGlobalRead: true } }
|
|
: resolved;
|
|
const expression = compileResolvedPath(model.model, pathMode, mode, tenantExpression);
|
|
return {
|
|
expression: optional ? optionalPathPredicate(model.model, pathMode, expression) : expression,
|
|
description: describeResolvedPath(pathMode),
|
|
};
|
|
});
|
|
|
|
const anyOf = resolveGroup(ownershipContract.anyOf, false);
|
|
const allOf = resolveGroup(ownershipContract.allOf, false);
|
|
const optionalAllOf = resolveGroup(ownershipContract.optionalAllOf, true);
|
|
const identityAnyOf = ownershipContract.identityAnyOf
|
|
.map((pathContract) => resolveOwnershipPath(model.model, pathContract, modelsByName, errors, "identity"))
|
|
.filter(Boolean)
|
|
.map((resolved) => ({
|
|
expression: compileResolvedIdentityPath(model.model, resolved),
|
|
description: describeResolvedPath(resolved),
|
|
}));
|
|
if (anyOf.length === 0 && allOf.length === 0 && optionalAllOf.length === 0 && identityAnyOf.length === 0) {
|
|
errors.push(`${model.model} ownership contract has no paths`);
|
|
return null;
|
|
}
|
|
|
|
const clauses = [];
|
|
if (anyOf.length > 0) clauses.push(`(${anyOf.map((path) => path.expression).join(" OR ")})`);
|
|
clauses.push(...allOf.map((path) => path.expression), ...optionalAllOf.map((path) => path.expression));
|
|
const combinedTenantExpression = clauses.length === 1 ? clauses[0] : `(${clauses.join(" AND ")})`;
|
|
const expression =
|
|
identityAnyOf.length > 0 ? `((${combinedTenantExpression}) OR (${identityAnyOf.map((path) => path.expression).join(" OR ")}))` : combinedTenantExpression;
|
|
return {
|
|
expression,
|
|
paths: [...anyOf, ...allOf, ...optionalAllOf, ...identityAnyOf].map((path) => path.description),
|
|
};
|
|
}
|
|
|
|
function compilePlatformAnalyticsExpression(model, ownershipContract, errors) {
|
|
const access = ownershipContract.platformAnalytics;
|
|
if (!access) return null;
|
|
|
|
const expected = {
|
|
AnalyticsUniqueVisitor: { kind: "anonymous-visitor", commands: ["select", "insert", "update"] },
|
|
AnalyticsPageView: { kind: "anonymous-visitor-child", commands: ["select", "insert"] },
|
|
AnalyticsEvent: { kind: "anonymous-visitor-child", commands: ["select", "insert"] },
|
|
}[model.model];
|
|
if (!expected) {
|
|
errors.push(`${model.model} declares unsupported platform analytics access`);
|
|
return null;
|
|
}
|
|
if (access.kind !== expected.kind || JSON.stringify(access.commands) !== JSON.stringify(expected.commands)) {
|
|
errors.push(`${model.model} platform analytics access must be ${expected.kind} with commands ${expected.commands.join(", ")}`);
|
|
return null;
|
|
}
|
|
|
|
const table = quoteIdentifier(model.table);
|
|
const ownAnonymousFields = [`${table}."portalId" IS NULL`, `${table}."portalUserId" IS NULL`];
|
|
if (access.kind === "anonymous-visitor") {
|
|
return `(${PLATFORM_ANALYTICS_CONTEXT_SQL} AND ${table}."userId" IS NULL AND ${ownAnonymousFields.join(" AND ")})`;
|
|
}
|
|
|
|
const visitorRelation = model.owningRelations.find(
|
|
(relation) =>
|
|
relation.field === "uniqueVisitor" &&
|
|
relation.target === "AnalyticsUniqueVisitor" &&
|
|
relation.fields.length === 1 &&
|
|
relation.fields[0] === "uniqueVisitorId" &&
|
|
relation.references.length === 1 &&
|
|
relation.references[0] === "id"
|
|
);
|
|
if (!visitorRelation) {
|
|
errors.push(`${model.model} platform analytics access requires the exact uniqueVisitorId ownership relation`);
|
|
return null;
|
|
}
|
|
return `(${PLATFORM_ANALYTICS_CONTEXT_SQL} AND ${ownAnonymousFields.join(" AND ")} AND EXISTS (SELECT 1 FROM "AnalyticsUniqueVisitor" AS "platform_analytics_visitor" WHERE "platform_analytics_visitor"."id" = ${table}."uniqueVisitorId" AND "platform_analytics_visitor"."userId" IS NULL AND "platform_analytics_visitor"."portalId" IS NULL AND "platform_analytics_visitor"."portalUserId" IS NULL))`;
|
|
}
|
|
|
|
function directTenantExpression(allowGlobal, globalReadWhere) {
|
|
const ownTenant = `"tenantId" = ${TENANT_CONTEXT_SQL}`;
|
|
const globalRow = globalReadWhere ? `("tenantId" IS NULL AND (${globalReadWhere}))` : `"tenantId" IS NULL`;
|
|
return allowGlobal ? `(${globalRow} OR ${ownTenant})` : ownTenant;
|
|
}
|
|
|
|
function directMixedExpression(semantics, mode) {
|
|
const access = semantics[mode];
|
|
const tenant = directTenantExpression(false);
|
|
const identityFields = [...(semantics.identityField ? [semantics.identityField] : []), ...(semantics.additionalIdentityFields ?? [])];
|
|
const identity =
|
|
identityFields.length > 0
|
|
? `("tenantId" IS NULL AND ${
|
|
identityFields.length === 1
|
|
? `${quoteIdentifier(identityFields[0])} = ${USER_CONTEXT_SQL}`
|
|
: `(${identityFields.map((field) => `${quoteIdentifier(field)} = ${USER_CONTEXT_SQL}`).join(" OR ")})`
|
|
})`
|
|
: null;
|
|
const global = `("tenantId" IS NULL${mode === "select" && semantics.globalReadWhere ? ` AND (${semantics.globalReadWhere})` : ""})`;
|
|
const baseTenantExpression =
|
|
access === "tenant-and-global" ? `(${tenant} OR ${global})` : access === "tenant-or-identity" && identity ? `(${tenant} OR ${identity})` : tenant;
|
|
const publicReadExpression =
|
|
mode === "select" && semantics.publicReadFields
|
|
? `(${APP_CONTEXT_SQL} AND "tenantId" IS NULL AND "id" = ${PUBLIC_KNOWLEDGE_BASE_CONTEXT_SQL} AND ${renderFieldPredicates('"KnowledgeBase"', semantics.publicReadFields).join(" AND ")})`
|
|
: null;
|
|
const baseAppExpression = publicReadExpression ? `(${baseTenantExpression} OR ${publicReadExpression})` : baseTenantExpression;
|
|
const operatorGlobal = mode === "select" ? semantics.operatorReadGlobal === true : semantics.operatorWriteGlobal === true;
|
|
const operatorAllTenants = mode === "select" && semantics.operatorReadAllTenants === true;
|
|
const appExpression = operatorAllTenants
|
|
? `(${baseAppExpression} OR ${OPERATOR_CONTEXT_SQL})`
|
|
: operatorGlobal
|
|
? `(${baseAppExpression} OR ("tenantId" IS NULL AND ${OPERATOR_CONTEXT_SQL}))`
|
|
: baseAppExpression;
|
|
const workerAllTenants = mode === "select" ? semantics.workerReadAllTenants === true : semantics.workerWriteAllTenants === true;
|
|
if (workerAllTenants) return `(${appExpression} OR ${WORKER_CONTEXT_SQL})`;
|
|
const workerGlobal = mode === "select" ? semantics.workerReadGlobal === true : semantics.workerWriteGlobal === true;
|
|
const workerGlobalPredicates = [WORKER_CONTEXT_SQL, '"tenantId" IS NULL'];
|
|
if (semantics.workerGlobalRequiresNoTenantContext === true) {
|
|
workerGlobalPredicates.push(`${TENANT_CONTEXT_SQL} IS NULL`);
|
|
}
|
|
if (semantics.workerGlobalWhere) {
|
|
workerGlobalPredicates.push(`(${semantics.workerGlobalWhere})`);
|
|
}
|
|
return workerGlobal ? `(${appExpression} OR (${workerGlobalPredicates.join(" AND ")}))` : appExpression;
|
|
}
|
|
|
|
function compileReviewedMixedCommandPolicy(model, semantics, errors) {
|
|
if (!semantics.commandPolicy) return null;
|
|
|
|
const expectedPolicy = {
|
|
Event: "immutable-event",
|
|
OutboxEvent: "immutable-user-trigger-outbox",
|
|
UserRole: "scoped-user-role-assignment",
|
|
}[model.model];
|
|
if (!expectedPolicy || semantics.commandPolicy !== expectedPolicy) {
|
|
errors.push(`${model.model} has unsupported reviewed command policy ${String(semantics.commandPolicy)}`);
|
|
return null;
|
|
}
|
|
if (model.model !== "UserRole" && (semantics.workerReadAllTenants !== true || semantics.workerWriteAllTenants !== true)) {
|
|
errors.push(`${model.model} reviewed command policy requires explicit worker all-tenant read/write access`);
|
|
}
|
|
|
|
const tenantOwned = `"tenantId" = ${TENANT_CONTEXT_SQL}`;
|
|
let appSelect;
|
|
let appInsert;
|
|
let path;
|
|
if (semantics.commandPolicy === "scoped-user-role-assignment") {
|
|
if (
|
|
semantics.identityField !== "userId" ||
|
|
semantics.workerReadGlobal !== true ||
|
|
semantics.workerWriteGlobal !== undefined ||
|
|
semantics.operatorReadGlobal !== true ||
|
|
semantics.operatorReadAllTenants !== undefined ||
|
|
semantics.operatorWriteGlobal !== true
|
|
) {
|
|
errors.push("UserRole scoped assignment policy requires user identity, global worker read, and global operator read/write only");
|
|
}
|
|
const exactUser = `"userId" = ${USER_CONTEXT_SQL}`;
|
|
const tenantAppRole = `("tenantId" = ${TENANT_CONTEXT_SQL} AND EXISTS (SELECT 1 FROM "Role" AS "assignment_role" WHERE "assignment_role"."id" = "UserRole"."roleId" AND "assignment_role"."type" = 'app' AND ("assignment_role"."tenantId" IS NULL OR "assignment_role"."tenantId" = ${TENANT_CONTEXT_SQL})))`;
|
|
const globalAdminRole = `("tenantId" IS NULL AND ${OPERATOR_CONTEXT_SQL} AND EXISTS (SELECT 1 FROM "Role" AS "assignment_role" WHERE "assignment_role"."id" = "UserRole"."roleId" AND "assignment_role"."tenantId" IS NULL AND "assignment_role"."type" = 'admin'))`;
|
|
appSelect = `(${APP_CONTEXT_SQL} AND ("tenantId" = ${TENANT_CONTEXT_SQL} OR ("tenantId" IS NULL AND ${exactUser}) OR ("tenantId" IS NULL AND ${OPERATOR_CONTEXT_SQL})))`;
|
|
appInsert = `(${APP_CONTEXT_SQL} AND (${tenantAppRole} OR ${globalAdminRole}))`;
|
|
path = "tenant app-role assignment + operator-only global admin-role assignment + global worker read";
|
|
return {
|
|
readExpression: `(${appSelect} OR (${WORKER_CONTEXT_SQL} AND "tenantId" IS NULL))`,
|
|
writeExpression: appInsert,
|
|
commandExpressions: {
|
|
select: `(${appSelect} OR (${WORKER_CONTEXT_SQL} AND "tenantId" IS NULL))`,
|
|
insert: appInsert,
|
|
update: appInsert,
|
|
delete: appInsert,
|
|
},
|
|
commandRoles: {
|
|
select: [APP_ROLE, WORKER_ROLE],
|
|
insert: [APP_ROLE],
|
|
update: [APP_ROLE],
|
|
delete: [APP_ROLE],
|
|
},
|
|
path,
|
|
};
|
|
}
|
|
if (semantics.commandPolicy === "immutable-event") {
|
|
if (semantics.identityField !== "userId" || semantics.operatorReadAllTenants !== true || semantics.operatorWriteGlobal !== undefined) {
|
|
errors.push("Event immutable policy requires userId identity, operator all-tenant read, and no operator write access");
|
|
}
|
|
const exactUser = `"userId" IS NOT NULL AND "userId" = ${USER_CONTEXT_SQL}`;
|
|
const tenantInsert = `(${tenantOwned} AND ("userId" IS NULL OR "userId" = ${USER_CONTEXT_SQL}))`;
|
|
const identityInsert = `("tenantId" IS NULL AND ${exactUser})`;
|
|
appSelect = `(${APP_CONTEXT_SQL} AND (${tenantOwned} OR ("tenantId" IS NULL AND ${exactUser}) OR ${OPERATOR_CONTEXT_SQL}))`;
|
|
appInsert = `(${APP_CONTEXT_SQL} AND (${tenantInsert} OR ${identityInsert}))`;
|
|
path = "immutable Event app ownership + read-only operator inbox + global worker";
|
|
} else {
|
|
if (semantics.operatorReadGlobal !== undefined || semantics.operatorReadAllTenants !== undefined || semantics.operatorWriteGlobal !== undefined) {
|
|
errors.push("OutboxEvent immutable policy does not allow operator access");
|
|
}
|
|
const exactUserTrigger = `("tenantId" IS NULL AND "eventType" = 'workflow.trigger.event' AND jsonb_typeof("payload") = 'object' AND ${USER_CONTEXT_SQL} IS NOT NULL AND NULLIF(BTRIM("payload" ->> 'userId'), '') = ${USER_CONTEXT_SQL})`;
|
|
appSelect = `(${APP_CONTEXT_SQL} AND (${tenantOwned} OR ${exactUserTrigger}))`;
|
|
appInsert = appSelect;
|
|
path = "immutable tenant/user-trigger OutboxEvent app ownership + global worker";
|
|
}
|
|
|
|
return {
|
|
readExpression: `(${appSelect} OR ${WORKER_CONTEXT_SQL})`,
|
|
writeExpression: `(${appInsert} OR ${WORKER_CONTEXT_SQL})`,
|
|
commandExpressions: {
|
|
select: `(${appSelect} OR ${WORKER_CONTEXT_SQL})`,
|
|
insert: `(${appInsert} OR ${WORKER_CONTEXT_SQL})`,
|
|
update: WORKER_CONTEXT_SQL,
|
|
delete: WORKER_CONTEXT_SQL,
|
|
},
|
|
commandRoles: {
|
|
select: [APP_ROLE, WORKER_ROLE],
|
|
insert: [APP_ROLE, WORKER_ROLE],
|
|
update: [WORKER_ROLE],
|
|
delete: [WORKER_ROLE],
|
|
},
|
|
path,
|
|
};
|
|
}
|
|
|
|
function prependRelationPath(relation, pathContract, globalParentContract) {
|
|
return {
|
|
...pathContract,
|
|
relations: [relation.field, ...pathContract.relations],
|
|
...(globalParentContract?.read === true ? { allowGlobalRead: true } : {}),
|
|
...(globalParentContract?.write === true ? { allowGlobalWrite: true } : {}),
|
|
};
|
|
}
|
|
|
|
function compileDirectRelationIntegrity(model, modelsByName, manifest, derivedContract, globalParentContract, errors) {
|
|
const checks = [];
|
|
|
|
for (const relation of model.owningRelations) {
|
|
const target = modelsByName.get(relation.target);
|
|
const targetManifest = manifest[relation.target];
|
|
if (!target || !targetManifest || relation.target === "Tenant" || !modelRequiresTenantRls(targetManifest)) {
|
|
continue;
|
|
}
|
|
|
|
const contractKey = `${model.model}.${relation.field}`;
|
|
const parentContract = globalParentContract[contractKey];
|
|
let compileForTenant;
|
|
|
|
if (target.tenantField) {
|
|
const pathContract = {
|
|
relations: [relation.field],
|
|
...(parentContract?.read === true ? { allowGlobalRead: true } : {}),
|
|
...(parentContract?.write === true ? { allowGlobalWrite: true } : {}),
|
|
};
|
|
const resolved = resolveOwnershipPath(model.model, pathContract, modelsByName, errors);
|
|
if (!resolved) continue;
|
|
compileForTenant = (tenantExpression) => compileResolvedPath(model.model, resolved, "write", tenantExpression);
|
|
} else if (targetManifest.scope === "derived-child") {
|
|
const targetOwnership = derivedContract[target.model];
|
|
if (!targetOwnership) {
|
|
errors.push(`${contractKey} targets ${target.model} without a derived ownership contract`);
|
|
continue;
|
|
}
|
|
const prefixedOwnership = {
|
|
readGlobal: false,
|
|
anyOf: targetOwnership.anyOf.map((entry) => prependRelationPath(relation, entry, parentContract)),
|
|
allOf: targetOwnership.allOf.map((entry) => prependRelationPath(relation, entry, parentContract)),
|
|
optionalAllOf: targetOwnership.optionalAllOf.map((entry) => prependRelationPath(relation, entry, parentContract)),
|
|
identityAnyOf: [],
|
|
};
|
|
compileForTenant = (tenantExpression) =>
|
|
compileOwnershipExpression(model, prefixedOwnership, modelsByName, "write", errors, tenantExpression)?.expression;
|
|
} else {
|
|
errors.push(`${contractKey} targets unsupported protected scope ${targetManifest.scope}`);
|
|
continue;
|
|
}
|
|
|
|
const policyExpression = compileForTenant(TENANT_CONTEXT_SQL);
|
|
const rowExpression = compileForTenant(`${quoteIdentifier(model.table)}."tenantId"`);
|
|
if (!policyExpression || !rowExpression) continue;
|
|
checks.push({
|
|
key: contractKey,
|
|
relation: relation.field,
|
|
target: relation.target,
|
|
policyExpression: relation.nullable ? optionalForeignKeyPredicate(model, relation, policyExpression) : policyExpression,
|
|
rowExpression: relation.nullable ? optionalForeignKeyPredicate(model, relation, rowExpression) : rowExpression,
|
|
});
|
|
}
|
|
|
|
return checks;
|
|
}
|
|
|
|
function compileDirectScalarTenantIntegrity(model, modelsByName, manifest, scalarReferenceContract, errors) {
|
|
const checks = [];
|
|
|
|
for (const [key, contract] of Object.entries(scalarReferenceContract)) {
|
|
const separator = key.indexOf(".");
|
|
const sourceModel = key.slice(0, separator);
|
|
const localField = key.slice(separator + 1);
|
|
if (separator <= 0 || !localField) {
|
|
errors.push(`scalar tenant reference has invalid key ${key}`);
|
|
continue;
|
|
}
|
|
if (sourceModel !== model.model) continue;
|
|
|
|
const target = modelsByName.get(contract.targetModel);
|
|
const targetManifest = manifest[contract.targetModel];
|
|
if (!model.fieldNames.includes(localField)) {
|
|
errors.push(`${key} references missing local scalar field ${localField}`);
|
|
continue;
|
|
}
|
|
const targetsRequiredTenant = target?.tenantField?.nullable === false;
|
|
const targetsReviewedTenantRow =
|
|
targetManifest?.scope === "tenant-or-global" && target?.tenantField !== undefined && contract.requireTenantOwnedTarget === true;
|
|
if (!target || !targetManifest || !modelRequiresTenantRls(targetManifest) || (!targetsRequiredTenant && !targetsReviewedTenantRow)) {
|
|
errors.push(`${key} targets non-tenant-required model ${String(contract.targetModel)}`);
|
|
continue;
|
|
}
|
|
if (contract.requireTenantOwnedTarget !== undefined && contract.requireTenantOwnedTarget !== true) {
|
|
errors.push(`${key} requireTenantOwnedTarget must declare true when present`);
|
|
continue;
|
|
}
|
|
if (!target.fieldNames.includes(contract.targetField)) {
|
|
errors.push(`${key} references missing target field ${String(contract.targetField)}`);
|
|
continue;
|
|
}
|
|
const unknownPredicate = Object.keys(contract.targetWhere ?? {}).find((field) => !target.fieldNames.includes(field));
|
|
if (unknownPredicate) {
|
|
errors.push(`${key} references missing target predicate field ${unknownPredicate}`);
|
|
continue;
|
|
}
|
|
if (typeof contract.risk !== "string" || !contract.risk.trim()) {
|
|
errors.push(`${key} must document its tenant-integrity risk`);
|
|
}
|
|
if (contract.optional !== undefined && contract.optional !== true) {
|
|
errors.push(`${key} optional scalar tenant reference must declare optional: true`);
|
|
}
|
|
|
|
const alias = quoteIdentifier(`scalar_owner_${checks.length}`);
|
|
const compileForTenant = (tenantExpression) => {
|
|
const predicates = [
|
|
`${alias}.${quoteIdentifier(contract.targetField)} = ${quoteIdentifier(model.table)}.${quoteIdentifier(localField)}`,
|
|
`${alias}."tenantId" = ${tenantExpression}`,
|
|
...renderFieldPredicates(alias, contract.targetWhere),
|
|
];
|
|
const ownershipExpression = `EXISTS (SELECT 1 FROM ${quoteIdentifier(target.table)} AS ${alias} WHERE ${predicates.join(" AND ")})`;
|
|
return contract.optional === true
|
|
? `((${quoteIdentifier(model.table)}.${quoteIdentifier(localField)} IS NULL) OR ${ownershipExpression})`
|
|
: ownershipExpression;
|
|
};
|
|
|
|
checks.push({
|
|
key,
|
|
relation: localField,
|
|
target: target.model,
|
|
policyExpression: compileForTenant(TENANT_CONTEXT_SQL),
|
|
rowExpression: compileForTenant(`${quoteIdentifier(model.table)}."tenantId"`),
|
|
insertUpdateOnly: true,
|
|
});
|
|
}
|
|
|
|
return checks;
|
|
}
|
|
|
|
function optionalForeignKeyPredicate(model, relation, expression) {
|
|
const table = quoteIdentifier(model.table);
|
|
const nullableFields = relation.fields.filter((field) => model.nullableFieldNames?.includes(field));
|
|
const emptyReferenceFields = nullableFields.length > 0 ? nullableFields : relation.fields;
|
|
const emptyReference = emptyReferenceFields.map((field) => `${table}.${quoteIdentifier(field)} IS NULL`).join(" AND ");
|
|
return `((${emptyReference}) OR ${expression})`;
|
|
}
|
|
|
|
function appendIntegrityChecks(baseExpression, checks) {
|
|
if (checks.length === 0) return baseExpression;
|
|
return `(${baseExpression} AND ${checks.map((check) => check.policyExpression).join(" AND ")})`;
|
|
}
|
|
|
|
function identityPolicyExpressions(model, contract, modelsByName, errors) {
|
|
const membership = modelsByName.get(contract.membershipModel);
|
|
if (!membership) {
|
|
errors.push(`${model.model} root policy references unknown membership model ${contract.membershipModel}`);
|
|
return null;
|
|
}
|
|
const membershipFields = new Set([contract.tenantField, contract.userField]);
|
|
for (const field of membershipFields) {
|
|
if (!membership.tenantField && field === contract.tenantField) {
|
|
errors.push(`${contract.membershipModel} does not expose required tenant field ${field}`);
|
|
}
|
|
}
|
|
const tenantTable = quoteIdentifier(model.table);
|
|
const membershipTable = quoteIdentifier(membership.table);
|
|
const currentTenant = `"id" = ${TENANT_CONTEXT_SQL}`;
|
|
const currentUserMembership = `EXISTS (SELECT 1 FROM ${membershipTable} AS "membership" WHERE "membership".${quoteIdentifier(contract.tenantField)} = ${tenantTable}."id" AND "membership".${quoteIdentifier(contract.userField)} = ${USER_CONTEXT_SQL})`;
|
|
|
|
return {
|
|
select: `(${currentTenant} OR ${currentUserMembership} OR ${WORKER_CONTEXT_SQL} OR ${OPERATOR_CONTEXT_SQL})`,
|
|
// Tenant bootstrap runs before the first owner User exists. The application
|
|
// pre-generates the Tenant id and binds exactly that id as app.tenant_id.
|
|
insert: `(${currentTenant} OR ${OPERATOR_CONTEXT_SQL})`,
|
|
update: currentTenant,
|
|
delete: currentTenant,
|
|
};
|
|
}
|
|
|
|
function tenantMembershipPolicyExpressions() {
|
|
const currentTenant = `"tenantId" = ${TENANT_CONTEXT_SQL}`;
|
|
const currentMembership = `"userId" = ${USER_CONTEXT_SQL}`;
|
|
return {
|
|
select: `(${currentTenant} OR ${currentMembership})`,
|
|
insert: currentTenant,
|
|
update: currentTenant,
|
|
delete: currentTenant,
|
|
};
|
|
}
|
|
|
|
function policyNames(model, splitReadWrite) {
|
|
return splitReadWrite ? { read: `hg_${model}_read`, write: `hg_${model}_write` } : { all: `hg_${model}_all` };
|
|
}
|
|
|
|
function commandPolicyNames(model) {
|
|
return {
|
|
select: `hg_${model}_select`,
|
|
insert: `hg_${model}_insert`,
|
|
update: `hg_${model}_update`,
|
|
delete: `hg_${model}_delete`,
|
|
};
|
|
}
|
|
|
|
export function inspectTenantPolicyContract(rootDirectory = process.cwd(), options = {}) {
|
|
const manifest = options.manifest ?? TENANT_SCOPE_MANIFEST;
|
|
const appendOnlyTenantContract = options.appendOnlyTenantContract ?? APPEND_ONLY_TENANT_MODEL_CONTRACT;
|
|
const mixedContract = options.mixedContract ?? MIXED_POLICY_CONTRACT;
|
|
const derivedContract = options.derivedContract ?? DERIVED_OWNERSHIP_CONTRACT;
|
|
const directWorkerContract = options.directWorkerContract ?? DIRECT_WORKER_POLICY_CONTRACT;
|
|
const scalarReferenceContract = options.scalarReferenceContract ?? DIRECT_SCALAR_TENANT_REFERENCE_CONTRACT;
|
|
const rootContract = options.rootContract ?? TENANT_ROOT_POLICY_CONTRACT;
|
|
const globalParentContract = options.globalParentContract ?? DIRECT_RELATION_GLOBAL_PARENT_CONTRACT;
|
|
const globalGuardContract = options.globalGuardContract ?? GLOBAL_GUARDED_MODEL_CONTRACT;
|
|
const globalSharedContract = options.globalSharedContract ?? GLOBAL_SHARED_POLICY_CONTRACT;
|
|
const platformContract = options.platformContract ?? PLATFORM_ADMIN_POLICY_CONTRACT;
|
|
const resolverContract = options.resolverContract ?? TENANT_RESOLVER_CONTRACT;
|
|
const models = parsePrismaSchemaDirectory(path.join(rootDirectory, "prisma", "schema"));
|
|
const modelsByName = new Map(models.map((model) => [model.model, model]));
|
|
const manifestValidation = validateTenantScopeManifest(models, manifest);
|
|
const errors = [...manifestValidation.errors];
|
|
const resolvers = inspectTenantResolvers(resolverContract, modelsByName, errors);
|
|
|
|
compareContractKeys("append-only tenant model contract", EXPECTED_APPEND_ONLY_TENANT_MODELS, appendOnlyTenantContract, errors);
|
|
for (const [modelName, contract] of Object.entries(appendOnlyTenantContract)) {
|
|
const model = modelsByName.get(modelName);
|
|
if (!model || manifest[modelName]?.scope !== "tenant-required") {
|
|
errors.push(`append-only tenant model contract references non-tenant-required model ${modelName}`);
|
|
continue;
|
|
}
|
|
const expectedCommands = { select: "tenant-only", insert: "tenant-only", update: "none", delete: "none" };
|
|
if (JSON.stringify(contract.commands) !== JSON.stringify(expectedCommands)) {
|
|
errors.push(`${modelName} append-only contract must allow tenant-only SELECT and INSERT while denying UPDATE and DELETE`);
|
|
}
|
|
const expectedSequenceName = `${model.table}_sequence_seq`;
|
|
if (
|
|
contract.sequence?.name !== expectedSequenceName ||
|
|
contract.sequence?.privilege !== "USAGE" ||
|
|
JSON.stringify(contract.sequence?.roles) !== JSON.stringify(TENANT_POLICY_ROLES)
|
|
) {
|
|
errors.push(`${modelName} append-only contract must grant only USAGE on ${expectedSequenceName} to hivegrid_app and hivegrid_worker`);
|
|
}
|
|
if (typeof contract.risk !== "string" || !contract.risk.trim()) {
|
|
errors.push(`${modelName} append-only contract requires an explicit risk statement`);
|
|
}
|
|
}
|
|
|
|
compareContractKeys(
|
|
"mixed policy contract",
|
|
models.filter((model) => manifest[model.model]?.scope === "tenant-or-global").map((model) => model.model),
|
|
mixedContract,
|
|
errors
|
|
);
|
|
for (const [modelName, contract] of Object.entries(directWorkerContract)) {
|
|
const model = modelsByName.get(modelName);
|
|
if (!model || manifest[modelName]?.scope !== "tenant-required") {
|
|
errors.push(`direct worker policy references non-tenant-required model ${modelName}`);
|
|
continue;
|
|
}
|
|
for (const flag of ["readAllTenants", "writeAllTenants", "operatorReadAllTenants"]) {
|
|
if (contract[flag] !== undefined && contract[flag] !== true) {
|
|
errors.push(`${modelName} direct runtime policy has invalid ${flag} flag`);
|
|
}
|
|
}
|
|
if (contract.readAllTenants !== true && contract.writeAllTenants !== true && contract.operatorReadAllTenants !== true) {
|
|
errors.push(`${modelName} direct runtime policy must declare at least one reviewed cross-tenant access path`);
|
|
}
|
|
if (contract.writeAllTenants === true && contract.readAllTenants !== true) {
|
|
errors.push(`${modelName} direct runtime policy cannot grant worker writes without worker reads`);
|
|
}
|
|
if (typeof contract.risk !== "string" || !contract.risk.trim()) {
|
|
errors.push(`${modelName} direct runtime policy requires an explicit risk statement`);
|
|
}
|
|
}
|
|
const expectedGlobalGuards = [
|
|
...models.filter((model) => manifest[model.model]?.scope === "global-catalog").map((model) => model.model),
|
|
...GLOBAL_GUARDED_EXTRA_MODELS,
|
|
];
|
|
compareContractKeys("global guarded model contract", expectedGlobalGuards, globalGuardContract, errors);
|
|
for (const [modelName, guard] of Object.entries(globalGuardContract)) {
|
|
if (guard.workerRead !== true || Object.keys(guard).some((key) => key !== "workerRead")) {
|
|
errors.push(`${modelName} global guard must declare exactly workerRead: true`);
|
|
}
|
|
}
|
|
compareContractKeys(
|
|
"global-shared policy contract",
|
|
models.filter((model) => manifest[model.model]?.scope === "global-shared").map((model) => model.model),
|
|
globalSharedContract,
|
|
errors
|
|
);
|
|
compareContractKeys(
|
|
"platform admin policy contract",
|
|
models.filter((model) => manifest[model.model]?.scope === "platform-admin" && model.model !== "AdminUser").map((model) => model.model),
|
|
platformContract,
|
|
errors
|
|
);
|
|
compareContractKeys(
|
|
"derived ownership contract",
|
|
models.filter((model) => manifest[model.model]?.scope === "derived-child").map((model) => model.model),
|
|
derivedContract,
|
|
errors
|
|
);
|
|
compareContractKeys(
|
|
"tenant root policy contract",
|
|
models.filter((model) => manifest[model.model]?.scope === "tenant-root").map((model) => model.model),
|
|
rootContract,
|
|
errors
|
|
);
|
|
|
|
// Validate every derived path even when AD-1 exempts the model from RLS.
|
|
for (const model of models.filter((candidate) => manifest[candidate.model]?.scope === "derived-child")) {
|
|
const ownershipContract = derivedContract[model.model];
|
|
if (!ownershipContract) continue;
|
|
compileOwnershipExpression(model, ownershipContract, modelsByName, "read", errors);
|
|
compileOwnershipExpression(model, ownershipContract, modelsByName, "write", errors);
|
|
}
|
|
|
|
const definitions = [];
|
|
for (const model of models) {
|
|
const manifestEntry = manifest[model.model];
|
|
if (!manifestEntry || !modelRequiresTenantRls(manifestEntry)) continue;
|
|
|
|
let readExpression;
|
|
let writeExpression;
|
|
let commandExpressions;
|
|
let commandRoles;
|
|
let sequenceGrants = [];
|
|
let integrityChecks = [];
|
|
let paths = [];
|
|
if (manifestEntry.scope === "tenant-required") {
|
|
if (model.model === "TenantUser") {
|
|
commandExpressions = tenantMembershipPolicyExpressions();
|
|
readExpression = commandExpressions.select;
|
|
writeExpression = commandExpressions.update;
|
|
paths = ["TenantUser.tenantId + self membership via app.user_id"];
|
|
} else {
|
|
const tenantExpression = directTenantExpression(false);
|
|
const workerContract = directWorkerContract[model.model];
|
|
const readPaths = [
|
|
tenantExpression,
|
|
...(workerContract?.readAllTenants === true ? [WORKER_CONTEXT_SQL] : []),
|
|
...(workerContract?.operatorReadAllTenants === true ? [OPERATOR_CONTEXT_SQL] : []),
|
|
];
|
|
readExpression = readPaths.length > 1 ? `(${readPaths.join(" OR ")})` : tenantExpression;
|
|
writeExpression = workerContract?.writeAllTenants === true ? `(${tenantExpression} OR ${WORKER_CONTEXT_SQL})` : tenantExpression;
|
|
}
|
|
} else if (manifestEntry.scope === "tenant-or-global") {
|
|
const semantics = mixedContract[model.model];
|
|
if (!semantics) continue;
|
|
if (!new Set(["tenant-only", "tenant-and-global", "tenant-or-identity"]).has(semantics.select)) {
|
|
errors.push(`${model.model} has invalid mixed SELECT semantics ${String(semantics.select)}`);
|
|
}
|
|
if (!new Set(["tenant-only", "tenant-or-identity"]).has(semantics.write)) {
|
|
errors.push(`${model.model} has unsafe mixed WRITE semantics ${String(semantics.write)}`);
|
|
}
|
|
if ((semantics.select === "tenant-or-identity" || semantics.write === "tenant-or-identity") && typeof semantics.identityField !== "string") {
|
|
errors.push(`${model.model} uses tenant-or-identity without identityField`);
|
|
}
|
|
if (
|
|
semantics.additionalIdentityFields !== undefined &&
|
|
(!Array.isArray(semantics.additionalIdentityFields) ||
|
|
semantics.additionalIdentityFields.length === 0 ||
|
|
semantics.additionalIdentityFields.some(
|
|
(field) => typeof field !== "string" || !model.fieldNames.includes(field) || field === semantics.identityField
|
|
))
|
|
) {
|
|
errors.push(`${model.model} has invalid additionalIdentityFields`);
|
|
}
|
|
if (semantics.workerReadAllTenants === true && semantics.workerReadGlobal === true) {
|
|
errors.push(`${model.model} redundantly declares workerReadAllTenants and workerReadGlobal`);
|
|
}
|
|
if (semantics.workerWriteAllTenants === true && semantics.workerWriteGlobal === true) {
|
|
errors.push(`${model.model} redundantly declares workerWriteAllTenants and workerWriteGlobal`);
|
|
}
|
|
for (const flag of ["operatorReadGlobal", "operatorReadAllTenants", "operatorWriteGlobal"]) {
|
|
if (semantics[flag] !== undefined && semantics[flag] !== true) {
|
|
errors.push(`${model.model} has invalid ${flag} flag`);
|
|
}
|
|
}
|
|
if (semantics.publicReadFields && model.model !== "KnowledgeBase") {
|
|
errors.push(`${model.model} declares a public knowledge-base direct-read contract`);
|
|
}
|
|
if (semantics.operatorReadAllTenants === true && semantics.operatorReadGlobal === true) {
|
|
errors.push(`${model.model} redundantly declares operatorReadAllTenants and operatorReadGlobal`);
|
|
}
|
|
if (semantics.workerGlobalWhere && semantics.workerReadGlobal !== true && semantics.workerWriteGlobal !== true) {
|
|
errors.push(`${model.model} declares workerGlobalWhere without worker global access`);
|
|
}
|
|
if (semantics.workerGlobalRequiresNoTenantContext === true && semantics.workerReadGlobal !== true && semantics.workerWriteGlobal !== true) {
|
|
errors.push(`${model.model} requires an unbound worker without worker global access`);
|
|
}
|
|
if (
|
|
semantics.workerGlobalWhere &&
|
|
(/;/.test(semantics.workerGlobalWhere) || /\b(?:SELECT|INSERT|UPDATE|DELETE|GRANT|REVOKE)\b/i.test(semantics.workerGlobalWhere))
|
|
) {
|
|
errors.push(`${model.model} has unsafe workerGlobalWhere`);
|
|
}
|
|
const reviewedCommandPolicy = compileReviewedMixedCommandPolicy(model, semantics, errors);
|
|
if (reviewedCommandPolicy) {
|
|
readExpression = reviewedCommandPolicy.readExpression;
|
|
writeExpression = reviewedCommandPolicy.writeExpression;
|
|
commandExpressions = reviewedCommandPolicy.commandExpressions;
|
|
commandRoles = reviewedCommandPolicy.commandRoles;
|
|
paths = [reviewedCommandPolicy.path];
|
|
} else {
|
|
readExpression = directMixedExpression(semantics, "select");
|
|
writeExpression = directMixedExpression(semantics, "write");
|
|
}
|
|
} else if (manifestEntry.scope === "derived-child") {
|
|
const ownershipContract = derivedContract[model.model];
|
|
if (!ownershipContract) continue;
|
|
const read = compileOwnershipExpression(model, ownershipContract, modelsByName, "read", errors);
|
|
const write = compileOwnershipExpression(model, ownershipContract, modelsByName, "write", errors);
|
|
if (!read || !write) continue;
|
|
readExpression = read.expression;
|
|
writeExpression = write.expression;
|
|
paths = read.paths;
|
|
const platformAnalyticsExpression = compilePlatformAnalyticsExpression(model, ownershipContract, errors);
|
|
if (ownershipContract.platformAnalytics && platformAnalyticsExpression) {
|
|
const platformAnalyticsCommands = new Set(ownershipContract.platformAnalytics.commands);
|
|
commandExpressions = {
|
|
select: platformAnalyticsCommands.has("select") ? `(${readExpression} OR ${platformAnalyticsExpression})` : readExpression,
|
|
insert: platformAnalyticsCommands.has("insert") ? `(${writeExpression} OR ${platformAnalyticsExpression})` : writeExpression,
|
|
update: platformAnalyticsCommands.has("update") ? `(${writeExpression} OR ${platformAnalyticsExpression})` : writeExpression,
|
|
delete: platformAnalyticsCommands.has("delete") ? `(${writeExpression} OR ${platformAnalyticsExpression})` : writeExpression,
|
|
};
|
|
readExpression = commandExpressions.select;
|
|
writeExpression = commandExpressions.update;
|
|
paths.push(`isolated platform analytics capability: ${ownershipContract.platformAnalytics.commands.join(", ")}`);
|
|
}
|
|
} else if (manifestEntry.scope === "tenant-root") {
|
|
const contract = rootContract[model.model];
|
|
if (!contract) continue;
|
|
commandExpressions = identityPolicyExpressions(model, contract, modelsByName, errors);
|
|
if (!commandExpressions) continue;
|
|
readExpression = commandExpressions.select;
|
|
writeExpression = commandExpressions.update;
|
|
paths = [`${model.model}.id + ${contract.membershipModel}.${contract.userField} + AdminUser.id`];
|
|
} else {
|
|
errors.push(`${model.model} requires tenant RLS but has unsupported scope ${manifestEntry.scope}`);
|
|
continue;
|
|
}
|
|
|
|
if (model.tenantField) {
|
|
const relationIntegrityChecks = compileDirectRelationIntegrity(model, modelsByName, manifest, derivedContract, globalParentContract, errors);
|
|
const scalarIntegrityChecks = compileDirectScalarTenantIntegrity(model, modelsByName, manifest, scalarReferenceContract, errors);
|
|
integrityChecks = [...relationIntegrityChecks, ...scalarIntegrityChecks];
|
|
writeExpression = appendIntegrityChecks(writeExpression, relationIntegrityChecks);
|
|
if (commandExpressions) {
|
|
commandExpressions = {
|
|
...commandExpressions,
|
|
insert: appendIntegrityChecks(commandExpressions.insert, relationIntegrityChecks),
|
|
update: appendIntegrityChecks(commandExpressions.update, relationIntegrityChecks),
|
|
};
|
|
}
|
|
if (scalarIntegrityChecks.length > 0) {
|
|
commandExpressions ??= {
|
|
select: readExpression,
|
|
insert: writeExpression,
|
|
update: writeExpression,
|
|
delete: writeExpression,
|
|
};
|
|
commandExpressions = {
|
|
...commandExpressions,
|
|
insert: appendIntegrityChecks(commandExpressions.insert, scalarIntegrityChecks),
|
|
update: appendIntegrityChecks(commandExpressions.update, scalarIntegrityChecks),
|
|
};
|
|
writeExpression = commandExpressions.update;
|
|
paths.push(...scalarIntegrityChecks.map((check) => `reviewed scalar tenant reference: ${check.key} -> ${check.target}`));
|
|
}
|
|
}
|
|
|
|
const appendOnlyContract = appendOnlyTenantContract[model.model];
|
|
if (appendOnlyContract) {
|
|
const insertExpression = commandExpressions?.insert ?? writeExpression;
|
|
commandExpressions = {
|
|
select: readExpression,
|
|
insert: insertExpression,
|
|
update: "false",
|
|
delete: "false",
|
|
};
|
|
commandRoles = {
|
|
select: [...TENANT_POLICY_ROLES],
|
|
insert: [...TENANT_POLICY_ROLES],
|
|
update: [],
|
|
delete: [],
|
|
};
|
|
writeExpression = insertExpression;
|
|
sequenceGrants = [
|
|
{
|
|
name: appendOnlyContract.sequence.name,
|
|
privilege: appendOnlyContract.sequence.privilege,
|
|
roles: [...appendOnlyContract.sequence.roles],
|
|
},
|
|
];
|
|
paths.push("append-only tenant ledger: SELECT + INSERT only");
|
|
}
|
|
|
|
const splitReadWrite = readExpression !== writeExpression;
|
|
if (!commandExpressions && splitReadWrite) {
|
|
commandExpressions = {
|
|
select: readExpression,
|
|
insert: writeExpression,
|
|
update: writeExpression,
|
|
delete: writeExpression,
|
|
};
|
|
}
|
|
definitions.push({
|
|
model: model.model,
|
|
schema: model.schema,
|
|
table: model.table,
|
|
scope: manifestEntry.scope,
|
|
enforcement: manifestEntry.enforcement,
|
|
readExpression,
|
|
writeExpression,
|
|
commandExpressions,
|
|
...(commandRoles ? { commandRoles } : {}),
|
|
sequenceGrants,
|
|
integrityChecks,
|
|
paths,
|
|
policyNames: commandExpressions ? commandPolicyNames(model.model) : policyNames(model.model, splitReadWrite),
|
|
});
|
|
}
|
|
|
|
const encounteredGlobalParentContracts = new Set(definitions.flatMap((definition) => definition.integrityChecks.map((check) => check.key)));
|
|
for (const contractKey of Object.keys(globalParentContract)) {
|
|
if (!encounteredGlobalParentContracts.has(contractKey)) {
|
|
errors.push(`direct global-parent contract references unknown protected relation ${contractKey}`);
|
|
}
|
|
}
|
|
const encounteredScalarContracts = new Set(
|
|
definitions.flatMap((definition) => definition.integrityChecks.filter((check) => check.insertUpdateOnly === true).map((check) => check.key))
|
|
);
|
|
for (const contractKey of Object.keys(scalarReferenceContract)) {
|
|
if (!encounteredScalarContracts.has(contractKey)) {
|
|
errors.push(`scalar tenant reference contract references unknown protected field ${contractKey}`);
|
|
}
|
|
}
|
|
|
|
for (const implicit of TENANT_SCOPED_IMPLICIT_TABLES) {
|
|
const table = quoteIdentifier(implicit.table);
|
|
const tenantContext = `${table}."A" = ${TENANT_CONTEXT_SQL}`;
|
|
const userMembership = `EXISTS (SELECT 1 FROM "TenantUser" AS "implicit_membership" WHERE "implicit_membership"."tenantId" = ${table}."A" AND "implicit_membership"."userId" = ${USER_CONTEXT_SQL})`;
|
|
const readExpression = `(${tenantContext} OR ${userMembership})`;
|
|
const writeExpression = tenantContext;
|
|
definitions.push({
|
|
...implicit,
|
|
readExpression,
|
|
writeExpression,
|
|
commandExpressions: {
|
|
select: readExpression,
|
|
insert: writeExpression,
|
|
update: writeExpression,
|
|
delete: writeExpression,
|
|
},
|
|
integrityChecks: [],
|
|
paths: [`${implicit.table}.A -> Tenant.id`],
|
|
policyNames: commandPolicyNames(implicit.model),
|
|
forceRls: true,
|
|
});
|
|
}
|
|
|
|
for (const [modelName, guard] of Object.entries(globalGuardContract)) {
|
|
const model = modelsByName.get(modelName);
|
|
if (!model) {
|
|
errors.push(`global guarded model contract references unknown model ${modelName}`);
|
|
continue;
|
|
}
|
|
const selectRoles = guard.workerRead === true ? TENANT_POLICY_ROLES : ["hivegrid_app"];
|
|
definitions.push({
|
|
model: model.model,
|
|
schema: model.schema,
|
|
table: model.table,
|
|
scope: manifest[model.model]?.scope ?? "global-guarded",
|
|
enforcement: "operator-write-policy",
|
|
readExpression: "true",
|
|
writeExpression: OPERATOR_CONTEXT_SQL,
|
|
commandExpressions: {
|
|
select: "true",
|
|
insert: OPERATOR_CONTEXT_SQL,
|
|
update: OPERATOR_CONTEXT_SQL,
|
|
delete: OPERATOR_CONTEXT_SQL,
|
|
},
|
|
commandRoles: {
|
|
select: selectRoles,
|
|
insert: ["hivegrid_app"],
|
|
update: ["hivegrid_app"],
|
|
delete: ["hivegrid_app"],
|
|
},
|
|
integrityChecks: [],
|
|
paths: ["global read + hivegrid_is_operator() write guard"],
|
|
policyNames: commandPolicyNames(model.model),
|
|
forceRls: true,
|
|
});
|
|
}
|
|
|
|
for (const [modelName, contract] of Object.entries(globalSharedContract)) {
|
|
const model = modelsByName.get(modelName);
|
|
if (!model) {
|
|
errors.push(`global-shared policy contract references unknown model ${modelName}`);
|
|
continue;
|
|
}
|
|
if (manifest[modelName]?.scope !== "global-shared") {
|
|
errors.push(`${modelName} global-shared policy targets scope ${String(manifest[modelName]?.scope)}`);
|
|
}
|
|
definitions.push(compileGlobalSharedPolicy(model, contract, errors));
|
|
}
|
|
|
|
for (const implicit of GLOBAL_IMPLICIT_TABLES) {
|
|
definitions.push({
|
|
...implicit,
|
|
enforcement: "operator-write-policy",
|
|
readExpression: "true",
|
|
writeExpression: OPERATOR_CONTEXT_SQL,
|
|
commandExpressions: {
|
|
select: "true",
|
|
insert: OPERATOR_CONTEXT_SQL,
|
|
update: OPERATOR_CONTEXT_SQL,
|
|
delete: OPERATOR_CONTEXT_SQL,
|
|
},
|
|
commandRoles: {
|
|
select: TENANT_POLICY_ROLES,
|
|
insert: ["hivegrid_app"],
|
|
update: ["hivegrid_app"],
|
|
delete: ["hivegrid_app"],
|
|
},
|
|
integrityChecks: [],
|
|
paths: ["global read + hivegrid_is_operator() write guard"],
|
|
policyNames: commandPolicyNames(implicit.model),
|
|
forceRls: true,
|
|
});
|
|
}
|
|
|
|
for (const [modelName, contract] of Object.entries(platformContract)) {
|
|
const model = modelsByName.get(modelName);
|
|
if (!model) {
|
|
errors.push(`platform admin policy contract references unknown model ${modelName}`);
|
|
continue;
|
|
}
|
|
if (manifest[modelName]?.scope !== "platform-admin") {
|
|
errors.push(`${modelName} platform policy targets scope ${String(manifest[modelName]?.scope)}`);
|
|
}
|
|
definitions.push(compilePlatformPolicy(model, contract, errors));
|
|
}
|
|
|
|
const adminUser = modelsByName.get("AdminUser");
|
|
if (!adminUser) {
|
|
errors.push("operator identity policy requires AdminUser");
|
|
} else {
|
|
definitions.push({
|
|
model: adminUser.model,
|
|
schema: adminUser.schema,
|
|
table: adminUser.table,
|
|
scope: "platform-admin",
|
|
enforcement: "operator-identity-policy",
|
|
readExpression: OPERATOR_CONTEXT_SQL,
|
|
writeExpression: OPERATOR_CONTEXT_SQL,
|
|
commandExpressions: {
|
|
select: OPERATOR_CONTEXT_SQL,
|
|
insert: OPERATOR_CONTEXT_SQL,
|
|
update: OPERATOR_CONTEXT_SQL,
|
|
delete: OPERATOR_CONTEXT_SQL,
|
|
},
|
|
commandRoles: {
|
|
select: ["hivegrid_app"],
|
|
insert: ["hivegrid_app"],
|
|
update: ["hivegrid_app"],
|
|
delete: ["hivegrid_app"],
|
|
},
|
|
integrityChecks: [],
|
|
paths: ["platform operator identity"],
|
|
policyNames: commandPolicyNames(adminUser.model),
|
|
forceRls: true,
|
|
});
|
|
}
|
|
|
|
const risks = [
|
|
...Object.entries(mixedContract)
|
|
.filter(([, contract]) => contract.risk)
|
|
.map(([model, contract]) => ({ model, risk: contract.risk })),
|
|
...Object.entries(derivedContract)
|
|
.filter(([, contract]) => contract.risk)
|
|
.map(([model, contract]) => ({ model, risk: contract.risk })),
|
|
...Object.entries(platformContract)
|
|
.filter(([, contract]) => contract.risk)
|
|
.map(([model, contract]) => ({ model, risk: contract.risk })),
|
|
...Object.entries(globalSharedContract)
|
|
.filter(([, contract]) => contract.risk)
|
|
.map(([model, contract]) => ({ model, risk: contract.risk })),
|
|
...Object.entries(scalarReferenceContract)
|
|
.filter(([, contract]) => contract.risk)
|
|
.map(([model, contract]) => ({ model, risk: contract.risk })),
|
|
...Object.entries(directWorkerContract)
|
|
.filter(([, contract]) => contract.risk)
|
|
.map(([model, contract]) => ({ model, risk: contract.risk })),
|
|
].sort((left, right) => left.model.localeCompare(right.model));
|
|
|
|
const expectedDefinitionModels = new Set([
|
|
...models.filter((model) => modelRequiresTenantRls(manifest[model.model])).map((model) => model.model),
|
|
...TENANT_SCOPED_IMPLICIT_TABLES.map((entry) => entry.model),
|
|
...Object.keys(globalGuardContract),
|
|
...Object.keys(globalSharedContract),
|
|
...GLOBAL_IMPLICIT_TABLES.map((entry) => entry.model),
|
|
...Object.keys(platformContract),
|
|
"AdminUser",
|
|
]);
|
|
compareContractKeys(
|
|
"generated policy definitions",
|
|
expectedDefinitionModels,
|
|
Object.fromEntries(definitions.map((definition) => [definition.model, true])),
|
|
errors
|
|
);
|
|
if (expectedDefinitionModels.size !== EXPECTED_POLICY_DEFINITION_COUNT) {
|
|
errors.push(`reviewed policy definition baseline changed: expected ${EXPECTED_POLICY_DEFINITION_COUNT}, discovered ${expectedDefinitionModels.size}`);
|
|
}
|
|
if (definitions.length !== new Set(definitions.map((definition) => definition.model)).size) {
|
|
errors.push("generated policy definitions contain duplicate models");
|
|
}
|
|
const forcedRlsCount = definitions.filter((definition) => definition.forceRls !== false).length;
|
|
if (forcedRlsCount !== EXPECTED_FORCED_RLS_COUNT) {
|
|
errors.push(`reviewed FORCE RLS baseline changed: expected ${EXPECTED_FORCED_RLS_COUNT}, generated ${forcedRlsCount}`);
|
|
}
|
|
|
|
return {
|
|
ok: errors.length === 0,
|
|
errors,
|
|
definitions,
|
|
resolvers,
|
|
expectedDefinitionCount: expectedDefinitionModels.size,
|
|
forcedRlsCount,
|
|
risks,
|
|
models,
|
|
manifestValidation,
|
|
};
|
|
}
|
|
|
|
function renderPolicyDefinition(definition) {
|
|
const table = quoteIdentifier(definition.table);
|
|
const lines = [
|
|
`-- ${definition.model}: ${definition.scope} / ${definition.enforcement}`,
|
|
...(definition.paths.length > 0 ? definition.paths.map((pathDescription) => `-- Ownership: ${pathDescription}`) : []),
|
|
`ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;`,
|
|
`ALTER TABLE ${table} ${definition.forceRls === false ? "NO " : ""}FORCE ROW LEVEL SECURITY;`,
|
|
...((definition.sequenceGrants?.length ?? 0) > 0 ? [`REVOKE ALL PRIVILEGES ON ${table} FROM PUBLIC, hivegrid_app, hivegrid_worker;`] : []),
|
|
];
|
|
|
|
if (definition.commandExpressions) {
|
|
for (const command of ["select", "insert", "update", "delete"]) {
|
|
const roles = definition.commandRoles?.[command] ?? TENANT_POLICY_ROLES;
|
|
const policy = quoteIdentifier(definition.policyNames[command]);
|
|
if (roles.length === 0) {
|
|
lines.push(`DROP POLICY IF EXISTS ${policy} ON ${table};`);
|
|
continue;
|
|
}
|
|
const expression = definition.commandExpressions[command];
|
|
lines.push(
|
|
`DROP POLICY IF EXISTS ${policy} ON ${table};`,
|
|
`CREATE POLICY ${policy} ON ${table}`,
|
|
` FOR ${command.toUpperCase()} TO ${renderRoles(roles)}`
|
|
);
|
|
if (command === "insert") {
|
|
lines.push(` WITH CHECK (${expression});`);
|
|
} else if (command === "update") {
|
|
lines.push(` USING (${expression})`, ` WITH CHECK (${definition.updateCheckExpression ?? expression});`);
|
|
} else {
|
|
lines.push(` USING (${expression});`);
|
|
}
|
|
}
|
|
} else if (definition.policyNames.all) {
|
|
const policy = quoteIdentifier(definition.policyNames.all);
|
|
lines.push(
|
|
`DROP POLICY IF EXISTS ${policy} ON ${table};`,
|
|
`CREATE POLICY ${policy} ON ${table}`,
|
|
` FOR ALL TO ${renderRoles(TENANT_POLICY_ROLES)}`,
|
|
` USING (${definition.readExpression})`,
|
|
` WITH CHECK (${definition.writeExpression});`
|
|
);
|
|
} else {
|
|
const readPolicy = quoteIdentifier(definition.policyNames.read);
|
|
const writePolicy = quoteIdentifier(definition.policyNames.write);
|
|
lines.push(
|
|
`DROP POLICY IF EXISTS ${readPolicy} ON ${table};`,
|
|
`CREATE POLICY ${readPolicy} ON ${table}`,
|
|
` FOR SELECT TO ${renderRoles(TENANT_POLICY_ROLES)}`,
|
|
` USING (${definition.readExpression});`,
|
|
`DROP POLICY IF EXISTS ${writePolicy} ON ${table};`,
|
|
`CREATE POLICY ${writePolicy} ON ${table}`,
|
|
` FOR ALL TO ${renderRoles(TENANT_POLICY_ROLES)}`,
|
|
` USING (${definition.writeExpression})`,
|
|
` WITH CHECK (${definition.writeExpression});`
|
|
);
|
|
}
|
|
lines.push(...renderDefinitionGrants(definition, table), ...renderSequenceGrants(definition), "");
|
|
return lines.join("\n");
|
|
}
|
|
|
|
function renderRoles(roles) {
|
|
return roles.join(", ");
|
|
}
|
|
|
|
function renderDefinitionGrants(definition, table) {
|
|
if (!definition.commandRoles) {
|
|
return TENANT_POLICY_ROLES.map((role) => `GRANT SELECT, INSERT, UPDATE, DELETE ON ${table} TO ${role};`);
|
|
}
|
|
const operationsByRole = new Map();
|
|
for (const [command, roles] of Object.entries(definition.commandRoles)) {
|
|
for (const role of roles) {
|
|
const operations = operationsByRole.get(role) ?? [];
|
|
operations.push(command.toUpperCase());
|
|
operationsByRole.set(role, operations);
|
|
}
|
|
}
|
|
return [...operationsByRole.entries()].map(([role, operations]) => `GRANT ${operations.join(", ")} ON ${table} TO ${role};`);
|
|
}
|
|
|
|
function renderSequenceGrants(definition) {
|
|
return (definition.sequenceGrants ?? []).flatMap((grant) => {
|
|
const sequence = quoteIdentifier(grant.name);
|
|
return [
|
|
`REVOKE ALL PRIVILEGES ON SEQUENCE ${sequence} FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;`,
|
|
`GRANT ${grant.privilege} ON SEQUENCE ${sequence} TO ${renderRoles(grant.roles)};`,
|
|
];
|
|
});
|
|
}
|
|
|
|
function renderSequenceGrantRevokes(definition) {
|
|
return (definition.sequenceGrants ?? []).map(
|
|
(grant) => `-- REVOKE ${grant.privilege} ON SEQUENCE ${quoteIdentifier(grant.name)} FROM ${renderRoles(grant.roles)};`
|
|
);
|
|
}
|
|
|
|
function renderTenantOwnershipSchemaPrelude() {
|
|
return [
|
|
"-- Introduce final tenant ownership columns before any policy refers to them.",
|
|
"-- Backfill only ownership patterns that are unambiguous. Unknown legacy",
|
|
"-- scopes abort the migration instead of becoming implicitly system-owned.",
|
|
'ALTER TABLE "IdempotencyKey"',
|
|
' ADD COLUMN "tenantId" TEXT,',
|
|
' ADD COLUMN "partitionKey" TEXT,',
|
|
' ADD COLUMN "systemOwned" BOOLEAN NOT NULL DEFAULT false;',
|
|
"WITH candidates AS (",
|
|
' SELECT idempotency."id", CASE',
|
|
" WHEN idempotency.\"scope\" LIKE 'api:tenant:%' THEN split_part(idempotency.\"scope\", ':', 3)",
|
|
" WHEN idempotency.\"scope\" ~ '^workflow-(trigger|execution|continuation):tenant:[^:]+' THEN split_part(idempotency.\"scope\", ':', 3)",
|
|
" WHEN idempotency.\"scope\" ~ '^integrations-webhook:[^:]+' THEN split_part(idempotency.\"scope\", ':', 2)",
|
|
" WHEN idempotency.\"scope\" ~ '^workflow-(trigger|execution|continuation)-native:[^:]+'",
|
|
" AND split_part(idempotency.\"scope\", ':', 2) <> 'platform' THEN split_part(idempotency.\"scope\", ':', 2)",
|
|
" WHEN idempotency.\"scope\" = 'billing:provider-sync'",
|
|
" AND jsonb_typeof(idempotency.\"responseBody\") = 'object' THEN idempotency.\"responseBody\"->>'tenantId'",
|
|
" ELSE NULL",
|
|
' END AS "tenantId"',
|
|
' FROM "IdempotencyKey" AS idempotency',
|
|
")",
|
|
'UPDATE "IdempotencyKey" AS idempotency',
|
|
'SET "tenantId" = candidate."tenantId",',
|
|
' "partitionKey" = \'tenant:\' || candidate."tenantId",',
|
|
' "systemOwned" = false',
|
|
"FROM candidates AS candidate",
|
|
'WHERE candidate."id" = idempotency."id"',
|
|
' AND candidate."tenantId" IS NOT NULL',
|
|
' AND EXISTS (SELECT 1 FROM "Tenant" WHERE "Tenant"."id" = candidate."tenantId");',
|
|
'UPDATE "IdempotencyKey"',
|
|
'SET "tenantId" = NULL, "partitionKey" = \'system\', "systemOwned" = true',
|
|
"WHERE \"scope\" ~ '^workflow-(trigger|execution|continuation)-native:platform($|:)';",
|
|
"DO $$",
|
|
"BEGIN",
|
|
' IF EXISTS (SELECT 1 FROM "IdempotencyKey" WHERE "partitionKey" IS NULL) THEN',
|
|
" RAISE EXCEPTION 'IdempotencyKey contains rows without a reviewed tenant or platform owner';",
|
|
" END IF;",
|
|
"END$$;",
|
|
'ALTER TABLE "IdempotencyKey" ALTER COLUMN "partitionKey" SET NOT NULL;',
|
|
'DROP INDEX IF EXISTS "idempotency_key_scope_key";',
|
|
'DROP INDEX IF EXISTS "IdempotencyKey_scope_key_key";',
|
|
'CREATE UNIQUE INDEX "idempotency_key_partition_scope_key" ON "IdempotencyKey"("partitionKey", "scope", "key");',
|
|
'CREATE INDEX "idempotency_key_tenant_expires_at_idx" ON "IdempotencyKey"("tenantId", "expiresAt");',
|
|
'CREATE INDEX "idempotency_key_system_expires_at_idx" ON "IdempotencyKey"("systemOwned", "expiresAt");',
|
|
'ALTER TABLE "IdempotencyKey" ADD CONSTRAINT "IdempotencyKey_tenantId_fkey" FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE CASCADE ON UPDATE CASCADE;',
|
|
'ALTER TABLE "IdempotencyKey" ADD CONSTRAINT "IdempotencyKey_ownership_check" CHECK (',
|
|
' ("systemOwned" = true AND "tenantId" IS NULL AND "partitionKey" = \'system\')',
|
|
' OR ("systemOwned" = false AND "tenantId" IS NOT NULL AND "partitionKey" = \'tenant:\' || "tenantId")',
|
|
");",
|
|
"",
|
|
"-- Checkout rows become tenant-owned before RLS is enabled. Prefer the source",
|
|
"-- tenant, fall back to the created tenant, and fail on missing/orphan owners.",
|
|
'ALTER TABLE "CheckoutSessionStatus" ADD COLUMN "tenantId" TEXT;',
|
|
'UPDATE "CheckoutSessionStatus" AS checkout',
|
|
'SET "tenantId" = COALESCE(checkout."fromTenantId", checkout."createdTenantId")',
|
|
'WHERE COALESCE(checkout."fromTenantId", checkout."createdTenantId") IS NOT NULL',
|
|
" AND EXISTS (",
|
|
' SELECT 1 FROM "Tenant"',
|
|
' WHERE "Tenant"."id" = COALESCE(checkout."fromTenantId", checkout."createdTenantId")',
|
|
" );",
|
|
"DO $$",
|
|
"BEGIN",
|
|
' IF EXISTS (SELECT 1 FROM "CheckoutSessionStatus" WHERE "tenantId" IS NULL) THEN',
|
|
" RAISE EXCEPTION 'CheckoutSessionStatus contains rows without a valid tenant owner';",
|
|
" END IF;",
|
|
"END$$;",
|
|
'ALTER TABLE "CheckoutSessionStatus" ALTER COLUMN "tenantId" SET NOT NULL;',
|
|
'DROP INDEX IF EXISTS "CheckoutSessionStatus_fromTenantId_pending_idx";',
|
|
'ALTER TABLE "CheckoutSessionStatus" DROP COLUMN "fromTenantId";',
|
|
'ALTER TABLE "CheckoutSessionStatus" ADD CONSTRAINT "CheckoutSessionStatus_pkey" PRIMARY KEY USING INDEX "CheckoutSessionStatus_id_key";',
|
|
'ALTER TABLE "CheckoutSessionStatus" ADD CONSTRAINT "CheckoutSessionStatus_tenantId_fkey" FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE CASCADE ON UPDATE CASCADE;',
|
|
'CREATE INDEX "CheckoutSessionStatus_tenantId_pending_idx" ON "CheckoutSessionStatus"("tenantId", "pending");',
|
|
"",
|
|
];
|
|
}
|
|
|
|
function renderResolverReadGrants(resolvers) {
|
|
const tables = [...new Set(resolvers.flatMap((resolver) => resolver.readModels ?? []))].sort();
|
|
return tables.length > 0 ? [`GRANT SELECT ON ${tables.map(quoteIdentifier).join(", ")} TO hivegrid_rls_definer;`] : [];
|
|
}
|
|
|
|
function renderRuntimeRolePrelude(result) {
|
|
return [
|
|
"-- Roles and passwords are an external pre-migration prerequisite. This",
|
|
"-- migration only asserts their exact shape and never needs CREATEROLE.",
|
|
"DO $$",
|
|
"DECLARE app_role record; worker_role record; authentik_jit_role record; definer_role record;",
|
|
"BEGIN",
|
|
" IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'hivegrid_app') THEN",
|
|
" RAISE EXCEPTION 'hivegrid_app must be provisioned before migration; run pnpm db:roles:provision' USING ERRCODE = '55000';",
|
|
" END IF;",
|
|
" IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'hivegrid_worker') THEN",
|
|
" RAISE EXCEPTION 'hivegrid_worker must be provisioned before migration; run pnpm db:roles:provision' USING ERRCODE = '55000';",
|
|
" END IF;",
|
|
" IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'hivegrid_authentik_jit') THEN",
|
|
" RAISE EXCEPTION 'hivegrid_authentik_jit must be provisioned before migration; run pnpm db:roles:provision' USING ERRCODE = '55000';",
|
|
" END IF;",
|
|
" SELECT rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, rolinherit, rolreplication, rolbypassrls",
|
|
" INTO app_role FROM pg_roles WHERE rolname = 'hivegrid_app';",
|
|
" SELECT rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, rolinherit, rolreplication, rolbypassrls",
|
|
" INTO worker_role FROM pg_roles WHERE rolname = 'hivegrid_worker';",
|
|
" SELECT rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, rolinherit, rolreplication, rolbypassrls",
|
|
" INTO authentik_jit_role FROM pg_roles WHERE rolname = 'hivegrid_authentik_jit';",
|
|
" IF NOT app_role.rolcanlogin OR app_role.rolsuper OR app_role.rolcreatedb OR app_role.rolcreaterole",
|
|
" OR app_role.rolinherit OR app_role.rolreplication OR app_role.rolbypassrls THEN",
|
|
" RAISE EXCEPTION 'hivegrid_app must be LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS';",
|
|
" END IF;",
|
|
" IF NOT worker_role.rolcanlogin OR worker_role.rolsuper OR worker_role.rolcreatedb OR worker_role.rolcreaterole",
|
|
" OR worker_role.rolinherit OR worker_role.rolreplication OR worker_role.rolbypassrls THEN",
|
|
" RAISE EXCEPTION 'hivegrid_worker must be LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS';",
|
|
" END IF;",
|
|
" IF NOT authentik_jit_role.rolcanlogin OR authentik_jit_role.rolsuper OR authentik_jit_role.rolcreatedb OR authentik_jit_role.rolcreaterole",
|
|
" OR authentik_jit_role.rolinherit OR authentik_jit_role.rolreplication OR authentik_jit_role.rolbypassrls THEN",
|
|
" RAISE EXCEPTION 'hivegrid_authentik_jit must be LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS';",
|
|
" END IF;",
|
|
" IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'hivegrid_rls_definer') THEN",
|
|
" RAISE EXCEPTION 'hivegrid_rls_definer must be provisioned before migration; run pnpm db:roles:provision' USING ERRCODE = '55000';",
|
|
" END IF;",
|
|
" SELECT rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, rolinherit, rolreplication, rolbypassrls",
|
|
" INTO definer_role FROM pg_roles WHERE rolname = 'hivegrid_rls_definer';",
|
|
" IF definer_role.rolcanlogin OR definer_role.rolsuper OR definer_role.rolcreatedb",
|
|
" OR definer_role.rolcreaterole OR definer_role.rolinherit OR definer_role.rolreplication",
|
|
" OR NOT definer_role.rolbypassrls THEN",
|
|
" RAISE EXCEPTION 'hivegrid_rls_definer must be NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION BYPASSRLS';",
|
|
" END IF;",
|
|
" IF NOT current_setting('is_superuser')::boolean",
|
|
" AND NOT pg_has_role(current_user, 'hivegrid_rls_definer', 'MEMBER') THEN",
|
|
" RAISE EXCEPTION 'Migration role must be superuser or a member of hivegrid_rls_definer';",
|
|
" END IF;",
|
|
" IF EXISTS (",
|
|
" SELECT 1 FROM pg_roles AS privileged",
|
|
" WHERE privileged.rolname NOT IN ('hivegrid_app', 'hivegrid_worker', 'hivegrid_authentik_jit')",
|
|
" AND (privileged.rolsuper OR privileged.rolcreatedb OR privileged.rolcreaterole OR privileged.rolreplication OR privileged.rolbypassrls)",
|
|
" AND (pg_has_role('hivegrid_app', privileged.rolname, 'MEMBER')",
|
|
" OR pg_has_role('hivegrid_worker', privileged.rolname, 'MEMBER')",
|
|
" OR pg_has_role('hivegrid_authentik_jit', privileged.rolname, 'MEMBER'))",
|
|
" ) THEN",
|
|
" RAISE EXCEPTION 'Runtime roles must not inherit or SET ROLE to privileged roles';",
|
|
" END IF;",
|
|
" IF EXISTS (",
|
|
" SELECT 1 FROM pg_roles AS granted_role",
|
|
" WHERE (granted_role.rolname <> 'hivegrid_app'",
|
|
" AND pg_has_role('hivegrid_app', granted_role.oid, 'MEMBER'))",
|
|
" OR (granted_role.rolname <> 'hivegrid_worker'",
|
|
" AND pg_has_role('hivegrid_worker', granted_role.oid, 'MEMBER'))",
|
|
" OR (granted_role.rolname <> 'hivegrid_authentik_jit'",
|
|
" AND pg_has_role('hivegrid_authentik_jit', granted_role.oid, 'MEMBER'))",
|
|
" ) THEN",
|
|
" RAISE EXCEPTION 'Runtime roles must not be members of any other role';",
|
|
" END IF;",
|
|
"END$$;",
|
|
"",
|
|
"REVOKE CREATE ON SCHEMA public FROM PUBLIC;",
|
|
"REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;",
|
|
"REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;",
|
|
"REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM hivegrid_rls_definer;",
|
|
"REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM hivegrid_rls_definer;",
|
|
"GRANT USAGE ON SCHEMA public TO hivegrid_app;",
|
|
"GRANT USAGE ON SCHEMA public TO hivegrid_worker;",
|
|
"GRANT USAGE ON SCHEMA public TO hivegrid_authentik_jit;",
|
|
"GRANT USAGE, CREATE ON SCHEMA public TO hivegrid_rls_definer;",
|
|
'GRANT SELECT ON "AdminUser", "AdminSession", "AdminRole", "AdminPermission", "AdminRolePermission", "AdminUserRole", "Registration", "Blacklist", "IpAddress", "IpAddressLog", "McpOAuthClient", "User", "UserSession", "TrustedDevice", "Form", "Tenant", "TenantUser", "BookingPage", "CalendarConnection", "EmailIntegrationMailbox", "ProjektSignatureSigner", "OutboundEmail", "KnowledgeBase", "TenantUserInvitation", "ApiKey", "PublicIncomingWebhookEndpoint", "McpOAuthAccessToken", "McpOAuthRefreshToken", "McpOAuthAuthorizationCode", "TenantInboundAddress", "EmailSequenceStepDelivery", "EmailSequenceRun", "EventWebhookAttempt", "Event", "OutboxEvent", "NotificationDelivery", "AuditEvent", "AuditChainHead", "Lead", "TenantAcquisition", "AdminLeadSource", "AdminLeadSourceCredential", "AdminLead", "IdempotencyKey", "UserRole", "Role", "RolePermission", "Permission", "Portal", "PortalUser", "PortalSession", "PortalToken" TO hivegrid_rls_definer;',
|
|
'GRANT INSERT ON "Registration", "Blacklist", "IpAddress", "IpAddressLog", "McpOAuthClient", "User", "AdminUser", "AuditEvent", "AuditChainHead", "Lead", "LeadEvent", "TenantAcquisition", "AdminLead", "AdminLeadActivity", "IdempotencyKey", "OutboxEvent", "NotificationDelivery" TO hivegrid_rls_definer;',
|
|
'GRANT UPDATE ON "Registration", "Blacklist", "IpAddress", "AdminUser", "AuditChainHead", "Lead", "TenantAcquisition", "AdminLeadSourceCredential", "NotificationDelivery" TO hivegrid_rls_definer;',
|
|
'GRANT UPDATE ("defaultTenantId", "updatedAt") ON "User" TO hivegrid_rls_definer;',
|
|
// AK-P21 tenant hard-delete capabilities. SECURITY DEFINER runs with the
|
|
// owner's privileges and BYPASSRLS waives policies but not table grants,
|
|
// so the definer needs exactly what the three capabilities below touch.
|
|
// SELECT is required next to DELETE/UPDATE because every statement filters
|
|
// on columns and Postgres checks read access for the WHERE clause.
|
|
'GRANT SELECT ON "AdminFeatureFlagOverride", "FeatureFlag", "FeatureFlagFilter", "FeatureFlagAudit", "TeamChatEvent", "AdminTenantNote", "SupportTicket", "SupportTicketMessage", "Feedback" TO hivegrid_rls_definer;',
|
|
'GRANT DELETE ON "AdminFeatureFlagOverride", "FeatureFlag", "FeatureFlagFilter", "FeatureFlagAudit", "UserRole", "TeamChatEvent", "AdminTenantNote", "SupportTicket", "SupportTicketMessage", "Feedback" TO hivegrid_rls_definer;',
|
|
'GRANT UPDATE ON "SupportTicket", "SupportTicketMessage", "Feedback" TO hivegrid_rls_definer;',
|
|
...renderResolverReadGrants(result.resolvers),
|
|
"SET LOCAL ROLE hivegrid_rls_definer;",
|
|
"CREATE OR REPLACE FUNCTION public.hivegrid_is_operator()",
|
|
"RETURNS boolean",
|
|
"LANGUAGE sql",
|
|
"STABLE",
|
|
"SECURITY DEFINER",
|
|
"SET search_path = pg_catalog, public",
|
|
"SET row_security = off",
|
|
"AS $function$",
|
|
` SELECT session_user = ${quoteLiteral(APP_ROLE)}`,
|
|
` AND ${USER_CONTEXT_SQL} IS NOT NULL`,
|
|
` AND EXISTS (`,
|
|
` SELECT 1`,
|
|
` FROM public."AdminUser" AS operator_admin`,
|
|
` WHERE operator_admin."id" = ${USER_CONTEXT_SQL}`,
|
|
` AND operator_admin."status" = 'active'`,
|
|
` );`,
|
|
"$function$;",
|
|
"ALTER FUNCTION public.hivegrid_is_operator() OWNER TO hivegrid_rls_definer;",
|
|
"REVOKE ALL ON FUNCTION public.hivegrid_is_operator() FROM PUBLIC, hivegrid_authentik_jit;",
|
|
"GRANT EXECUTE ON FUNCTION public.hivegrid_is_operator() TO hivegrid_app, hivegrid_worker;",
|
|
"",
|
|
"CREATE OR REPLACE FUNCTION public.hivegrid_admin_has_permission(p_permission text)",
|
|
"RETURNS boolean",
|
|
"LANGUAGE sql",
|
|
"STABLE",
|
|
"SECURITY DEFINER",
|
|
"SET search_path = pg_catalog, public",
|
|
"SET row_security = off",
|
|
"AS $function$",
|
|
` SELECT session_user = ${quoteLiteral(APP_ROLE)}`,
|
|
` AND ${USER_CONTEXT_SQL} IS NOT NULL`,
|
|
" AND EXISTS (",
|
|
' SELECT 1 FROM public."AdminUser" AS permission_admin',
|
|
' JOIN public."AdminUserRole" AS assignment ON assignment."adminUserId" = permission_admin."id"',
|
|
' JOIN public."AdminRole" AS role ON role."id" = assignment."adminRoleId" AND role."active" = true',
|
|
' JOIN public."AdminRolePermission" AS role_permission ON role_permission."adminRoleId" = role."id"',
|
|
' JOIN public."AdminPermission" AS permission ON permission."id" = role_permission."adminPermissionId"',
|
|
` WHERE permission_admin."id" = ${USER_CONTEXT_SQL}`,
|
|
" AND permission_admin.\"status\" = 'active'",
|
|
' AND permission."name" = p_permission',
|
|
" );",
|
|
"$function$;",
|
|
"ALTER FUNCTION public.hivegrid_admin_has_permission(text) OWNER TO hivegrid_rls_definer;",
|
|
"REVOKE ALL ON FUNCTION public.hivegrid_admin_has_permission(text) FROM PUBLIC, hivegrid_authentik_jit;",
|
|
"GRANT EXECUTE ON FUNCTION public.hivegrid_admin_has_permission(text) TO hivegrid_app, hivegrid_worker;",
|
|
"",
|
|
"CREATE OR REPLACE FUNCTION public.hivegrid_reject_admin_audit_mutation()",
|
|
"RETURNS trigger",
|
|
"LANGUAGE plpgsql",
|
|
"SECURITY DEFINER",
|
|
"SET search_path = pg_catalog, public",
|
|
"SET row_security = off",
|
|
"AS $function$",
|
|
"BEGIN",
|
|
' IF OLD."tenantId" IS NULL AND OLD."actorType" = \'admin\' THEN',
|
|
" RAISE EXCEPTION 'Platform admin audit events are append-only' USING ERRCODE = '42501';",
|
|
" END IF;",
|
|
" RETURN OLD;",
|
|
"END",
|
|
"$function$;",
|
|
"ALTER FUNCTION public.hivegrid_reject_admin_audit_mutation() OWNER TO hivegrid_rls_definer;",
|
|
"REVOKE ALL ON FUNCTION public.hivegrid_reject_admin_audit_mutation() FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;",
|
|
"GRANT EXECUTE ON FUNCTION public.hivegrid_reject_admin_audit_mutation() TO hivegrid_migrator;",
|
|
"RESET ROLE;",
|
|
'DROP TRIGGER IF EXISTS "hg_AuditEvent_admin_append_only" ON public."AuditEvent";',
|
|
'CREATE TRIGGER "hg_AuditEvent_admin_append_only"',
|
|
' BEFORE UPDATE OR DELETE ON public."AuditEvent"',
|
|
" FOR EACH ROW EXECUTE FUNCTION public.hivegrid_reject_admin_audit_mutation();",
|
|
"SET LOCAL ROLE hivegrid_rls_definer;",
|
|
"REVOKE EXECUTE ON FUNCTION public.hivegrid_reject_admin_audit_mutation() FROM hivegrid_migrator;",
|
|
"",
|
|
];
|
|
}
|
|
|
|
function renderRegistrationBillingPreferenceCapability({ expiredPendingRotation }) {
|
|
const conflictClause = expiredPendingRotation
|
|
? `
|
|
ON CONFLICT ("email") DO UPDATE
|
|
SET "createdAt" = CURRENT_TIMESTAMP,
|
|
"firstName" = EXCLUDED."firstName",
|
|
"lastName" = EXCLUDED."lastName",
|
|
"token" = EXCLUDED."token",
|
|
"company" = EXCLUDED."company",
|
|
"selectedSubscriptionPriceId" = EXCLUDED."selectedSubscriptionPriceId",
|
|
"selectedOfficeSeatQuantity" = EXCLUDED."selectedOfficeSeatQuantity",
|
|
"selectedFieldSeatQuantity" = EXCLUDED."selectedFieldSeatQuantity",
|
|
"leadConversionLeadId" = EXCLUDED."leadConversionLeadId",
|
|
"leadConversionToken" = EXCLUDED."leadConversionToken",
|
|
"leadConversionPlanId" = EXCLUDED."leadConversionPlanId",
|
|
"ipAddress" = EXCLUDED."ipAddress",
|
|
"slug" = EXCLUDED."slug"
|
|
WHERE registration."createdTenantId" IS NULL
|
|
AND registration."createdAt" <= CURRENT_TIMESTAMP - INTERVAL '24 hours'
|
|
AND registration."token" <> EXCLUDED."token"`
|
|
: "";
|
|
return `CREATE OR REPLACE FUNCTION public.hivegrid_create_registration_v2(
|
|
p_id text, p_email text, p_first_name text, p_last_name text, p_token text,
|
|
p_company text, p_price_id text, p_office_seat_quantity integer,
|
|
p_field_seat_quantity integer, p_lead_id text, p_lead_token text,
|
|
p_lead_plan_id text, p_ip_address text, p_slug text
|
|
)
|
|
RETURNS SETOF public."Registration"
|
|
LANGUAGE sql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
INSERT INTO public."Registration" AS registration (
|
|
"id", "email", "firstName", "lastName", "token", "company",
|
|
"selectedSubscriptionPriceId", "selectedOfficeSeatQuantity",
|
|
"selectedFieldSeatQuantity", "leadConversionLeadId", "leadConversionToken",
|
|
"leadConversionPlanId", "ipAddress", "slug"
|
|
)
|
|
SELECT
|
|
p_id, lower(trim(p_email)), p_first_name, p_last_name, p_token, p_company,
|
|
p_price_id, p_office_seat_quantity, p_field_seat_quantity, p_lead_id,
|
|
p_lead_token, p_lead_plan_id, p_ip_address, p_slug
|
|
WHERE
|
|
(p_office_seat_quantity IS NULL AND p_field_seat_quantity IS NULL)
|
|
OR (
|
|
p_office_seat_quantity BETWEEN 1 AND 10000
|
|
AND p_field_seat_quantity BETWEEN 0 AND 10000
|
|
)${conflictClause}
|
|
RETURNING registration.*
|
|
$function$;`;
|
|
}
|
|
|
|
function renderRegistrationCapabilityFunctions({ expiredPendingRotation }) {
|
|
const billingPreferenceCapability = renderRegistrationBillingPreferenceCapability({ expiredPendingRotation });
|
|
if (!expiredPendingRotation) {
|
|
return `CREATE OR REPLACE FUNCTION public.hivegrid_create_registration(
|
|
p_id text, p_email text, p_first_name text, p_last_name text, p_token text,
|
|
p_company text, p_price_id text, p_lead_id text, p_lead_token text,
|
|
p_lead_plan_id text, p_ip_address text, p_slug text
|
|
)
|
|
RETURNS SETOF public."Registration"
|
|
LANGUAGE sql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
INSERT INTO public."Registration" (
|
|
"id", "email", "firstName", "lastName", "token", "company",
|
|
"selectedSubscriptionPriceId", "leadConversionLeadId", "leadConversionToken",
|
|
"leadConversionPlanId", "ipAddress", "slug"
|
|
) VALUES (
|
|
p_id, lower(trim(p_email)), p_first_name, p_last_name, p_token, p_company,
|
|
p_price_id, p_lead_id, p_lead_token, p_lead_plan_id, p_ip_address, p_slug
|
|
)
|
|
RETURNING *
|
|
$function$;
|
|
|
|
${billingPreferenceCapability}
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_update_registration(
|
|
p_id text, p_expected_email text, p_expected_token text, p_patch jsonb
|
|
)
|
|
RETURNS boolean
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE affected_rows integer;
|
|
BEGIN
|
|
IF ((p_expected_email IS NOT NULL)::integer + (p_expected_token IS NOT NULL)::integer) <> 1 THEN
|
|
RETURN false;
|
|
END IF;
|
|
UPDATE public."Registration" AS registration
|
|
SET "firstName" = CASE WHEN p_expected_email IS NOT NULL AND p_patch ? 'firstName' THEN p_patch->>'firstName' ELSE registration."firstName" END,
|
|
"lastName" = CASE WHEN p_expected_email IS NOT NULL AND p_patch ? 'lastName' THEN p_patch->>'lastName' ELSE registration."lastName" END,
|
|
"company" = CASE WHEN p_expected_email IS NOT NULL AND p_patch ? 'company' THEN p_patch->>'company' ELSE registration."company" END,
|
|
"token" = CASE WHEN p_expected_email IS NOT NULL AND p_patch ? 'token' THEN p_patch->>'token' ELSE registration."token" END,
|
|
"leadConversionLeadId" = CASE WHEN p_expected_email IS NOT NULL AND p_patch ? 'leadConversionLeadId' THEN p_patch->>'leadConversionLeadId' ELSE registration."leadConversionLeadId" END,
|
|
"leadConversionToken" = CASE WHEN p_expected_email IS NOT NULL AND p_patch ? 'leadConversionToken' THEN p_patch->>'leadConversionToken' ELSE registration."leadConversionToken" END,
|
|
"leadConversionPlanId" = CASE WHEN p_expected_email IS NOT NULL AND p_patch ? 'leadConversionPlanId' THEN p_patch->>'leadConversionPlanId' ELSE registration."leadConversionPlanId" END,
|
|
"createdTenantId" = CASE WHEN p_expected_token IS NOT NULL AND p_patch ? 'createdTenantId' THEN p_patch->>'createdTenantId' ELSE registration."createdTenantId" END
|
|
WHERE registration."id" = p_id
|
|
AND registration."createdTenantId" IS NULL
|
|
AND ((p_expected_email IS NOT NULL AND registration."email" = lower(trim(p_expected_email)))
|
|
OR (p_expected_token IS NOT NULL AND registration."token" = p_expected_token));
|
|
GET DIAGNOSTICS affected_rows = ROW_COUNT;
|
|
RETURN affected_rows = 1;
|
|
END
|
|
$function$;`;
|
|
}
|
|
|
|
return `CREATE OR REPLACE FUNCTION public.hivegrid_create_registration(
|
|
p_id text, p_email text, p_first_name text, p_last_name text, p_token text,
|
|
p_company text, p_price_id text, p_lead_id text, p_lead_token text,
|
|
p_lead_plan_id text, p_ip_address text, p_slug text
|
|
)
|
|
RETURNS SETOF public."Registration"
|
|
LANGUAGE sql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
INSERT INTO public."Registration" AS registration (
|
|
"id", "email", "firstName", "lastName", "token", "company",
|
|
"selectedSubscriptionPriceId", "leadConversionLeadId", "leadConversionToken",
|
|
"leadConversionPlanId", "ipAddress", "slug"
|
|
) VALUES (
|
|
p_id, lower(trim(p_email)), p_first_name, p_last_name, p_token, p_company,
|
|
p_price_id, p_lead_id, p_lead_token, p_lead_plan_id, p_ip_address, p_slug
|
|
)
|
|
ON CONFLICT ("email") DO UPDATE
|
|
SET "createdAt" = CURRENT_TIMESTAMP,
|
|
"firstName" = EXCLUDED."firstName",
|
|
"lastName" = EXCLUDED."lastName",
|
|
"token" = EXCLUDED."token",
|
|
"company" = EXCLUDED."company",
|
|
"selectedSubscriptionPriceId" = EXCLUDED."selectedSubscriptionPriceId",
|
|
"leadConversionLeadId" = EXCLUDED."leadConversionLeadId",
|
|
"leadConversionToken" = EXCLUDED."leadConversionToken",
|
|
"leadConversionPlanId" = EXCLUDED."leadConversionPlanId",
|
|
"ipAddress" = EXCLUDED."ipAddress",
|
|
"slug" = EXCLUDED."slug"
|
|
WHERE registration."createdTenantId" IS NULL
|
|
AND registration."createdAt" <= CURRENT_TIMESTAMP - INTERVAL '24 hours'
|
|
AND registration."token" <> EXCLUDED."token"
|
|
RETURNING registration.*
|
|
$function$;
|
|
|
|
${billingPreferenceCapability}
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_update_registration(
|
|
p_id text, p_expected_email text, p_expected_token text, p_patch jsonb
|
|
)
|
|
RETURNS boolean
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE affected_rows integer;
|
|
BEGIN
|
|
IF p_expected_email IS NOT NULL OR p_expected_token IS NULL THEN
|
|
RETURN false;
|
|
END IF;
|
|
|
|
UPDATE public."Registration" AS registration
|
|
SET "createdAt" = CASE
|
|
WHEN p_expected_token IS NOT NULL AND p_patch ? 'token' THEN CURRENT_TIMESTAMP
|
|
ELSE registration."createdAt"
|
|
END,
|
|
"token" = CASE
|
|
WHEN p_expected_token IS NOT NULL AND p_patch ? 'token' THEN p_patch->>'token'
|
|
ELSE registration."token"
|
|
END,
|
|
"createdTenantId" = CASE WHEN p_expected_token IS NOT NULL AND p_patch ? 'createdTenantId' THEN p_patch->>'createdTenantId' ELSE registration."createdTenantId" END
|
|
WHERE registration."id" = p_id
|
|
AND registration."createdTenantId" IS NULL
|
|
AND registration."token" = p_expected_token
|
|
AND (
|
|
(
|
|
p_patch ? 'createdTenantId'
|
|
AND NOT (p_patch ? 'token')
|
|
AND p_patch = jsonb_build_object('createdTenantId', p_patch->'createdTenantId')
|
|
AND COALESCE(length(p_patch->>'createdTenantId'), 0) > 0
|
|
)
|
|
OR (
|
|
p_patch ? 'token'
|
|
AND NOT (p_patch ? 'createdTenantId')
|
|
AND p_patch = jsonb_build_object('token', p_patch->'token')
|
|
AND COALESCE(p_patch->>'token', '') ~ '^[A-Fa-f0-9]{40}$'
|
|
AND registration."token" <> p_patch->>'token'
|
|
)
|
|
);
|
|
GET DIAGNOSTICS affected_rows = ROW_COUNT;
|
|
RETURN affected_rows = 1;
|
|
END
|
|
$function$;`;
|
|
}
|
|
|
|
function renderPretenantSecurityFunctions(options = {}) {
|
|
const registrationCapabilities = renderRegistrationCapabilityFunctions({
|
|
expiredPendingRotation: options.expiredPendingRotation === true,
|
|
});
|
|
return `-- Pre-tenant capability functions expose only the operation needed by public auth.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_find_registration_by_email(p_email text)
|
|
RETURNS TABLE (id text, created_tenant_id text)
|
|
LANGUAGE sql STABLE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
SELECT registration."id", registration."createdTenantId"
|
|
FROM public."Registration" AS registration
|
|
WHERE registration."email" = lower(trim(p_email))
|
|
LIMIT 1
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_find_registration_by_token(p_token text)
|
|
RETURNS SETOF public."Registration"
|
|
LANGUAGE sql STABLE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
SELECT registration.*
|
|
FROM public."Registration" AS registration
|
|
WHERE registration."token" = p_token
|
|
LIMIT 1
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_find_registration_billing_preference(
|
|
p_tenant_id text, p_user_id text
|
|
)
|
|
RETURNS TABLE (
|
|
selected_subscription_price_id text,
|
|
selected_office_seat_quantity integer,
|
|
selected_field_seat_quantity integer
|
|
)
|
|
LANGUAGE sql STABLE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
registration."selectedSubscriptionPriceId",
|
|
registration."selectedOfficeSeatQuantity",
|
|
registration."selectedFieldSeatQuantity"
|
|
FROM public."Registration" AS registration
|
|
WHERE session_user = 'hivegrid_app'
|
|
AND p_tenant_id IS NOT DISTINCT FROM NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND p_user_id IS NOT DISTINCT FROM NULLIF(current_setting('app.user_id', true), '')
|
|
AND registration."createdTenantId" = p_tenant_id
|
|
AND registration."selectedSubscriptionPriceId" IS NOT NULL
|
|
AND length(trim(registration."selectedSubscriptionPriceId")) BETWEEN 1 AND 191
|
|
AND registration."selectedOfficeSeatQuantity" BETWEEN 1 AND 10000
|
|
AND registration."selectedFieldSeatQuantity" BETWEEN 0 AND 10000
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."Tenant" AS tenant
|
|
WHERE tenant."id" = p_tenant_id
|
|
AND tenant."active" = true
|
|
)
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."User" AS app_user
|
|
WHERE app_user."id" = p_user_id
|
|
AND app_user."active" = true
|
|
AND app_user."pseudonymized" = false
|
|
)
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."TenantUser" AS membership
|
|
WHERE membership."tenantId" = p_tenant_id
|
|
AND membership."userId" = p_user_id
|
|
AND membership."status" = 2
|
|
)
|
|
LIMIT 1
|
|
$function$;
|
|
|
|
${registrationCapabilities}
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_capture_marketing_lead(
|
|
p_lead_id text, p_event_id text, p_input jsonb
|
|
)
|
|
RETURNS jsonb
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
normalized_email text;
|
|
existing_lead_id text;
|
|
now_at timestamp(3) without time zone := CURRENT_TIMESTAMP;
|
|
BEGIN
|
|
normalized_email := lower(trim(p_input->>'email'));
|
|
IF p_input IS NULL OR jsonb_typeof(p_input) <> 'object' OR length(p_input::text) > 16384
|
|
OR p_lead_id IS NULL OR trim(p_lead_id) = '' OR length(p_lead_id) > 191
|
|
OR p_event_id IS NULL OR trim(p_event_id) = '' OR length(p_event_id) > 191
|
|
OR normalized_email IS NULL OR length(normalized_email) > 320
|
|
OR normalized_email !~ '^[^[:space:]@]+@[^[:space:]@]+$'
|
|
OR COALESCE(length(p_input->>'firstName'), 0) > 200
|
|
OR COALESCE(length(p_input->>'lastName'), 0) > 200
|
|
OR COALESCE(length(p_input->>'phone'), 0) > 100
|
|
OR COALESCE(length(p_input->>'company'), 0) > 300
|
|
OR COALESCE(length(p_input->>'source'), 0) > 200
|
|
OR COALESCE(length(p_input->>'utmSource'), 0) > 500
|
|
OR COALESCE(length(p_input->>'utmMedium'), 0) > 500
|
|
OR COALESCE(length(p_input->>'utmCampaign'), 0) > 500
|
|
OR COALESCE(length(p_input->>'utmTerm'), 0) > 500
|
|
OR COALESCE(length(p_input->>'utmContent'), 0) > 500
|
|
OR COALESCE(length(p_input->>'gclid'), 0) > 2048
|
|
OR COALESCE(length(p_input->>'fbclid'), 0) > 2048
|
|
OR COALESCE(length(p_input->>'referrer'), 0) > 2048
|
|
OR COALESCE(length(p_input->>'landingPage'), 0) > 2048
|
|
OR COALESCE(length(p_input->>'userAgent'), 0) > 500
|
|
OR (p_input->>'lastIpHash' IS NOT NULL AND p_input->>'lastIpHash' !~ '^[0-9a-f]{32}$')
|
|
OR jsonb_typeof(COALESCE(p_input->'eventPayload', '{}'::jsonb)) <> 'object' THEN
|
|
RAISE EXCEPTION 'Invalid marketing lead capture request' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
PERFORM pg_advisory_xact_lock(hashtextextended('marketing-lead-email:' || normalized_email, 24091));
|
|
SELECT lead_row."id" INTO existing_lead_id
|
|
FROM public."Lead" AS lead_row
|
|
WHERE lead_row."email" = normalized_email
|
|
LIMIT 1;
|
|
|
|
IF existing_lead_id IS NULL THEN
|
|
INSERT INTO public."Lead" (
|
|
"id", "email", "firstName", "lastName", "phone", "company", "source",
|
|
"utmSource", "utmMedium", "utmCampaign", "utmTerm", "utmContent",
|
|
"gclid", "fbclid", "referrer", "landingPage", "lastIpHash", "userAgent",
|
|
"updatedAt"
|
|
) VALUES (
|
|
p_lead_id, normalized_email, NULLIF(trim(p_input->>'firstName'), ''),
|
|
NULLIF(trim(p_input->>'lastName'), ''), NULLIF(trim(p_input->>'phone'), ''),
|
|
NULLIF(trim(p_input->>'company'), ''), NULLIF(trim(p_input->>'source'), ''),
|
|
NULLIF(trim(p_input->>'utmSource'), ''), NULLIF(trim(p_input->>'utmMedium'), ''),
|
|
NULLIF(trim(p_input->>'utmCampaign'), ''), NULLIF(trim(p_input->>'utmTerm'), ''),
|
|
NULLIF(trim(p_input->>'utmContent'), ''), NULLIF(trim(p_input->>'gclid'), ''),
|
|
NULLIF(trim(p_input->>'fbclid'), ''), NULLIF(trim(p_input->>'referrer'), ''),
|
|
NULLIF(trim(p_input->>'landingPage'), ''), NULLIF(trim(p_input->>'lastIpHash'), ''),
|
|
NULLIF(trim(p_input->>'userAgent'), ''), now_at
|
|
);
|
|
INSERT INTO public."LeadEvent" ("id", "leadId", "type", "payload")
|
|
VALUES (p_event_id, p_lead_id, 'captured', COALESCE(p_input->'eventPayload', '{}'::jsonb));
|
|
RETURN jsonb_build_object('leadId', p_lead_id, 'created', true);
|
|
END IF;
|
|
|
|
UPDATE public."Lead" AS lead_row
|
|
SET "lastTouchAt" = now_at,
|
|
"lastIpHash" = NULLIF(trim(p_input->>'lastIpHash'), ''),
|
|
"userAgent" = NULLIF(trim(p_input->>'userAgent'), ''),
|
|
"firstName" = COALESCE(lead_row."firstName", NULLIF(trim(p_input->>'firstName'), '')),
|
|
"lastName" = COALESCE(lead_row."lastName", NULLIF(trim(p_input->>'lastName'), '')),
|
|
"phone" = COALESCE(lead_row."phone", NULLIF(trim(p_input->>'phone'), '')),
|
|
"company" = COALESCE(lead_row."company", NULLIF(trim(p_input->>'company'), '')),
|
|
"updatedAt" = now_at
|
|
WHERE lead_row."id" = existing_lead_id;
|
|
INSERT INTO public."LeadEvent" ("id", "leadId", "type", "payload")
|
|
VALUES (p_event_id, existing_lead_id, 're-captured', COALESCE(p_input->'eventPayload', '{}'::jsonb));
|
|
RETURN jsonb_build_object('leadId', existing_lead_id, 'created', false);
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_find_lead_for_signed_conversion(p_lead_id text)
|
|
RETURNS jsonb
|
|
LANGUAGE sql STABLE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
SELECT (
|
|
SELECT jsonb_build_object(
|
|
'leadId', lead_row."id", 'email', lead_row."email",
|
|
'firstName', lead_row."firstName", 'lastName', lead_row."lastName",
|
|
'company', lead_row."company", 'convertedToTenantId', lead_row."convertedToTenantId"
|
|
)
|
|
FROM public."Lead" AS lead_row
|
|
WHERE p_lead_id IS NOT NULL AND length(p_lead_id) <= 191 AND lead_row."id" = p_lead_id
|
|
LIMIT 1
|
|
)
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_convert_self_service_lead(
|
|
p_event_id text, p_acquisition_id text, p_input jsonb
|
|
)
|
|
RETURNS jsonb
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
context_user_id text := NULLIF(current_setting('app.user_id', true), '');
|
|
context_tenant_id text := NULLIF(current_setting('app.tenant_id', true), '');
|
|
requested_user_id text := trim(p_input->>'userId');
|
|
requested_tenant_id text := trim(p_input->>'tenantId');
|
|
requested_lead_id text := trim(p_input->>'leadId');
|
|
normalized_email text := lower(trim(p_input->>'expectedEmail'));
|
|
lead_row public."Lead"%ROWTYPE;
|
|
now_at timestamp(3) without time zone := CURRENT_TIMESTAMP;
|
|
BEGIN
|
|
IF p_input IS NULL OR jsonb_typeof(p_input) <> 'object' OR length(p_input::text) > 16384
|
|
OR p_event_id IS NULL OR trim(p_event_id) = '' OR length(p_event_id) > 191
|
|
OR p_acquisition_id IS NULL OR trim(p_acquisition_id) = '' OR length(p_acquisition_id) > 191
|
|
OR requested_user_id IS NULL OR requested_user_id = '' OR length(requested_user_id) > 191
|
|
OR requested_tenant_id IS NULL OR requested_tenant_id = '' OR length(requested_tenant_id) > 191
|
|
OR requested_lead_id IS NULL OR requested_lead_id = '' OR length(requested_lead_id) > 191
|
|
OR normalized_email IS NULL OR length(normalized_email) > 320
|
|
OR normalized_email !~ '^[^[:space:]@]+@[^[:space:]@]+$'
|
|
OR COALESCE(length(p_input->>'planId'), 0) > 191
|
|
OR context_user_id IS DISTINCT FROM requested_user_id
|
|
OR context_tenant_id IS DISTINCT FROM requested_tenant_id THEN
|
|
RAISE EXCEPTION 'Invalid self-service lead conversion identity' USING ERRCODE = '28000';
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1
|
|
FROM public."User" AS user_row
|
|
JOIN public."TenantUser" AS membership ON membership."userId" = user_row."id"
|
|
JOIN public."Tenant" AS tenant_row ON tenant_row."id" = membership."tenantId"
|
|
WHERE user_row."id" = requested_user_id
|
|
AND lower(user_row."email") = normalized_email
|
|
AND user_row."active" = true
|
|
AND membership."tenantId" = requested_tenant_id
|
|
AND membership."status" = 2
|
|
AND tenant_row."active" = true
|
|
) THEN
|
|
RAISE EXCEPTION 'Self-service lead conversion membership is not active' USING ERRCODE = '28000';
|
|
END IF;
|
|
|
|
PERFORM pg_advisory_xact_lock(hashtextextended('marketing-lead-id:' || requested_lead_id, 24091));
|
|
PERFORM pg_advisory_xact_lock(hashtextextended('marketing-lead-tenant:' || requested_tenant_id, 24091));
|
|
SELECT * INTO lead_row FROM public."Lead" WHERE "id" = requested_lead_id LIMIT 1;
|
|
IF NOT FOUND THEN
|
|
RETURN NULL;
|
|
END IF;
|
|
IF lower(lead_row."email") <> normalized_email THEN
|
|
RAISE EXCEPTION 'Self-service lead conversion email mismatch' USING ERRCODE = '28000';
|
|
END IF;
|
|
|
|
IF lead_row."convertedToTenantId" IS NOT NULL THEN
|
|
RETURN jsonb_build_object(
|
|
'leadId', lead_row."id", 'convertedToTenantId', lead_row."convertedToTenantId",
|
|
'alreadyConverted', true, 'email', lead_row."email", 'firstName', lead_row."firstName",
|
|
'lastName', lead_row."lastName", 'company', lead_row."company", 'source', lead_row."source",
|
|
'utmSource', lead_row."utmSource", 'utmMedium', lead_row."utmMedium",
|
|
'utmCampaign', lead_row."utmCampaign", 'utmTerm', lead_row."utmTerm",
|
|
'utmContent', lead_row."utmContent", 'gclid', lead_row."gclid", 'fbclid', lead_row."fbclid",
|
|
'referrer', lead_row."referrer", 'landingPage', lead_row."landingPage",
|
|
'firstSeenAt', lead_row."firstSeenAt", 'convertedAt', lead_row."convertedAt"
|
|
);
|
|
END IF;
|
|
|
|
IF EXISTS (
|
|
SELECT 1 FROM public."TenantAcquisition" AS acquisition
|
|
WHERE acquisition."tenantId" = requested_tenant_id
|
|
AND acquisition."leadId" IS NOT NULL
|
|
AND acquisition."leadId" <> requested_lead_id
|
|
) THEN
|
|
RAISE EXCEPTION 'Tenant already has a different acquisition lead' USING ERRCODE = '23505';
|
|
END IF;
|
|
|
|
UPDATE public."Lead"
|
|
SET "status" = 'trial'::public."LeadStatus", "convertedToTenantId" = requested_tenant_id,
|
|
"convertedAt" = now_at, "updatedAt" = now_at
|
|
WHERE "id" = requested_lead_id;
|
|
|
|
INSERT INTO public."LeadEvent" ("id", "leadId", "type", "actorId", "payload")
|
|
VALUES (
|
|
p_event_id, requested_lead_id, 'converted', requested_user_id,
|
|
jsonb_build_object(
|
|
'tenantId', requested_tenant_id, 'conversionPath', 'self-service',
|
|
'targetStatus', 'trial', 'planId', p_input->>'planId'
|
|
)
|
|
);
|
|
|
|
INSERT INTO public."TenantAcquisition" (
|
|
"id", "tenantId", "leadId", "source", "utmSource", "utmMedium", "utmCampaign",
|
|
"utmTerm", "utmContent", "gclid", "fbclid", "referrer", "landingPage",
|
|
"capturedAt", "convertedAt", "conversionPath", "customFields", "updatedAt"
|
|
) VALUES (
|
|
p_acquisition_id, requested_tenant_id, requested_lead_id,
|
|
COALESCE(lead_row."source", 'self-service'), lead_row."utmSource", lead_row."utmMedium",
|
|
lead_row."utmCampaign", lead_row."utmTerm", lead_row."utmContent", lead_row."gclid",
|
|
lead_row."fbclid", lead_row."referrer", lead_row."landingPage", lead_row."firstSeenAt",
|
|
now_at, 'self-service',
|
|
CASE WHEN p_input->>'planId' IS NULL THEN 'null'::jsonb ELSE jsonb_build_object('planId', p_input->>'planId') END,
|
|
now_at
|
|
) ON CONFLICT ("tenantId") DO UPDATE SET
|
|
"leadId" = EXCLUDED."leadId", "source" = EXCLUDED."source", "utmSource" = EXCLUDED."utmSource",
|
|
"utmMedium" = EXCLUDED."utmMedium", "utmCampaign" = EXCLUDED."utmCampaign",
|
|
"utmTerm" = EXCLUDED."utmTerm", "utmContent" = EXCLUDED."utmContent",
|
|
"gclid" = EXCLUDED."gclid", "fbclid" = EXCLUDED."fbclid", "referrer" = EXCLUDED."referrer",
|
|
"landingPage" = EXCLUDED."landingPage", "capturedAt" = EXCLUDED."capturedAt",
|
|
"convertedAt" = EXCLUDED."convertedAt", "conversionPath" = EXCLUDED."conversionPath",
|
|
"customFields" = EXCLUDED."customFields", "updatedAt" = EXCLUDED."updatedAt";
|
|
|
|
RETURN jsonb_build_object(
|
|
'leadId', lead_row."id", 'convertedToTenantId', requested_tenant_id,
|
|
'alreadyConverted', false, 'email', lead_row."email", 'firstName', lead_row."firstName",
|
|
'lastName', lead_row."lastName", 'company', lead_row."company", 'source', lead_row."source",
|
|
'utmSource', lead_row."utmSource", 'utmMedium', lead_row."utmMedium",
|
|
'utmCampaign', lead_row."utmCampaign", 'utmTerm', lead_row."utmTerm",
|
|
'utmContent', lead_row."utmContent", 'gclid', lead_row."gclid", 'fbclid', lead_row."fbclid",
|
|
'referrer', lead_row."referrer", 'landingPage', lead_row."landingPage",
|
|
'firstSeenAt', lead_row."firstSeenAt", 'convertedAt', now_at
|
|
);
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_find_blacklist(p_type text, p_value text)
|
|
RETURNS SETOF public."Blacklist"
|
|
LANGUAGE sql STABLE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
SELECT item.* FROM public."Blacklist" AS item
|
|
WHERE item."type" = p_type AND item."value" = p_value
|
|
ORDER BY item."id" LIMIT 1
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_add_blacklist(p_id text, p_type text, p_value text)
|
|
RETURNS SETOF public."Blacklist"
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
BEGIN
|
|
IF p_type NOT IN ('email', 'domain', 'ip') OR p_value IS NULL OR length(p_value) > 2048 THEN
|
|
RAISE EXCEPTION 'Invalid blacklist entry';
|
|
END IF;
|
|
RETURN QUERY INSERT INTO public."Blacklist" ("id", "type", "value")
|
|
VALUES (p_id, p_type, p_value) RETURNING *;
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_record_blacklist_attempt(p_id text, p_type text, p_value text)
|
|
RETURNS SETOF public."Blacklist"
|
|
LANGUAGE sql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
UPDATE public."Blacklist" AS item
|
|
SET "registerAttempts" = item."registerAttempts" + 1
|
|
WHERE item."id" = p_id AND item."type" = p_type AND item."value" = p_value
|
|
RETURNING *
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_find_ip_address(p_ip_hash text)
|
|
RETURNS SETOF public."IpAddress"
|
|
LANGUAGE sql STABLE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
SELECT address.* FROM public."IpAddress" AS address
|
|
WHERE address."ip" = p_ip_hash LIMIT 1
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_upsert_ip_address(
|
|
p_id text, p_ip text, p_provider text, p_type text, p_country_code text,
|
|
p_country_name text, p_region_code text, p_region_name text, p_city text,
|
|
p_zip_code text, p_latitude numeric, p_longitude numeric, p_metadata text
|
|
)
|
|
RETURNS SETOF public."IpAddress"
|
|
LANGUAGE sql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
INSERT INTO public."IpAddress" (
|
|
"id", "createdAt", "updatedAt", "ip", "provider", "type", "countryCode", "countryName", "regionCode",
|
|
"regionName", "city", "zipCode", "latitude", "longitude", "metadata"
|
|
) VALUES (
|
|
p_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, p_ip, p_provider, p_type, p_country_code, p_country_name, p_region_code,
|
|
p_region_name, p_city, p_zip_code, p_latitude, p_longitude, p_metadata
|
|
)
|
|
ON CONFLICT ("ip") DO UPDATE SET "updatedAt" = CURRENT_TIMESTAMP
|
|
RETURNING *
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_append_ip_address_log(
|
|
p_id text, p_ip text, p_url text, p_action text, p_description text,
|
|
p_success boolean, p_error text, p_metadata text, p_ip_address_id text
|
|
)
|
|
RETURNS SETOF public."IpAddressLog"
|
|
LANGUAGE sql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
INSERT INTO public."IpAddressLog" (
|
|
"id", "ip", "url", "action", "description", "success", "error", "metadata", "ipAddressId"
|
|
) VALUES (
|
|
p_id, p_ip, p_url, p_action, p_description, p_success, p_error, p_metadata, p_ip_address_id
|
|
)
|
|
RETURNING *
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_register_mcp_oauth_client(
|
|
p_id text, p_client_id text, p_client_name text, p_redirect_uris jsonb,
|
|
p_grant_types jsonb, p_scopes jsonb, p_contacts jsonb, p_metadata jsonb
|
|
)
|
|
RETURNS SETOF public."McpOAuthClient"
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
BEGIN
|
|
IF p_id IS NULL OR p_client_id IS NULL OR trim(p_client_name) = ''
|
|
OR length(p_client_name) > 200
|
|
OR jsonb_typeof(p_redirect_uris) <> 'array'
|
|
OR jsonb_array_length(p_redirect_uris) = 0
|
|
OR jsonb_array_length(p_redirect_uris) > 10
|
|
OR jsonb_typeof(p_grant_types) <> 'array'
|
|
OR jsonb_typeof(p_scopes) <> 'array'
|
|
OR (p_contacts IS NOT NULL AND jsonb_typeof(p_contacts) <> 'array')
|
|
OR (p_metadata IS NOT NULL AND jsonb_typeof(p_metadata) <> 'object') THEN
|
|
RAISE EXCEPTION 'Invalid MCP OAuth client registration';
|
|
END IF;
|
|
RETURN QUERY INSERT INTO public."McpOAuthClient" (
|
|
"id", "createdAt", "updatedAt", "clientId", "clientName", "redirectUris",
|
|
"grantTypes", "scopes", "contacts", "metadata", "active"
|
|
) VALUES (
|
|
p_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, p_client_id, p_client_name,
|
|
p_redirect_uris, p_grant_types, p_scopes, p_contacts, p_metadata, true
|
|
) RETURNING *;
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_bind_prepared_authentik_admin_v3(
|
|
p_subject text, p_email text, p_email_verified boolean, p_groups text[], p_first_name text,
|
|
p_last_name text, p_locale text, p_login_at timestamptz
|
|
)
|
|
RETURNS TABLE (admin_user_id text, subject_bound boolean)
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
normalized_email text := lower(trim(p_email));
|
|
resolved_admin_id text;
|
|
linked_subject text;
|
|
resolved_email text;
|
|
resolved_status text;
|
|
matching_admin_count integer;
|
|
BEGIN
|
|
IF session_user <> ${quoteLiteral(AUTHENTIK_JIT_ROLE)} THEN
|
|
RAISE EXCEPTION 'Authentik prepared-admin binding capability is required' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
IF p_subject IS NULL OR trim(p_subject) = '' OR length(p_subject) > 2048
|
|
OR p_email_verified IS DISTINCT FROM true
|
|
OR normalized_email = '' OR length(normalized_email) > 320
|
|
OR position('@' IN normalized_email) <= 1
|
|
OR p_groups IS NULL OR cardinality(p_groups) = 0 OR cardinality(p_groups) > 64
|
|
OR NOT (p_groups && ARRAY['hivegrid-admin', 'hivegrid-staff']::text[])
|
|
OR EXISTS (SELECT 1 FROM unnest(p_groups) AS claimed_group WHERE claimed_group IS NULL OR trim(claimed_group) = '' OR length(claimed_group) > 256)
|
|
OR p_first_name IS NULL OR trim(p_first_name) = '' OR length(p_first_name) > 200
|
|
OR p_last_name IS NULL OR length(p_last_name) > 200
|
|
OR (p_locale IS NOT NULL AND length(p_locale) > 20)
|
|
OR p_login_at IS NULL OR p_login_at < CURRENT_TIMESTAMP - INTERVAL '10 minutes' OR p_login_at > CURRENT_TIMESTAMP + INTERVAL '10 minutes' THEN
|
|
RAISE EXCEPTION 'Invalid Authentik prepared-admin binding request' USING ERRCODE = '28000';
|
|
END IF;
|
|
|
|
PERFORM pg_advisory_xact_lock(hashtextextended('authentik-prepared-admin-sub:' || trim(p_subject), 28001));
|
|
PERFORM pg_advisory_xact_lock(hashtextextended('authentik-prepared-admin-email:' || normalized_email, 28001));
|
|
|
|
SELECT admin_row."id", lower(admin_row."email"), admin_row."status"::text
|
|
INTO resolved_admin_id, resolved_email, resolved_status
|
|
FROM public."AdminUser" AS admin_row
|
|
WHERE admin_row."authentikSubject" = trim(p_subject)
|
|
LIMIT 1
|
|
FOR UPDATE;
|
|
|
|
IF resolved_admin_id IS NOT NULL THEN
|
|
IF resolved_email <> normalized_email OR resolved_status <> 'active' THEN
|
|
RETURN;
|
|
END IF;
|
|
subject_bound := false;
|
|
ELSE
|
|
SELECT COUNT(*)::integer INTO matching_admin_count
|
|
FROM public."AdminUser" AS admin_row
|
|
WHERE lower(admin_row."email") = normalized_email
|
|
AND admin_row."status" = 'active';
|
|
IF matching_admin_count = 0 THEN
|
|
RETURN;
|
|
END IF;
|
|
IF matching_admin_count <> 1 THEN
|
|
RAISE EXCEPTION 'Prepared AdminUser email is ambiguous' USING ERRCODE = '28000';
|
|
END IF;
|
|
|
|
SELECT admin_row."id", admin_row."authentikSubject"
|
|
INTO resolved_admin_id, linked_subject
|
|
FROM public."AdminUser" AS admin_row
|
|
WHERE lower(admin_row."email") = normalized_email
|
|
AND admin_row."status" = 'active'
|
|
LIMIT 1
|
|
FOR UPDATE;
|
|
IF linked_subject IS NOT NULL AND linked_subject <> trim(p_subject) THEN
|
|
RAISE EXCEPTION 'Admin identity is linked to a different Authentik subject' USING ERRCODE = '28000';
|
|
END IF;
|
|
subject_bound := linked_subject IS NULL;
|
|
END IF;
|
|
|
|
UPDATE public."AdminUser"
|
|
SET "firstName" = trim(p_first_name),
|
|
"lastName" = trim(p_last_name),
|
|
"locale" = COALESCE(p_locale, "locale"),
|
|
"authentikSubject" = trim(p_subject),
|
|
"authentikGroups" = p_groups,
|
|
"lastSsoLoginAt" = p_login_at,
|
|
"updatedAt" = CURRENT_TIMESTAMP
|
|
WHERE "id" = resolved_admin_id
|
|
AND "status" = 'active'
|
|
AND ("authentikSubject" IS NULL OR "authentikSubject" = trim(p_subject));
|
|
IF NOT FOUND THEN
|
|
RETURN;
|
|
END IF;
|
|
|
|
admin_user_id := resolved_admin_id;
|
|
RETURN NEXT;
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_lock_admin_sso_audit_head()
|
|
RETURNS TABLE (event_id text, event_hash text, event_created_at timestamptz, head_mac text)
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
BEGIN
|
|
PERFORM pg_advisory_xact_lock(hashtextextended('platform', 0));
|
|
RETURN QUERY
|
|
SELECT chain_head."eventId", chain_head."eventHash", chain_head."eventCreatedAt"::timestamptz, chain_head."headMac"
|
|
FROM public."AuditChainHead" AS chain_head
|
|
WHERE chain_head."chainKey" = 'platform' AND chain_head."tenantId" IS NULL
|
|
LIMIT 1;
|
|
IF FOUND THEN
|
|
RETURN;
|
|
END IF;
|
|
RETURN QUERY
|
|
SELECT audit_event."id", audit_event."eventHash", audit_event."createdAt"::timestamptz, NULL::text
|
|
FROM public."AuditEvent" AS audit_event
|
|
WHERE audit_event."tenantId" IS NULL AND audit_event."eventHash" IS NOT NULL
|
|
ORDER BY audit_event."createdAt" DESC, audit_event."id" DESC
|
|
LIMIT 1;
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_append_admin_sso_audit(
|
|
p_event jsonb, p_previous_hash text, p_event_hash text, p_head_mac text
|
|
)
|
|
RETURNS TABLE (event_id text)
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
current_hash text;
|
|
current_created_at timestamptz;
|
|
new_id text;
|
|
new_created_at timestamptz;
|
|
actor_id text;
|
|
BEGIN
|
|
IF jsonb_typeof(p_event) IS DISTINCT FROM 'object' OR octet_length(p_event::text) > 32768
|
|
OR p_event->>'action' IS NULL OR p_event->>'action' NOT IN (
|
|
'admin.login.sso.success', 'admin.login.sso.failure',
|
|
'admin.login.fallback.success', 'admin.login.fallback.failure',
|
|
'admin.logout.sso', 'admin.mfa.app.challenge.success', 'admin.mfa.app.challenge.failure'
|
|
)
|
|
OR p_event->>'actorType' IS DISTINCT FROM 'admin'
|
|
OR p_event->>'sourceModule' IS DISTINCT FROM 'admin-sso'
|
|
OR p_event->>'outcome' IS NULL OR p_event->>'outcome' NOT IN ('success', 'failure', 'blocked')
|
|
OR p_event->>'dataSensitivity' IS NULL OR p_event->>'dataSensitivity' NOT IN ('public', 'internal', 'confidential', 'pii')
|
|
OR p_event->'tenantId' IS DISTINCT FROM 'null'::jsonb
|
|
OR jsonb_typeof(p_event->'regulatoryScope') IS DISTINCT FROM 'array'
|
|
OR p_event_hash IS NULL OR p_event_hash !~ '^v2:[0-9a-f]{64}$'
|
|
OR p_head_mac IS NULL OR p_head_mac !~ '^ah1:[0-9a-f]{64}$'
|
|
OR (p_previous_hash IS NOT NULL AND p_previous_hash !~ '^(v2:)?[0-9a-f]{64}$') THEN
|
|
RAISE EXCEPTION 'Invalid Admin SSO audit append request' USING ERRCODE = '28000';
|
|
END IF;
|
|
|
|
new_id := p_event->>'id';
|
|
new_created_at := (p_event->>'createdAt')::timestamptz;
|
|
actor_id := p_event->>'actorId';
|
|
IF new_id IS NULL OR trim(new_id) = '' OR length(new_id) > 191
|
|
OR new_created_at IS NULL
|
|
OR length(p_event->>'action') > 191
|
|
OR (actor_id IS NOT NULL AND NOT EXISTS (
|
|
SELECT 1 FROM public."AdminUser" AS admin_row WHERE admin_row."id" = actor_id
|
|
)) THEN
|
|
RAISE EXCEPTION 'Invalid Admin SSO audit identity' USING ERRCODE = '28000';
|
|
END IF;
|
|
|
|
PERFORM pg_advisory_xact_lock(hashtextextended('platform', 0));
|
|
SELECT chain_head."eventHash", chain_head."eventCreatedAt"::timestamptz
|
|
INTO current_hash, current_created_at
|
|
FROM public."AuditChainHead" AS chain_head
|
|
WHERE chain_head."chainKey" = 'platform' AND chain_head."tenantId" IS NULL
|
|
LIMIT 1;
|
|
IF NOT FOUND THEN
|
|
SELECT audit_event."eventHash", audit_event."createdAt"::timestamptz
|
|
INTO current_hash, current_created_at
|
|
FROM public."AuditEvent" AS audit_event
|
|
WHERE audit_event."tenantId" IS NULL AND audit_event."eventHash" IS NOT NULL
|
|
ORDER BY audit_event."createdAt" DESC, audit_event."id" DESC
|
|
LIMIT 1;
|
|
END IF;
|
|
IF current_hash IS DISTINCT FROM p_previous_hash OR (current_created_at IS NOT NULL AND new_created_at <= current_created_at) THEN
|
|
RAISE EXCEPTION 'Admin SSO audit chain changed during append' USING ERRCODE = '40001';
|
|
END IF;
|
|
|
|
INSERT INTO public."AuditEvent" (
|
|
"id", "createdAt", "tenantId", "actorId", "actorType", "actorEmail", "actorIp", "actorUserAgent",
|
|
"action", "targetType", "targetId", "requestId", "sourceModule", "outcome", "dataSensitivity",
|
|
"regulatoryScope", "metadata", "beforeDiff", "afterDiff", "summaryText", "previousHash", "eventHash"
|
|
) VALUES (
|
|
new_id, new_created_at, NULL, actor_id, 'admin', p_event->>'actorEmail', p_event->>'actorIp', p_event->>'actorUserAgent',
|
|
p_event->>'action', p_event->>'targetType', p_event->>'targetId', p_event->>'requestId', 'admin-sso',
|
|
p_event->>'outcome', p_event->>'dataSensitivity',
|
|
ARRAY(SELECT jsonb_array_elements_text(p_event->'regulatoryScope')),
|
|
NULLIF(p_event->'metadata', 'null'::jsonb), NULLIF(p_event->'beforeDiff', 'null'::jsonb),
|
|
NULLIF(p_event->'afterDiff', 'null'::jsonb), p_event->>'summaryText', p_previous_hash, p_event_hash
|
|
);
|
|
INSERT INTO public."AuditChainHead" (
|
|
"chainKey", "tenantId", "eventId", "eventHash", "eventCreatedAt", "headMac"
|
|
) VALUES (
|
|
'platform', NULL, new_id, p_event_hash, new_created_at, p_head_mac
|
|
) ON CONFLICT ("chainKey") DO UPDATE SET
|
|
"tenantId" = NULL, "eventId" = EXCLUDED."eventId", "eventHash" = EXCLUDED."eventHash",
|
|
"eventCreatedAt" = EXCLUDED."eventCreatedAt", "headMac" = EXCLUDED."headMac";
|
|
|
|
event_id := new_id;
|
|
RETURN NEXT;
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_detach_default_tenant_users(p_tenant_id text)
|
|
RETURNS integer
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
affected_rows integer;
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_worker'
|
|
OR p_tenant_id IS NULL
|
|
OR btrim(p_tenant_id) = ''
|
|
OR p_tenant_id IS DISTINCT FROM NULLIF(current_setting('app.tenant_id', true), '') THEN
|
|
RAISE EXCEPTION 'Tenant hard-delete context does not match requested tenant'
|
|
USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
UPDATE public."User" AS account
|
|
SET "defaultTenantId" = NULL,
|
|
"updatedAt" = CURRENT_TIMESTAMP
|
|
WHERE account."defaultTenantId" = p_tenant_id;
|
|
|
|
GET DIAGNOSTICS affected_rows = ROW_COUNT;
|
|
RETURN affected_rows;
|
|
END
|
|
$function$;
|
|
|
|
-- AK-P21 tenant hard-delete capabilities. Same shape as the detach capability
|
|
-- above: worker-only, and the requested tenant must match the bound
|
|
-- app.tenant_id. IS DISTINCT FROM, not <>, so an unset context rejects instead
|
|
-- of comparing against NULL.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_purge_tenant_guarded_rows(p_tenant_id text)
|
|
RETURNS integer
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
purged_count integer := 0;
|
|
step_count integer;
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_worker'
|
|
OR p_tenant_id IS NULL
|
|
OR btrim(p_tenant_id) = ''
|
|
OR p_tenant_id IS DISTINCT FROM NULLIF(current_setting('app.tenant_id', true), '') THEN
|
|
RAISE EXCEPTION 'Tenant hard-delete context does not match requested tenant'
|
|
USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
-- Feature-flag children before their parent.
|
|
DELETE FROM public."FeatureFlagAudit" AS flag_audit
|
|
WHERE flag_audit."flagId" IN (
|
|
SELECT flag."id" FROM public."FeatureFlag" AS flag WHERE flag."tenantId" = p_tenant_id
|
|
);
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
purged_count := purged_count + step_count;
|
|
|
|
DELETE FROM public."FeatureFlagFilter" AS flag_filter
|
|
WHERE flag_filter."featureFlagId" IN (
|
|
SELECT flag."id" FROM public."FeatureFlag" AS flag WHERE flag."tenantId" = p_tenant_id
|
|
);
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
purged_count := purged_count + step_count;
|
|
|
|
DELETE FROM public."FeatureFlag" WHERE "tenantId" = p_tenant_id;
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
purged_count := purged_count + step_count;
|
|
|
|
DELETE FROM public."UserRole" WHERE "tenantId" = p_tenant_id;
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
purged_count := purged_count + step_count;
|
|
|
|
DELETE FROM public."TeamChatEvent" WHERE "tenantId" = p_tenant_id;
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
purged_count := purged_count + step_count;
|
|
|
|
DELETE FROM public."AdminTenantNote" WHERE "tenantId" = p_tenant_id;
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
purged_count := purged_count + step_count;
|
|
|
|
RETURN purged_count;
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_minimize_tenant_support_pii(p_tenant_id text)
|
|
RETURNS integer
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
minimized_count integer := 0;
|
|
step_count integer;
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_worker'
|
|
OR p_tenant_id IS NULL
|
|
OR btrim(p_tenant_id) = ''
|
|
OR p_tenant_id IS DISTINCT FROM NULLIF(current_setting('app.tenant_id', true), '') THEN
|
|
RAISE EXCEPTION 'Tenant hard-delete context does not match requested tenant'
|
|
USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
-- Free-text bodies may carry third-party personal data from the tenant's own
|
|
-- business. Structural fields (ids, status, timestamps) stay: they carry the
|
|
-- retention purpose without the personal content.
|
|
UPDATE public."SupportTicketMessage" AS ticket_message
|
|
SET "body" = '[minimized]'
|
|
WHERE ticket_message."body" <> '[minimized]'
|
|
AND ticket_message."supportTicketId" IN (
|
|
SELECT ticket."id" FROM public."SupportTicket" AS ticket WHERE ticket."tenantId" = p_tenant_id
|
|
);
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
minimized_count := minimized_count + step_count;
|
|
|
|
UPDATE public."SupportTicket"
|
|
SET "subject" = '[minimized]',
|
|
"message" = '[minimized]',
|
|
"fromEmail" = NULL,
|
|
"fromUrl" = NULL,
|
|
"updatedAt" = CURRENT_TIMESTAMP
|
|
WHERE "tenantId" = p_tenant_id
|
|
AND ("subject" <> '[minimized]' OR "message" <> '[minimized]' OR "fromEmail" IS NOT NULL OR "fromUrl" IS NOT NULL);
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
minimized_count := minimized_count + step_count;
|
|
|
|
UPDATE public."Feedback"
|
|
SET "message" = '[minimized]',
|
|
"fromUrl" = '[minimized]'
|
|
WHERE "tenantId" = p_tenant_id
|
|
AND ("message" <> '[minimized]' OR "fromUrl" <> '[minimized]');
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
minimized_count := minimized_count + step_count;
|
|
|
|
RETURN minimized_count;
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_purge_tenant_retained_support(p_tenant_id text)
|
|
RETURNS integer
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
purged_count integer := 0;
|
|
step_count integer;
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_worker'
|
|
OR p_tenant_id IS NULL
|
|
OR btrim(p_tenant_id) = ''
|
|
OR p_tenant_id IS DISTINCT FROM NULLIF(current_setting('app.tenant_id', true), '') THEN
|
|
RAISE EXCEPTION 'Tenant hard-delete context does not match requested tenant'
|
|
USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
DELETE FROM public."SupportTicketMessage" AS ticket_message
|
|
WHERE ticket_message."supportTicketId" IN (
|
|
SELECT ticket."id" FROM public."SupportTicket" AS ticket WHERE ticket."tenantId" = p_tenant_id
|
|
);
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
purged_count := purged_count + step_count;
|
|
|
|
DELETE FROM public."SupportTicket" WHERE "tenantId" = p_tenant_id;
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
purged_count := purged_count + step_count;
|
|
|
|
DELETE FROM public."Feedback" WHERE "tenantId" = p_tenant_id;
|
|
GET DIAGNOSTICS step_count = ROW_COUNT;
|
|
purged_count := purged_count + step_count;
|
|
|
|
RETURN purged_count;
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_admin_outbox_counts()
|
|
RETURNS TABLE (pending_or_processing_count bigint, failed_count bigint)
|
|
LANGUAGE plpgsql STABLE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_app' OR NOT public.hivegrid_is_operator() THEN
|
|
RAISE EXCEPTION 'Platform operator context is required for outbox aggregates'
|
|
USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
RETURN QUERY
|
|
SELECT
|
|
COUNT(*) FILTER (WHERE outbox."status" IN ('PENDING', 'PROCESSING')),
|
|
COUNT(*) FILTER (WHERE outbox."status" = 'FAILED')
|
|
FROM public."OutboxEvent" AS outbox;
|
|
END
|
|
$function$;
|
|
|
|
ALTER FUNCTION public.hivegrid_find_registration_by_email(text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_find_registration_by_token(text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_find_registration_billing_preference(text,text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_create_registration(text,text,text,text,text,text,text,text,text,text,text,text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_create_registration_v2(text,text,text,text,text,text,text,integer,integer,text,text,text,text,text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_update_registration(text,text,text,jsonb) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_capture_marketing_lead(text,text,jsonb) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_find_lead_for_signed_conversion(text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_convert_self_service_lead(text,text,jsonb) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_find_blacklist(text,text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_add_blacklist(text,text,text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_record_blacklist_attempt(text,text,text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_find_ip_address(text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_upsert_ip_address(text,text,text,text,text,text,text,text,text,text,numeric,numeric,text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_append_ip_address_log(text,text,text,text,text,boolean,text,text,text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_register_mcp_oauth_client(text,text,text,jsonb,jsonb,jsonb,jsonb,jsonb) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_bind_prepared_authentik_admin_v3(text,text,boolean,text[],text,text,text,timestamptz) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_lock_admin_sso_audit_head() OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_append_admin_sso_audit(jsonb,text,text,text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_detach_default_tenant_users(text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_purge_tenant_guarded_rows(text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_minimize_tenant_support_pii(text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_purge_tenant_retained_support(text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_admin_outbox_counts() OWNER TO hivegrid_rls_definer;
|
|
|
|
REVOKE ALL ON FUNCTION public.hivegrid_find_registration_by_email(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_find_registration_by_token(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_find_registration_billing_preference(text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_create_registration(text,text,text,text,text,text,text,text,text,text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_create_registration_v2(text,text,text,text,text,text,text,integer,integer,text,text,text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_update_registration(text,text,text,jsonb) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_capture_marketing_lead(text,text,jsonb) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_find_lead_for_signed_conversion(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_convert_self_service_lead(text,text,jsonb) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_find_blacklist(text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_add_blacklist(text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_record_blacklist_attempt(text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_find_ip_address(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_upsert_ip_address(text,text,text,text,text,text,text,text,text,text,numeric,numeric,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_append_ip_address_log(text,text,text,text,text,boolean,text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_register_mcp_oauth_client(text,text,text,jsonb,jsonb,jsonb,jsonb,jsonb) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_bind_prepared_authentik_admin_v3(text,text,boolean,text[],text,text,text,timestamptz) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_lock_admin_sso_audit_head() FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_append_admin_sso_audit(jsonb,text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_detach_default_tenant_users(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_purge_tenant_guarded_rows(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_minimize_tenant_support_pii(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_purge_tenant_retained_support(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_admin_outbox_counts() FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_find_registration_by_email(text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_find_registration_by_token(text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_find_registration_billing_preference(text,text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_create_registration(text,text,text,text,text,text,text,text,text,text,text,text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_create_registration_v2(text,text,text,text,text,text,text,integer,integer,text,text,text,text,text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_update_registration(text,text,text,jsonb) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_find_lead_for_signed_conversion(text) TO hivegrid_app;
|
|
-- R-LEADS: anonymous legacy capture remains retired. The tightly scoped,
|
|
-- membership- and email-bound conversion capability stays executable so
|
|
-- already issued signed registration links retain TenantAcquisition attribution.
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_convert_self_service_lead(text,text,jsonb) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_find_blacklist(text,text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_add_blacklist(text,text,text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_record_blacklist_attempt(text,text,text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_find_ip_address(text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_upsert_ip_address(text,text,text,text,text,text,text,text,text,text,numeric,numeric,text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_append_ip_address_log(text,text,text,text,text,boolean,text,text,text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_register_mcp_oauth_client(text,text,text,jsonb,jsonb,jsonb,jsonb,jsonb) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_bind_prepared_authentik_admin_v3(text,text,boolean,text[],text,text,text,timestamptz) TO hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_lock_admin_sso_audit_head() TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_append_admin_sso_audit(jsonb,text,text,text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_detach_default_tenant_users(text) TO hivegrid_worker;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_purge_tenant_guarded_rows(text) TO hivegrid_worker;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_minimize_tenant_support_pii(text) TO hivegrid_worker;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_purge_tenant_retained_support(text) TO hivegrid_worker;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_admin_outbox_counts() TO hivegrid_app;
|
|
`;
|
|
}
|
|
|
|
function renderAdminLeadSecurityFunctions() {
|
|
return `-- R-LEADS: source authentication and atomic pre-tenant lead capture.
|
|
-- The login role remains NOBYPASSRLS and has no unscoped platform-lead policy;
|
|
-- only these exact functions execute through the reviewed definer boundary.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_authenticate_admin_lead_source(p_credential_hash text)
|
|
RETURNS TABLE (source_id text, source_key text, rate_limit_per_minute integer)
|
|
LANGUAGE sql STABLE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
SELECT source_row."id", source_row."key", source_row."rateLimitPerMinute"
|
|
FROM public."AdminLeadSourceCredential" AS credential
|
|
JOIN public."AdminLeadSource" AS source_row ON source_row."id" = credential."sourceId"
|
|
WHERE session_user = 'hivegrid_app'
|
|
AND p_credential_hash ~ '^[0-9a-f]{64}$'
|
|
AND credential."keyHash" = p_credential_hash
|
|
AND credential."revokedAt" IS NULL
|
|
AND (credential."expiresAt" IS NULL OR credential."expiresAt" > CURRENT_TIMESTAMP)
|
|
AND source_row."enabled" = true
|
|
LIMIT 1
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_enqueue_admin_lead_audit(
|
|
p_event_id text,
|
|
p_action text,
|
|
p_actor_user_id text,
|
|
p_actor_email text,
|
|
p_actor_ip text,
|
|
p_actor_user_agent text,
|
|
p_request_id text,
|
|
p_target_type text,
|
|
p_target_id text,
|
|
p_reason text,
|
|
p_before jsonb,
|
|
p_after jsonb
|
|
)
|
|
RETURNS boolean
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
now_at timestamp(3) without time zone := timezone('UTC', CURRENT_TIMESTAMP);
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_app'
|
|
OR NOT public.hivegrid_is_operator()
|
|
OR p_actor_user_id IS DISTINCT FROM NULLIF(current_setting('app.user_id', true), '')
|
|
OR p_event_id IS NULL OR btrim(p_event_id) = '' OR length(p_event_id) > 191
|
|
OR p_event_id !~ '^[A-Za-z0-9_-]+$'
|
|
OR p_action IS NULL OR p_action NOT IN (
|
|
'admin.lead.manuallyCreated', 'admin.lead.imported',
|
|
'admin.lead.statusChanged', 'admin.lead.assigned', 'admin.lead.noteAdded',
|
|
'admin.lead.archived', 'admin.lead.restored',
|
|
'admin.lead.sourceCreated', 'admin.lead.sourceUpdated',
|
|
'admin.lead.sourceCredentialCreated', 'admin.lead.sourceCredentialRotated',
|
|
'admin.lead.sourceCredentialRevoked'
|
|
)
|
|
OR p_target_type IS NULL OR p_target_type NOT IN ('AdminLead', 'AdminLeadSource', 'AdminLeadSourceCredential')
|
|
OR p_target_id IS NULL OR btrim(p_target_id) = '' OR length(p_target_id) > 191
|
|
OR p_reason IS NULL OR length(btrim(p_reason)) < 5 OR length(p_reason) > 2000
|
|
OR regexp_replace(p_reason, E'[\\t\\n\\r]', '', 'g') ~ '[[:cntrl:]]'
|
|
OR COALESCE(length(p_actor_email), 0) > 320 OR COALESCE(length(p_actor_ip), 0) > 100
|
|
OR COALESCE(length(p_actor_user_agent), 0) > 1000 OR COALESCE(length(p_request_id), 0) > 191
|
|
OR regexp_replace(COALESCE(p_actor_email, ''), E'[\\t\\n\\r]', '', 'g') ~ '[[:cntrl:]]'
|
|
OR regexp_replace(COALESCE(p_actor_ip, ''), E'[\\t\\n\\r]', '', 'g') ~ '[[:cntrl:]]'
|
|
OR regexp_replace(COALESCE(p_actor_user_agent, ''), E'[\\t\\n\\r]', '', 'g') ~ '[[:cntrl:]]'
|
|
OR regexp_replace(COALESCE(p_request_id, ''), E'[\\t\\n\\r]', '', 'g') ~ '[[:cntrl:]]'
|
|
OR (p_before IS NOT NULL AND p_before <> 'null'::jsonb AND jsonb_typeof(p_before) <> 'object')
|
|
OR (p_after IS NOT NULL AND p_after <> 'null'::jsonb AND jsonb_typeof(p_after) <> 'object')
|
|
OR octet_length(COALESCE(p_before, 'null'::jsonb)::text) > 8192
|
|
OR octet_length(COALESCE(p_after, 'null'::jsonb)::text) > 8192 THEN
|
|
RAISE EXCEPTION 'Invalid platform lead audit request' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
INSERT INTO public."OutboxEvent" (
|
|
"id", "tenantId", "eventType", "payload", "status", "createdAt",
|
|
"retries", "scheduledAt", "dispatchKey", "priority"
|
|
) VALUES (
|
|
p_event_id || ':outbox', NULL, 'audit.event.create',
|
|
jsonb_build_object(
|
|
'tenantId', NULL,
|
|
'actorId', p_actor_user_id,
|
|
'actorType', 'admin',
|
|
'actorEmail', NULLIF(btrim(p_actor_email), ''),
|
|
'actorIp', NULLIF(btrim(p_actor_ip), ''),
|
|
'actorUserAgent', NULLIF(btrim(p_actor_user_agent), ''),
|
|
'action', p_action,
|
|
'targetType', p_target_type,
|
|
'targetId', p_target_id,
|
|
'requestId', NULLIF(btrim(p_request_id), ''),
|
|
'sourceModule', 'admin-leads',
|
|
'outcome', 'success',
|
|
'dataSensitivity', 'confidential',
|
|
'regulatoryScope', jsonb_build_array('soc2'),
|
|
'metadata', jsonb_build_object('reason', btrim(p_reason)),
|
|
'beforeDiff', COALESCE(p_before, 'null'::jsonb),
|
|
'afterDiff', COALESCE(p_after, 'null'::jsonb),
|
|
'summaryText', NULL
|
|
),
|
|
'PENDING', now_at, 0, now_at, 'admin-lead-audit:' || p_event_id, 0
|
|
);
|
|
RETURN true;
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_capture_admin_lead(
|
|
p_source_id text,
|
|
p_credential_hash text,
|
|
p_idempotency_key text,
|
|
p_request_hash text,
|
|
p_lead_id text,
|
|
p_activity_id text,
|
|
p_input jsonb
|
|
)
|
|
RETURNS jsonb
|
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
source_row public."AdminLeadSource"%ROWTYPE;
|
|
existing_idempotency public."IdempotencyKey"%ROWTYPE;
|
|
duplicate_lead_id text;
|
|
existing_external_lead public."AdminLead"%ROWTYPE;
|
|
normalized_email text := NULLIF(lower(btrim(p_input->>'normalizedEmail')), '');
|
|
normalized_phone text := NULLIF(btrim(p_input->>'normalizedPhone'), '');
|
|
scope_key text;
|
|
now_at timestamp(3) without time zone := timezone('UTC', CURRENT_TIMESTAMP);
|
|
response_body jsonb;
|
|
lead_event_metadata jsonb;
|
|
recipient_user_id text;
|
|
delivery_channel public."NotificationPreferenceChannel";
|
|
delivery_id text;
|
|
delivery_source_key text;
|
|
delivery_channel_key text;
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_app' THEN
|
|
RAISE EXCEPTION 'Platform lead capture requires the application runtime role' USING ERRCODE = '42501';
|
|
END IF;
|
|
IF p_input IS NULL OR jsonb_typeof(p_input) <> 'object' OR octet_length(p_input::text) > 16384
|
|
OR p_source_id IS NULL OR btrim(p_source_id) = '' OR length(p_source_id) > 191
|
|
OR p_credential_hash IS NULL OR p_credential_hash !~ '^[0-9a-f]{64}$'
|
|
OR p_idempotency_key IS NULL OR btrim(p_idempotency_key) = '' OR length(p_idempotency_key) > 200
|
|
OR p_idempotency_key ~ '[[:cntrl:]]'
|
|
OR p_request_hash IS NULL OR p_request_hash !~ '^[0-9a-f]{64}$'
|
|
OR p_lead_id IS NULL OR btrim(p_lead_id) = '' OR length(p_lead_id) > 128
|
|
OR p_lead_id !~ '^[A-Za-z0-9_-]+$'
|
|
OR p_activity_id IS NULL OR btrim(p_activity_id) = '' OR length(p_activity_id) > 128
|
|
OR p_activity_id !~ '^[A-Za-z0-9_-]+$'
|
|
OR EXISTS (
|
|
SELECT 1 FROM jsonb_object_keys(p_input) AS input_key
|
|
WHERE input_key NOT IN (
|
|
'externalId', 'sourceDetail', 'firstName', 'lastName', 'email', 'normalizedEmail',
|
|
'phone', 'normalizedPhone', 'company', 'message', 'utmSource', 'utmMedium',
|
|
'utmCampaign', 'utmTerm', 'utmContent', 'referrer', 'landingPage', 'metadata'
|
|
)
|
|
)
|
|
OR EXISTS (
|
|
SELECT 1 FROM jsonb_each(p_input) AS input_entry(key, value)
|
|
WHERE key <> 'metadata' AND jsonb_typeof(value) NOT IN ('string', 'null')
|
|
)
|
|
OR COALESCE(length(p_input->>'externalId'), 0) > 256
|
|
OR COALESCE(length(p_input->>'sourceDetail'), 0) > 500
|
|
OR COALESCE(length(p_input->>'firstName'), 0) > 200
|
|
OR COALESCE(length(p_input->>'lastName'), 0) > 200
|
|
OR COALESCE(length(p_input->>'email'), 0) > 320
|
|
OR COALESCE(length(p_input->>'phone'), 0) > 100
|
|
OR COALESCE(length(p_input->>'company'), 0) > 300
|
|
OR COALESCE(length(p_input->>'message'), 0) > 8000
|
|
OR COALESCE(length(p_input->>'utmSource'), 0) > 500
|
|
OR COALESCE(length(p_input->>'utmMedium'), 0) > 500
|
|
OR COALESCE(length(p_input->>'utmCampaign'), 0) > 500
|
|
OR COALESCE(length(p_input->>'utmTerm'), 0) > 500
|
|
OR COALESCE(length(p_input->>'utmContent'), 0) > 500
|
|
OR COALESCE(length(p_input->>'referrer'), 0) > 2048
|
|
OR COALESCE(length(p_input->>'landingPage'), 0) > 2048
|
|
OR (p_input->>'email' IS NOT NULL AND p_input->>'email' !~ '^[^[:space:]@]+@[^[:space:]@]+$')
|
|
OR (p_input->>'email' IS NOT NULL AND p_input->>'normalizedEmail' IS DISTINCT FROM lower(btrim(p_input->>'email')))
|
|
OR (p_input->>'email' IS NULL AND p_input->>'normalizedEmail' IS NOT NULL)
|
|
OR (p_input->>'phone' IS NOT NULL AND p_input->>'normalizedPhone' IS NULL)
|
|
OR (p_input->>'phone' IS NULL AND p_input->>'normalizedPhone' IS NOT NULL)
|
|
OR (p_input->>'normalizedPhone' IS NOT NULL AND p_input->>'normalizedPhone' !~ '^\\+?[0-9]{5,20}$')
|
|
OR (
|
|
p_input->>'phone' IS NOT NULL
|
|
AND p_input->>'normalizedPhone' IS DISTINCT FROM
|
|
(CASE WHEN btrim(p_input->>'phone') LIKE '+%' THEN '+' ELSE '' END)
|
|
|| regexp_replace(p_input->>'phone', '[^0-9]', '', 'g')
|
|
)
|
|
OR (p_input->'metadata' IS NOT NULL AND p_input->'metadata' <> 'null'::jsonb AND jsonb_typeof(p_input->'metadata') <> 'object')
|
|
OR octet_length(COALESCE(p_input->'metadata', 'null'::jsonb)::text) > 4096
|
|
OR EXISTS (
|
|
SELECT 1 FROM jsonb_object_keys(
|
|
CASE WHEN jsonb_typeof(p_input->'metadata') = 'object' THEN p_input->'metadata' ELSE '{}'::jsonb END
|
|
) AS metadata_key
|
|
WHERE metadata_key NOT IN ('consent', 'formId', 'formName', 'legacyId', 'legacyStore', 'locale', 'productInterest', 'submissionId')
|
|
)
|
|
OR EXISTS (
|
|
SELECT 1
|
|
FROM jsonb_each(
|
|
CASE WHEN jsonb_typeof(p_input->'metadata') = 'object' THEN p_input->'metadata' ELSE '{}'::jsonb END
|
|
) AS metadata_entry(key, value)
|
|
WHERE jsonb_typeof(value) NOT IN ('string', 'number', 'boolean', 'null')
|
|
OR (jsonb_typeof(value) = 'string' AND (
|
|
length(value #>> '{}') > 500 OR (value #>> '{}') ~ '[[:cntrl:]]'
|
|
))
|
|
)
|
|
OR NOT (
|
|
NULLIF(btrim(p_input->>'email'), '') IS NOT NULL
|
|
OR NULLIF(btrim(p_input->>'phone'), '') IS NOT NULL
|
|
OR NULLIF(btrim(p_input->>'company'), '') IS NOT NULL
|
|
OR NULLIF(btrim(p_input->>'firstName'), '') IS NOT NULL
|
|
OR NULLIF(btrim(p_input->>'lastName'), '') IS NOT NULL
|
|
OR NULLIF(btrim(p_input->>'message'), '') IS NOT NULL
|
|
) THEN
|
|
RAISE EXCEPTION 'Invalid platform lead capture request' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
SELECT source_candidate.* INTO source_row
|
|
FROM public."AdminLeadSourceCredential" AS credential
|
|
JOIN public."AdminLeadSource" AS source_candidate ON source_candidate."id" = credential."sourceId"
|
|
WHERE credential."keyHash" = p_credential_hash
|
|
AND credential."sourceId" = p_source_id
|
|
AND credential."revokedAt" IS NULL
|
|
AND (credential."expiresAt" IS NULL OR credential."expiresAt" > now_at)
|
|
LIMIT 1;
|
|
IF NOT FOUND THEN
|
|
RETURN jsonb_build_object('outcome', 'authentication_failed');
|
|
END IF;
|
|
IF source_row."enabled" IS DISTINCT FROM true THEN
|
|
RETURN jsonb_build_object('outcome', 'source_disabled');
|
|
END IF;
|
|
IF cardinality(COALESCE(source_row."notifyAdminUserIds", ARRAY[]::text[])) NOT BETWEEN 1 AND 20 THEN
|
|
RAISE EXCEPTION 'Platform lead source must have between one and twenty durable notification recipients' USING ERRCODE = '23514';
|
|
END IF;
|
|
IF EXISTS (
|
|
SELECT 1
|
|
FROM unnest(source_row."notifyAdminUserIds") AS recipient(value)
|
|
WHERE value !~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$'
|
|
) THEN
|
|
RAISE EXCEPTION 'Platform lead source has an invalid notification recipient' USING ERRCODE = '23514';
|
|
END IF;
|
|
|
|
scope_key := 'platform-leads:' || source_row."id";
|
|
PERFORM pg_advisory_xact_lock(hashtextextended(scope_key || ':' || p_idempotency_key, 24091));
|
|
SELECT idempotency.* INTO existing_idempotency
|
|
FROM public."IdempotencyKey" AS idempotency
|
|
WHERE idempotency."partitionKey" = 'system'
|
|
AND idempotency."scope" = scope_key
|
|
AND idempotency."key" = p_idempotency_key
|
|
LIMIT 1;
|
|
IF FOUND THEN
|
|
UPDATE public."AdminLeadSourceCredential" AS credential
|
|
SET "lastUsedAt" = now_at
|
|
WHERE credential."keyHash" = p_credential_hash
|
|
AND credential."sourceId" = source_row."id";
|
|
IF existing_idempotency."requestHash" <> p_request_hash THEN
|
|
RETURN jsonb_build_object('outcome', 'conflict');
|
|
END IF;
|
|
IF existing_idempotency."responseStatus" <= 0 OR existing_idempotency."responseBody" IS NULL THEN
|
|
RETURN jsonb_build_object('outcome', 'in_progress');
|
|
END IF;
|
|
RETURN existing_idempotency."responseBody" || jsonb_build_object('outcome', 'replayed');
|
|
END IF;
|
|
|
|
IF NULLIF(btrim(p_input->>'externalId'), '') IS NOT NULL THEN
|
|
PERFORM pg_advisory_xact_lock(
|
|
hashtextextended(
|
|
'platform-lead-external:' || source_row."id" || ':' || NULLIF(btrim(p_input->>'externalId'), ''),
|
|
24092
|
|
)
|
|
);
|
|
SELECT lead_row.* INTO existing_external_lead
|
|
FROM public."AdminLead" AS lead_row
|
|
WHERE lead_row."sourceId" = source_row."id"
|
|
AND lead_row."externalId" = NULLIF(btrim(p_input->>'externalId'), '')
|
|
LIMIT 1;
|
|
IF FOUND THEN
|
|
response_body := jsonb_build_object(
|
|
'outcome', 'replayed',
|
|
'lead', jsonb_build_object(
|
|
'id', existing_external_lead."id",
|
|
'status', existing_external_lead."status"::text,
|
|
'createdAt', to_char(existing_external_lead."createdAt", 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')
|
|
)
|
|
);
|
|
INSERT INTO public."IdempotencyKey" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "partitionKey", "systemOwned",
|
|
"scope", "key", "requestHash", "responseStatus", "responseBody", "responseHeaders"
|
|
) VALUES (
|
|
p_activity_id || ':idempotency', now_at, now_at, NULL, 'system', true,
|
|
scope_key, p_idempotency_key, p_request_hash, 201, response_body, '{}'::jsonb
|
|
);
|
|
UPDATE public."AdminLeadSourceCredential" AS credential
|
|
SET "lastUsedAt" = now_at
|
|
WHERE credential."keyHash" = p_credential_hash
|
|
AND credential."sourceId" = source_row."id";
|
|
RETURN response_body;
|
|
END IF;
|
|
END IF;
|
|
|
|
IF normalized_email IS NOT NULL OR normalized_phone IS NOT NULL THEN
|
|
SELECT lead_row."id" INTO duplicate_lead_id
|
|
FROM public."AdminLead" AS lead_row
|
|
WHERE (normalized_email IS NOT NULL AND lead_row."normalizedEmail" = normalized_email)
|
|
OR (normalized_phone IS NOT NULL AND lead_row."normalizedPhone" = normalized_phone)
|
|
ORDER BY lead_row."capturedAt" DESC, lead_row."id" DESC
|
|
LIMIT 1;
|
|
END IF;
|
|
|
|
INSERT INTO public."AdminLead" (
|
|
"id", "createdAt", "updatedAt", "capturedAt", "sourceId", "sourceDetail",
|
|
"externalId", "idempotencyKey", "firstName", "lastName", "email",
|
|
"normalizedEmail", "phone", "normalizedPhone", "company", "message",
|
|
"utmSource", "utmMedium", "utmCampaign", "utmTerm", "utmContent",
|
|
"referrer", "landingPage", "status", "assignedToAdminUserId",
|
|
"duplicateHintOfLeadId", "metadata"
|
|
) VALUES (
|
|
p_lead_id, now_at, now_at, now_at, source_row."id", NULLIF(btrim(p_input->>'sourceDetail'), ''),
|
|
NULLIF(btrim(p_input->>'externalId'), ''), p_idempotency_key,
|
|
NULLIF(btrim(p_input->>'firstName'), ''), NULLIF(btrim(p_input->>'lastName'), ''),
|
|
NULLIF(btrim(p_input->>'email'), ''), normalized_email,
|
|
NULLIF(btrim(p_input->>'phone'), ''), normalized_phone,
|
|
NULLIF(btrim(p_input->>'company'), ''), NULLIF(btrim(p_input->>'message'), ''),
|
|
NULLIF(btrim(p_input->>'utmSource'), ''), NULLIF(btrim(p_input->>'utmMedium'), ''),
|
|
NULLIF(btrim(p_input->>'utmCampaign'), ''), NULLIF(btrim(p_input->>'utmTerm'), ''),
|
|
NULLIF(btrim(p_input->>'utmContent'), ''), NULLIF(btrim(p_input->>'referrer'), ''),
|
|
NULLIF(btrim(p_input->>'landingPage'), ''), 'new', source_row."defaultAssigneeAdminUserId",
|
|
duplicate_lead_id, NULLIF(p_input->'metadata', 'null'::jsonb)
|
|
);
|
|
INSERT INTO public."AdminLeadActivity" ("id", "createdAt", "leadId", "type", "payload")
|
|
VALUES (p_activity_id, now_at, p_lead_id, 'captured', jsonb_build_object('sourceId', source_row."id"));
|
|
IF duplicate_lead_id IS NOT NULL THEN
|
|
INSERT INTO public."AdminLeadActivity" ("id", "createdAt", "leadId", "type", "payload")
|
|
VALUES (
|
|
p_activity_id || ':duplicate', now_at, p_lead_id, 'duplicate_hint_recorded',
|
|
jsonb_build_object('duplicateHintOfLeadId', duplicate_lead_id)
|
|
);
|
|
END IF;
|
|
|
|
lead_event_metadata := jsonb_build_object(
|
|
'leadId', p_lead_id,
|
|
'sourceId', source_row."id",
|
|
'eventType', 'platform.admin_lead.captured.v1',
|
|
'deeplink', '/leads/' || p_lead_id
|
|
);
|
|
|
|
INSERT INTO public."OutboxEvent" (
|
|
"id", "tenantId", "eventType", "payload", "status", "createdAt",
|
|
"retries", "scheduledAt", "dispatchKey", "priority"
|
|
) VALUES (
|
|
p_activity_id || ':lead-outbox', NULL, 'platform.admin_lead.captured.v1',
|
|
jsonb_build_object(
|
|
'leadId', p_lead_id,
|
|
'sourceId', source_row."id",
|
|
'eventTime', to_char(now_at, 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
|
|
'routingUserIds', to_jsonb(source_row."notifyAdminUserIds")
|
|
),
|
|
'PENDING', now_at, 0, now_at, 'platform-lead-captured:' || p_lead_id, 0
|
|
);
|
|
|
|
INSERT INTO public."OutboxEvent" (
|
|
"id", "tenantId", "eventType", "payload", "status", "createdAt",
|
|
"retries", "scheduledAt", "dispatchKey", "priority"
|
|
) VALUES (
|
|
p_activity_id || ':audit-outbox', NULL, 'audit.event.create',
|
|
jsonb_build_object(
|
|
'tenantId', NULL,
|
|
'actorId', NULL,
|
|
'actorType', 'system',
|
|
'actorEmail', NULL,
|
|
'actorIp', NULL,
|
|
'actorUserAgent', NULL,
|
|
'action', 'admin.lead.captured',
|
|
'targetType', 'AdminLead',
|
|
'targetId', p_lead_id,
|
|
'requestId', NULL,
|
|
'sourceModule', 'admin-leads',
|
|
'outcome', 'success',
|
|
'dataSensitivity', 'confidential',
|
|
'regulatoryScope', jsonb_build_array('soc2'),
|
|
'metadata', jsonb_build_object('sourceId', source_row."id"),
|
|
'beforeDiff', NULL,
|
|
'afterDiff', jsonb_build_object(
|
|
'status', 'new',
|
|
'assignedToAdminUserId', source_row."defaultAssigneeAdminUserId"
|
|
),
|
|
'summaryText', NULL
|
|
),
|
|
'PENDING', now_at, 0, now_at, 'admin-lead-audit:' || p_activity_id, 0
|
|
);
|
|
|
|
FOREACH recipient_user_id IN ARRAY source_row."notifyAdminUserIds" LOOP
|
|
FOREACH delivery_channel IN ARRAY ARRAY['IN_APP'::public."NotificationPreferenceChannel", 'EMAIL'::public."NotificationPreferenceChannel"] LOOP
|
|
delivery_channel_key := CASE delivery_channel WHEN 'IN_APP' THEN 'in-app' ELSE 'email' END;
|
|
delivery_source_key := 'platform-lead:' || p_lead_id || ':' || delivery_channel_key;
|
|
delivery_id := 'platform-delivery:' || md5(p_lead_id || ':' || recipient_user_id || ':' || delivery_channel::text);
|
|
|
|
INSERT INTO public."NotificationDelivery" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "userId", "channel",
|
|
"category", "messageKey", "sourceKey", "status", "attemptsMade",
|
|
"payloadMetadata"
|
|
) VALUES (
|
|
delivery_id, now_at, now_at, NULL, recipient_user_id, delivery_channel,
|
|
'leads', 'platform.leads.captured', delivery_source_key, 'PENDING', 0,
|
|
lead_event_metadata
|
|
)
|
|
ON CONFLICT ("userId", "channel", "sourceKey") WHERE "tenantId" IS NULL
|
|
DO UPDATE SET "updatedAt" = public."NotificationDelivery"."updatedAt"
|
|
RETURNING "id" INTO delivery_id;
|
|
|
|
INSERT INTO public."OutboxEvent" (
|
|
"id", "tenantId", "eventType", "payload", "status", "createdAt",
|
|
"retries", "scheduledAt", "dispatchKey", "priority"
|
|
) VALUES (
|
|
delivery_id || ':outbox', NULL, 'notification.platform.requested.v1',
|
|
jsonb_build_object(
|
|
'deliveryId', delivery_id,
|
|
'userId', recipient_user_id,
|
|
'sourceKey', delivery_source_key,
|
|
'channel', delivery_channel_key,
|
|
'messageKey', 'platform.leads.captured',
|
|
'category', 'leads',
|
|
'metadata', lead_event_metadata
|
|
),
|
|
'PENDING', now_at, 0, now_at, 'platform-notification:' || delivery_id, 0
|
|
) ON CONFLICT ("dispatchKey") DO NOTHING;
|
|
END LOOP;
|
|
END LOOP;
|
|
|
|
response_body := jsonb_build_object(
|
|
'outcome', 'created',
|
|
'lead', jsonb_build_object(
|
|
'id', p_lead_id,
|
|
'status', 'new',
|
|
'createdAt', to_char(now_at, 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')
|
|
)
|
|
);
|
|
INSERT INTO public."IdempotencyKey" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "partitionKey", "systemOwned",
|
|
"scope", "key", "requestHash", "responseStatus", "responseBody", "responseHeaders"
|
|
) VALUES (
|
|
p_activity_id || ':idempotency', now_at, now_at, NULL, 'system', true,
|
|
scope_key, p_idempotency_key, p_request_hash, 201, response_body, '{}'::jsonb
|
|
);
|
|
UPDATE public."AdminLeadSourceCredential" AS credential
|
|
SET "lastUsedAt" = now_at
|
|
WHERE credential."keyHash" = p_credential_hash
|
|
AND credential."sourceId" = source_row."id";
|
|
RETURN response_body;
|
|
END
|
|
$function$;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_resolve_platform_lead_notification_recipient(
|
|
p_user_id text,
|
|
p_lead_id text
|
|
)
|
|
RETURNS TABLE (email text)
|
|
LANGUAGE sql STABLE SECURITY DEFINER
|
|
SET search_path = pg_catalog, public SET row_security = off
|
|
AS $function$
|
|
SELECT operator_admin."email"
|
|
FROM public."AdminUser" AS operator_admin
|
|
JOIN public."AdminLead" AS lead_row ON lead_row."id" = p_lead_id
|
|
WHERE session_user = 'hivegrid_worker'
|
|
AND p_user_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$'
|
|
AND p_lead_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$'
|
|
AND operator_admin."id" = p_user_id
|
|
AND operator_admin."status" = 'active'
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."AdminUserRole" AS assignment
|
|
JOIN public."AdminRole" AS role_row ON role_row."id" = assignment."adminRoleId"
|
|
JOIN public."AdminRolePermission" AS role_permission ON role_permission."adminRoleId" = role_row."id"
|
|
JOIN public."AdminPermission" AS permission ON permission."id" = role_permission."adminPermissionId"
|
|
WHERE assignment."adminUserId" = p_user_id
|
|
AND role_row."active" = true
|
|
AND permission."name" = 'admin_sales.crm.read'
|
|
)
|
|
LIMIT 1
|
|
$function$;
|
|
|
|
ALTER FUNCTION public.hivegrid_authenticate_admin_lead_source(text) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_enqueue_admin_lead_audit(text,text,text,text,text,text,text,text,text,text,jsonb,jsonb) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_capture_admin_lead(text,text,text,text,text,text,jsonb) OWNER TO hivegrid_rls_definer;
|
|
ALTER FUNCTION public.hivegrid_resolve_platform_lead_notification_recipient(text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_authenticate_admin_lead_source(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_enqueue_admin_lead_audit(text,text,text,text,text,text,text,text,text,text,jsonb,jsonb) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_capture_admin_lead(text,text,text,text,text,text,jsonb) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_resolve_platform_lead_notification_recipient(text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_authenticate_admin_lead_source(text) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_enqueue_admin_lead_audit(text,text,text,text,text,text,text,text,text,text,jsonb,jsonb) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_capture_admin_lead(text,text,text,text,text,text,jsonb) TO hivegrid_app;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_resolve_platform_lead_notification_recipient(text,text) TO hivegrid_worker;
|
|
`;
|
|
}
|
|
|
|
const PRETENANT_SECURITY_FUNCTION_SIGNATURES = Object.freeze([
|
|
"public.hivegrid_is_operator()",
|
|
"public.hivegrid_admin_has_permission(text)",
|
|
"public.hivegrid_reject_admin_audit_mutation()",
|
|
"public.hivegrid_find_registration_by_email(text)",
|
|
"public.hivegrid_find_registration_by_token(text)",
|
|
"public.hivegrid_find_registration_billing_preference(text,text)",
|
|
"public.hivegrid_create_registration(text,text,text,text,text,text,text,text,text,text,text,text)",
|
|
"public.hivegrid_create_registration_v2(text,text,text,text,text,text,text,integer,integer,text,text,text,text,text)",
|
|
"public.hivegrid_update_registration(text,text,text,jsonb)",
|
|
"public.hivegrid_capture_marketing_lead(text,text,jsonb)",
|
|
"public.hivegrid_find_lead_for_signed_conversion(text)",
|
|
"public.hivegrid_convert_self_service_lead(text,text,jsonb)",
|
|
"public.hivegrid_find_blacklist(text,text)",
|
|
"public.hivegrid_add_blacklist(text,text,text)",
|
|
"public.hivegrid_record_blacklist_attempt(text,text,text)",
|
|
"public.hivegrid_find_ip_address(text)",
|
|
"public.hivegrid_upsert_ip_address(text,text,text,text,text,text,text,text,text,text,numeric,numeric,text)",
|
|
"public.hivegrid_append_ip_address_log(text,text,text,text,text,boolean,text,text,text)",
|
|
"public.hivegrid_register_mcp_oauth_client(text,text,text,jsonb,jsonb,jsonb,jsonb,jsonb)",
|
|
"public.hivegrid_bind_prepared_authentik_admin_v3(text,text,boolean,text[],text,text,text,timestamp with time zone)",
|
|
"public.hivegrid_lock_admin_sso_audit_head()",
|
|
"public.hivegrid_append_admin_sso_audit(jsonb,text,text,text)",
|
|
"public.hivegrid_detach_default_tenant_users(text)",
|
|
"public.hivegrid_purge_tenant_guarded_rows(text)",
|
|
"public.hivegrid_minimize_tenant_support_pii(text)",
|
|
"public.hivegrid_purge_tenant_retained_support(text)",
|
|
"public.hivegrid_admin_outbox_counts()",
|
|
"public.hivegrid_authenticate_admin_lead_source(text)",
|
|
"public.hivegrid_enqueue_admin_lead_audit(text,text,text,text,text,text,text,text,text,text,jsonb,jsonb)",
|
|
"public.hivegrid_capture_admin_lead(text,text,text,text,text,text,jsonb)",
|
|
"public.hivegrid_resolve_platform_lead_notification_recipient(text,text)",
|
|
]);
|
|
|
|
const CROSS_SURFACE_SECURITY_FUNCTION_SIGNATURES = Object.freeze(["public.hivegrid_form_submission_actor_contract(text,text,text,text)"]);
|
|
|
|
const WORKER_EXECUTE_SECURITY_FUNCTION_SIGNATURES = new Set([
|
|
"public.hivegrid_is_operator()",
|
|
"public.hivegrid_admin_has_permission(text)",
|
|
"public.hivegrid_purge_tenant_guarded_rows(text)",
|
|
"public.hivegrid_minimize_tenant_support_pii(text)",
|
|
"public.hivegrid_purge_tenant_retained_support(text)",
|
|
"public.hivegrid_detach_default_tenant_users(text)",
|
|
...CROSS_SURFACE_SECURITY_FUNCTION_SIGNATURES,
|
|
"public.hivegrid_resolve_platform_lead_notification_recipient(text,text)",
|
|
]);
|
|
|
|
const WORKER_ONLY_SECURITY_FUNCTION_SIGNATURES = new Set([
|
|
"public.hivegrid_purge_tenant_guarded_rows(text)",
|
|
"public.hivegrid_minimize_tenant_support_pii(text)",
|
|
"public.hivegrid_purge_tenant_retained_support(text)",
|
|
"public.hivegrid_detach_default_tenant_users(text)",
|
|
"public.hivegrid_resolve_platform_lead_notification_recipient(text,text)",
|
|
]);
|
|
|
|
const APP_DISABLED_SECURITY_FUNCTION_SIGNATURES = new Set([
|
|
"public.hivegrid_capture_marketing_lead(text,text,jsonb)",
|
|
"public.hivegrid_reject_admin_audit_mutation()",
|
|
]);
|
|
|
|
const AUTHENTIK_JIT_EXECUTE_SECURITY_FUNCTION_SIGNATURES = new Set([
|
|
"public.hivegrid_bind_prepared_authentik_admin_v3(text,text,boolean,text[],text,text,text,timestamp with time zone)",
|
|
]);
|
|
|
|
function rlsDefinerFunctionSignatures(result) {
|
|
return [
|
|
...PRETENANT_SECURITY_FUNCTION_SIGNATURES,
|
|
...CROSS_SURFACE_SECURITY_FUNCTION_SIGNATURES,
|
|
...result.resolvers.map((resolver) => `public.${resolver.name}(${resolver.parameters.map((parameter) => parameter.type).join(",")})`),
|
|
];
|
|
}
|
|
|
|
function renderDefinerFunctionPreflight(result) {
|
|
const signatures = rlsDefinerFunctionSignatures(result);
|
|
const values = signatures
|
|
.map(
|
|
(signature) =>
|
|
` (${quoteLiteral(signature)}, ${WORKER_ONLY_SECURITY_FUNCTION_SIGNATURES.has(signature) || AUTHENTIK_JIT_EXECUTE_SECURITY_FUNCTION_SIGNATURES.has(signature) || APP_DISABLED_SECURITY_FUNCTION_SIGNATURES.has(signature) ? "false" : "true"}, ${WORKER_EXECUTE_SECURITY_FUNCTION_SIGNATURES.has(signature) ? "true" : "false"}, ${AUTHENTIK_JIT_EXECUTE_SECURITY_FUNCTION_SIGNATURES.has(signature) ? "true" : "false"})`
|
|
)
|
|
.join(",\n");
|
|
return [
|
|
"-- The BYPASSRLS owner may own only this reviewed, non-public function set.",
|
|
"DO $$",
|
|
"DECLARE reviewed_count integer; unexpected_count integer;",
|
|
"BEGIN",
|
|
" WITH expected(signature, app_execute, worker_execute, authentik_jit_execute) AS (VALUES",
|
|
values,
|
|
" )",
|
|
" SELECT COUNT(*)::int INTO reviewed_count",
|
|
" FROM expected",
|
|
" JOIN pg_proc AS procedure ON procedure.oid = to_regprocedure(expected.signature)",
|
|
" JOIN pg_roles AS owner ON owner.oid = procedure.proowner",
|
|
" WHERE owner.rolname = 'hivegrid_rls_definer'",
|
|
" AND procedure.prokind = 'f'",
|
|
" AND procedure.prosecdef = true",
|
|
" AND procedure.proconfig @> ARRAY['search_path=pg_catalog, public', 'row_security=off']::text[]",
|
|
" AND has_function_privilege('hivegrid_app', procedure.oid, 'EXECUTE') = expected.app_execute",
|
|
" AND has_function_privilege('hivegrid_worker', procedure.oid, 'EXECUTE') = expected.worker_execute",
|
|
" AND has_function_privilege('hivegrid_authentik_jit', procedure.oid, 'EXECUTE') = expected.authentik_jit_execute",
|
|
" AND NOT EXISTS (",
|
|
" SELECT 1",
|
|
" FROM aclexplode(COALESCE(procedure.proacl, acldefault('f', procedure.proowner))) AS access",
|
|
" LEFT JOIN pg_roles AS grantee ON grantee.oid = access.grantee",
|
|
" WHERE access.privilege_type = 'EXECUTE'",
|
|
" AND (",
|
|
" access.grantee = 0",
|
|
" OR (",
|
|
" access.grantee <> procedure.proowner",
|
|
" AND NOT (expected.app_execute AND grantee.rolname = 'hivegrid_app')",
|
|
" AND NOT (expected.worker_execute AND grantee.rolname = 'hivegrid_worker')",
|
|
" AND NOT (expected.authentik_jit_execute AND grantee.rolname = 'hivegrid_authentik_jit')",
|
|
" )",
|
|
" )",
|
|
" );",
|
|
` IF reviewed_count <> ${signatures.length} THEN`,
|
|
` RAISE EXCEPTION 'Reviewed hivegrid_rls_definer function contract is incomplete or unsafe (%/${signatures.length} valid)', reviewed_count;`,
|
|
" END IF;",
|
|
" WITH expected(signature) AS (VALUES",
|
|
signatures.map((signature) => ` (${quoteLiteral(signature)})`).join(",\n"),
|
|
" )",
|
|
" SELECT COUNT(*)::int INTO unexpected_count",
|
|
" FROM pg_proc AS procedure",
|
|
" JOIN pg_roles AS owner ON owner.oid = procedure.proowner",
|
|
" WHERE owner.rolname = 'hivegrid_rls_definer'",
|
|
" AND procedure.proname NOT LIKE 'hivegrid_portal_%'",
|
|
" AND NOT EXISTS (SELECT 1 FROM expected WHERE procedure.oid = to_regprocedure(expected.signature));",
|
|
" IF unexpected_count <> 0 THEN",
|
|
" RAISE EXCEPTION 'hivegrid_rls_definer owns an unreviewed function';",
|
|
" END IF;",
|
|
"END$$;",
|
|
"",
|
|
];
|
|
}
|
|
|
|
function renderResolverArguments(parameters, includeDefaults) {
|
|
return parameters
|
|
.map((parameter) => {
|
|
const defaultClause = includeDefaults && parameter.defaultSql !== undefined ? ` DEFAULT ${parameter.defaultSql}` : "";
|
|
return `${quoteIdentifier(parameter.name)} ${parameter.type}${defaultClause}`;
|
|
})
|
|
.join(", ");
|
|
}
|
|
|
|
function renderTenantResolvers(result) {
|
|
const lines = [
|
|
"-- Bootstrap resolvers expose only tenant/resource/user ids. They do not",
|
|
"-- grant table access and every full read is repeated under app.tenant_id.",
|
|
];
|
|
for (const resolver of result.resolvers) {
|
|
const name = `public.${quoteIdentifier(resolver.name)}`;
|
|
const declaration = renderResolverArguments(resolver.parameters, true);
|
|
const signature = resolver.parameters.map((parameter) => parameter.type).join(", ");
|
|
lines.push(
|
|
`CREATE OR REPLACE FUNCTION ${name}(${declaration})`,
|
|
"RETURNS TABLE (tenant_id text, resource_id text, user_id text)",
|
|
"LANGUAGE sql",
|
|
"STABLE",
|
|
"SECURITY DEFINER",
|
|
"SET search_path = pg_catalog, public",
|
|
"SET row_security = off",
|
|
"AS $function$",
|
|
...resolver.query.split("\n").map((line) => ` ${line}`),
|
|
"$function$;",
|
|
`ALTER FUNCTION ${name}(${signature}) OWNER TO hivegrid_rls_definer;`,
|
|
`REVOKE ALL ON FUNCTION ${name}(${signature}) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;`,
|
|
`GRANT EXECUTE ON FUNCTION ${name}(${signature}) TO hivegrid_app;`,
|
|
""
|
|
);
|
|
}
|
|
return lines;
|
|
}
|
|
|
|
function renderExistingPolicyReset(result) {
|
|
const protectedTables = result.definitions.map((definition) => quoteLiteral(definition.table)).join(", ");
|
|
return [
|
|
"-- PostgreSQL combines permissive policies with OR. Remove every earlier",
|
|
"-- rollout-policy variant before installing this exact reviewed contract.",
|
|
"DO $$",
|
|
"DECLARE existing_policy record;",
|
|
"BEGIN",
|
|
" FOR existing_policy IN",
|
|
" SELECT namespace.nspname AS schema_name, class.relname AS table_name, policy.polname AS policy_name",
|
|
" FROM pg_policy AS policy",
|
|
" JOIN pg_class AS class ON class.oid = policy.polrelid",
|
|
" JOIN pg_namespace AS namespace ON namespace.oid = class.relnamespace",
|
|
` WHERE namespace.nspname = 'public' AND class.relname = ANY (ARRAY[${protectedTables}])`,
|
|
" AND policy.polname NOT LIKE 'hg_portal_%'",
|
|
" LOOP",
|
|
" EXECUTE format('DROP POLICY %I ON %I.%I', existing_policy.policy_name, existing_policy.schema_name, existing_policy.table_name);",
|
|
" END LOOP;",
|
|
"END$$;",
|
|
"",
|
|
];
|
|
}
|
|
|
|
function renderDirectRelationPreflight(result) {
|
|
const lines = [
|
|
"-- Refuse the cutover if legacy rows already contain a cross-tenant FK.",
|
|
"-- PostgreSQL FK checks intentionally bypass RLS, so every future write is",
|
|
"-- additionally guarded by the generated WITH CHECK expressions below.",
|
|
];
|
|
for (const definition of result.definitions) {
|
|
for (const check of definition.integrityChecks) {
|
|
lines.push(
|
|
"DO $$",
|
|
"BEGIN",
|
|
` IF EXISTS (SELECT 1 FROM ${quoteIdentifier(definition.table)} WHERE NOT (${check.rowExpression})) THEN`,
|
|
` RAISE EXCEPTION 'Cross-tenant FK invariant failed: ${definition.model}.${check.relation} -> ${check.target}';`,
|
|
" END IF;",
|
|
"END$$;"
|
|
);
|
|
}
|
|
}
|
|
lines.push("");
|
|
return lines;
|
|
}
|
|
|
|
export function renderTenantPolicySql(result, options = {}) {
|
|
if (!result.ok) throw new Error(`Cannot render invalid tenant policy contract:\n${result.errors.join("\n")}`);
|
|
const deployment = options.deployment === true;
|
|
const lines = [
|
|
"-- GENERATED FILE. DO NOT EDIT BY HAND.",
|
|
"-- Source: prisma/tenant-scope-manifest.mjs + prisma/tenant-policy-contract.mjs",
|
|
"-- Generator: node scripts/generate-tenant-policy-contract.mjs",
|
|
deployment
|
|
? "-- Forward-only deployment migration for the reviewed app-wide RLS cutover."
|
|
: "-- Review artifact: current policy and post-cutover capability contract.",
|
|
"-- Managed role passwords remain external deployment secrets.",
|
|
`-- Coverage: ${result.definitions.length}/${result.definitions.length} RLS-enforced models.`,
|
|
"",
|
|
"BEGIN;",
|
|
"",
|
|
...(deployment ? renderTenantOwnershipSchemaPrelude() : []),
|
|
...renderRuntimeRolePrelude(result),
|
|
...renderPretenantSecurityFunctions({ expiredPendingRotation: !deployment }).trimEnd().split("\n"),
|
|
...renderAdminLeadSecurityFunctions().trimEnd().split("\n"),
|
|
"",
|
|
...renderTenantResolvers(result),
|
|
"RESET ROLE;",
|
|
"REVOKE CREATE ON SCHEMA public FROM hivegrid_rls_definer;",
|
|
"",
|
|
...renderDefinerFunctionPreflight(result),
|
|
...renderDirectRelationPreflight(result),
|
|
...renderExistingPolicyReset(result),
|
|
...result.definitions.map(renderPolicyDefinition),
|
|
"COMMIT;",
|
|
"",
|
|
"-- Inverse SQL (execute deliberately during a coordinated rollback):",
|
|
];
|
|
|
|
for (const definition of [...result.definitions].reverse()) {
|
|
const table = quoteIdentifier(definition.table);
|
|
for (const policy of Object.values(definition.policyNames)) {
|
|
lines.push(`-- DROP POLICY IF EXISTS ${quoteIdentifier(policy)} ON ${table};`);
|
|
}
|
|
lines.push(
|
|
...renderSequenceGrantRevokes(definition),
|
|
`-- REVOKE SELECT, INSERT, UPDATE, DELETE ON ${table} FROM hivegrid_app;`,
|
|
`-- REVOKE SELECT, INSERT, UPDATE, DELETE ON ${table} FROM hivegrid_worker;`,
|
|
`-- ALTER TABLE ${table} NO FORCE ROW LEVEL SECURITY;`,
|
|
`-- ALTER TABLE ${table} DISABLE ROW LEVEL SECURITY;`
|
|
);
|
|
}
|
|
const unprotectedTables = [...result.models, ...GLOBAL_IMPLICIT_TABLES]
|
|
.filter((model) => !result.definitions.some((definition) => definition.table === model.table))
|
|
.map((model) => quoteIdentifier(model.table));
|
|
lines.push(
|
|
...unprotectedTables.map((table) => `-- REVOKE SELECT, INSERT, UPDATE, DELETE ON ${table} FROM hivegrid_app;`),
|
|
...unprotectedTables.map((table) => `-- REVOKE SELECT, INSERT, UPDATE, DELETE ON ${table} FROM hivegrid_worker;`),
|
|
"-- REVOKE USAGE ON ALL SEQUENCES IN SCHEMA public FROM hivegrid_app;",
|
|
"-- REVOKE USAGE ON ALL SEQUENCES IN SCHEMA public FROM hivegrid_worker;",
|
|
"-- REVOKE USAGE ON ALL SEQUENCES IN SCHEMA public FROM hivegrid_authentik_jit;",
|
|
...[...result.resolvers]
|
|
.reverse()
|
|
.map(
|
|
(resolver) =>
|
|
`-- DROP FUNCTION IF EXISTS public.${quoteIdentifier(resolver.name)}(${resolver.parameters.map((parameter) => parameter.type).join(", ")});`
|
|
),
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_append_admin_sso_audit(jsonb,text,text,text);",
|
|
'-- DROP TRIGGER IF EXISTS "hg_AuditEvent_admin_append_only" ON public."AuditEvent";',
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_reject_admin_audit_mutation();",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_detach_default_tenant_users(text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_purge_tenant_guarded_rows(text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_minimize_tenant_support_pii(text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_purge_tenant_retained_support(text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_admin_outbox_counts();",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_capture_admin_lead(text,text,text,text,text,text,jsonb);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_enqueue_admin_lead_audit(text,text,text,text,text,text,text,text,text,text,jsonb,jsonb);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_authenticate_admin_lead_source(text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_resolve_platform_lead_notification_recipient(text,text);",
|
|
'-- REVOKE UPDATE ("defaultTenantId", "updatedAt") ON "User" FROM hivegrid_rls_definer;',
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_lock_admin_sso_audit_head();",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_bind_prepared_authentik_admin_v3(text,text,boolean,text[],text,text,text,timestamptz);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_register_mcp_oauth_client(text,text,text,jsonb,jsonb,jsonb,jsonb,jsonb);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_append_ip_address_log(text,text,text,text,text,boolean,text,text,text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_upsert_ip_address(text,text,text,text,text,text,text,text,text,text,numeric,numeric,text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_find_ip_address(text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_record_blacklist_attempt(text,text,text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_add_blacklist(text,text,text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_find_blacklist(text,text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_update_registration(text,text,text,jsonb);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_convert_self_service_lead(text,text,jsonb);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_find_lead_for_signed_conversion(text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_capture_marketing_lead(text,text,jsonb);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_create_registration(text,text,text,text,text,text,text,text,text,text,text,text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_create_registration_v2(text,text,text,text,text,text,text,integer,integer,text,text,text,text,text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_find_registration_by_token(text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_find_registration_by_email(text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_find_registration_billing_preference(text,text);",
|
|
"-- REVOKE EXECUTE ON FUNCTION public.hivegrid_is_operator() FROM hivegrid_app, hivegrid_worker;",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_is_operator();",
|
|
"-- REVOKE EXECUTE ON FUNCTION public.hivegrid_admin_has_permission(text) FROM hivegrid_app, hivegrid_worker;",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_admin_has_permission(text);",
|
|
"-- REVOKE SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public FROM hivegrid_rls_definer;",
|
|
"-- REVOKE USAGE ON ALL SEQUENCES IN SCHEMA public FROM hivegrid_rls_definer;",
|
|
"-- REVOKE USAGE ON SCHEMA public FROM hivegrid_rls_definer;",
|
|
"-- REVOKE USAGE ON SCHEMA public FROM hivegrid_app;",
|
|
"-- REVOKE USAGE ON SCHEMA public FROM hivegrid_worker;",
|
|
"-- REVOKE USAGE ON SCHEMA public FROM hivegrid_authentik_jit;",
|
|
"-- Runtime and definer roles are externally managed; rollback never drops them.",
|
|
'-- ALTER TABLE "CheckoutSessionStatus" DROP CONSTRAINT IF EXISTS "CheckoutSessionStatus_tenantId_fkey";',
|
|
'-- DROP INDEX IF EXISTS "CheckoutSessionStatus_tenantId_pending_idx";',
|
|
'-- ALTER TABLE "CheckoutSessionStatus" ADD COLUMN "fromTenantId" TEXT;',
|
|
'-- UPDATE "CheckoutSessionStatus" SET "fromTenantId" = "tenantId";',
|
|
'-- ALTER TABLE "CheckoutSessionStatus" DROP CONSTRAINT IF EXISTS "CheckoutSessionStatus_pkey";',
|
|
'-- CREATE UNIQUE INDEX "CheckoutSessionStatus_id_key" ON "CheckoutSessionStatus"("id");',
|
|
'-- ALTER TABLE "CheckoutSessionStatus" DROP COLUMN IF EXISTS "tenantId";',
|
|
'-- CREATE INDEX "CheckoutSessionStatus_fromTenantId_pending_idx" ON "CheckoutSessionStatus"("fromTenantId", "pending");',
|
|
'-- ALTER TABLE "IdempotencyKey" DROP CONSTRAINT IF EXISTS "IdempotencyKey_ownership_check";',
|
|
'-- ALTER TABLE "IdempotencyKey" DROP CONSTRAINT IF EXISTS "IdempotencyKey_tenantId_fkey";',
|
|
'-- DROP INDEX IF EXISTS "idempotency_key_partition_scope_key";',
|
|
'-- DROP INDEX IF EXISTS "idempotency_key_tenant_expires_at_idx";',
|
|
'-- DROP INDEX IF EXISTS "idempotency_key_system_expires_at_idx";',
|
|
'-- CREATE UNIQUE INDEX "IdempotencyKey_scope_key_key" ON "IdempotencyKey"("scope", "key");',
|
|
'-- ALTER TABLE "IdempotencyKey" DROP COLUMN IF EXISTS "tenantId", DROP COLUMN IF EXISTS "partitionKey", DROP COLUMN IF EXISTS "systemOwned";'
|
|
);
|
|
lines.push("");
|
|
return lines.join("\n");
|
|
}
|
|
|
|
function readCutoverSurface(sql) {
|
|
const tables = new Set([...sql.matchAll(/ALTER TABLE\s+(?:ONLY\s+)?(?:public\.)?"([^"]+)"\s+ENABLE ROW LEVEL SECURITY/giu)].map((match) => match[1]));
|
|
const resolvers = new Set(
|
|
[...sql.matchAll(/CREATE(?:\s+OR\s+REPLACE)?\s+FUNCTION\s+public\."?(hivegrid_resolve_[a-z0-9_]+)"?\s*\(/giu)].map((match) => match[1])
|
|
);
|
|
return { tables, resolvers };
|
|
}
|
|
|
|
export function readPostCutoverMigrationSql(rootDirectory = process.cwd()) {
|
|
const migrationsDirectory = path.join(rootDirectory, "prisma/migrations");
|
|
if (!existsSync(migrationsDirectory)) {
|
|
throw new Error("Prisma migrations directory is missing while collecting deployed post-cutover RLS surface");
|
|
}
|
|
|
|
const frozenCutoverMigrationName = path.basename(path.dirname(GENERATED_MIGRATION_PATH));
|
|
const postCutoverMigrationNames = readdirSync(migrationsDirectory, { withFileTypes: true })
|
|
.filter((entry) => entry.isDirectory() && entry.name > frozenCutoverMigrationName)
|
|
.map((entry) => entry.name)
|
|
.sort((left, right) => left.localeCompare(right));
|
|
|
|
return postCutoverMigrationNames
|
|
.map((migrationName) => {
|
|
const migrationPath = path.join(migrationsDirectory, migrationName, "migration.sql");
|
|
if (!existsSync(migrationPath)) {
|
|
throw new Error(`Post-cutover migration ${migrationName} is missing migration.sql`);
|
|
}
|
|
return readFileSync(migrationPath, "utf8");
|
|
})
|
|
.join("\n");
|
|
}
|
|
|
|
export function sha256(value) {
|
|
return createHash("sha256").update(value).digest("hex");
|
|
}
|
|
|
|
/**
|
|
* Renders only policy definitions and bootstrap resolvers added after the
|
|
* immutable baseline. Schema DDL must precede this block in the merge
|
|
* migration; feature branches keep it as a reviewable, deterministic delta.
|
|
*/
|
|
export function renderPostCutoverPolicyDeltaSql(result, frozenCutoverSql, postCutoverMigrationSql = "") {
|
|
if (!result.ok) throw new Error(`Cannot render invalid tenant policy contract:\n${result.errors.join("\n")}`);
|
|
if (sha256(frozenCutoverSql) !== FROZEN_BASELINE_MIGRATION_SHA256) {
|
|
throw new Error("The reviewed Prisma baseline is not byte-identical to its frozen checksum");
|
|
}
|
|
|
|
const deployed = readCutoverSurface(`${frozenCutoverSql}\n${postCutoverMigrationSql}`);
|
|
const definitions = result.definitions.filter((definition) => !deployed.tables.has(definition.table));
|
|
const resolvers = result.resolvers.filter((resolver) => !deployed.resolvers.has(resolver.name));
|
|
const includeAdminLeadCapabilities = definitions.some((definition) => definition.model === "AdminLead");
|
|
const delta = { ...result, definitions, resolvers };
|
|
const lines = [
|
|
"-- GENERATED POST-CUTOVER RLS DELTA. DO NOT EDIT BY HAND.",
|
|
"-- Fold this block after the matching schema DDL in the forward-only merge migration.",
|
|
`-- Additive coverage: ${definitions.length} tables, ${resolvers.length} bootstrap resolvers.`,
|
|
"",
|
|
"BEGIN;",
|
|
"",
|
|
...renderResolverReadGrants(resolvers),
|
|
];
|
|
|
|
if (includeAdminLeadCapabilities) {
|
|
lines.push(
|
|
'GRANT SELECT ON "AdminUser", "AdminRole", "AdminPermission", "AdminRolePermission", "AdminUserRole", "AdminLeadSource", "AdminLeadSourceCredential", "AdminLead", "IdempotencyKey", "OutboxEvent", "NotificationDelivery" TO hivegrid_rls_definer;',
|
|
'GRANT INSERT ON "AdminLead", "AdminLeadActivity", "IdempotencyKey", "OutboxEvent", "NotificationDelivery" TO hivegrid_rls_definer;',
|
|
'GRANT UPDATE ON "AdminLeadSourceCredential", "NotificationDelivery" TO hivegrid_rls_definer;',
|
|
"GRANT CREATE ON SCHEMA public TO hivegrid_rls_definer;",
|
|
"SET LOCAL ROLE hivegrid_rls_definer;",
|
|
...renderAdminLeadSecurityFunctions().trimEnd().split("\n"),
|
|
"RESET ROLE;",
|
|
"REVOKE CREATE ON SCHEMA public FROM hivegrid_rls_definer;",
|
|
""
|
|
);
|
|
}
|
|
|
|
if (resolvers.length > 0) {
|
|
lines.push(
|
|
"GRANT CREATE ON SCHEMA public TO hivegrid_rls_definer;",
|
|
"SET LOCAL ROLE hivegrid_rls_definer;",
|
|
...renderTenantResolvers(delta),
|
|
"RESET ROLE;",
|
|
"REVOKE CREATE ON SCHEMA public FROM hivegrid_rls_definer;",
|
|
"",
|
|
...renderDefinerFunctionPreflight(result)
|
|
);
|
|
} else if (includeAdminLeadCapabilities) {
|
|
lines.push(...renderDefinerFunctionPreflight(result));
|
|
}
|
|
|
|
lines.push(...renderDirectRelationPreflight(delta), ...definitions.map(renderPolicyDefinition), "COMMIT;", "", "-- Inverse SQL (review aid only):");
|
|
for (const definition of [...definitions].reverse()) {
|
|
const table = quoteIdentifier(definition.table);
|
|
for (const policy of Object.values(definition.policyNames)) {
|
|
lines.push(`-- DROP POLICY IF EXISTS ${quoteIdentifier(policy)} ON ${table};`);
|
|
}
|
|
lines.push(
|
|
...renderSequenceGrantRevokes(definition),
|
|
`-- REVOKE SELECT, INSERT, UPDATE, DELETE ON ${table} FROM hivegrid_app, hivegrid_worker;`,
|
|
`-- ALTER TABLE ${table} NO FORCE ROW LEVEL SECURITY;`,
|
|
`-- ALTER TABLE ${table} DISABLE ROW LEVEL SECURITY;`
|
|
);
|
|
}
|
|
for (const resolver of [...resolvers].reverse()) {
|
|
const signature = resolver.parameters.map((parameter) => parameter.type).join(", ");
|
|
lines.push(`-- DROP FUNCTION IF EXISTS public.${quoteIdentifier(resolver.name)}(${signature});`);
|
|
}
|
|
if (includeAdminLeadCapabilities) {
|
|
lines.push(
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_capture_admin_lead(text,text,text,text,text,text,jsonb);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_enqueue_admin_lead_audit(text,text,text,text,text,text,text,text,text,text,jsonb,jsonb);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_authenticate_admin_lead_source(text);",
|
|
"-- DROP FUNCTION IF EXISTS public.hivegrid_resolve_platform_lead_notification_recipient(text,text);",
|
|
'-- REVOKE SELECT ON "AdminUser", "AdminRole", "AdminPermission", "AdminRolePermission", "AdminUserRole", "AdminLeadSource", "AdminLeadSourceCredential", "AdminLead", "IdempotencyKey", "OutboxEvent", "NotificationDelivery" FROM hivegrid_rls_definer;',
|
|
'-- REVOKE INSERT ON "AdminLead", "AdminLeadActivity", "IdempotencyKey", "OutboxEvent", "NotificationDelivery" FROM hivegrid_rls_definer;',
|
|
'-- REVOKE UPDATE ON "AdminLeadSourceCredential", "NotificationDelivery" FROM hivegrid_rls_definer;'
|
|
);
|
|
}
|
|
for (const grant of renderResolverReadGrants(resolvers)) {
|
|
lines.push(`-- ${grant.replace("GRANT SELECT", "REVOKE SELECT").replace(" TO ", " FROM ")}`);
|
|
}
|
|
lines.push("");
|
|
return lines.join("\n");
|
|
}
|
|
|
|
const POSTGRES_POLICY_COMMANDS = Object.freeze({
|
|
select: "r",
|
|
insert: "a",
|
|
update: "w",
|
|
delete: "d",
|
|
all: "*",
|
|
});
|
|
|
|
function runtimePolicyEntries(definition) {
|
|
if (definition.commandExpressions) {
|
|
return ["select", "insert", "update", "delete"].flatMap((command) => {
|
|
const roles = definition.commandRoles?.[command] ?? TENANT_POLICY_ROLES;
|
|
if (roles.length === 0) return [];
|
|
return [
|
|
{
|
|
name: definition.policyNames[command],
|
|
command: POSTGRES_POLICY_COMMANDS[command],
|
|
roles: [...roles].sort(),
|
|
},
|
|
];
|
|
});
|
|
}
|
|
if (definition.policyNames.all) {
|
|
return [
|
|
{
|
|
name: definition.policyNames.all,
|
|
command: POSTGRES_POLICY_COMMANDS.all,
|
|
roles: [...TENANT_POLICY_ROLES].sort(),
|
|
},
|
|
];
|
|
}
|
|
return [
|
|
{
|
|
name: definition.policyNames.read,
|
|
command: POSTGRES_POLICY_COMMANDS.select,
|
|
roles: [...TENANT_POLICY_ROLES].sort(),
|
|
},
|
|
{
|
|
name: definition.policyNames.write,
|
|
command: POSTGRES_POLICY_COMMANDS.all,
|
|
roles: [...TENANT_POLICY_ROLES].sort(),
|
|
},
|
|
];
|
|
}
|
|
|
|
export function renderRlsRuntimeContract(result) {
|
|
if (!result.ok) throw new Error(`Cannot render invalid tenant policy contract:\n${result.errors.join("\n")}`);
|
|
const definitions = [...result.definitions].sort((left, right) => left.table.localeCompare(right.table));
|
|
const lines = [
|
|
"// GENERATED FILE. DO NOT EDIT BY HAND.",
|
|
"// Source: prisma/tenant-scope-manifest.mjs + prisma/tenant-policy-contract.mjs",
|
|
"// Generator: node scripts/generate-tenant-policy-contract.mjs",
|
|
"",
|
|
"export const EXPECTED_RLS_RUNTIME_CONTRACT = [",
|
|
];
|
|
for (const definition of definitions) {
|
|
lines.push(
|
|
" {",
|
|
` table: ${JSON.stringify(definition.table)},`,
|
|
" policies: [",
|
|
...runtimePolicyEntries(definition).map(
|
|
(policy) => ` { name: ${JSON.stringify(policy.name)}, command: ${JSON.stringify(policy.command)}, roles: ${JSON.stringify(policy.roles)} },`
|
|
),
|
|
" ],",
|
|
...((definition.sequenceGrants?.length ?? 0) > 0
|
|
? [
|
|
" sequences: [",
|
|
...definition.sequenceGrants.map(
|
|
(grant) =>
|
|
` { name: ${JSON.stringify(grant.name)}, privileges: ${JSON.stringify([grant.privilege])}, roles: ${JSON.stringify([...grant.roles].sort())} },`
|
|
),
|
|
" ],",
|
|
]
|
|
: []),
|
|
" },"
|
|
);
|
|
}
|
|
lines.push("] as const;", "");
|
|
return lines.join("\n");
|
|
}
|
|
|
|
export function runTenantPolicyGenerator(rootDirectory = process.cwd(), args = process.argv.slice(2)) {
|
|
const result = inspectTenantPolicyContract(rootDirectory);
|
|
if (!result.ok) {
|
|
process.stderr.write(`FAIL tenant policy contract\n${result.errors.map((error) => `- ${error}`).join("\n")}\n`);
|
|
return 1;
|
|
}
|
|
|
|
const sql = renderTenantPolicySql(result);
|
|
const target = path.join(rootDirectory, GENERATED_POLICY_PATH);
|
|
const migrationTarget = path.join(rootDirectory, GENERATED_MIGRATION_PATH);
|
|
const frozenMigration = existsSync(migrationTarget) ? readFileSync(migrationTarget, "utf8") : "";
|
|
if (sha256(frozenMigration) !== FROZEN_BASELINE_MIGRATION_SHA256) {
|
|
process.stderr.write(`FAIL frozen Prisma baseline changed: ${GENERATED_MIGRATION_PATH}\n`);
|
|
return 1;
|
|
}
|
|
if (args.includes("--post-cutover-delta")) {
|
|
const postCutoverMigrationSql = readPostCutoverMigrationSql(rootDirectory);
|
|
process.stdout.write(`${renderPostCutoverPolicyDeltaSql(result, frozenMigration, postCutoverMigrationSql)}\n`);
|
|
return 0;
|
|
}
|
|
const runtimeContract = renderRlsRuntimeContract(result);
|
|
const runtimeContractTarget = path.join(rootDirectory, GENERATED_RUNTIME_CONTRACT_PATH);
|
|
if (args.includes("--check")) {
|
|
const current = existsSync(target) ? readFileSync(target, "utf8") : "";
|
|
const currentRuntimeContract = existsSync(runtimeContractTarget) ? readFileSync(runtimeContractTarget, "utf8") : "";
|
|
const stale = [
|
|
...(current === sql ? [] : [GENERATED_POLICY_PATH]),
|
|
...(currentRuntimeContract === runtimeContract ? [] : [GENERATED_RUNTIME_CONTRACT_PATH]),
|
|
];
|
|
if (stale.length > 0) {
|
|
process.stderr.write(`FAIL generated tenant policy SQL is stale: ${stale.join(", ")}\n`);
|
|
return 1;
|
|
}
|
|
process.stdout.write(
|
|
`PASS tenant policy contract: ${result.definitions.length}/${EXPECTED_POLICY_DEFINITION_COUNT} definitions, artifact/runtime current, baseline frozen\n`
|
|
);
|
|
return 0;
|
|
}
|
|
|
|
mkdirSync(path.dirname(target), { recursive: true });
|
|
mkdirSync(path.dirname(runtimeContractTarget), { recursive: true });
|
|
writeFileSync(target, sql, "utf8");
|
|
writeFileSync(runtimeContractTarget, runtimeContract, "utf8");
|
|
process.stdout.write(
|
|
`Generated ${GENERATED_POLICY_PATH} and ${GENERATED_RUNTIME_CONTRACT_PATH}; preserved frozen ${GENERATED_MIGRATION_PATH}; ${result.definitions.length}/${EXPECTED_POLICY_DEFINITION_COUNT} policy definitions\n`
|
|
);
|
|
return 0;
|
|
}
|
|
|
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
process.exitCode = runTenantPolicyGenerator();
|
|
}
|