fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Tests for the per-minute webhook dispatch cron (#1257).
|
||||
*
|
||||
* The route is a thin wrapper, so there is exactly one thing here that is not
|
||||
* covered by lib/webhooks/__tests__: the function budget. The dispatcher's
|
||||
* CYCLE_BUDGET_MS is what hands unattempted claims back before a cycle ends,
|
||||
* and the 160 s stuck-recovery window is derived from it. Both are only real
|
||||
* if the platform grants the invocation more wall time than the budget spends,
|
||||
* which is what `export const maxDuration` buys. Without it the route runs on
|
||||
* the platform default, the release path can be killed before it fires, and
|
||||
* rows stay stranded in in_flight carrying their claim-time updated_at.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { verifyCronSecret } from '@/lib/auth/cron'
|
||||
import { __TESTING__ } from '@/lib/webhooks/dispatcher'
|
||||
|
||||
vi.mock('@/lib/auth/cron', () => ({
|
||||
verifyCronSecret: vi.fn(() => null),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', () => ({
|
||||
createServiceClientNoCookies: vi.fn(() => ({ __client: true })),
|
||||
}))
|
||||
|
||||
const dispatchDueDeliveries = vi.fn()
|
||||
vi.mock('@/lib/webhooks/dispatcher', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/webhooks/dispatcher')>()
|
||||
return {
|
||||
...actual,
|
||||
dispatchDueDeliveries: (...args: unknown[]) => dispatchDueDeliveries(...args),
|
||||
}
|
||||
})
|
||||
|
||||
import { GET, maxDuration } from '../route'
|
||||
|
||||
function cronRequest(): Request {
|
||||
return new Request('http://localhost:3000/api/webhooks/dispatch/cron')
|
||||
}
|
||||
|
||||
const SUMMARY = {
|
||||
picked: 3,
|
||||
delivered: 1,
|
||||
failed: 1,
|
||||
dead: 1,
|
||||
skipped: 0,
|
||||
released: 0,
|
||||
recovered: 2,
|
||||
recoveredDead: 1,
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(verifyCronSecret).mockReturnValue(null)
|
||||
dispatchDueDeliveries.mockResolvedValue(SUMMARY)
|
||||
})
|
||||
|
||||
describe('GET /api/webhooks/dispatch/cron', () => {
|
||||
it('declares a function budget above the dispatcher cycle budget', () => {
|
||||
expect(maxDuration).toBe(300)
|
||||
// The load-bearing relation, not just the literal: the in-code budget can
|
||||
// only hand claims back if the invocation is still alive when it expires.
|
||||
expect(maxDuration * 1000).toBeGreaterThan(__TESTING__.CYCLE_BUDGET_MS)
|
||||
// And the sweep window has to fit inside the invocation too, otherwise the
|
||||
// window is derived from a bound nothing enforces.
|
||||
expect(maxDuration * 1000).toBeGreaterThan(
|
||||
__TESTING__.CYCLE_BUDGET_MS +
|
||||
__TESTING__.REQUEST_TIMEOUT_MS +
|
||||
__TESTING__.STUCK_RECOVERY_SLACK_MS,
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 401 and dispatches nothing when the cron secret is invalid', async () => {
|
||||
vi.mocked(verifyCronSecret).mockReturnValueOnce(
|
||||
NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
)
|
||||
|
||||
const response = await GET(cronRequest())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(dispatchDueDeliveries).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns the full dispatch summary, including the sweep outcome', async () => {
|
||||
const response = await GET(cronRequest())
|
||||
expect(response.status).toBe(200)
|
||||
|
||||
const body = (await response.json()) as { data: typeof SUMMARY }
|
||||
// recovered / recoveredDead are the counts an operator needs to see that a
|
||||
// tick took deliveries to the terminal, immutable 'dead' state.
|
||||
expect(body.data).toEqual(SUMMARY)
|
||||
expect(dispatchDueDeliveries).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* GET /api/webhooks/dispatch/cron: per-minute webhook delivery dispatcher.
|
||||
*
|
||||
* Picks up due deliveries (pending or retry-due failed) and POSTs them to
|
||||
* their configured receivers. Each cycle handles up to 50 deliveries; with
|
||||
* the per-minute cadence this gives 3000/h headroom before deliveries start
|
||||
* to backlog. Bumps to a higher batch size or moves to a queue worker
|
||||
* (Vercel Queues, on the post-Phase-6 roadmap) are the migration path.
|
||||
*
|
||||
* Authenticated via CRON_SECRET (Authorization: Bearer ...). The route
|
||||
* returns the dispatch summary in the response body so an operator can grep
|
||||
* Vercel logs to see how many succeeded / failed / went dead per tick.
|
||||
*/
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withCronContext } from '@/lib/api/with-cron-context'
|
||||
import { dispatchDueDeliveries } from '@/lib/webhooks/dispatcher'
|
||||
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
|
||||
/**
|
||||
* Vercel function budget. Must stay comfortably above the dispatcher's own
|
||||
* CYCLE_BUDGET_MS (120 s, lib/webhooks/dispatcher.ts): the in-code budget is
|
||||
* what hands unattempted claims back before the loop ends, and it can only do
|
||||
* that if the platform has not already killed the invocation. Without this
|
||||
* export the route would run on the platform default, the budget check at
|
||||
* 110 s could never fire, and the 160 s stuck-recovery window would be derived
|
||||
* from a bound nothing enforces (#1257).
|
||||
*
|
||||
* Overlap with the per-minute schedule is expected and safe: claims are
|
||||
* FOR UPDATE SKIP LOCKED and every attempt re-checks ownership before POSTing.
|
||||
*/
|
||||
export const maxDuration = 300
|
||||
|
||||
export const GET = withCronContext('cron.webhook_dispatch', async (_request, ctx) => {
|
||||
const supabase = createServiceClientNoCookies()
|
||||
const summary = await dispatchDueDeliveries({ supabase })
|
||||
|
||||
ctx.log.info('webhook dispatch cycle complete', {
|
||||
picked: summary.picked,
|
||||
delivered: summary.delivered,
|
||||
failed: summary.failed,
|
||||
dead: summary.dead,
|
||||
skipped: summary.skipped,
|
||||
released: summary.released,
|
||||
// The sweep's own outcome. recoveredDead > 0 means this tick took
|
||||
// deliveries to the terminal, immutable 'dead' state: alertable.
|
||||
recovered: summary.recovered,
|
||||
recoveredDead: summary.recoveredDead,
|
||||
})
|
||||
|
||||
return NextResponse.json({ data: summary })
|
||||
})
|
||||
@@ -0,0 +1,164 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const rpcMock = vi.fn()
|
||||
const maybeSingleMock = vi.fn()
|
||||
const fromMock = vi.fn()
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: () => ({
|
||||
rpc: (...args: unknown[]) => rpcMock(...args),
|
||||
from: (...args: unknown[]) => fromMock(...args),
|
||||
}),
|
||||
}))
|
||||
|
||||
const fetchMock = vi.fn<typeof fetch>()
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const SECRET = 'shared-secret-1234567890'
|
||||
const ENV = {
|
||||
QVALIA_API_KEY: 'k',
|
||||
QVALIA_PARTNER_REG_NO: 'SE5560000000',
|
||||
QVALIA_BASE_URL: 'https://api-qa.qvalia.com',
|
||||
QVALIA_WEBHOOK_SECRET: SECRET,
|
||||
}
|
||||
|
||||
const delivered = {
|
||||
eventType: 'document_delivery',
|
||||
accountRegNo: 'SE5560000000',
|
||||
documentType: 'Invoice',
|
||||
direction: 'outgoing',
|
||||
integrationId: 'int-1',
|
||||
occurredAt: '2026-08-19T09:26:10.104Z',
|
||||
globalTransactionId: 'int-1',
|
||||
status: { status: 'processed', event: 'message-log/update', deliveryMethod: 'peppol', updatedAt: '2026-08-19T09:26:09.881Z' },
|
||||
peppol_metadata: { messageId: 'abc@QVALIA-PSE000094', accessPoint: 'PSE000094' },
|
||||
}
|
||||
|
||||
function request(body: unknown, secret: string | null = SECRET): Request {
|
||||
const headers: Record<string, string> = { 'content-type': 'application/json' }
|
||||
if (secret) headers['X-Accounted-Webhook-Key'] = secret
|
||||
return new Request('http://localhost:3000/api/webhooks/peppol/qvalia', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: typeof body === 'string' ? body : JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
function queryChain(result: { data: unknown; error: unknown }) {
|
||||
const chain = {
|
||||
select: vi.fn(() => chain),
|
||||
eq: vi.fn(() => chain),
|
||||
maybeSingle: maybeSingleMock.mockResolvedValue(result),
|
||||
}
|
||||
return chain
|
||||
}
|
||||
|
||||
describe('POST /api/webhooks/peppol/qvalia', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Object.assign(process.env, ENV)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
rpcMock.mockResolvedValue({ data: { id: 'delivery-1' }, error: null })
|
||||
fromMock.mockReturnValue(queryChain({
|
||||
data: { company_id: 'company-1', idempotency_key: '33333333-3333-4333-8333-333333333333' },
|
||||
error: null,
|
||||
}))
|
||||
// Evidence retrieval: status list, then XML copy.
|
||||
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify([{ uuid: 'int-1', metadata: { status: 'processed' } }]), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}))
|
||||
fetchMock.mockResolvedValueOnce(new Response('<Invoice/>', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/xml' },
|
||||
}))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
for (const key of Object.keys(ENV)) delete process.env[key]
|
||||
})
|
||||
|
||||
it('answers 503 when the webhook secret is not configured', async () => {
|
||||
delete process.env.QVALIA_WEBHOOK_SECRET
|
||||
const response = await POST(request(delivered))
|
||||
expect(response.status).toBe(503)
|
||||
expect(rpcMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('answers 401 for a missing or wrong shared secret and records nothing', async () => {
|
||||
expect((await POST(request(delivered, null))).status).toBe(401)
|
||||
expect((await POST(request(delivered, 'wrong'))).status).toBe(401)
|
||||
expect(rpcMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('answers 400 for a body that is not JSON', async () => {
|
||||
const response = await POST(request('not json'))
|
||||
expect(response.status).toBe(400)
|
||||
expect(rpcMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves the delivery by integrationId, records the verified event and stores evidence', async () => {
|
||||
const response = await POST(request(delivered))
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toEqual({ received: true, recorded: 1, unmatched: 0, failed: 0 })
|
||||
|
||||
expect(fromMock).toHaveBeenCalledWith('peppol_deliveries')
|
||||
const eventCall = rpcMock.mock.calls.find((call) => call[0] === 'record_peppol_delivery_event')
|
||||
expect(eventCall?.[1]).toMatchObject({
|
||||
p_company_id: 'company-1',
|
||||
p_idempotency_key: '33333333-3333-4333-8333-333333333333',
|
||||
p_provider: 'qvalia',
|
||||
p_provider_submission_id: 'int-1',
|
||||
p_provider_event_id: 'document_delivery:int-1:processed',
|
||||
p_normalized_status: 'transport_succeeded',
|
||||
p_is_terminal: false,
|
||||
p_verification_method: 'shared_secret_header',
|
||||
})
|
||||
const evidenceCall = rpcMock.mock.calls.find((call) => call[0] === 'record_peppol_delivery_evidence')
|
||||
expect(evidenceCall?.[1]).toMatchObject({
|
||||
p_company_id: 'company-1',
|
||||
p_provider: 'qvalia',
|
||||
p_evidence_type: 'qvalia_message_record',
|
||||
p_document_payload: '<Invoice/>',
|
||||
})
|
||||
})
|
||||
|
||||
it('acknowledges events for unknown submissions with 200 so Qvalia stops retrying', async () => {
|
||||
fromMock.mockReturnValue(queryChain({ data: null, error: null }))
|
||||
const response = await POST(request(delivered))
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({ received: true, recorded: 0, unmatched: 1, failed: 0 })
|
||||
expect(rpcMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores inbound-direction events and never touches the database for them', async () => {
|
||||
const response = await POST(request({ ...delivered, direction: 'incoming', eventType: 'new_document' }))
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({ received: true, recorded: 0, unmatched: 0, failed: 0 })
|
||||
expect(fromMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('answers 500 when our own persistence fails so Qvalia retries later', async () => {
|
||||
rpcMock.mockResolvedValue({ data: null, error: { message: 'db down' } })
|
||||
const response = await POST(request(delivered))
|
||||
expect(response.status).toBe(500)
|
||||
expect(await response.json()).toMatchObject({ received: true, recorded: 0, failed: 1 })
|
||||
})
|
||||
|
||||
it('keeps the verified event when evidence retrieval fails', async () => {
|
||||
fetchMock.mockReset()
|
||||
fetchMock.mockRejectedValue(new TypeError('fetch failed'))
|
||||
const response = await POST(request(delivered))
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({ received: true, recorded: 1, unmatched: 0, failed: 0 })
|
||||
expect(rpcMock.mock.calls.filter((call) => call[0] === 'record_peppol_delivery_evidence')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import {
|
||||
persistPeppolEvidence,
|
||||
persistVerifiedPeppolEvent,
|
||||
} from '@/lib/invoices/peppol-delivery'
|
||||
import { isPeppolTransportError, type PeppolTransport } from '@/lib/invoices/peppol-transport'
|
||||
import {
|
||||
QVALIA_PROVIDER,
|
||||
createQvaliaTransport,
|
||||
readQvaliaConfigFromEnv,
|
||||
} from '@/lib/invoices/transports/qvalia'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
const log = createLogger('peppol.qvalia.webhook')
|
||||
|
||||
/** Statuses worth fetching the provider's message record for. */
|
||||
const EVIDENCE_STATUSES = new Set([
|
||||
'transport_succeeded',
|
||||
'recipient_acknowledged',
|
||||
'business_accepted',
|
||||
'business_rejected',
|
||||
'failed',
|
||||
])
|
||||
|
||||
/**
|
||||
* POST /api/webhooks/peppol/qvalia
|
||||
*
|
||||
* Unauthenticated by design: Qvalia does not sign webhooks, so authenticity
|
||||
* comes from the shared secret Accounted configured as Qvalia's outbound auth
|
||||
* header (`QVALIA_WEBHOOK_SECRET`), checked constant-time in the adapter. The
|
||||
* raw body is hashed before parsing so every verified event keeps an exact
|
||||
* fingerprint.
|
||||
*
|
||||
* Delivery is at-least-once; the append-only event table dedupes on the
|
||||
* provider event id, so replays are harmless. Unknown submissions answer 200:
|
||||
* they are logged, and a retry would not make them known.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const config = readQvaliaConfigFromEnv()
|
||||
if (!config || !config.webhookSecret) {
|
||||
return NextResponse.json({ error: 'webhook_not_configured' }, { status: 503 })
|
||||
}
|
||||
const transport: PeppolTransport = createQvaliaTransport(config)
|
||||
|
||||
const rawBody = new Uint8Array(await request.arrayBuffer())
|
||||
let events
|
||||
try {
|
||||
events = await transport.verifyWebhook({ headers: request.headers, rawBody })
|
||||
} catch (err) {
|
||||
if (isPeppolTransportError(err) && /secret/i.test(err.message)) {
|
||||
return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
|
||||
}
|
||||
log.warn('Qvalia webhook rejected', { reason: err instanceof Error ? err.message : String(err) })
|
||||
return NextResponse.json({ error: 'invalid_payload' }, { status: 400 })
|
||||
}
|
||||
|
||||
const service = createServiceClient()
|
||||
let recorded = 0
|
||||
let unmatched = 0
|
||||
let failed = 0
|
||||
|
||||
for (const event of events) {
|
||||
if (!event.providerSubmissionId) {
|
||||
unmatched += 1
|
||||
continue
|
||||
}
|
||||
const { data: delivery, error } = await service
|
||||
.from('peppol_deliveries')
|
||||
.select('company_id, idempotency_key')
|
||||
.eq('provider', QVALIA_PROVIDER)
|
||||
.eq('provider_submission_id', event.providerSubmissionId)
|
||||
.maybeSingle()
|
||||
if (error) {
|
||||
failed += 1
|
||||
log.error('Qvalia webhook delivery lookup failed', error, {
|
||||
providerSubmissionId: event.providerSubmissionId,
|
||||
})
|
||||
continue
|
||||
}
|
||||
if (!delivery) {
|
||||
unmatched += 1
|
||||
log.warn('Qvalia webhook for unknown submission', {
|
||||
providerSubmissionId: event.providerSubmissionId,
|
||||
eventCode: event.eventCode,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
await persistVerifiedPeppolEvent({
|
||||
supabase: service,
|
||||
companyId: delivery.company_id as string,
|
||||
event: { ...event, idempotencyKey: delivery.idempotency_key as string },
|
||||
})
|
||||
recorded += 1
|
||||
} catch (err) {
|
||||
failed += 1
|
||||
log.error('Qvalia webhook event persistence failed', err as Error, {
|
||||
providerSubmissionId: event.providerSubmissionId,
|
||||
eventCode: event.eventCode,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
if (EVIDENCE_STATUSES.has(event.normalizedStatus)) {
|
||||
try {
|
||||
const evidence = await transport.retrieveEvidence(event.providerSubmissionId)
|
||||
for (const item of evidence) {
|
||||
await persistPeppolEvidence({
|
||||
supabase: service,
|
||||
companyId: delivery.company_id as string,
|
||||
idempotencyKey: delivery.idempotency_key as string,
|
||||
evidence: item,
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
// Evidence is best-effort: the verified event is already on record.
|
||||
log.warn('Qvalia evidence retrieval failed', {
|
||||
providerSubmissionId: event.providerSubmissionId,
|
||||
reason: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A persistence failure is ours, not Qvalia's: answer 500 so they retry.
|
||||
if (failed > 0 && recorded === 0) {
|
||||
return NextResponse.json({ received: true, recorded, unmatched, failed }, { status: 500 })
|
||||
}
|
||||
return NextResponse.json({ received: true, recorded, unmatched, failed })
|
||||
}
|
||||
Reference in New Issue
Block a user