Files
0pt/src/document-workbench/credit-tenant-scope.ts
T
admin 0f734297ce
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (push) Successful in 5s
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 6s
CI (SIAX Cloud) / security (push) Successful in 20s
Security Scan (SIAX Cloud) / security (push) Successful in 19s
CI (SIAX Cloud) / security (pull_request) Successful in 16s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 16s
CI (SIAX Cloud) / quality (push) Successful in 52s
CI (SIAX Cloud) / integration (pull_request) Successful in 51s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m9s
fix: enforce tenant isolation on credit storage
2026-11-02 07:39:35 +01:00

34 lines
1.8 KiB
TypeScript

import type postgres from 'postgres';
import type { RepositorySql } from '../repositories/db';
/** A scoped transaction is not a user authorization or payment verification. */
export async function withCreditTenant<T>(
sql: RepositorySql,
tenantId: string,
action: (tx: postgres.TransactionSql) => Promise<T>,
): Promise<T> {
if (typeof tenantId !== 'string' || !tenantId.trim() || tenantId.length > 256) throw new Error('Invalid credit tenant');
return sql.begin(async (tx) => {
const roles = await tx<{ rolsuper: boolean; rolbypassrls: boolean }[]>`
SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user`;
if (!roles[0] || roles[0].rolsuper || roles[0].rolbypassrls) throw new Error('Credits require an RLS-enforced database role');
// Do not silently run against pre-migration credit tables. Policy bodies
// themselves remain a trusted migration/database-administrator boundary.
const gates = await tx<{ enabled: boolean }[]>`
SELECT COUNT(*) = 4 AS enabled
FROM (VALUES
('opt_credit_accounts', 'opt_credit_accounts_tenant'),
('opt_credit_reservations', 'opt_credit_reservations_tenant'),
('opt_credit_events', 'opt_credit_events_tenant'),
('opt_credit_purchases', 'opt_credit_purchases_tenant')
) AS expected(table_name, policy_name)
JOIN pg_class AS c ON c.oid = to_regclass(expected.table_name)
WHERE c.relrowsecurity AND c.relforcerowsecurity
AND (SELECT COUNT(*) FROM pg_policy AS p WHERE p.polrelid = c.oid) = 1
AND EXISTS (SELECT 1 FROM pg_policy AS p WHERE p.polrelid = c.oid AND p.polname = expected.policy_name)`;
if (gates[0]?.enabled !== true) throw new Error('Credit tenant isolation migration is not active');
await tx`SELECT set_config('app.opt_credit_tenant_id', ${tenantId}, true)`;
return action(tx);
}) as Promise<T>;
}