import { getDbClient, type DbClient } from "@hivegrid/db/client.server"; import { auditChainKey, verifyAuditChainHead, type AuditChainHeadRecord, } from "@hivegrid/db/audit-chain-checkpoint.server"; import { runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { CustomerPortalUatError, type CustomerPortalUatDatabaseBinding } from "./contracts"; type DatabaseSession = { readonly sessionUser: string; readonly currentUser: string; readonly databaseName: string; readonly databaseEnvironmentMarked: boolean; readonly roleIsSuperuser: boolean; readonly roleBypassesRls: boolean; readonly roleCanCreateRole: boolean; readonly roleCanCreateDatabase: boolean; }; type OperatorIdentity = { readonly id: string; readonly status: string; }; export function assertCustomerPortalDatabaseSession(session: DatabaseSession | undefined, expectedDatabaseName: string): void { if ( !session || session.sessionUser !== "hivegrid_app" || session.currentUser !== "hivegrid_app" || session.roleIsSuperuser || session.roleBypassesRls || session.roleCanCreateRole || session.roleCanCreateDatabase ) { throw new CustomerPortalUatError("customer-portal UAT: database session is not the restricted hivegrid_app role"); } if (session.databaseName !== expectedDatabaseName) { throw new CustomerPortalUatError("customer-portal UAT: connected database does not match the explicit staging binding"); } if (!session.databaseEnvironmentMarked) { throw new CustomerPortalUatError("customer-portal UAT: database is not independently marked as staging"); } } export function assertCustomerPortalAuditAnchor(head: AuditChainHeadRecord | null, auditChainSecret: string): void { if (!head || head.chainKey !== auditChainKey(null) || head.tenantId !== null || !verifyAuditChainHead(head, auditChainSecret)) { throw new CustomerPortalUatError("customer-portal UAT: canonical platform audit-chain anchor authentication failed"); } } export function assertCustomerPortalOperatorIdentity(operator: OperatorIdentity | null, expectedOperatorId: string): void { if (!operator || operator.id !== expectedOperatorId || operator.status !== "active") { throw new CustomerPortalUatError("customer-portal UAT: operator identity is not an active AdminUser"); } } export async function withCustomerPortalOperatorDatabase(binding: CustomerPortalUatDatabaseBinding, callback: (db: DbClient) => Promise): Promise { const db = getDbClient({ connectionString: binding.databaseUrl, poolMax: 2 }); try { return await runWithRlsContext({ userId: binding.operatorUserId }, async () => { const sessions = await db.$queryRaw` SELECT session_user::text AS "sessionUser", current_user::text AS "currentUser", current_database()::text AS "databaseName", role.rolsuper AS "roleIsSuperuser", role.rolbypassrls AS "roleBypassesRls", role.rolcreaterole AS "roleCanCreateRole", role.rolcreatedb AS "roleCanCreateDatabase", EXISTS ( SELECT 1 FROM pg_catalog.pg_db_role_setting AS setting JOIN pg_catalog.pg_database AS database ON database.oid = setting.setdatabase WHERE database.datname = current_database() AND setting.setrole = 0 AND 'hivegrid.environment=staging' = ANY(setting.setconfig) ) AS "databaseEnvironmentMarked" FROM pg_catalog.pg_roles AS role WHERE role.rolname = current_user `; const session = sessions[0]; assertCustomerPortalDatabaseSession(session, binding.expectedDatabaseName); const operator = await db.adminUser.findUnique({ where: { id: binding.operatorUserId }, select: { id: true, status: true }, }); assertCustomerPortalOperatorIdentity(operator, binding.operatorUserId); const platformAuditHead = await db.auditChainHead.findUnique({ where: { chainKey: auditChainKey(null) } }); assertCustomerPortalAuditAnchor(platformAuditHead, binding.auditChainSecret); return callback(db); }); } finally { await db.$disconnect(); } }