Files
accounted/tests/pg/committed-at-preservation.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

144 lines
5.9 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import { getPool, withUserContext, runAsServiceRole } from './setup'
import { seedCompany, insertDraftJournalEntry, insertBalancedLines } from './fixtures'
// set_committed_at() after migration 20260806160000: on draft-to-posted the
// preset committed_at survives ONLY for backend writers, decided by the JWT
// claims role (service_role, or no claims at all: direct SQL and pg tests).
// Seeding flows backdate history that way. For end-user callers the stamp
// stays tamper-proof: RLS lets a member insert a draft with any committed_at,
// and the timeliness checks (BFL 5 kap) read committed_at as the genuine
// transition time, so an authenticated caller must never control it: not via
// a direct UPDATE, and not by laundering the post through the SECURITY
// DEFINER commit_journal_entry RPC (which is why the guard reads JWT claims,
// not current_user). Drafts with no committed_at are stamped now() for
// everyone.
const BACKDATED = '2026-03-15T10:00:00Z'
const BACKDATED_ISO = '2026-03-15T10:00:00.000Z'
async function seedBackdatedDraft(): Promise<{ entryId: string; userId: string }> {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
entryDate: '2026-03-15',
committedAt: BACKDATED,
})
await insertBalancedLines(entryId)
return { entryId, userId }
}
describe('set_committed_at trusted-writer preservation', () => {
it('preserves a backdated committed_at when posting as postgres', async () => {
const { entryId } = await seedBackdatedDraft()
const pool = getPool()
await pool.query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [
entryId,
])
const { rows } = await pool.query<{ committed_at: Date }>(
`SELECT committed_at FROM public.journal_entries WHERE id = $1`,
[entryId],
)
expect(rows[0].committed_at.toISOString()).toBe(BACKDATED_ISO)
})
it('preserves a backdated committed_at when posting as service_role', async () => {
const { entryId } = await seedBackdatedDraft()
const committedAt = await runAsServiceRole(async (client) => {
await client.query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [
entryId,
])
const { rows } = await client.query<{ committed_at: Date }>(
`SELECT committed_at FROM public.journal_entries WHERE id = $1`,
[entryId],
)
return rows[0].committed_at
})
expect(committedAt.toISOString()).toBe(BACKDATED_ISO)
})
it('overwrites a preset committed_at when an authenticated member posts', async () => {
const { entryId, userId } = await seedBackdatedDraft()
const before = Date.now()
const committedAt = await withUserContext(userId, async (client) => {
const updated = await client.query(
`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1 RETURNING id`,
[entryId],
)
// RLS must actually let the member's UPDATE through; 0 rows would make
// the assertion below pass vacuously against the seeded value.
expect(updated.rowCount).toBe(1)
const { rows } = await client.query<{ committed_at: Date }>(
`SELECT committed_at FROM public.journal_entries WHERE id = $1`,
[entryId],
)
return rows[0].committed_at
})
const after = Date.now()
expect(committedAt.toISOString()).not.toBe(BACKDATED_ISO)
expect(committedAt.getTime()).toBeGreaterThanOrEqual(before - 60_000)
expect(committedAt.getTime()).toBeLessThanOrEqual(after + 60_000)
})
it('overwrites a preset committed_at when an authenticated member posts via commit_journal_entry', async () => {
// The laundering path: the RPC is SECURITY DEFINER, so current_user
// inside it is the function owner. The guard must still see the caller's
// JWT claims and stamp now().
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
entryDate: '2026-03-15',
committedAt: BACKDATED,
})
await insertBalancedLines(entryId)
const before = Date.now()
const committedAt = await withUserContext(userId, async (client) => {
const committed = await client.query<{ voucher_number: number }>(
`SELECT * FROM public.commit_journal_entry($1, $2)`,
[companyId, entryId],
)
expect(committed.rows[0].voucher_number).toBeGreaterThan(0)
const { rows } = await client.query<{ committed_at: Date }>(
`SELECT committed_at FROM public.journal_entries WHERE id = $1`,
[entryId],
)
return rows[0].committed_at
})
const after = Date.now()
expect(committedAt.toISOString()).not.toBe(BACKDATED_ISO)
expect(committedAt.getTime()).toBeGreaterThanOrEqual(before - 60_000)
expect(committedAt.getTime()).toBeLessThanOrEqual(after + 60_000)
})
it('stamps now() when the draft carries no committed_at', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
entryDate: '2026-03-15',
})
await insertBalancedLines(entryId)
const pool = getPool()
const before = Date.now()
await pool.query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [
entryId,
])
const after = Date.now()
const { rows } = await pool.query<{ committed_at: Date | null }>(
`SELECT committed_at FROM public.journal_entries WHERE id = $1`,
[entryId],
)
expect(rows[0].committed_at).not.toBeNull()
// Stamped at posting time, not the (older) entry_date.
expect(rows[0].committed_at!.getTime()).toBeGreaterThanOrEqual(before - 60_000)
expect(rows[0].committed_at!.getTime()).toBeLessThanOrEqual(after + 60_000)
})
})