Files
accounted/tests/pg/link-voucher-rpcs-tenant-guard.pg.test.ts
T
MattssonandClaude Fable 5 cd344b6dbb fix(db): enforce balance check on directly inserted posted journal entries (v2) (#1439)
* fix(db): enforce balance check on directly inserted posted journal entries

check_balance_on_post only fires on the draft-to-posted UPDATE transition,
so any code path that INSERTs a row with status 'posted' directly skipped
balance validation entirely. The invariant sum(debit) = sum(credit) on
every posted entry was DB-enforced only for the engine's commit lifecycle.

Add check_balance_on_posted_insert, a deferred constraint trigger on
AFTER INSERT WHEN (NEW.status = 'posted') reusing the existing
check_journal_entry_balance() function, which already handles the
journal_entries INSERT context via NEW.id/NEW.status. Deferred semantics
let an atomic transaction insert header and lines together; zero-line and
unbalanced posted inserts are rejected at constraint evaluation. All
existing checks stay intact; this only adds coverage.

The one first-party posted-INSERT path outside an RPC, the sandbox seed,
now books through the bookkeeping engine (createJournalEntry) instead of
raw inserts. SIE import already inserts header and lines in a single
transaction via its structured RPC and passes unchanged.

pg tests cover the new path (zero-line rejected, unbalanced rejected at
SET CONSTRAINTS IMMEDIATE, balanced same-transaction insert accepted) and
existing posted-entry fixtures move to a transactional
insertPostedJournalEntry helper so they stay valid setup.

Fixes #327

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(tests): insert list-filters pg fixtures in one transaction

The list-filters suite (landed via a sibling merge) inserted posted
headers with getPool().query, where each query autocommits: the deferred
check_balance_on_posted_insert constraint fired at the header's own
commit with zero lines and correctly rejected the fixture. Header and
balanced lines now share one BEGIN/COMMIT so the constraint evaluates
the complete entry, mirroring the insertPostedJournalEntry helper.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(seed): insert journal headers as drafts, post after lines land

check_balance_on_posted_insert (renamed to apply-time version
20260806130000) rejects a posted header whose transaction has no lines.
PostgREST autocommits each request, so every seed path that inserted
posted headers first would die with "has zero total": the sandbox seed
(ledger history, invoice vouchers, salary vouchers), seed-demo-account
and seed-export-data. All now insert draft headers, insert lines, then
flip to posted so check_balance_on_post validates the finished
verifikat. The sandbox seed keeps its documented no-events design.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(db): preserve a preset committed_at on draft-to-posted transition

set_committed_at() stamped now() unconditionally, so the seed flows that
post backdated drafts lost their historical booking timestamps and every
demo verifikat read as booked today (CodeRabbit finding on PR 1439).
Stamp only when committed_at is NULL: the engine path (drafts carry no
committed_at) behaves exactly as before and a posted entry still always
has a committed_at; an explicitly supplied value now survives posting.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(db): preserve preset committed_at only for trusted roles

The IS NULL guard alone (20260806150000, never shipped; replaced by
20260806160000) let any RLS-permitted member backdate committed_at
through PostgREST by presetting it on a draft and posting, which the
Swedish accounting review flagged: committed_at is what the BFL 5 kap
timeliness checks and behandlingshistorik treat as the genuine
transition time. Preset values now survive posting only for
service_role/postgres/supabase_admin; authenticated and anon writers
always get the now() stamp. Consequence: the sandbox seed (runs as the
requesting user) gets committed_at = posting time, accepted and
documented in the route; the demo scripts run as service_role and keep
their backdated history. pg tests cover all four paths, with the upper
timestamp bound CodeRabbit asked for.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(db): restore superseded migration so the preview tracker stays consistent

The preview branch had already applied 20260806150000 when the previous
commit deleted the file, orphaning the preview's migration tracker
("Remote migration versions not found in local migrations directory").
Restored with a header explaining it is superseded in the same deploy by
20260806160000, so the unguarded semantics are never live on their own.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(db): decide committed_at trust by JWT claims, not current_user

The Swedish review found the current_user guard bypassable:
commit_journal_entry is SECURITY DEFINER and granted to authenticated,
so inside it current_user is the function owner and a member could
preset a backdated committed_at on a direct-inserted draft and launder
it through the RPC. The guard now reads the JWT claims role (same
primitive as the RPC's own tenant guard): preset values survive only
for service_role or claim-less backend connections; authenticated and
anon callers are always stamped now(), on both the direct UPDATE and
the RPC path (new pg test). Both migration files now carry the
identical final body so no unguarded intermediate exists as a
standalone applyable unit. Behandlingshistorik logging of trusted
overrides is follow-up #1444.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 23:00:05 +02:00

218 lines
8.8 KiB
TypeScript

/**
* pg-real test for the voucher-link write-RPC tenant guard
* (20260615120000_link_voucher_rpcs_tenant_guard.sql).
*
* link_invoice_to_voucher and link_supplier_invoice_to_voucher are SECURITY
* DEFINER and EXECUTE-able by authenticated, so without the guard any
* authenticated user could call them directly with another company's id and
* mutate that tenant's invoices + payment rows. The guard enforces membership
* for anon/authenticated while leaving service_role and direct/superuser access
* (this harness, migrations) untouched, same pattern as the GL read-RPC guard
* (tests/pg/gl_lines_rpc_tenant_guard.pg.test.ts).
*/
import { describe, it, expect } from 'vitest'
import { randomUUID } from 'node:crypto'
import { getPool, withUserContext } from './setup'
import { insertPostedJournalEntry, 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
// Time component for cross-run uniqueness, counter for within-run uniqueness.
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
}
/** Posted voucher crediting 1510 (AR settle) or debiting 244x (AP settle). */
async function seedPostedVoucher(params: {
userId: string
companyId: string
fiscalPeriodId: string
side: 'ar' | 'ap'
amount?: number
}): Promise<string> {
const amount = params.amount ?? 1000
const lines = params.side === 'ar'
? [
{ accountNumber: '1930', debitAmount: amount, creditAmount: 0 },
{ accountNumber: '1510', debitAmount: 0, creditAmount: amount },
]
: [
{ accountNumber: '2440', debitAmount: amount, creditAmount: 0 },
{ accountNumber: '1930', debitAmount: 0, creditAmount: amount },
]
return insertPostedJournalEntry({
userId: params.userId,
companyId: params.companyId,
fiscalPeriodId: params.fiscalPeriodId,
voucherNumber: Math.floor(Math.random() * 100000),
entryDate: '2026-05-05',
description: 'Betalning',
sourceType: 'manual',
lines,
})
}
const LINK_INVOICE = `SELECT public.link_invoice_to_voucher($1, $2, $3, $4, $5) AS result`
const LINK_SUPPLIER = `SELECT public.link_supplier_invoice_to_voucher($1, $2, $3, $4, $5) AS result`
describe('voucher-link write RPCs: tenant-isolation guard', () => {
it('blocks an authenticated non-member from linking another company\'s invoice', async () => {
const a = await seedCompany()
const b = await seedCompany()
const invoiceId = await seedCustomerInvoice({ userId: a.userId, companyId: a.companyId })
const voucherId = await seedPostedVoucher({
userId: a.userId,
companyId: a.companyId,
fiscalPeriodId: a.fiscalPeriodId,
side: 'ar',
})
// Member of company B probing company A: guard fires before any data
// access and answers indistinguishably from a missing invoice.
await withUserContext(b.userId, async (client) => {
const res = await client.query(LINK_INVOICE, [invoiceId, voucherId, b.userId, a.companyId, null])
expect(res.rows[0].result).toMatchObject({ ok: false, code: 'LINK_VOUCHER_INVOICE_NOT_FOUND' })
})
// Nothing was mutated on the cross-tenant attempt.
const inv = await getPool().query(`SELECT status, paid_amount FROM public.invoices WHERE id = $1`, [invoiceId])
expect(inv.rows[0]).toMatchObject({ status: 'sent' })
const payments = await getPool().query(
`SELECT id FROM public.invoice_payments WHERE invoice_id = $1`,
[invoiceId],
)
expect(payments.rows).toHaveLength(0)
// A member of company A still links successfully through the same path:
// the guard must not break legitimate user-session calls. The spoofed
// p_user_id is ignored for user-session callers: the JWT sub is
// authoritative for payment-row attribution (GDPR Art. 32). Asserted
// inside the context: withUserContext rolls its transaction back.
const spoofedUserId = randomUUID()
await withUserContext(a.userId, async (client) => {
const res = await client.query(LINK_INVOICE, [invoiceId, voucherId, spoofedUserId, a.companyId, null])
expect(res.rows[0].result).toMatchObject({ ok: true, invoice_status: 'paid' })
const payment = await client.query(
`SELECT user_id FROM public.invoice_payments WHERE invoice_id = $1`,
[invoiceId],
)
expect(payment.rows).toHaveLength(1)
expect(payment.rows[0].user_id).toBe(a.userId)
})
})
it('blocks an authenticated non-member from linking another company\'s supplier invoice', async () => {
const a = await seedCompany()
const b = await seedCompany()
const supplierInvoiceId = await seedSupplierInvoice({ userId: a.userId, companyId: a.companyId })
const voucherId = await seedPostedVoucher({
userId: a.userId,
companyId: a.companyId,
fiscalPeriodId: a.fiscalPeriodId,
side: 'ap',
})
await withUserContext(b.userId, async (client) => {
const res = await client.query(LINK_SUPPLIER, [supplierInvoiceId, voucherId, b.userId, a.companyId, null])
expect(res.rows[0].result).toMatchObject({ ok: false, code: 'LINK_SI_VOUCHER_INVOICE_NOT_FOUND' })
})
const inv = await getPool().query(
`SELECT status FROM public.supplier_invoices WHERE id = $1`,
[supplierInvoiceId],
)
expect(inv.rows[0]).toMatchObject({ status: 'approved' })
await withUserContext(a.userId, async (client) => {
const res = await client.query(LINK_SUPPLIER, [supplierInvoiceId, voucherId, a.userId, a.companyId, null])
expect(res.rows[0].result).toMatchObject({ ok: true, invoice_status: 'paid' })
})
})
it('direct/superuser access (no JWT role) bypasses the guard', async () => {
const a = await seedCompany()
const invoiceId = await seedCustomerInvoice({ userId: a.userId, companyId: a.companyId })
const voucherId = await seedPostedVoucher({
userId: a.userId,
companyId: a.companyId,
fiscalPeriodId: a.fiscalPeriodId,
side: 'ar',
})
// The bare pool has no request.jwt.claims: the trusted bypass that the
// harness, migrations and service-role API paths rely on.
const res = await getPool().query(LINK_INVOICE, [invoiceId, voucherId, a.userId, a.companyId, null])
expect(res.rows[0].result).toMatchObject({ ok: true, invoice_status: 'paid' })
})
it('rejects notes longer than the 2000-char Zod cap for all callers', async () => {
const a = await seedCompany()
const invoiceId = await seedCustomerInvoice({ userId: a.userId, companyId: a.companyId })
const voucherId = await seedPostedVoucher({
userId: a.userId,
companyId: a.companyId,
fiscalPeriodId: a.fiscalPeriodId,
side: 'ar',
})
const res = await getPool().query(LINK_INVOICE, [
invoiceId,
voucherId,
a.userId,
a.companyId,
'x'.repeat(2001),
])
expect(res.rows[0].result).toMatchObject({ ok: false, code: 'LINK_VOUCHER_NOTES_TOO_LONG' })
})
})