* fix(security): bind api_keys to the caller, lock hash-as-bearer RPCs and provider token tables Security audit 2026-09-01, critical items. - api_keys INSERT requires user_id = auth.uid() again (an admin could forge a key for any co-member and act as them in every company they belong to); SELECT is own-keys-or-admin; a BEFORE trigger freezes the identity and credential columns against user-session UPDATEs. - rotate_mcp_refresh_token and validate_and_increment_api_key become service_role only: they match rows by a presented SHA-256, so a hash readable by co-members was a bearer credential. - validate_and_increment_api_key fails closed when the key's user is no longer a member of the key's company. - provider_consent_tokens and provider_otc: the DELETE policies collapsed to "caller has any team row" (correlated subquery on a non-existent team_members.company_id). All member policies dropped; service_role only, matching every existing code path. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): role gates, ownership guards and posting integrity in the database Security audit 2026-09-01, high items at the database layer. - One table-level guard, enforce_company_writer_role(), blocks the read-only viewer role on 55 company-scoped tables including through the 15 membership-only SECURITY DEFINER writers. Keyed on the JWT role claim so it fires inside definer bodies; no-op for service_role and trigger cascades. - company_members user_id/company_id immutable from user sessions; invitations can never grant owner; team_members gains a transition guard (admins keep non-owner role moves); companies team_id and archiving are owner-only and team attachment needs team membership. - Direct statements (current_user = authenticated) can no longer insert posted headers, add lines under posted verifikat, or post a draft with a voucher number the sequence never issued. Sanctioned RPCs run as the definer and are untouched; the engine's own draft-then-post shapes still pass. - create_document_version refuses viewers and foreign storage paths; validate_version_chain needs membership and loses anon EXECUTE; match_documents / match_booking_templates lose anon; cron maintenance RPCs become service_role only; the production-only seed_asset_categories is dropped. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * build: pin tsx as an exact devDependency instead of fetching it with npx at build time prebuild ran "npx tsx" with no lockfile entry, so every Vercel, Docker and CI build downloaded tsx@latest and its transitive tree from the registry with no integrity check, inside the build environment. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): refuse the viewer role on API-key and MCP write paths The v1 wrapper and the MCP company routing checked company membership but never role, and both run as service role, so a read-only viewer holding an API key could post vouchers and change settings through the API. Mutating methods and non-read scopes now return 403 ROLE_READ_ONLY for viewers on v1; MCP write tools refuse viewers the same way. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): stop serving uploaded SVG, XML and HTML as executable content on the app origin Uploads persisted the browser-declared mime type and the inline proxy served it verbatim, sandboxing only text/html; the storage proxy forwarded the uploader's Content-Type. Any writer, or any Peppol sender, could plant a scripted SVG or XHTML that executed on app.gnubok.se. - inline route: allow-list of natively safe types (PDF, raster images) served as before; everything else gets the opaque sandbox CSP. - storage proxy: octet-stream + attachment + sandbox unless the DB mime for the key is on the allow-list. - document-service: the stored mime is the magic-byte validated type. - logo upload: magic-byte validation, SVG refused. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): byrå brand logo upload decides the type by magic bytes and drops SVG Same pattern as the company logo route: the logos bucket is public, so a scripted SVG (or anything declared as an image) must never land there. The upload pickers stop advertising SVG. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): bind Enable Banking, Stripe and WooCommerce callbacks to the initiating user The callbacks resolved the pending row by oauth_state alone, so a victim who completed an attacker-initiated consent had their bank account, merchant account or store attached to the attacker's company. requireFlowInitiator() now requires the cookie session of the user who started the flow: no session redirects to login with the callback URL preserved, a different user is refused and nothing is exchanged. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): guard tenant-controlled outbound fetches and surface the disabled rate limiter WooCommerce and Shopify syncs fetched a member-editable store URL with plain fetch() and redirect following under the service role, and the invoice PDF renderer fetched company_settings.logo_url unguarded. All three go through a new safeFetch() (public-IP validation via url-guard, https only, redirect: 'manual', body size cap) and re-normalise the stored host at use time. checkRateLimit() keeps failing open on hosted but logs one error per process when Upstash is not configured and exports isRateLimiterConfigured(). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): decide the API MFA gate from server-authenticated factors, not the session cookie getAuthenticatorAssuranceLevel() without arguments derives nextLevel from session.user.factors, which comes from the unsigned sb-*-auth-token cookie. Deleting factors from the cookie made an enrolled account look like it had nothing to step up to, on every /api route and in requireAuth. Both gates now read factors from the getUser() result or listFactors() and the level from the verified JWT claim, and fail closed on errors. Page-branch gate hardened the same way. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): bind Fortnox/Visma, Gmail and Skatteverket callbacks to the initiating user The arcim-migration callback exchanged the provider code onto whatever consent the one-time state named, with no check of who completed the flow and no org-number comparison, so a phished Fortnox admin handed their ledger to the attacker's company. provider_otc now records the initiating user (migration 20260902100000); the callback requires that session and, after the exchange, refuses a provider company whose org number differs from the consent's company. The Gmail and Skatteverket callbacks enforce the same initiator check. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): BankID signup confirms the email before linking the identity Signup created an email-confirmed, MFA-exempt account for any address the caller typed and returned a magic link, so an attacker could pre-register a victim's email and keep a permanent BankID login into the account the victim later adopted. The user is now created unconfirmed, the identity carries email_verified_at NULL (migration 20260902101000), bankid_linked is not set until the mailed confirmation is clicked, and BankID login of a pending identity is refused with the confirmation re-sent. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): bind MCP OAuth redirect URIs to the consenting user and cap scopes A user-registered redirect URI was allowlisted globally, the consent page named no client, and all scopes were pre-checked, so one phishing link handed an attacker a full-scope key for the victim's company. Registered URIs now resolve only for the registrant or a colleague sharing a company; the consent page shows the client identity and redirect host; non-built-in clients default to read-only pre-checks; scopes are capped by the user's role (viewer: read only) at consent and at /token. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(auth): client follow-ups for BankID confirmation, callback mismatch copy and decision log - register client handles the new confirmation_sent response from BankID signup with the existing inbox screen instead of calling verifyOtp. - BankID login surfaces the email_unconfirmed explanation. - WooCommerce settings map woocommerce_error=wrong_user to its own copy. - Logo help text no longer advertises SVG. - DECISIONS.md records the audit remediation choices. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(mcp-oauth): literal SoD columns in the api_keys insert so the phantom-column scanner resolves them Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test(logo): type the upload fixtures as Uint8Array<ArrayBuffer> so they are valid BlobParts Fixes the typecheck ratchet on PR #2155 and ratchets the baseline down by the one legacy error the change removed. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
283 lines
11 KiB
TypeScript
283 lines
11 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'
|
|
|
|
interface OverrideAuditRow {
|
|
action: string
|
|
new_state: {
|
|
preset_committed_at: string
|
|
wall_clock: string
|
|
jwt_role: string
|
|
}
|
|
created_at: Date
|
|
}
|
|
|
|
async function fetchOverrideRows(entryId: string): Promise<OverrideAuditRow[]> {
|
|
// Read as postgres: audit_log SELECT is restricted to the owning user.
|
|
const { rows } = await getPool().query<OverrideAuditRow>(
|
|
`SELECT action, new_state, created_at
|
|
FROM public.audit_log
|
|
WHERE table_name = 'journal_entries'
|
|
AND record_id = $1
|
|
AND action = 'COMMITTED_AT_OVERRIDE'`,
|
|
[entryId],
|
|
)
|
|
return rows
|
|
}
|
|
|
|
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) => {
|
|
// Direct draft -> posted flips from a user session must carry a
|
|
// sequence-issued voucher number (20260902093000); take one inline.
|
|
const updated = await client.query(
|
|
`UPDATE public.journal_entries
|
|
SET status = 'posted',
|
|
voucher_number = public.next_voucher_number(company_id, fiscal_period_id, voucher_series)
|
|
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)
|
|
})
|
|
})
|
|
|
|
// Migration 20260810121000: preserving a preset committed_at is a sanctioned
|
|
// override of the behandlingshistorik timestamp, so BFNAR 2013:2 kap 8 wants a
|
|
// durable trace: who kept which preset value, and what the wall clock said.
|
|
describe('committed_at override audit trail', () => {
|
|
it('writes a COMMITTED_AT_OVERRIDE audit row when postgres preserves a preset', async () => {
|
|
const { entryId } = await seedBackdatedDraft()
|
|
const before = Date.now()
|
|
await getPool().query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [
|
|
entryId,
|
|
])
|
|
const after = Date.now()
|
|
|
|
const rows = await fetchOverrideRows(entryId)
|
|
expect(rows).toHaveLength(1)
|
|
expect(new Date(rows[0].new_state.preset_committed_at).toISOString()).toBe(BACKDATED_ISO)
|
|
expect(rows[0].new_state.jwt_role).toBe('none')
|
|
// The row separates real from preset time: wall_clock is the transition
|
|
// moment, not the backdated stamp.
|
|
const wallClock = new Date(rows[0].new_state.wall_clock).getTime()
|
|
expect(wallClock).toBeGreaterThanOrEqual(before - 60_000)
|
|
expect(wallClock).toBeLessThanOrEqual(after + 60_000)
|
|
})
|
|
|
|
it('writes the audit row under SET ROLE service_role, despite audit_log RLS', async () => {
|
|
// service_role has no BYPASSRLS in this harness and audit_log has no
|
|
// INSERT policy: only the SECURITY DEFINER writer makes this pass.
|
|
const { entryId } = await seedBackdatedDraft()
|
|
await runAsServiceRole(async (client) => {
|
|
await client.query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [
|
|
entryId,
|
|
])
|
|
})
|
|
|
|
const rows = await fetchOverrideRows(entryId)
|
|
expect(rows).toHaveLength(1)
|
|
expect(rows[0].new_state.jwt_role).toBe('service_role')
|
|
expect(new Date(rows[0].new_state.preset_committed_at).toISOString()).toBe(BACKDATED_ISO)
|
|
})
|
|
|
|
it('stamps wall_clock at the update moment, not the transaction start', async () => {
|
|
// The seeding flows post many entries inside one transaction; now() would
|
|
// pin every override to the BEGIN. The writer must use clock_timestamp().
|
|
const { entryId } = await seedBackdatedDraft()
|
|
const client = await getPool().connect()
|
|
try {
|
|
await client.query('BEGIN')
|
|
const {
|
|
rows: [{ txn_start }],
|
|
} = await client.query<{ txn_start: Date }>(`SELECT now() AS txn_start`)
|
|
await client.query(`SELECT pg_sleep(1.2)`)
|
|
await client.query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [
|
|
entryId,
|
|
])
|
|
await client.query('COMMIT')
|
|
const rows = await fetchOverrideRows(entryId)
|
|
expect(rows).toHaveLength(1)
|
|
const wallClock = new Date(rows[0].new_state.wall_clock).getTime()
|
|
expect(wallClock).toBeGreaterThanOrEqual(txn_start.getTime() + 1_000)
|
|
} finally {
|
|
client.release()
|
|
}
|
|
})
|
|
|
|
it('writes no override row when an authenticated member posts (stamp path)', async () => {
|
|
const { entryId, userId } = await seedBackdatedDraft()
|
|
await withUserContext(userId, async (client) => {
|
|
// Direct draft -> posted flips from a user session must carry a
|
|
// sequence-issued voucher number (20260902093000); take one inline.
|
|
const updated = await client.query(
|
|
`UPDATE public.journal_entries
|
|
SET status = 'posted',
|
|
voucher_number = public.next_voucher_number(company_id, fiscal_period_id, voucher_series)
|
|
WHERE id = $1 RETURNING id`,
|
|
[entryId],
|
|
)
|
|
expect(updated.rowCount).toBe(1)
|
|
})
|
|
expect(await fetchOverrideRows(entryId)).toHaveLength(0)
|
|
})
|
|
|
|
it('writes no override row 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)
|
|
await getPool().query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [
|
|
entryId,
|
|
])
|
|
expect(await fetchOverrideRows(entryId)).toHaveLength(0)
|
|
})
|
|
|
|
it('does not expose the writer to client roles', async () => {
|
|
// PostgREST would surface any EXECUTE-granted SECURITY DEFINER function in
|
|
// public as an RPC; a member must not be able to write audit noise.
|
|
const { entryId, userId } = await seedBackdatedDraft()
|
|
await withUserContext(userId, async (client) => {
|
|
await expect(
|
|
client.query(
|
|
`SELECT public.log_committed_at_override(je, 'authenticated')
|
|
FROM public.journal_entries je WHERE je.id = $1`,
|
|
[entryId],
|
|
),
|
|
).rejects.toThrow(/permission denied/)
|
|
})
|
|
})
|
|
})
|