* harden(security): payment-row company-consistency triggers (tenant backstop) invoice_payments and supplier_invoice_payments are the only two child tables carrying BOTH a parent FK and their own company_id. A row whose company_id disagrees with its parent's company_id is a tenant-isolation defect that would surface a foreign tenant's payment in this company's AR/AP ledger. RLS scopes by company_id but never cross-checks the parent, so nothing at the DB layer guaranteed the invariant. - Pre-flight DO block: fail the migration loudly (listing offending ids) if any existing row already violates child.company_id = parent.company_id, rather than arm a trigger over dirty data that can never be updated again. - enforce_payment_company_consistency(): one INVOKER trigger function parameterized on TG_TABLE_NAME, wired BEFORE INSERT OR UPDATE OF (company_id, parent_fk) on both payment tables; raises on mismatch. Matches the SECURITY posture of the sibling enforcement triggers in migration 017. - pg-real coverage in tests/pg/payment-company-consistency.pg.test.ts: matching pair inserts ok; cross-tenant insert + cross-tenant UPDATE raise; both the customer and supplier side. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * harden(security): tenant guards on six SECURITY DEFINER write RPCs (backstop) bulk_book_transactions, match_batch_allocate, mark_entry_as_opening_balance, reserve_voucher_range, release_voucher_range and rotate_company_inbox are all SECURITY DEFINER and EXECUTE-able by `authenticated`, so an authenticated user could call them via PostgREST with ANOTHER company's p_company_id. Three already carried an auth.uid()-based membership check and rotate_company_inbox an owner/admin gate, but the two voucher-range RPCs had NO tenant check at all. Adds the canonical claims-based guard (mirrors 20260615120000_link_voucher_rpcs_tenant_guard.sql lines 54-69) at the top of each body: for anon/authenticated callers, membership of p_company_id (public.user_company_ids()) is required else RAISE 42501; service_role and no-claims callers (migrations, pg-harness, MCP / API-key paths whose company scoping happens in TS) bypass BY DESIGN. Each function body is otherwise copied verbatim from its latest definition; existing GRANTs re-applied. pg-real coverage in tests/pg/securitydefiner_write_rpc_tenant_guards.pg.test.ts: per RPC — userA session targeting companyB raises 42501; targeting own company passes the guard (succeeds or yields a non-42501 domain outcome, documented inline); a no-claims bare-pool cross-tenant call bypasses the new guard, proving the service-role / MCP paths are unaffected. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore(db): renumber tenant-backstop migrations to 20260619130000/130100 PR1 (agent attribution) claimed the 20260619120000 version slot in the same batch; Supabase migration versions must be unique across the repo, so the tenant-backstop pair moves to 130000/130100. Filename-only change plus the matching doc-comment references in the two pg tests. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(db): restore source comments dropped in copied RPC bodies The guarded redefinitions of bulk_book_transactions and match_batch_allocate must be byte-verbatim copies of their latest sources (modulo the inserted tenant-guard block) so the next CREATE OR REPLACE copy keeps full provenance. Restores the Round-2/Round-3 compliance-fix annotations that were lost in the copy. Verified mechanically: zero residual diff vs sources after stripping the guard block, for all six functions. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(db): drop raise-guards from bulk_book/match_batch — they break the jsonb error contract Local full-migration replay + pg-real run surfaced that prepending the 42501 raise-guard to bulk_book_transactions and match_batch_allocate changes their error contract for authenticated cross-tenant callers: both already enforce membership in-function and return structured domain errors (BULK_BOOK_UNAUTHORIZED / BATCH_UNAUTHORIZED) that routes, MCP tools, and their existing pg tests branch on. The guard added no isolation (they were tenant-safe) but broke that contract. The migration now guards only the four RPCs where it is sound: mark_entry_as_opening_balance (P0001→42501, still an exception), rotate_company_inbox (already 42501), and the two genuinely unguarded voucher-range RPCs. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(db): compliance-review round — log hygiene, explicit INVOKER, anon revoke, UPDATE-path test Addresses the compliance-swarm findings on this PR: - Pre-flight dirty-data check now raises with COUNTS only; the row ids move to RAISE NOTICE so error pipelines do not ingest identifier dumps (ASVS V8.2.1 / SOC 2 CC6.1). - enforce_payment_company_consistency() declares SECURITY INVOKER explicitly — the default was already INVOKER; this makes the security model self-documenting. - REVOKE ... FROM PUBLIC, anon on reserve/release_voucher_range and rotate_company_inbox, matching the mark_entry_as_opening_balance pattern. - Adds the missing supplier_invoice_payments UPDATE-path trigger probe (SOC 2 PI1.3). Dismissed as by-design: the JWT-claim trust boundary (set_config requires direct SQL access, which already bypasses by design — same model as 20260615120000). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(db): voucher-range compliance guards + FK-rerouting trigger probes Review round 2 on this PR: Swedish compliance review (both pre-existing function behaviour, hardened while the PR owns these bodies): - reserve/release_voucher_range now refuse closed/locked fiscal periods (BFL 5 kap 5§ — the sequence of a locked period is räkenskapsinformation; mirrors mark_entry_as_opening_balance). - release_voucher_range asserts no verifikat exist in the released range before rolling last_number back (BFL 5 kap 6-7§ — never re-issue or orphan posted verifikationsnummer). Neither guard can fire in the legit SIE-import flow, which only releases numbers above its highest inserted verifikat into an open period — and the import caller treats a failed release as non-fatal. Greptile P2: the UPDATE OF <parent_fk> trigger leg was never probed — added cross-tenant FK-rerouting rejection tests for both payment tables (the supplier company_id UPDATE probe landed in the previous commit). Verified: full migration replay on fresh supabase/postgres + 333/333 pg-real green on an origin/main merge (incl. merged #678). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(test): release-succeeds probe must persist — callBare rolls back The legit-path release test asserted last_number after calling the RPC via callBare, whose BEGIN...ROLLBACK wrapper undoes the UPDATE before the assertion reads it (caught in CI; the local pre-push replay had validated the branch's committed state, not the then-uncommitted test). Call the RPC directly on the pool, like the engine pg tests do for persisting calls. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
204 lines
8.4 KiB
TypeScript
204 lines
8.4 KiB
TypeScript
/**
|
|
* pg-real test for the payment company-consistency triggers
|
|
* (20260619130000_payment_company_consistency.sql).
|
|
*
|
|
* invoice_payments and supplier_invoice_payments are the only two child tables
|
|
* carrying BOTH a parent FK and their own company_id. A row whose company_id
|
|
* disagrees with its parent's company_id is a tenant-isolation defect. The
|
|
* BEFORE INSERT/UPDATE triggers make a mismatched pair impossible to persist
|
|
* regardless of how it is written — so these probes go through the superuser
|
|
* pool (which bypasses RLS), proving the trigger fires even for the most
|
|
* privileged writer.
|
|
*/
|
|
import { describe, it, expect } from 'vitest'
|
|
import { randomUUID } from 'node:crypto'
|
|
import { getPool } from './setup'
|
|
import { seedCompany } from './fixtures'
|
|
|
|
let arrivalSeq = 0
|
|
|
|
async function seedCustomerInvoice(params: {
|
|
userId: string
|
|
companyId: string
|
|
total?: number
|
|
}): Promise<string> {
|
|
const customerId = randomUUID()
|
|
await getPool().query(
|
|
`INSERT INTO public.customers (id, user_id, company_id, name, customer_type)
|
|
VALUES ($1, $2, $3, 'Test Kund AB', 'swedish_business')`,
|
|
[customerId, params.userId, params.companyId],
|
|
)
|
|
const id = randomUUID()
|
|
const total = params.total ?? 1000
|
|
await getPool().query(
|
|
`INSERT INTO public.invoices
|
|
(id, user_id, company_id, customer_id, invoice_number, invoice_date, due_date,
|
|
currency, subtotal, vat_amount, total, vat_treatment, vat_rate, status,
|
|
paid_amount, remaining_amount)
|
|
VALUES ($1, $2, $3, $4, $5, '2026-04-01', '2026-05-01', 'SEK',
|
|
$6, 0, $6, 'standard_25', 25, 'sent', 0, $6)`,
|
|
[id, params.userId, params.companyId, customerId, `F-${id.slice(0, 8)}`, total],
|
|
)
|
|
return id
|
|
}
|
|
|
|
async function seedSupplierInvoice(params: {
|
|
userId: string
|
|
companyId: string
|
|
total?: number
|
|
}): Promise<string> {
|
|
const supplierId = randomUUID()
|
|
await getPool().query(
|
|
`INSERT INTO public.suppliers
|
|
(id, user_id, company_id, name, supplier_type, country, default_payment_terms, default_currency)
|
|
VALUES ($1, $2, $3, 'Leverantör AB', 'swedish_business', 'SE', 30, 'SEK')`,
|
|
[supplierId, params.userId, params.companyId],
|
|
)
|
|
const id = randomUUID()
|
|
const total = params.total ?? 1000
|
|
const arrivalNumber = (Date.now() % 1_000_000) * 1000 + arrivalSeq++
|
|
await getPool().query(
|
|
`INSERT INTO public.supplier_invoices
|
|
(id, user_id, company_id, supplier_id, arrival_number, supplier_invoice_number,
|
|
invoice_date, due_date, received_date, status, currency,
|
|
subtotal, vat_amount, total, paid_amount, remaining_amount,
|
|
vat_treatment, reverse_charge, is_credit_note)
|
|
VALUES ($1, $2, $3, $4, $5, $6, '2026-04-01', '2026-05-01', '2026-04-01', 'approved', 'SEK',
|
|
$7, 0, $7, 0, $7, 'standard_25', false, false)`,
|
|
[id, params.userId, params.companyId, supplierId, arrivalNumber, `LF-${arrivalNumber}`, total],
|
|
)
|
|
return id
|
|
}
|
|
|
|
const INSERT_INVOICE_PAYMENT = `
|
|
INSERT INTO public.invoice_payments
|
|
(user_id, company_id, invoice_id, payment_date, amount, currency)
|
|
VALUES ($1, $2, $3, '2026-05-05', 100, 'SEK')
|
|
RETURNING id`
|
|
|
|
const INSERT_SUPPLIER_PAYMENT = `
|
|
INSERT INTO public.supplier_invoice_payments
|
|
(user_id, company_id, supplier_invoice_id, payment_date, amount, currency)
|
|
VALUES ($1, $2, $3, '2026-05-05', 100, 'SEK')
|
|
RETURNING id`
|
|
|
|
describe('invoice_payments — company-consistency trigger', () => {
|
|
it('accepts a payment whose company_id matches its invoice', async () => {
|
|
const a = await seedCompany()
|
|
const invoiceId = await seedCustomerInvoice({ userId: a.userId, companyId: a.companyId })
|
|
|
|
const res = await getPool().query(INSERT_INVOICE_PAYMENT, [a.userId, a.companyId, invoiceId])
|
|
expect(res.rows).toHaveLength(1)
|
|
expect(res.rows[0].id).toBeTruthy()
|
|
})
|
|
|
|
it('rejects a payment whose company_id is a different tenant than its invoice', async () => {
|
|
const a = await seedCompany()
|
|
const b = await seedCompany()
|
|
const invoiceId = await seedCustomerInvoice({ userId: a.userId, companyId: a.companyId })
|
|
|
|
// company_id = B but the invoice belongs to A → trigger must raise.
|
|
await expect(
|
|
getPool().query(INSERT_INVOICE_PAYMENT, [b.userId, b.companyId, invoiceId]),
|
|
).rejects.toThrow(/does not match invoices\.company_id/i)
|
|
|
|
// Nothing persisted.
|
|
const rows = await getPool().query(
|
|
`SELECT id FROM public.invoice_payments WHERE invoice_id = $1`,
|
|
[invoiceId],
|
|
)
|
|
expect(rows.rows).toHaveLength(0)
|
|
})
|
|
|
|
it('rejects an UPDATE that points company_id at a foreign tenant', async () => {
|
|
const a = await seedCompany()
|
|
const b = await seedCompany()
|
|
const invoiceId = await seedCustomerInvoice({ userId: a.userId, companyId: a.companyId })
|
|
const ins = await getPool().query(INSERT_INVOICE_PAYMENT, [a.userId, a.companyId, invoiceId])
|
|
const paymentId = ins.rows[0].id as string
|
|
|
|
await expect(
|
|
getPool().query(`UPDATE public.invoice_payments SET company_id = $1 WHERE id = $2`, [
|
|
b.companyId,
|
|
paymentId,
|
|
]),
|
|
).rejects.toThrow(/does not match invoices\.company_id/i)
|
|
})
|
|
|
|
it('rejects rerouting invoice_id to a foreign tenant invoice (UPDATE OF invoice_id path)', async () => {
|
|
const a = await seedCompany()
|
|
const b = await seedCompany()
|
|
const invoiceA = await seedCustomerInvoice({ userId: a.userId, companyId: a.companyId })
|
|
const invoiceB = await seedCustomerInvoice({ userId: b.userId, companyId: b.companyId })
|
|
const ins = await getPool().query(INSERT_INVOICE_PAYMENT, [a.userId, a.companyId, invoiceA])
|
|
const paymentId = ins.rows[0].id as string
|
|
|
|
// company_id stays A; only the parent FK is rerouted to B's invoice —
|
|
// exercises the UPDATE OF invoice_id leg of the trigger column filter.
|
|
await expect(
|
|
getPool().query(`UPDATE public.invoice_payments SET invoice_id = $1 WHERE id = $2`, [
|
|
invoiceB,
|
|
paymentId,
|
|
]),
|
|
).rejects.toThrow(/does not match invoices\.company_id/i)
|
|
})
|
|
})
|
|
|
|
describe('supplier_invoice_payments — company-consistency trigger', () => {
|
|
it('accepts a payment whose company_id matches its supplier invoice', async () => {
|
|
const a = await seedCompany()
|
|
const supplierInvoiceId = await seedSupplierInvoice({ userId: a.userId, companyId: a.companyId })
|
|
|
|
const res = await getPool().query(INSERT_SUPPLIER_PAYMENT, [a.userId, a.companyId, supplierInvoiceId])
|
|
expect(res.rows).toHaveLength(1)
|
|
expect(res.rows[0].id).toBeTruthy()
|
|
})
|
|
|
|
it('rejects a payment whose company_id is a different tenant than its supplier invoice', async () => {
|
|
const a = await seedCompany()
|
|
const b = await seedCompany()
|
|
const supplierInvoiceId = await seedSupplierInvoice({ userId: a.userId, companyId: a.companyId })
|
|
|
|
await expect(
|
|
getPool().query(INSERT_SUPPLIER_PAYMENT, [b.userId, b.companyId, supplierInvoiceId]),
|
|
).rejects.toThrow(/does not match supplier_invoices\.company_id/i)
|
|
|
|
const rows = await getPool().query(
|
|
`SELECT id FROM public.supplier_invoice_payments WHERE supplier_invoice_id = $1`,
|
|
[supplierInvoiceId],
|
|
)
|
|
expect(rows.rows).toHaveLength(0)
|
|
})
|
|
|
|
it('rejects an UPDATE that points company_id at a foreign tenant', async () => {
|
|
const a = await seedCompany()
|
|
const b = await seedCompany()
|
|
const supplierInvoiceId = await seedSupplierInvoice({ userId: a.userId, companyId: a.companyId })
|
|
const ins = await getPool().query(INSERT_SUPPLIER_PAYMENT, [a.userId, a.companyId, supplierInvoiceId])
|
|
const paymentId = ins.rows[0].id as string
|
|
|
|
await expect(
|
|
getPool().query(`UPDATE public.supplier_invoice_payments SET company_id = $1 WHERE id = $2`, [
|
|
b.companyId,
|
|
paymentId,
|
|
]),
|
|
).rejects.toThrow(/does not match supplier_invoices\.company_id/i)
|
|
})
|
|
|
|
it('rejects rerouting supplier_invoice_id to a foreign tenant invoice (UPDATE OF supplier_invoice_id path)', async () => {
|
|
const a = await seedCompany()
|
|
const b = await seedCompany()
|
|
const siA = await seedSupplierInvoice({ userId: a.userId, companyId: a.companyId })
|
|
const siB = await seedSupplierInvoice({ userId: b.userId, companyId: b.companyId })
|
|
const ins = await getPool().query(INSERT_SUPPLIER_PAYMENT, [a.userId, a.companyId, siA])
|
|
const paymentId = ins.rows[0].id as string
|
|
|
|
await expect(
|
|
getPool().query(
|
|
`UPDATE public.supplier_invoice_payments SET supplier_invoice_id = $1 WHERE id = $2`,
|
|
[siB, paymentId],
|
|
),
|
|
).rejects.toThrow(/does not match supplier_invoices\.company_id/i)
|
|
})
|
|
})
|