docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
@@ -1,284 +0,0 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getClient, getPool } from '@/tests/pg/setup'
import { seedCompany } from '@/tests/pg/fixtures'
// ──────────────────────────────────────────────────────────────────────
// Fixtures: parent webhook + child delivery
// ──────────────────────────────────────────────────────────────────────
async function insertWebhook(params: {
// userId kept in the signature for parity with seedCompany's return: the
// webhooks table itself has no user_id column (see route comment in
// app/api/v1/companies/[companyId]/webhooks/route.ts).
userId: string
companyId: string
eventType?: string
active?: boolean
}): Promise<string> {
void params.userId
const id = randomUUID()
await getPool().query(
`INSERT INTO public.webhooks
(id, company_id, name, event_type, webhook_url, secret, active)
VALUES ($1, $2, 'pg-test', $3, 'https://example.com/hook', $4, $5)`,
[
id,
params.companyId,
params.eventType ?? 'invoice.paid',
`whsec_${randomUUID().replace(/-/g, '')}`,
params.active ?? true,
],
)
return id
}
async function insertDelivery(params: {
webhookId: string | null
companyId: string
status?: 'pending' | 'in_flight' | 'delivered' | 'failed' | 'dead'
nextAttemptAt?: string
eventType?: string
attempts?: number
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at, attempts)
VALUES ($1, $2, $3, $4, '{"hello":"world"}'::jsonb, '2026-05-12',
$5, $6, $7)`,
[
id,
params.webhookId,
params.companyId,
params.eventType ?? 'invoice.paid',
params.status ?? 'pending',
params.nextAttemptAt ?? new Date().toISOString(),
params.attempts ?? 0,
],
)
return id
}
async function getDeliveryStatus(id: string): Promise<string | null> {
const r = await getPool().query<{ status: string }>(
`SELECT status FROM public.webhook_deliveries WHERE id = $1`,
[id],
)
return r.rows[0]?.status ?? null
}
// Direct-insert rows for one test isolation. Each it() seeds its own
// company + webhook so the dispatcher sees a clean slate; we just need to
// make sure the function only returns rows we created, which we do by
// asserting on ids.
describe('claim_due_webhook_deliveries.pg: atomic SKIP LOCKED claim', () => {
it('claims a pending row that is due', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'pending' })
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(rows.map((r) => r.id)).toContain(deliveryId)
expect(await getDeliveryStatus(deliveryId)).toBe('in_flight')
})
it('claims a failed row that has reached its retry deadline', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
// next_attempt_at in the past: retry due.
const deliveryId = await insertDelivery({
webhookId,
companyId,
status: 'failed',
nextAttemptAt: new Date(Date.now() - 60_000).toISOString(),
attempts: 2,
})
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(rows.map((r) => r.id)).toContain(deliveryId)
expect(await getDeliveryStatus(deliveryId)).toBe('in_flight')
})
it('skips a row whose next_attempt_at is still in the future', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({
webhookId,
companyId,
status: 'failed',
nextAttemptAt: new Date(Date.now() + 5 * 60_000).toISOString(),
})
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(rows.map((r) => r.id)).not.toContain(deliveryId)
// Status stays pre-claim.
expect(await getDeliveryStatus(deliveryId)).toBe('failed')
})
it('skips dangling rows (webhook_id IS NULL)', async () => {
const { companyId } = await seedCompany()
// webhook deleted between enqueue and dispatch: FK ON DELETE SET NULL.
const deliveryId = await insertDelivery({
webhookId: null,
companyId,
status: 'pending',
})
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(rows.map((r) => r.id)).not.toContain(deliveryId)
})
it('skips terminal-status rows', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveredId = await insertDelivery({
webhookId,
companyId,
status: 'delivered',
})
const deadId = await insertDelivery({
webhookId,
companyId,
status: 'dead',
})
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
const ids = rows.map((r) => r.id)
expect(ids).not.toContain(deliveredId)
expect(ids).not.toContain(deadId)
})
// The status filter `IN ('pending', 'failed')` is what prevents
// double-delivery once a tick has already claimed a row to in_flight.
// recoverStuckInFlight is the ONLY legitimate path back from in_flight
// (sweeps the row to 'failed' after the stuck-threshold), so the claim
// function must NEVER re-pick a row already marked in_flight.
it('skips rows already in in_flight status', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const inFlightId = await insertDelivery({
webhookId,
companyId,
status: 'in_flight',
})
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(rows.map((r) => r.id)).not.toContain(inFlightId)
// Status must NOT have been re-flipped.
expect(await getDeliveryStatus(inFlightId)).toBe('in_flight')
})
it('respects the batch size', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const ids = await Promise.all(
Array.from({ length: 5 }, () =>
insertDelivery({ webhookId, companyId, status: 'pending' }),
),
)
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[2],
)
expect(rows.length).toBe(2)
// The 3 unclaimed rows stay pending.
const unclaimed = ids.filter((id) => !rows.some((r) => r.id === id))
for (const id of unclaimed) {
expect(await getDeliveryStatus(id)).toBe('pending')
}
})
it('rejects out-of-range batch sizes', async () => {
await expect(
getPool().query(`SELECT * FROM public.claim_due_webhook_deliveries($1, now())`, [0]),
).rejects.toThrow(/p_batch_size must be in/i)
await expect(
getPool().query(`SELECT * FROM public.claim_due_webhook_deliveries($1, now())`, [-1]),
).rejects.toThrow(/p_batch_size must be in/i)
await expect(
getPool().query(`SELECT * FROM public.claim_due_webhook_deliveries($1, now())`, [10000]),
).rejects.toThrow(/p_batch_size must be in/i)
})
// SKIP LOCKED is the entire point of this migration. Two transactions
// calling the function at the same moment must not both see the same
// row: the row locked by the first caller is invisible to the second,
// closing the duplicate-delivery window the old SELECT-then-UPDATE-
// intersect pattern documented as load-bearing.
it('SKIP LOCKED: a concurrent caller does not see rows locked by an in-flight transaction', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({
webhookId,
companyId,
status: 'pending',
})
const a = await getClient()
const b = await getClient()
try {
await a.query('BEGIN')
await b.query('BEGIN')
// A claims first. The row is now status='in_flight' AND held under
// a row lock by transaction A (UPDATE sets ROW EXCLUSIVE).
const aClaim = await a.query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(aClaim.rows.map((r) => r.id)).toContain(deliveryId)
// B's call SKIPs the locked row entirely. Without SKIP LOCKED this
// call would BLOCK on the row lock; the test would hang and only
// fail via testTimeout. SKIP LOCKED makes it return promptly with
// the row simply absent from results.
const bClaim = await b.query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(bClaim.rows.map((r) => r.id)).not.toContain(deliveryId)
// Commit A and roll back B (no-op since B claimed nothing).
await a.query('COMMIT')
await b.query('ROLLBACK')
} finally {
a.release()
b.release()
}
// Final state: row is in_flight, claimed exactly once.
expect(await getDeliveryStatus(deliveryId)).toBe('in_flight')
})
})
@@ -1,126 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn(() => ({ __client: true })),
}))
// `after` is a no-op outside a request scope in these tests; the module falls
// back to a floating promise, which is the path a plain node server takes too.
vi.mock('next/server', () => ({
after: () => {
throw new Error('after() called outside a request scope')
},
}))
import { kickWebhookDispatch, resetKickStateForTests, KICK_BATCH_SIZE } from '../dispatch-kick'
/**
* A zero DispatchSummary. Spread rather than repeated so adding a counter to
* the summary does not mean re-editing every case in this file; these tests
* are about scheduling and coalescing, never about the counts.
*/
const EMPTY_SUMMARY = {
picked: 0,
delivered: 0,
failed: 0,
dead: 0,
skipped: 0,
released: 0,
recovered: 0,
recoveredDead: 0,
}
/** Resolves after the microtask queue drains, so floating work has run. */
const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
beforeEach(() => {
vi.clearAllMocks()
resetKickStateForTests()
})
describe('kickWebhookDispatch', () => {
it('runs one dispatch cycle with the small kick batch size', async () => {
const dispatch = vi.fn().mockResolvedValue({ ...EMPTY_SUMMARY, picked: 1, delivered: 1 })
kickWebhookDispatch(dispatch)
await flush()
expect(dispatch).toHaveBeenCalledTimes(1)
expect(dispatch.mock.calls[0][0]).toMatchObject({ batchSize: KICK_BATCH_SIZE })
})
it('claims far fewer rows than the cron, so a backlog cannot own a request tail', () => {
// Each delivery can burn the full 10 s receiver timeout; the cron's 50 is
// fine on a dedicated invocation, not on the tail of a user request.
expect(KICK_BATCH_SIZE).toBeLessThan(50)
})
it('returns synchronously: the emitter never waits on receiver HTTP', async () => {
let settled = false
const dispatch = vi.fn(
() =>
new Promise((resolve) => {
setTimeout(() => {
settled = true
resolve({ ...EMPTY_SUMMARY })
}, 20)
}),
)
const returned = kickWebhookDispatch(dispatch as never)
// eventBus.emit awaits its subscribers, so a kick that blocked here would
// put a stranger's slow endpoint on the critical path of committing a
// verifikat.
expect(returned).toBeUndefined()
expect(settled).toBe(false)
await new Promise((resolve) => setTimeout(resolve, 40))
expect(settled).toBe(true)
})
it('coalesces a burst of kicks into a single cycle', async () => {
// A bulk booking emits once per row. Without coalescing, 100 rows would
// mean 100 claim round trips against the same handful of due deliveries.
const dispatch = vi.fn().mockResolvedValue({ ...EMPTY_SUMMARY })
for (let i = 0; i < 100; i++) kickWebhookDispatch(dispatch)
await flush()
expect(dispatch).toHaveBeenCalledTimes(1)
})
it('accepts a new kick once the previous cycle has started', async () => {
const dispatch = vi.fn().mockResolvedValue({ ...EMPTY_SUMMARY })
kickWebhookDispatch(dispatch)
await flush()
kickWebhookDispatch(dispatch)
await flush()
expect(dispatch).toHaveBeenCalledTimes(2)
})
it('swallows a dispatch failure: a failed kick is latency, not a lost delivery', async () => {
const dispatch = vi.fn().mockRejectedValue(new Error('receiver unreachable'))
expect(() => kickWebhookDispatch(dispatch)).not.toThrow()
await flush()
expect(dispatch).toHaveBeenCalledTimes(1)
})
it('does not wedge the coalescing flag when a cycle fails', async () => {
// The cron still covers every row, but a stuck flag would silently
// disable the fast path for the life of the function instance.
const failing = vi.fn().mockRejectedValue(new Error('boom'))
kickWebhookDispatch(failing)
await flush()
const ok = vi.fn().mockResolvedValue({ ...EMPTY_SUMMARY })
kickWebhookDispatch(ok)
await flush()
expect(ok).toHaveBeenCalledTimes(1)
})
})
@@ -1,231 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import type { PinnedFetchResult } from '../pinned-fetch'
// Mock the logger so the warn-vs-error level can be asserted: the real logger
// suppresses warn in the test environment, and the point of this suite is that
// a dropped audit row surfaces at error level (which always forwards to the
// observability sink) rather than being swallowed.
const { logWarn, logError } = vi.hoisted(() => ({
logWarn: vi.fn(),
logError: vi.fn(),
}))
vi.mock('@/lib/logger', () => ({
createLogger: () => ({
info: vi.fn(),
warn: logWarn,
error: logError,
child: vi.fn(),
}),
}))
// Import after mocks
import { dispatchDueDeliveries } from '../dispatcher'
const COMPANY_ID = '11111111-1111-4111-8111-111111111111'
const WEBHOOK_ID = '22222222-2222-4222-8222-222222222222'
const DELIVERY_ID = '33333333-3333-4333-8333-333333333333'
interface Recorded {
auditInserts: Record<string, unknown>[]
webhookUpdates: Record<string, unknown>[]
webhookSelects: string[]
}
/**
* Minimal Supabase stub shaped to the exact call chains the dispatcher uses.
* `webhooksSelectResult` lets a test simulate the PostgREST 42703 that a
* phantom column would produce, so the audit row's company scope can be
* proven independent of the prior-state snapshot.
*/
function makeSupabase(opts: {
auditInsertError?: { message: string; code: string } | null
priorSnapshotError?: { message: string; code: string } | null
} = {}): { client: SupabaseClient; recorded: Recorded } {
const recorded: Recorded = { auditInserts: [], webhookUpdates: [], webhookSelects: [] }
const client = {
rpc: vi.fn(async (fn: string) => {
if (fn === 'claim_due_webhook_deliveries') {
return {
data: [
{
id: DELIVERY_ID,
webhook_id: WEBHOOK_ID,
company_id: COMPANY_ID,
event_type: 'invoice.paid',
payload: { id: 'inv-1' },
previous_attributes: null,
api_version: '2026-05-12',
attempts: 0,
},
],
error: null,
}
}
return { data: null, error: null }
}),
from: vi.fn((table: string) => {
if (table === 'audit_log') {
return {
insert: vi.fn(async (row: Record<string, unknown>) => {
recorded.auditInserts.push(row)
return { error: opts.auditInsertError ?? null }
}),
}
}
if (table === 'webhook_deliveries') {
// update(...).eq(...) -> markDead / markDelivered
// update(...).eq('id').eq('status').select('id') -> touchInFlight
//
// The touch must resolve to a NON-empty row set: an empty result means
// "this delivery is no longer ours" and the dispatcher skips the
// attempt, which would take the 410 auto-disable path out of reach.
// The stuck sweep no longer runs through this chain at all; it goes
// through rpc('recover_stuck_webhook_deliveries').
const thenable = {
eq: () => thenable,
select: async () => ({ data: [{ id: DELIVERY_ID }], error: null }),
then: (resolve: (v: { error: null }) => unknown) => resolve({ error: null }),
}
return { update: () => thenable }
}
if (table === 'webhooks') {
return {
select: (cols: string) => {
recorded.webhookSelects.push(cols)
return {
// loadWebhooksByIds
in: async () => ({
data: [
{
id: WEBHOOK_ID,
company_id: COMPANY_ID,
webhook_url: 'https://receiver.example.com/hook',
secret: 'whsec_test',
},
],
error: null,
}),
// disableWebhook prior-state snapshot
eq: () => ({
maybeSingle: async () =>
opts.priorSnapshotError
? { data: null, error: opts.priorSnapshotError }
: {
data: {
company_id: COMPANY_ID,
name: 'Payments receiver',
active: true,
disabled_at: null,
disabled_reason: null,
},
error: null,
},
}),
}
},
update: (row: Record<string, unknown>) => {
recorded.webhookUpdates.push(row)
return { eq: async () => ({ error: null }) }
},
}
}
throw new Error(`unexpected table: ${table}`)
}),
} as unknown as SupabaseClient
return { client, recorded }
}
/** Receiver responds 410 Gone: the auto-disable path. */
const gone410 = async (): Promise<PinnedFetchResult> => ({
kind: 'ok',
status: 410,
headers: { 'content-type': 'application/json' },
body: '{}',
bodyTruncated: false,
pinnedAddress: '93.184.216.34',
})
describe('dispatcher auto-disable audit row', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('writes a company-scoped SECURITY_EVENT row attributed to the system dispatcher', async () => {
const { client, recorded } = makeSupabase()
const summary = await dispatchDueDeliveries({
supabase: client,
pinnedFetchImpl: gone410 as never,
})
expect(summary.dead).toBe(1)
expect(recorded.webhookUpdates[0]).toMatchObject({ active: false, disabled_reason: 'http_410_gone' })
expect(recorded.auditInserts).toHaveLength(1)
const audit = recorded.auditInserts[0]
expect(audit).toMatchObject({
company_id: COMPANY_ID,
action: 'SECURITY_EVENT',
table_name: 'webhooks',
record_id: WEBHOOK_ID,
user_id: null,
actor_id: null,
actor_type: 'system',
actor_label: 'webhook-dispatcher',
})
expect(audit.description).toContain('http_410_gone')
expect(audit.old_state).toMatchObject({ active: true })
})
it('never selects a user_id column from webhooks (no such column exists)', async () => {
const { client, recorded } = makeSupabase()
await dispatchDueDeliveries({ supabase: client, pinnedFetchImpl: gone410 as never })
expect(recorded.webhookSelects.length).toBeGreaterThan(0)
for (const cols of recorded.webhookSelects) {
expect(cols).not.toContain('user_id')
}
})
it('keeps the audit row company-scoped when the prior-state snapshot read fails', async () => {
const { client, recorded } = makeSupabase({
priorSnapshotError: { message: 'column webhooks.x does not exist', code: '42703' },
})
await dispatchDueDeliveries({ supabase: client, pinnedFetchImpl: gone410 as never })
expect(recorded.auditInserts).toHaveLength(1)
const audit = recorded.auditInserts[0]
expect(audit.company_id).toBe(COMPANY_ID)
expect(audit.actor_type).toBe('system')
expect(audit.old_state).toBeNull()
expect(audit.description).toContain('prior snapshot unavailable')
})
it('surfaces a failed audit insert at error level rather than swallowing it', async () => {
const { client } = makeSupabase({
auditInsertError: { message: 'insert denied', code: '42501' },
})
await dispatchDueDeliveries({ supabase: client, pinnedFetchImpl: gone410 as never })
expect(logError).toHaveBeenCalledWith(
'audit_log insert failed for webhook auto-disable',
expect.any(Error),
expect.objectContaining({ webhookId: WEBHOOK_ID, companyId: COMPANY_ID, reason: 'http_410_gone' }),
)
// Must not degrade to warn: warn is suppressed in test and never reaches
// the observability sink, which is what made the gap silent.
expect(logWarn).not.toHaveBeenCalledWith(
'audit_log insert failed for webhook auto-disable',
expect.anything(),
)
})
})
@@ -1,470 +0,0 @@
/**
* Stuck-in_flight recovery and per-row re-stamping (#1257).
*
* Two defects are pinned here:
*
* 1. the sweep window used to be a fixed 2x REQUEST_TIMEOUT_MS (20 s), which
* is shorter than a single serial cycle, so cycle N recovered rows cycle
* N-1 was still working through;
* 2. recovery reset rows to 'failed' without charging an attempt, so
* MAX_ATTEMPTS stopped being a real cap.
*
* The window is now derived from the bounded cycle and the cap is enforced
* server-side by recover_stuck_webhook_deliveries, so the assertions here are
* about what the dispatcher hands the RPC and about the per-row re-stamp that
* makes a row's in_flight age measure its own attempt.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import type { PinnedFetchResult } from '../pinned-fetch'
vi.mock('@/lib/logger', () => ({
createLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
child: vi.fn(),
}),
}))
// Import after mocks
import { dispatchDueDeliveries, __TESTING__ } from '../dispatcher'
const COMPANY_ID = '11111111-1111-4111-8111-111111111111'
const WEBHOOK_ID = '22222222-2222-4222-8222-222222222222'
const DELIVERY_IDS = [
'aaaaaaaa-0001-4000-8000-000000000001',
'aaaaaaaa-0002-4000-8000-000000000002',
'aaaaaaaa-0003-4000-8000-000000000003',
]
/** Fixed clock so the derived window is exactly assertable. */
const NOW = new Date('2026-07-30T10:00:00.000Z')
interface RecordedUpdate {
payload: Record<string, unknown>
filters: Record<string, unknown>
}
interface Recorded {
rpcCalls: { fn: string; args: Record<string, unknown> }[]
deliveryUpdates: RecordedUpdate[]
}
/**
* Ordered-log Supabase stub in the same house style as
* dispatcher-auto-disable.test.ts. Every write against webhook_deliveries is
* appended to `deliveryUpdates` in the order it resolves, so the interleaving
* of touch writes and terminal writes is directly assertable.
*
* `lostOwnership` makes a specific delivery's touch resolve to zero rows,
* which is how the real table reports "another cycle owns this row now".
*/
function makeSupabase(opts: {
deliveryCount?: number
attempts?: number
lostOwnership?: Set<string>
/** Rows the sweep RPC reports as recovered this tick. */
recovered?: Array<{ id: string; status: string; attempts: number }>
} = {}): { client: SupabaseClient; recorded: Recorded } {
const recorded: Recorded = { rpcCalls: [], deliveryUpdates: [] }
const count = opts.deliveryCount ?? 1
const client = {
rpc: vi.fn(async (fn: string, args: Record<string, unknown>) => {
recorded.rpcCalls.push({ fn, args })
if (fn === 'claim_due_webhook_deliveries') {
return {
data: DELIVERY_IDS.slice(0, count).map((id) => ({
id,
webhook_id: WEBHOOK_ID,
company_id: COMPANY_ID,
event_type: 'invoice.paid',
payload: { id: 'inv-1' },
previous_attributes: null,
api_version: '2026-05-12',
attempts: opts.attempts ?? 0,
})),
error: null,
}
}
// recover_stuck_webhook_deliveries: nothing stuck unless a case says so.
return { data: opts.recovered ?? [], error: null }
}),
from: vi.fn((table: string) => {
if (table === 'webhook_deliveries') {
return {
update: (payload: Record<string, unknown>) => {
const filters: Record<string, unknown> = {}
const rec: RecordedUpdate = { payload, filters }
const chain: Record<string, unknown> = {
eq: (col: string, val: unknown) => {
filters[col] = val
return chain
},
in: (col: string, val: unknown) => {
filters[col] = val
return chain
},
// touchInFlight terminates with .select('id')
select: async () => {
recorded.deliveryUpdates.push(rec)
const id = filters.id as string
const lost = opts.lostOwnership?.has(id) ?? false
return { data: lost ? [] : [{ id }], error: null }
},
// markDelivered / markDead / markFailedForRetry await the chain
then: (resolve: (v: { error: null }) => unknown) => {
recorded.deliveryUpdates.push(rec)
return resolve({ error: null })
},
}
return chain
},
}
}
if (table === 'webhooks') {
return {
select: () => ({
in: async () => ({
data: [
{
id: WEBHOOK_ID,
company_id: COMPANY_ID,
webhook_url: 'https://receiver.example.com/hook',
secret: 'whsec_test',
},
],
error: null,
}),
}),
}
}
throw new Error(`unexpected table: ${table}`)
}),
} as unknown as SupabaseClient
return { client, recorded }
}
/** Receiver answers 200 and records which delivery ids were actually POSTed. */
function makeOkFetch(postedIds: string[]) {
return async (
_url: string,
init: { headers: Record<string, string> },
): Promise<PinnedFetchResult> => {
postedIds.push(init.headers['X-Gnubok-Delivery'])
return {
kind: 'ok',
status: 200,
headers: { 'content-type': 'application/json' },
body: '{"ok":true}',
bodyTruncated: false,
pinnedAddress: '93.184.216.34',
}
}
}
function recoverArgs(recorded: Recorded): Record<string, unknown> {
const call = recorded.rpcCalls.find((c) => c.fn === 'recover_stuck_webhook_deliveries')
if (!call) throw new Error('recover_stuck_webhook_deliveries was never called')
return call.args
}
describe('dispatcher stuck-in_flight recovery window', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('derives a window wider than one bounded cycle, so a mid-cycle row cannot be swept', async () => {
const { client, recorded } = makeSupabase()
await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch([]) as never,
})
const args = recoverArgs(recorded)
const windowMs = NOW.getTime() - Date.parse(args.p_stuck_before as string)
// The cycle budget (what actually bounds a cycle, whatever its batch size)
// plus one in-flight request plus slack. Spelled out as a literal as well
// as a derivation so a change to any constant has to be deliberate.
expect(windowMs).toBe(160_000)
expect(windowMs).toBe(
__TESTING__.CYCLE_BUDGET_MS +
__TESTING__.REQUEST_TIMEOUT_MS +
__TESTING__.STUCK_RECOVERY_SLACK_MS,
)
// The old threshold. A concurrent tick must no longer be able to re-arm a
// row that a live cycle claimed only a couple of attempts ago.
expect(windowMs).toBeGreaterThan(__TESTING__.REQUEST_TIMEOUT_MS * 2)
// And it must cover the whole bounded cycle, not just part of it.
expect(windowMs).toBeGreaterThan(__TESTING__.CYCLE_BUDGET_MS)
expect(args.p_now).toBe(NOW.toISOString())
})
it('uses the same window for the 5-row kick as for the 50-row cron', async () => {
const windows: number[] = []
for (const batchSize of [5, __TESTING__.DEFAULT_BATCH_SIZE, 500]) {
const { client, recorded } = makeSupabase()
await dispatchDueDeliveries({
supabase: client,
batchSize,
now: NOW,
pinnedFetchImpl: makeOkFetch([]) as never,
})
windows.push(NOW.getTime() - Date.parse(recoverArgs(recorded).p_stuck_before as string))
}
// The sweep is tenant-global, so a small batch must not shrink the window
// and a large one must not stretch it: the cycle budget bounds every
// caller alike. A batch-derived window (the pre-#1257 shape, and the shape
// a "floor at DEFAULT_BATCH_SIZE" would silently allow again above 50)
// would produce 50_000 here for the kick and 160_000 for the cron.
expect(windows).toEqual([160_000, 160_000, 160_000])
})
it('hands the attempts cap and the retry schedule to the RPC', async () => {
const { client, recorded } = makeSupabase()
await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch([]) as never,
})
const args = recoverArgs(recorded)
// The cap stays single-sourced in TS; the increment happens in SQL, which
// is the only place `attempts = attempts + 1` can be expressed atomically.
expect(args.p_max_attempts).toBe(__TESTING__.MAX_ATTEMPTS)
expect(__TESTING__.MAX_ATTEMPTS).toBe(8)
// And so does the backoff: a swept row must wait exactly as long as a row
// whose receiver answered 500. Re-arming at p_now let a repeatedly
// stranded delivery spend all 8 attempts inside half an hour and land in
// the terminal, immutable 'dead' state without ever being contacted.
expect(args.p_backoff).toEqual([...__TESTING__.RETRY_BACKOFF_SECONDS])
expect(args.p_backoff).toEqual([60, 300, 1800, 7200, 43200, 86400, 172800])
})
it('surfaces the sweep outcome in the summary, dead rows separately', async () => {
const { client } = makeSupabase({
recovered: [
{ id: DELIVERY_IDS[0], status: 'failed', attempts: 2 },
{ id: DELIVERY_IDS[1], status: 'dead', attempts: 8 },
{ id: DELIVERY_IDS[2], status: 'dead', attempts: 8 },
],
})
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch([]) as never,
})
// A tick that takes deliveries terminal has to be visible in the cron's
// own summary line, not only in a helper-level log.warn.
expect(summary.recovered).toBe(3)
expect(summary.recoveredDead).toBe(2)
})
})
describe('dispatcher per-row in_flight re-stamp', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('re-stamps each row immediately before its own attempt, not once at claim time', async () => {
const { client, recorded } = makeSupabase({ deliveryCount: 3 })
const posted: string[] = []
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch(posted) as never,
})
expect(summary.delivered).toBe(3)
expect(posted).toEqual(DELIVERY_IDS)
// touch, terminal, touch, terminal, touch, terminal. A single re-stamp at
// claim time (the pre-fix behaviour) would leave only the three terminal
// writes here, and rows 2 and 3 would carry the claim's updated_at into
// the next cycle's sweep window.
expect(recorded.deliveryUpdates).toHaveLength(6)
for (let i = 0; i < 3; i++) {
const touch = recorded.deliveryUpdates[i * 2]
expect(touch.payload).toEqual({ status: 'in_flight' })
expect(touch.filters).toEqual({ id: DELIVERY_IDS[i], status: 'in_flight' })
const terminal = recorded.deliveryUpdates[i * 2 + 1]
expect(terminal.payload).toMatchObject({ status: 'delivered' })
expect(terminal.filters).toEqual({ id: DELIVERY_IDS[i] })
}
})
it('drops the POST when the touch shows the row is no longer ours', async () => {
const { client, recorded } = makeSupabase({
deliveryCount: 3,
lostOwnership: new Set([DELIVERY_IDS[1]]),
})
const posted: string[] = []
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch(posted) as never,
})
// The duplicate POST is what the issue calls avoidable load: the loser of
// the race would have had its terminal write swallowed by the immutability
// trigger anyway.
expect(posted).toEqual([DELIVERY_IDS[0], DELIVERY_IDS[2]])
expect(posted).not.toContain(DELIVERY_IDS[1])
expect(summary.skipped).toBe(1)
expect(summary.delivered).toBe(2)
// No terminal write for the row we no longer own.
const terminalForRow2 = recorded.deliveryUpdates.filter(
(u) => u.filters.id === DELIVERY_IDS[1] && u.payload.status !== 'in_flight',
)
expect(terminalForRow2).toHaveLength(0)
})
it('reconciles the summary: picked === delivered + failed + dead + skipped + released', async () => {
const { client } = makeSupabase({
deliveryCount: 3,
lostOwnership: new Set([DELIVERY_IDS[2]]),
})
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch([]) as never,
})
expect(summary.picked).toBe(3)
expect(
summary.delivered + summary.failed + summary.dead + summary.skipped + summary.released,
).toBe(summary.picked)
})
})
describe('dispatcher cycle budget', () => {
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
vi.restoreAllMocks()
})
it('hands back unattempted claims instead of stranding them in in_flight', async () => {
const { client, recorded } = makeSupabase({ deliveryCount: 3 })
const posted: string[] = []
// `Date.now` is the dispatcher's only real-clock read (the injected `now`
// covers everything else), so driving it directly is enough to simulate a
// receiver that ate the whole budget on the first row.
let clock = 1_000_000
vi.spyOn(Date, 'now').mockImplementation(() => clock)
const slowFetch = async (
_url: string,
init: { headers: Record<string, string> },
): Promise<PinnedFetchResult> => {
posted.push(init.headers['X-Gnubok-Delivery'])
clock += __TESTING__.CYCLE_BUDGET_MS
return {
kind: 'ok',
status: 200,
headers: { 'content-type': 'application/json' },
body: '{"ok":true}',
bodyTruncated: false,
pinnedAddress: '93.184.216.34',
}
}
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: slowFetch as never,
})
// Row 1 fits, rows 2 and 3 do not: they are released, not POSTed.
expect(posted).toEqual([DELIVERY_IDS[0]])
expect(summary.delivered).toBe(1)
expect(summary.released).toBe(2)
expect(summary.picked).toBe(3)
// Released rows go back to a re-claimable state immediately. Without this
// they would sit in in_flight for the full 160 s window before any sweep
// could re-arm them, and the sweep would then charge them an attempt they
// never made.
//
// 'pending', not 'failed': these rows carry attempts = 0, so they had
// never been attempted and their pre-claim status was necessarily
// 'pending'. webhook_deliveries is customer-visible behandlingshistorik;
// a delivery that was claimed and handed back without a single POST must
// not read as a failure there.
const release = recorded.deliveryUpdates.at(-1)
expect(release?.payload).toEqual({
status: 'pending',
next_attempt_at: NOW.toISOString(),
})
expect(release?.filters).toEqual({
id: [DELIVERY_IDS[1], DELIVERY_IDS[2]],
status: 'in_flight',
})
// Not an attempt: `attempts` must not be bumped and the previous attempt's
// diagnostic must survive.
expect(release?.payload).not.toHaveProperty('attempts')
expect(release?.payload).not.toHaveProperty('error')
})
it('releases a previously attempted row back to failed, not pending', async () => {
const { client, recorded } = makeSupabase({ deliveryCount: 3, attempts: 2 })
const posted: string[] = []
let clock = 1_000_000
vi.spyOn(Date, 'now').mockImplementation(() => clock)
const slowFetch = async (
_url: string,
init: { headers: Record<string, string> },
): Promise<PinnedFetchResult> => {
posted.push(init.headers['X-Gnubok-Delivery'])
clock += __TESTING__.CYCLE_BUDGET_MS
return {
kind: 'ok',
status: 200,
headers: { 'content-type': 'application/json' },
body: '{"ok":true}',
bodyTruncated: false,
pinnedAddress: '93.184.216.34',
}
}
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: slowFetch as never,
})
expect(summary.released).toBe(2)
// attempts > 0 means the row was already in the retry loop before this
// cycle claimed it, so 'failed' is its real pre-claim status.
const release = recorded.deliveryUpdates.at(-1)
expect(release?.payload).toEqual({
status: 'failed',
next_attempt_at: NOW.toISOString(),
})
})
})
@@ -1,29 +0,0 @@
/**
* registerWebhookHandler() must subscribe to exactly the catalogue in
* lib/webhooks/public-events.ts: an event an agent can subscribe to via the
* API but that the handler never fans out would be silently undeliverable.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn(() => ({ __client: true })),
}))
vi.mock('next/server', () => ({ after: vi.fn() }))
import { eventBus } from '@/lib/events/bus'
import { registerWebhookHandler } from '../handler'
import { PUBLIC_WEBHOOK_EVENTS } from '../public-events'
describe('registerWebhookHandler', () => {
beforeEach(() => {
eventBus.clear()
vi.clearAllMocks()
})
it('subscribes to every catalogued event type and nothing else', () => {
const on = vi.spyOn(eventBus, 'on')
registerWebhookHandler()
const subscribed = on.mock.calls.map(([eventType]) => eventType).sort()
expect(subscribed).toEqual([...PUBLIC_WEBHOOK_EVENTS].sort())
})
})
-271
View File
@@ -1,271 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { EventEmitter } from 'node:events'
import type { ClientRequest, IncomingMessage } from 'node:http'
import type { RequestOptions } from 'node:https'
import { pinnedHttpsFetch } from '@/lib/webhooks/pinned-fetch'
// Stand up a minimal stub for node:https.request that captures the args
// we want to assert on (pinned IP, SNI, Host header) and lets us synthesise
// a controlled response back to the caller.
function makeStubRequest(args: {
status: number
headers?: Record<string, string>
body?: string
emitError?: Error
emitTimeout?: boolean
}) {
const captured: {
options: RequestOptions | null
bodyWritten: string
} = { options: null, bodyWritten: '' }
const fakeRequest = (
options: RequestOptions,
callback: (res: IncomingMessage) => void,
): ClientRequest => {
captured.options = options
const req = new EventEmitter() as ClientRequest & EventEmitter
// ClientRequest API surface we touch in pinned-fetch:
req.write = ((chunk: string) => {
captured.bodyWritten += chunk
return true
}) as ClientRequest['write']
req.end = (() => {
// Dispatch the response (or error) asynchronously to mimic real
// network timing: pinned-fetch attaches handlers BEFORE end().
queueMicrotask(() => {
if (args.emitError) {
req.emit('error', args.emitError)
return
}
if (args.emitTimeout) {
req.emit('timeout')
return
}
const res = new EventEmitter() as IncomingMessage & EventEmitter
;(res as unknown as { statusCode: number }).statusCode = args.status
;(res as unknown as { headers: Record<string, string> }).headers =
args.headers ?? { 'content-type': 'application/json' }
// IncomingMessage stubs need stream-shaped methods that pinned-fetch
// calls (resume on redirect-drain, destroy on size truncation).
;(res as unknown as { resume: () => unknown }).resume = () => {
/* no-op: body is already buffered in args.body */
}
;(res as unknown as { destroy: () => unknown }).destroy = () => {
// Truncation path: emit `close` so finalize() runs.
queueMicrotask(() => res.emit('close'))
}
callback(res)
// Emit body bytes then `end`.
queueMicrotask(() => {
if (args.body) res.emit('data', Buffer.from(args.body, 'utf8'))
res.emit('end')
})
})
return req
}) as ClientRequest['end']
req.destroy = (() => {
// no-op: tests don't read the socket after destroy.
return req
}) as ClientRequest['destroy']
req.setTimeout = (() => req) as ClientRequest['setTimeout']
return req
}
return { captured, fakeRequest }
}
function makeStubValidator(addresses: string[]) {
return vi.fn(async () => ({
ok: true as const,
hostname: 'example.com',
resolvedAddresses: addresses,
}))
}
describe('pinnedHttpsFetch', () => {
it('pins the socket to the validated IP while keeping SNI + Host on the hostname', async () => {
const { captured, fakeRequest } = makeStubRequest({
status: 200,
body: 'ok',
})
const result = await pinnedHttpsFetch(
'https://example.com/hooks',
{
method: 'POST',
headers: { 'X-Gnubok-Event': 'invoice.paid' },
body: '{"hello":"world"}',
timeoutMs: 1000,
maxResponseBytes: 1024,
},
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(result.kind).toBe('ok')
if (result.kind !== 'ok') throw new Error('unreachable')
expect(result.status).toBe(200)
expect(result.body).toBe('ok')
expect(result.pinnedAddress).toBe('203.0.113.42')
// Socket goes to the IP: DNS does not re-resolve.
expect(captured.options?.host).toBe('203.0.113.42')
// SNI carries the hostname so the receiver's TLS cert validates.
expect(captured.options?.servername).toBe('example.com')
// HTTP Host header carries the hostname for vhost routing.
const headers = captured.options?.headers as Record<string, string>
expect(headers.host).toBe('example.com')
// Custom dispatcher header survives.
expect(headers['X-Gnubok-Event']).toBe('invoice.paid')
expect(captured.bodyWritten).toBe('{"hello":"world"}')
})
it('includes the port in the Host header when non-default', async () => {
const { captured, fakeRequest } = makeStubRequest({ status: 204 })
await pinnedHttpsFetch(
'https://example.com:8443/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(captured.options?.port).toBe(8443)
const headers = captured.options?.headers as Record<string, string>
expect(headers.host).toBe('example.com:8443')
})
it('returns unsafe_url when validation rejects the hostname', async () => {
const { fakeRequest } = makeStubRequest({ status: 200 })
const spyRequest = vi.fn(fakeRequest)
const validator = vi.fn(async () => ({
ok: false as const,
reason: 'private_address' as const,
detail: '10.0.0.1 is private',
}))
const result = await pinnedHttpsFetch(
'https://internal.example/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{ validateUrl: validator, httpsRequest: spyRequest },
)
expect(result.kind).toBe('unsafe_url')
if (result.kind === 'unsafe_url') {
expect(result.reason).toBe('private_address')
expect(result.pinnedAddress).toBeNull()
}
// Critically: we never opened a socket.
expect(spyRequest).not.toHaveBeenCalled()
})
it('treats 3xx responses as redirect_blocked', async () => {
const { fakeRequest } = makeStubRequest({
status: 302,
headers: { location: 'https://elsewhere.example/' },
})
const result = await pinnedHttpsFetch(
'https://example.com/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(result.kind).toBe('redirect_blocked')
if (result.kind === 'redirect_blocked') {
expect(result.status).toBe(302)
expect(result.pinnedAddress).toBe('203.0.113.42')
}
})
it('maps transport errors to transport_error', async () => {
const { fakeRequest } = makeStubRequest({
status: 0,
emitError: new Error('ECONNREFUSED 203.0.113.42:443'),
})
const result = await pinnedHttpsFetch(
'https://example.com/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(result.kind).toBe('transport_error')
if (result.kind === 'transport_error') {
expect(result.detail).toContain('ECONNREFUSED')
expect(result.pinnedAddress).toBe('203.0.113.42')
}
})
it('maps timeout events to timeout', async () => {
const { fakeRequest } = makeStubRequest({
status: 0,
emitTimeout: true,
})
const result = await pinnedHttpsFetch(
'https://example.com/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(result.kind).toBe('timeout')
})
it('truncates response body at maxResponseBytes', async () => {
const big = 'x'.repeat(10_000)
const { fakeRequest } = makeStubRequest({
status: 200,
headers: { 'content-type': 'text/plain' },
body: big,
})
const result = await pinnedHttpsFetch(
'https://example.com/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 100 },
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(result.kind).toBe('ok')
if (result.kind === 'ok') {
expect(result.body.length).toBe(100)
expect(result.bodyTruncated).toBe(true)
}
})
it('picks the first resolved IP deterministically', async () => {
const { captured, fakeRequest } = makeStubRequest({ status: 200 })
await pinnedHttpsFetch(
'https://example.com/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{
validateUrl: makeStubValidator(['203.0.113.42', '198.51.100.55']),
httpsRequest: fakeRequest,
},
)
// First entry, not the second, not random.
expect(captured.options?.host).toBe('203.0.113.42')
})
})
@@ -1,47 +0,0 @@
/**
* The webhook event catalogue (lib/webhooks/public-events.ts) is the single
* source for three surfaces that used to be hand-copied and drifted (24 vs
* 28 events): the v1 create schema (and so the OpenAPI spec and the generated
* agent skill), the docs page, and the fan-out handler. These tests pin each
* surface back to the catalogue so a re-hardcoded list fails CI.
*/
import { describe, expect, it } from 'vitest'
import { PUBLIC_WEBHOOK_EVENTS, PUBLIC_WEBHOOK_EVENT_GROUPS } from '../public-events'
import { WEBHOOKS_MD } from '@/lib/docs/content/webhooks'
import { generateOpenApiSpec } from '@/lib/api/v1/registry'
// Side-effect import: populates the endpoint registry from every route file.
import '@/lib/api/v1/load-routes'
describe('public webhook event catalogue', () => {
it('has no duplicate event types and no empty groups', () => {
expect(new Set(PUBLIC_WEBHOOK_EVENTS).size).toBe(PUBLIC_WEBHOOK_EVENTS.length)
for (const group of PUBLIC_WEBHOOK_EVENT_GROUPS) expect(group.events.length).toBeGreaterThan(0)
})
it('includes the reconciliation events the handler delivers', () => {
expect(PUBLIC_WEBHOOK_EVENTS).toEqual(
expect.arrayContaining([
'reconciliation.matched',
'reconciliation.unmatched',
'reconciliation.signed_off',
'reconciliation.reopened',
]),
)
})
it('is exactly the event_type enum the v1 create endpoint advertises in the OpenAPI spec', () => {
const spec = generateOpenApiSpec('https://unit.test')
const op = (spec.paths['/api/v1/companies/{companyId}/webhooks'] as Record<string, unknown>).post as {
requestBody: { content: Record<string, { schema: { properties: Record<string, { enum?: unknown[] }> } }> }
}
const enumValues = op.requestBody.content['application/json'].schema.properties.event_type.enum
expect(enumValues).toEqual([...PUBLIC_WEBHOOK_EVENTS])
})
it('is exactly the list the docs page renders', () => {
const section = WEBHOOKS_MD.split('## Event types')[1]?.split('## Payload shape')[0] ?? ''
const documented = [...section.matchAll(/^- `([a-z_]+\.[a-z_]+)`/gm)].map((m) => m[1])
expect(documented).toEqual([...PUBLIC_WEBHOOK_EVENTS])
for (const group of PUBLIC_WEBHOOK_EVENT_GROUPS) expect(section).toContain(`**${group.title}**`)
})
})
File diff suppressed because it is too large Load Diff
@@ -1,261 +0,0 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool } from '@/tests/pg/setup'
import { seedCompany } from '@/tests/pg/fixtures'
// Verifies the three webhook-substrate DB guards shipped in Phase 6 PR-1:
// - enforce_webhook_delivery_immutability (BEFORE UPDATE)
// - block_webhook_delivery_terminal_delete (BEFORE DELETE)
// - assert_webhook_delivery_company_match (BEFORE INSERT)
//
// CLAUDE.md ("Migration Rules" + Testing section) mandates a *.pg.test.ts
// for any PR that touches a trigger / RPC / RLS / DEFERRABLE constraint.
// PR-1 (#496) shipped the triggers without the accompanying pg test; this
// closes that test debt.
async function insertWebhook(params: {
// userId kept in the signature for parity with seedCompany's return: the
// webhooks table itself has no user_id column (see route comment in
// app/api/v1/companies/[companyId]/webhooks/route.ts).
userId: string
companyId: string
eventType?: string
}): Promise<string> {
void params.userId
const id = randomUUID()
await getPool().query(
`INSERT INTO public.webhooks
(id, company_id, name, event_type, webhook_url, secret, active)
VALUES ($1, $2, 'pg-test', $3, 'https://example.com/hook', $4, true)`,
[
id,
params.companyId,
params.eventType ?? 'invoice.paid',
`whsec_${randomUUID().replace(/-/g, '')}`,
],
)
return id
}
async function insertDelivery(params: {
webhookId: string | null
companyId: string
status?: 'pending' | 'in_flight' | 'delivered' | 'failed' | 'dead'
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at)
VALUES ($1, $2, $3, 'invoice.paid', '{"hello":"world"}'::jsonb,
'2026-05-12', $4, now())`,
[id, params.webhookId, params.companyId, params.status ?? 'pending'],
)
return id
}
describe('webhook_deliveries triggers: immutability + DELETE block', () => {
// The lifecycle that dispatcher.ts depends on must remain mutable:
// pending → in_flight (claim), in_flight → failed (retry-pending),
// failed → in_flight (re-claim). Only `delivered` and `dead` are
// terminal and locked.
it('allows pending → in_flight (claim) transition', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'pending' })
const result = await getPool().query(
`UPDATE public.webhook_deliveries SET status = 'in_flight' WHERE id = $1`,
[deliveryId],
)
expect(result.rowCount).toBe(1)
})
it('allows in_flight → failed (retry-pending) transition', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'in_flight' })
const result = await getPool().query(
`UPDATE public.webhook_deliveries SET status = 'failed', attempts = 1 WHERE id = $1`,
[deliveryId],
)
expect(result.rowCount).toBe(1)
})
it('allows failed → in_flight (re-claim) transition', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'failed' })
const result = await getPool().query(
`UPDATE public.webhook_deliveries SET status = 'in_flight' WHERE id = $1`,
[deliveryId],
)
expect(result.rowCount).toBe(1)
})
it('allows in_flight → delivered (success terminal) transition', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'in_flight' })
const result = await getPool().query(
`UPDATE public.webhook_deliveries
SET status = 'delivered', delivered_at = now(), response_status = 200
WHERE id = $1`,
[deliveryId],
)
expect(result.rowCount).toBe(1)
})
it('rejects UPDATE on a delivered row (status flip-back blocked)', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'delivered' })
await expect(
getPool().query(
`UPDATE public.webhook_deliveries SET status = 'pending' WHERE id = $1`,
[deliveryId],
),
).rejects.toThrow(/terminal status \(delivered\) is immutable/i)
})
it('rejects UPDATE on a dead row (response rewrite blocked)', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'dead' })
await expect(
getPool().query(
`UPDATE public.webhook_deliveries
SET response_body = 'tampered' WHERE id = $1`,
[deliveryId],
),
).rejects.toThrow(/terminal status \(dead\) is immutable/i)
})
it('rejects DELETE on a delivered row', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'delivered' })
await expect(
getPool().query(
`DELETE FROM public.webhook_deliveries WHERE id = $1`,
[deliveryId],
),
).rejects.toThrow(/terminal status \(delivered\) cannot be deleted/i)
})
it('rejects DELETE on a dead row', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'dead' })
await expect(
getPool().query(
`DELETE FROM public.webhook_deliveries WHERE id = $1`,
[deliveryId],
),
).rejects.toThrow(/terminal status \(dead\) cannot be deleted/i)
})
// Non-terminal rows are still deletable: the queue-cleanup path
// (operator clears a stuck pending row, dev environment wipes,
// companies CASCADE delete) keeps working.
it('allows DELETE on a pending row', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'pending' })
const result = await getPool().query(
`DELETE FROM public.webhook_deliveries WHERE id = $1`,
[deliveryId],
)
expect(result.rowCount).toBe(1)
})
})
describe('webhook_deliveries triggers: cross-tenant INSERT guard', () => {
it('rejects INSERT when delivery.company_id != webhooks.company_id', async () => {
// Tenant A owns the webhook; tenant B owns the company on the
// delivery row. A compromised service-role caller (or future bug)
// attempting to enqueue a delivery against another tenant's webhook
// is refused at write time: closes cases (a) (cross-tenant
// visibility) and (c) (existence leak) flagged in migration
// 20260515190000's comment.
const a = await seedCompany()
const b = await seedCompany()
const webhookId = await insertWebhook({ userId: a.userId, companyId: a.companyId })
await expect(
getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at)
VALUES (gen_random_uuid(), $1, $2, 'invoice.paid',
'{"hello":"world"}'::jsonb, '2026-05-12', 'pending', now())`,
[webhookId, b.companyId],
),
).rejects.toThrow(/company_id .+ does not match parent webhooks\.company_id/i)
})
it('accepts INSERT when delivery.company_id == webhooks.company_id', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const result = await getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at)
VALUES (gen_random_uuid(), $1, $2, 'invoice.paid',
'{"hello":"world"}'::jsonb, '2026-05-12', 'pending', now())
RETURNING id`,
[webhookId, companyId],
)
expect(result.rowCount).toBe(1)
})
it('allows INSERT with webhook_id IS NULL (dangling row after webhook delete)', async () => {
// ON DELETE SET NULL on the FK leaves these rows after a webhook is
// deleted. New inserts with webhook_id IS NULL aren't a normal write
// path (the handler never inserts a null webhook_id) but the trigger
// explicitly bypasses the check rather than blocking: leaving room
// for an admin-side audit-replay tool that recreates an archived
// delivery for forensic export.
const { companyId } = await seedCompany()
const result = await getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at)
VALUES (gen_random_uuid(), NULL, $1, 'invoice.paid',
'{"hello":"world"}'::jsonb, '2026-05-12', 'pending', now())
RETURNING id`,
[companyId],
)
expect(result.rowCount).toBe(1)
})
it('rejects INSERT pointing at a non-existent webhook_id', async () => {
// Bypass-check path: the trigger early-returns when the parent
// lookup yields NULL so the FK constraint surfaces the bad
// reference rather than the more-confusing company_match error.
// This test pins the FK-error pathway.
const { companyId } = await seedCompany()
const ghostWebhookId = randomUUID()
await expect(
getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at)
VALUES (gen_random_uuid(), $1, $2, 'invoice.paid',
'{"hello":"world"}'::jsonb, '2026-05-12', 'pending', now())`,
[ghostWebhookId, companyId],
),
).rejects.toThrow(/webhook_deliveries_webhook_id_fkey|foreign key/i)
})
})