* 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>
113 lines
4.5 KiB
TypeScript
113 lines
4.5 KiB
TypeScript
/**
|
|
* pg-real test for the GL-line read-RPC tenant guard
|
|
* (20260611120000_gl_lines_rpc_tenant_guard.sql).
|
|
*
|
|
* get_unlinked_gl_lines and get_account_gl_lines_for_matching are SECURITY
|
|
* DEFINER and EXECUTE-able by anon/authenticated, so without the guard any
|
|
* authenticated user could call them directly with another company's id and read
|
|
* its general ledger. The guard enforces membership for anon/authenticated while
|
|
* leaving service_role and direct/superuser access (this harness, migrations,
|
|
* the reconciliation cron) untouched.
|
|
*/
|
|
import { describe, it, expect } from 'vitest'
|
|
import { getPool, withUserContext } from './setup'
|
|
import {
|
|
insertPostedJournalEntry as insertAtomicPostedJournalEntry,
|
|
seedCompany,
|
|
} from './fixtures'
|
|
|
|
async function insertPostedJournalEntry(params: {
|
|
userId: string
|
|
companyId: string
|
|
fiscalPeriodId: string
|
|
entryDate: string
|
|
voucherNumber: number
|
|
amount?: number
|
|
}): Promise<string> {
|
|
const amount = params.amount ?? 1500
|
|
return insertAtomicPostedJournalEntry({
|
|
userId: params.userId,
|
|
companyId: params.companyId,
|
|
fiscalPeriodId: params.fiscalPeriodId,
|
|
voucherNumber: params.voucherNumber,
|
|
entryDate: params.entryDate,
|
|
description: 'Bank tx',
|
|
sourceType: 'bank_transaction',
|
|
lines: [
|
|
{ accountNumber: '1930', debitAmount: amount, creditAmount: 0 },
|
|
{ accountNumber: '2091', debitAmount: 0, creditAmount: amount },
|
|
],
|
|
})
|
|
}
|
|
|
|
const UNLINKED = `SELECT journal_entry_id FROM public.get_unlinked_gl_lines($1)`
|
|
const MATCHING = `SELECT journal_entry_id FROM public.get_account_gl_lines_for_matching($1, '1930', NULL, NULL, true)`
|
|
|
|
describe('GL-line read RPCs: tenant-isolation guard', () => {
|
|
it('lets a member read its own company but blocks an authenticated non-member', async () => {
|
|
const a = await seedCompany() // userA is owner-member of companyA
|
|
const b = await seedCompany() // userB belongs to companyB only
|
|
const entryA = await insertPostedJournalEntry({
|
|
userId: a.userId,
|
|
companyId: a.companyId,
|
|
fiscalPeriodId: a.fiscalPeriodId,
|
|
entryDate: '2026-03-15',
|
|
voucherNumber: 1,
|
|
})
|
|
|
|
// Direct / superuser connection (no JWT role): the trusted bypass that this
|
|
// harness, migrations and the service-role cron rely on. Data is visible.
|
|
const bare = await getPool().query(UNLINKED, [a.companyId])
|
|
expect(bare.rows.map((r) => r.journal_entry_id)).toContain(entryA)
|
|
|
|
// A member of company A sees A's line through both RPCs.
|
|
await withUserContext(a.userId, async (client) => {
|
|
const u = await client.query(UNLINKED, [a.companyId])
|
|
expect(u.rows.map((r) => r.journal_entry_id)).toContain(entryA)
|
|
const m = await client.query(MATCHING, [a.companyId])
|
|
expect(m.rows.map((r) => r.journal_entry_id)).toContain(entryA)
|
|
})
|
|
|
|
// A member of company B probing company A gets nothing: the cross-tenant
|
|
// read that SECURITY DEFINER + anon/authenticated EXECUTE used to allow.
|
|
await withUserContext(b.userId, async (client) => {
|
|
const u = await client.query(UNLINKED, [a.companyId])
|
|
expect(u.rows).toHaveLength(0)
|
|
const m = await client.query(MATCHING, [a.companyId])
|
|
expect(m.rows).toHaveLength(0)
|
|
})
|
|
})
|
|
|
|
it('rejects an anon (unauthenticated) caller outright: EXECUTE revoked from anon + PUBLIC', async () => {
|
|
const a = await seedCompany()
|
|
await insertPostedJournalEntry({
|
|
userId: a.userId,
|
|
companyId: a.companyId,
|
|
fiscalPeriodId: a.fiscalPeriodId,
|
|
entryDate: '2026-03-15',
|
|
voucherNumber: 1,
|
|
})
|
|
|
|
// Each probe runs in its own transaction: a permission-denied error aborts
|
|
// the transaction, so the two can't share one. anon has no EXECUTE (revoked
|
|
// from its own grant AND from PUBLIC, of which anon is a member), so the call
|
|
// is rejected at the privilege layer: defense in depth on top of the
|
|
// in-function tenant guard.
|
|
const callAsAnon = async (sql: string): Promise<void> => {
|
|
const client = await getPool().connect()
|
|
try {
|
|
await client.query('BEGIN')
|
|
await client.query(`SELECT set_config('request.jwt.claims', '{"role":"anon"}', true)`)
|
|
await client.query('SET LOCAL ROLE anon')
|
|
await client.query(sql, [a.companyId])
|
|
} finally {
|
|
await client.query('ROLLBACK').catch(() => {})
|
|
client.release()
|
|
}
|
|
}
|
|
|
|
await expect(callAsAnon(UNLINKED)).rejects.toThrow(/permission denied/i)
|
|
await expect(callAsAnon(MATCHING)).rejects.toThrow(/permission denied/i)
|
|
})
|
|
})
|