Merge pull request 'Enforce tenant isolation for document credit storage' (#422) from codex/credit-ledger-tenant-rls into main
Release chain (G17, ADR-W16-003) / Build, push, G17 (SBOM/scan/attest/verify/evidence) (push) Successful in 1m1s
Deploy to Coolify / deploy (push) Successful in 1m13s
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (pull_request) Successful in 7s
masterplan-lock / check (push) Successful in 16s
CI (SIAX Cloud) / security (push) Successful in 26s
Security Scan (SIAX Cloud) / security (push) Successful in 27s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 50s
CI (SIAX Cloud) / integration (pull_request) Successful in 1m2s
CI (SIAX Cloud) / security (pull_request) Successful in 28s
CI (SIAX Cloud) / sonar (pull_request) Skipped
CI (SIAX Cloud) / quality (pull_request) Successful in 1m33s
CI (SIAX Cloud) / quality (push) Successful in 1m41s
Release chain (G17, ADR-W16-003) / Build, push, G17 (SBOM/scan/attest/verify/evidence) (push) Successful in 1m1s
Deploy to Coolify / deploy (push) Successful in 1m13s
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (pull_request) Successful in 7s
masterplan-lock / check (push) Successful in 16s
CI (SIAX Cloud) / security (push) Successful in 26s
Security Scan (SIAX Cloud) / security (push) Successful in 27s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 50s
CI (SIAX Cloud) / integration (pull_request) Successful in 1m2s
CI (SIAX Cloud) / security (pull_request) Successful in 28s
CI (SIAX Cloud) / sonar (pull_request) Skipped
CI (SIAX Cloud) / quality (pull_request) Successful in 1m33s
CI (SIAX Cloud) / quality (push) Successful in 1m41s
This commit was merged in pull request #422.
This commit is contained in:
@@ -8,31 +8,55 @@ import { reconcileCreditPurchase } from '../../src/document-workbench/reconcile-
|
||||
|
||||
const url = process.env.CREDIT_LEDGER_TEST_DATABASE_URL;
|
||||
const schema = `credit_test_${process.pid}_${Date.now()}`;
|
||||
const role = `credit_role_${process.pid}_${Date.now()}`;
|
||||
let admin: ReturnType<typeof postgres>;
|
||||
let scopedUrl: string;
|
||||
let sql: ReturnType<typeof postgres>;
|
||||
let ledger: PostgresCreditLedger;
|
||||
|
||||
describe.skipIf(!url)('credit ledger against isolated PostgreSQL schema', () => {
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
beforeAll(async () => {
|
||||
const admin = postgres(url!, { max: 1 });
|
||||
try {
|
||||
await admin.unsafe(`CREATE SCHEMA ${schema}`);
|
||||
} finally {
|
||||
await admin.end({ timeout: 2 });
|
||||
if (process.env.CREDIT_LEDGER_TEST_ALLOW_LOCAL !== '1' || new URL(url!).hostname !== '127.0.0.1') {
|
||||
throw new Error('Only an explicitly enabled isolated loopback database may be used');
|
||||
}
|
||||
sql = postgres(url!, { max: 8, prepare: false, connection: { search_path: schema } });
|
||||
await sql.unsafe(await fs.readFile('sql/017_document_credits.sql', 'utf8'));
|
||||
admin = postgres(url!, { max: 1, prepare: false, connection: { search_path: schema } });
|
||||
await admin.unsafe(`CREATE SCHEMA ${schema}`);
|
||||
await admin.unsafe(`CREATE ROLE ${role} LOGIN NOSUPERUSER NOBYPASSRLS`);
|
||||
await admin.unsafe(await fs.readFile('sql/017_document_credits.sql', 'utf8'));
|
||||
await admin.unsafe(await fs.readFile('sql/019_document_credit_rls.sql', 'utf8'));
|
||||
await admin.unsafe(`GRANT USAGE ON SCHEMA ${schema} TO ${role}`);
|
||||
await admin.unsafe(`GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA ${schema} TO ${role}`);
|
||||
await admin.unsafe(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${schema} TO ${role}`);
|
||||
const appUrl = new URL(url!);
|
||||
appUrl.username = role;
|
||||
scopedUrl = appUrl.toString();
|
||||
sql = postgres(scopedUrl, { max: 8, prepare: false, connection: { search_path: schema } });
|
||||
ledger = new PostgresCreditLedger(sql);
|
||||
});
|
||||
afterAll(async () => {
|
||||
if (sql) await sql.end();
|
||||
const admin = postgres(url!, { max: 1 });
|
||||
try {
|
||||
await admin.unsafe(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
|
||||
} finally {
|
||||
await admin.end({ timeout: 2 });
|
||||
if (admin) {
|
||||
try {
|
||||
await admin.unsafe(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
|
||||
await admin.unsafe(`DROP ROLE IF EXISTS ${role}`);
|
||||
} finally { await admin.end({ timeout: 2 }); }
|
||||
}
|
||||
});
|
||||
it('rejects superusers and does not expose rows without a tenant scope', async () => {
|
||||
await expect(new PostgresCreditLedger(admin).apply({ tenantId: 'a', idempotencyKey: 'bad-role', kind: 'verified_payment', reference: 'bad-role', amount: 1 })).rejects.toThrow(/RLS-enforced/);
|
||||
expect(await sql`SELECT * FROM opt_credit_accounts`).toEqual([]);
|
||||
expect(await sql`SELECT * FROM opt_credit_purchases`).toEqual([]);
|
||||
});
|
||||
|
||||
it('fails before writing when the isolation migration is not fully active', async () => {
|
||||
await admin.unsafe('ALTER TABLE opt_credit_accounts DISABLE ROW LEVEL SECURITY');
|
||||
try {
|
||||
await expect(ledger.apply({ tenantId: 'unscoped', idempotencyKey: 'disabled-rls', kind: 'verified_payment', reference: 'disabled-rls', amount: 1 })).rejects.toThrow(/isolation migration/);
|
||||
} finally { await admin.unsafe('ALTER TABLE opt_credit_accounts ENABLE ROW LEVEL SECURITY'); }
|
||||
const rows = await admin`SELECT * FROM opt_credit_accounts WHERE tenant_id = 'unscoped'`;
|
||||
expect(rows).toEqual([]);
|
||||
});
|
||||
|
||||
it('grants verified payments only once and rejects a payment reused across tenants', async () => {
|
||||
const payment = {
|
||||
@@ -61,9 +85,10 @@ describe.skipIf(!url)('credit ledger against isolated PostgreSQL schema', () =>
|
||||
balance: { available: number; reserved: number };
|
||||
}>;
|
||||
expect(won.value.balance).toEqual({ available: 20, reserved: 80 });
|
||||
const rows = await sql<
|
||||
{ reservation_id: string }[]
|
||||
>`SELECT reservation_id FROM opt_credit_reservations WHERE tenant_id = 'a'`;
|
||||
const rows = await sql.begin(async (tx) => {
|
||||
await tx`SELECT set_config('app.opt_credit_tenant_id', 'a', true)`;
|
||||
return tx<{ reservation_id: string }[]>`SELECT reservation_id FROM opt_credit_reservations`;
|
||||
});
|
||||
const reservationId = rows[0]!.reservation_id;
|
||||
await expect(
|
||||
ledger.apply({
|
||||
@@ -133,7 +158,7 @@ describe.skipIf(!url)('credit ledger against isolated PostgreSQL schema', () =>
|
||||
};
|
||||
const results = await Promise.all([ledger.apply(payment), ledger.apply(payment)]);
|
||||
expect(results.map((item) => item.replay).sort()).toEqual([false, true]);
|
||||
const secondSql = postgres(url!, { max: 1, prepare: false, connection: { search_path: schema } });
|
||||
const secondSql = postgres(scopedUrl, { max: 1, prepare: false, connection: { search_path: schema } });
|
||||
try {
|
||||
const replay = await new PostgresCreditLedger(secondSql).apply(payment);
|
||||
expect(replay).toEqual({ replay: true, balance: { available: 25, reserved: 0 } });
|
||||
@@ -223,4 +248,20 @@ describe.skipIf(!url)('credit ledger against isolated PostgreSQL schema', () =>
|
||||
reconcileCreditPurchase(deps, 'd', 'purchase-d', { ...context, tenantId: 'other' }),
|
||||
).rejects.toThrow(/scope/);
|
||||
});
|
||||
it('enforces tenant filters even when a query omits its predicate', async () => {
|
||||
const visible = await sql.begin(async (tx) => {
|
||||
await tx`SELECT set_config('app.opt_credit_tenant_id', 'a', true)`;
|
||||
const accounts = await tx<{ tenant_id: string }[]>`SELECT tenant_id FROM opt_credit_accounts`;
|
||||
const purchases = await tx<{ tenant_id: string }[]>`SELECT tenant_id FROM opt_credit_purchases`;
|
||||
return { accounts, purchases };
|
||||
});
|
||||
expect(visible.accounts).toEqual([{ tenant_id: 'a' }]);
|
||||
expect(visible.purchases).toEqual([{ tenant_id: 'a' }]);
|
||||
expect(await sql`SELECT * FROM opt_credit_accounts`).toEqual([]);
|
||||
await expect(sql.begin(async (tx) => {
|
||||
await tx`SELECT set_config('app.opt_credit_tenant_id', 'b', true)`;
|
||||
await tx`INSERT INTO opt_credit_accounts (tenant_id) VALUES ('wrong-tenant')`;
|
||||
})).rejects.toThrow();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user