Files
accounted/tests/pg/link-voucher-rpcs-tenant-guard.pg.test.ts
T
Jakob WennbergandClaude Opus 4.8 f538401988 Invoice correctness bundle: voucher-link race, agent send guards, payment-reversal restore (audit C2/C17, F-2026080) (#666)
* fix(invoices): atomic link_invoice_to_voucher RPC — close the customer voucher-link race (audit C2)

linkInvoiceToVoucher() did UPDATE-then-INSERT with a manual rollback restoring a STALE pre-link snapshot: under concurrent linking on the same invoice, A's failed insert could overwrite B's successful link while B's payment row remained — corrupting paid_amount/AR. Mirrors the supplier-side link_supplier_invoice_to_voucher fix (PR #602).

- New SECURITY DEFINER RPC locks the invoice FOR UPDATE, re-validates (status, posted voucher, 151x AR credit, currency, overshoot, already-linked) and applies UPDATE + INSERT in one PG transaction. Inherits the supplier RPC's remaining-amount fix (trust stored remaining_amount even at 0 — the TS '> 0' guard let rounding drift slip past FULLY_PAID). Hardened per audit A5: REVOKE from PUBLIC/anon, GRANT to authenticated + service_role.
- linkInvoiceToVoucher() now delegates to the RPC — same signature, same LINK_VOUCHER_* codes, so all callers (route, pending-op executor, MCP) are unchanged. Keeps the invoice.paid event (now emitted with the post-link row, mirroring the supplier wrapper) and the best-effort bank auto-reconcile.
- pg-real tests: full/partial link, overshoot leaves the invoice untouched, ALREADY_LINKED, and the race regression (two concurrent full links -> exactly one wins, paid_amount never exceeds total, exactly one payment row). Verified locally against supabase/postgres:15.8.1.060 with all 334 migrations replayed: 10/10 pass. Two unrelated pg tests fail locally with AND without this change (pre-existing env sensitivity; green in CI).
- Unit tests re-mocked to the RPC-wrapper contract.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(invoices): agent send path — block cancelled invoices + preflight PDF render (audit C17)

commitSendInvoice (the agent/MCP path) was missing two guards the send route has:

- No cancelled guard: a cancelled invoice passed the already-sent check, got re-rendered and EMAILED (a 'MAKULERAD' PDF delivered as if live), and the unguarded status flip silently re-activated it to 'sent'. Now rejected with the registry's INVOICE_SEND_CANCELLED message (400), mirroring the route.
- No preflight render: the executor assigned the F-series number BEFORE rendering, so a render failure left a numbered-but-never-issued invoice (an F-series gap if the draft is abandoned). Now mirrors the route: on fresh allocation, render with an 'F-PREVIEW' placeholder first and reject with INVOICE_SEND_PDF_RENDER_FAILED before any number is consumed; retries with an existing number skip the preflight.

Items/credit-note lookup moved above the preflight (it needs them); the real render and everything downstream are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(bookkeeping): payment reversal restores invoice state and releases bank line (F-2026080)

Reversing a payment voucher left the customer invoice deadlocked: status
stayed 'paid' while remaining_amount stayed stale (= total), and the bank
transaction kept pointing at the reversed JE so the line could neither be
re-matched nor deleted.

- Customer branch now recomputes remaining_amount from total (the supplier
  branch already did) and clamps paid_amount at 0.
- Both branches delete the payment row(s) tied to the reversed voucher so a
  re-match doesn't double-count or trip the unique indexes.
- New releaseLinkedTransactions() detaches bank transactions from the
  reversed JE (by journal_entry_id and by captured payment transaction ids),
  clearing the link/categorization columns so the line returns to the inbox.

Covers every standalone storno path (reverse route, MCP reverse tool,
delete-last-voucher); the match-invoice route already handled its own case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(transactions): match-invoice preview double-subtracted VAT on per-item path (F-2026080)

InvoiceItem.line_total is the NET line amount (it sums to invoice.subtotal,
each line's vat_amount = line_total * rate), but the preview's per-item rate
aggregation computed sub = line_total - vat_amount, double-subtracting VAT
and producing an unbalanced previewed verifikat (revenue credit too low
against the 1930 debit). The commit path (generatePerRateLines) was already
correct; only the preview disagreed.

Regression test mirrors the F-2026080 invoice: multi-item 25% SEK cash entry
must balance, with 3001 = subtotal and 2611 = vat_amount.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(bookkeeping): address PR #666 review — supplier cash reversal, RPC tenant guard, CI fixes

Review feedback fixes:

- Supplier cash-payment reversal (Greptile): the supplier branch required a
  payment row before restoring status/amounts, so reversing a
  supplier_invoice_cash_payment (which books no payment row) left the invoice
  deadlocked at paid/remaining=0 — the same bug the customer branch fixed.
  Mirror the customer fallback (revert full paid_amount when no row exists).

- Payment-row lookups now filter by invoice id + company_id: a batch voucher
  (match_batch_allocate) carries one payment row per invoice under the same
  journal_entry_id, so the unfiltered .single() errored out and silently
  yielded null.

- Tenant guard on the voucher-link write RPCs (compliance V8.2.1, audit A5):
  link_invoice_to_voucher and link_supplier_invoice_to_voucher are SECURITY
  DEFINER + authenticated-executable, so any signed-in user could mutate
  another tenant's invoices via PostgREST. New migration applies the PR #625
  claims-based membership guard to both, caps p_notes at the Zod layer's
  2000 chars, and gives the supplier RPC the explicit REVOKE/GRANT it never
  had (was default PUBLIC execute). Covered by a new pg-real test.

- releaseLinkedTransactions now logs Supabase errors (compliance V16.1) —
  a failed release leaves a bank line stuck on a reversed JE and must be
  observable.

CI fixes:

- naive-ore-round ratchet (core-only): payment-sync.ts converted to
  roundOre() from @/lib/money (-4 occurrences vs baseline).
- match-batch-allocate.pg.test.ts flake (pg-real): Date.now()+random arrival
  numbers collided in CI; now time-component + monotonic counter.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(bookkeeping): address PR #666 review round 2 — payment attribution, batch-scoped deletes, send guard

- RPC payment attribution (GDPR Art.32): user-session callers can no longer
  attribute invoice_payments / supplier_invoice_payments rows to an arbitrary
  user via p_user_id — the JWT sub is authoritative when role is
  anon/authenticated. service_role / direct callers keep p_user_id verbatim
  (their scoping happens in TS). pg-real test asserts the spoofed id is
  ignored.

- Payment-row deletes scoped to the source invoice (SOC 2 CC6.3): a batch
  voucher carries sibling payment rows for other invoices whose status this
  sync doesn't restore; deleting them desynced paid_amount from the rows.

- releaseLinkedTransactions success audit log: transactions has no
  write_audit_log trigger, so clearing the link/categorization columns now
  logs the affected transaction ids for incident reconstruction.

- commitSendInvoice guard extended with partially_paid/credited (ASVS V2.3):
  both imply the invoice was already issued; the status flip would have
  regressed them to 'sent'.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 15:32:39 +02:00

224 lines
9.1 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 { 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 id = randomUUID()
const amount = params.amount ?? 1000
await getPool().query(
`INSERT INTO public.journal_entries
(id, user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
entry_date, description, source_type, status)
VALUES ($1, $2, $3, $4, $5, 'A', '2026-05-05', 'Betalning', 'manual', 'posted')`,
[id, params.userId, params.companyId, params.fiscalPeriodId, Math.floor(Math.random() * 100000)],
)
if (params.side === 'ar') {
await getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, '1930', $2, 0),
($1, '1510', 0, $2)`,
[id, amount],
)
} else {
await getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, '2440', $2, 0),
($1, '1930', 0, $2)`,
[id, amount],
)
}
return id
}
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' })
})
})