Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): send queued deliveries with the webhook's current config
Yudhi Armyndharisf5c487561f94
diff --git a/src/modules/queue/processors/webhook.processor.spec.ts b/src/modules/queue/processors/webhook.processor.spec.tsindex e7ef5f45a..8d8a0eede 100644--- a/src/modules/queue/processors/webhook.processor.spec.ts+++ b/src/modules/queue/processors/webhook.processor.spec.ts@@ -8,6 +8,7 @@ import { HookManager } from '../../../core/hooks';import { WebhookJobData } from '../../webhook/webhook.service';import { getWebhookDeliveryFailuresTotal } from '../../../common/metrics/webhook-delivery-metrics';import { fetch as undiciFetch } from 'undici';+import { createHmac } from 'crypto';// Delivery goes through undici's fetch (via the SSRF-pinning helper), so mock that, not global fetch.jest.mock('undici', () => {@@ -22,7 +23,7 @@ jest.mock('undici', () => {*/describe('WebhookProcessor', () => {let processor: WebhookProcessor;- let repo: { update: jest.Mock };+ let repo: { update: jest.Mock; findOne: jest.Mock };let failureRepo: { insert: jest.Mock; count: jest.Mock };let hookManager: { execute: jest.Mock };let configService: { get: jest.Mock };@@ -53,7 +54,11 @@ describe('WebhookProcessor', () => {}) as unknown as Job<WebhookJobData>;beforeEach(() => {- repo = { update: jest.fn().mockResolvedValue({ affected: 1 }) };+ repo = {+ update: jest.fn().mockResolvedValue({ affected: 1 }),+ // The live row matches makeJob()'s snapshot unless a test says otherwise.+ findOne: jest.fn().mockResolvedValue({ id: 'wh-1', active: true, url: 'https://8.8.8.8/hook', events: ['*'] }),+ };// Stateful like the real table: the recorder counts existing rows for the delivery before it// inserts, so a constant would leave that guard unexercised here and let a duplicated row pass.const insertedFailures: Array<{ webhookId?: string; idempotencyKey?: string | null }> = [];@@ -141,6 +146,7 @@ describe('WebhookProcessor', () => {it('persists a durable delivery-failure record on the final attempt (with parsed HTTP status)', async () => {mockFetch.mockResolvedValue({ ok: false, status: 503, statusText: 'Service Unavailable' });+ repo.findOne.mockResolvedValue({ id: 'wh-x', active: true, url: 'https://8.8.8.8/h', events: ['*'] });await expect(processor.process(makeJob({ maxRetries: 3, webhookId: 'wh-x', url: 'https://8.8.8.8/h' }, 2)),@@ -180,6 +186,7 @@ describe('WebhookProcessor', () => {// message — the resolved internal IP is a recon oracle. The server-side logger.error keeps full detail.it('redacts the resolved internal IP from the webhook:error payload and DLQ row on an SSRF block', async () => {process.env.WEBHOOK_SSRF_PROTECT = 'true';+ repo.findOne.mockResolvedValue({ id: 'wh-1', active: true, url: 'https://169.254.169.254/h', events: ['*'] });// final attempt (attemptsMade=0, maxRetries=1 → 1 >= 1) so the hook + DLQ fireawait expect(processor.process(makeJob({ url: 'https://169.254.169.254/h', maxRetries: 1 }, 0))).rejects.toThrow();@@ -214,15 +221,81 @@ describe('WebhookProcessor', () => {expect(hookManager.execute).not.toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());});+ // The job is a snapshot from enqueue time; the operator may have changed the webhook since.+ describe('stale snapshot', () => {+ const live = { id: 'wh-1', active: true, url: 'https://8.8.8.8/hook', events: ['*'] };++ it.each([+ ['deleted', null],+ ['disabled', { ...live, active: false }],+ ['unsubscribed', { ...live, events: ['message.sent'] }],+ ])('does not POST, retry or dead-letter a job for a %s webhook', async (_label, row) => {+ repo.findOne.mockResolvedValue(row);+ mockFetch.mockResolvedValue({ ok: true, status: 200 });++ // Final attempt, so a failure path would file a dead-letter row.+ const result = await processor.process(makeJob({ maxRetries: 3 }, 2));++ expect(result.success).toBe(false);+ expect(mockFetch).not.toHaveBeenCalled();+ expect(failureRepo.insert).not.toHaveBeenCalled();+ expect(hookManager.execute).not.toHaveBeenCalled();+ });++ it('treats a failed webhook read as a failed attempt: retried, and dead-lettered on the last one', async () => {+ repo.findOne.mockRejectedValue(new Error('db down'));++ await expect(processor.process(makeJob({ maxRetries: 3 }, 0))).rejects.toThrow('db down');+ expect(failureRepo.insert).not.toHaveBeenCalled();++ await expect(processor.process(makeJob({ maxRetries: 3 }, 2))).rejects.toThrow('db down');+ expect(mockFetch).not.toHaveBeenCalled();+ expect(failureRepo.insert).toHaveBeenCalledTimes(1);+ });++ it('delivers to the current URL with the current headers and secret, not the enqueue-time ones', async () => {+ repo.findOne.mockResolvedValue({+ ...live,+ url: 'https://8.8.4.4/new',+ events: ['message.received'],+ headers: { Authorization: 'Bearer new' },+ secret: 'rotated',+ });+ mockFetch.mockResolvedValue({ ok: true, status: 200 });+ const job = makeJob({+ headers: {+ 'Content-Type': 'application/json',+ Authorization: 'Bearer old',+ 'X-OpenWA-Signature': 'sha256=old',+ },+ });++ const result = await processor.process(job);++ expect(result.success).toBe(true);+ const [url, init] = mockFetch.mock.calls[0] as unknown as [+ string,+ { headers: Record<string, string>; body: string },+ ];+ expect(url).toBe('https://8.8.4.4/new');+ expect(init.headers.Authorization).toBe('Bearer new');+ const expected = `sha256=${createHmac('sha256', 'rotated').update(init.body).digest('hex')}`;+ expect(init.headers['X-OpenWA-Signature']).toBe(expected);+ expect(init.body).toBe(JSON.stringify(job.data.payload));+ });+ });+// BullMQ fails a job that stalls more than maxStalledCount (default 1) WITHOUT calling process():// the worker emits 'failed' with "job stalled more than allowable limit". Those failures must land// in the same dead-letter/metric/hook channels as an ordinary final-attempt failure.describe('stall exhaustion (worker failed event)', () => {it('records a dead-letter row, metric, and webhook:error for a job failed by a double stall', async () => {const failuresBefore = getWebhookDeliveryFailuresTotal();+ // Re-pointed since enqueue: the row names the URL a retry would have used, not the snapshot's.+ repo.findOne.mockResolvedValue({ id: 'wh-stall', active: true, url: 'https://8.8.8.8/s', events: ['*'] });await processor.onWorkerFailed(- makeJob({ webhookId: 'wh-stall', url: 'https://8.8.8.8/s' }, 1),+ makeJob({ webhookId: 'wh-stall', url: 'https://8.8.8.8/old' }, 1),new Error('job stalled more than allowable limit'),);@@ -245,6 +318,26 @@ describe('WebhookProcessor', () => {expect(getWebhookDeliveryFailuresTotal()).toBe(failuresBefore + 1);});+ it.each([+ ['deleted', null],+ ['disabled', { id: 'wh-1', active: false, url: 'https://8.8.8.8/hook', events: ['*'] }],+ ])('files nothing for a job whose webhook was %s', async (_label, row) => {+ repo.findOne.mockResolvedValue(row);++ await processor.onWorkerFailed(makeJob({}, 1), new Error('job stalled more than allowable limit'));++ expect(failureRepo.insert).not.toHaveBeenCalled();+ expect(hookManager.execute).not.toHaveBeenCalled();+ });++ it('still records the stall against the enqueue-time URL when the webhook row cannot be read', async () => {+ repo.findOne.mockRejectedValue(new Error('db down'));++ await processor.onWorkerFailed(makeJob({}, 1), new Error('job stalled more than allowable limit'));++ expect(failureRepo.insert).toHaveBeenCalledWith(expect.objectContaining({ url: 'https://8.8.8.8/hook' }));+ });+it('ignores ordinary delivery failures — process() already records those on the final attempt', async () => {await processor.onWorkerFailed(makeJob(), new Error('HTTP 500: Server Error'));diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.tsindex 2b44c376f..1abdc055b 100644--- a/src/modules/queue/processors/webhook.processor.ts+++ b/src/modules/queue/processors/webhook.processor.ts@@ -10,7 +10,7 @@ import { WebhookJobData, WebhookPayload } from '../../webhook/webhook.service';import { Webhook } from '../../webhook/entities/webhook.entity';import { WebhookDeliveryFailure } from '../../webhook/entities/webhook-delivery-failure.entity';import { recordWebhookDeliveryFailure, statusCodeFromError } from '../../webhook/utils/record-delivery-failure';-import { postWebhookPayload } from '../../webhook/utils/deliver-once';+import { buildDeliveryHeaders, postWebhookPayload } from '../../webhook/utils/deliver-once';import { HookManager } from '../../../core/hooks';import { redactSsrfError } from '../../../common/security/ssrf-guard';import { incrementWebhookDeliveryFailures } from '../../../common/metrics/webhook-delivery-metrics';@@ -63,7 +63,7 @@ export class WebhookProcessor extends WorkerHost {}async process(job: Job<WebhookJobData>): Promise<WebhookJobResult> {- const { webhookId, url, event, payload, headers, maxRetries } = job.data;+ const { webhookId, event, payload, maxRetries } = job.data;const startTime = Date.now();const sessionId = payload.sessionId;@@ -76,16 +76,49 @@ export class WebhookProcessor extends WorkerHost {action: 'webhook_process_start',});- // Update retry count in headers- const requestHeaders = {- ...headers,- 'X-OpenWA-Retry-Count': String(job.attemptsMade),+ const ctx: WebhookDeliveryContext = {+ job,+ webhookId,+ url: job.data.url,+ event,+ payload,+ maxRetries,+ sessionId,+ startTime,};- const ctx: WebhookDeliveryContext = { job, webhookId, url, event, payload, maxRetries, sessionId, startTime };-try {- const { status, responseTime } = await this.postToReceiver(ctx, requestHeaders);+ // The job carries a snapshot taken at enqueue time. Re-read the row before every attempt: a+ // webhook that was deleted, disabled or unsubscribed from this event since then must not+ // receive it (the reconciler skips only deleted and disabled rows; neither re-applies the+ // webhook's filters, which need the event data). Completing the job instead of throwing+ // stops the retries and files no dead-letter row. Otherwise deliver with the CURRENT url,+ // headers and secret, as the reconciler's replay does, so a receiver move or a rotated+ // secret or auth header applies to jobs already waiting in the queue.+ // A read error lands in the catch below and counts as a failed attempt, like a failed POST.+ const current = await this.loadDeliverableWebhook(webhookId, event);+ if (!current) {+ this.logger.warn('Skipping queued webhook delivery: webhook removed, disabled or unsubscribed', {+ webhookId,+ event,+ deliveryId: payload.deliveryId,+ idempotencyKey: payload.idempotencyKey,+ action: 'webhook_skipped_stale',+ });+ return { statusCode: 0, success: false, error: 'webhook removed, disabled or unsubscribed', responseTime: 0 };+ }+ ctx.url = current.url;+ const body = JSON.stringify(payload);+ const requestHeaders = buildDeliveryHeaders(+ current,+ event,+ payload.idempotencyKey,+ payload.deliveryId,+ body,+ job.attemptsMade,+ );++ const { status, responseTime } = await this.postToReceiver(ctx, body, requestHeaders);await this.recordSuccessfulDelivery(ctx, status, responseTime);return {statusCode: status,@@ -99,18 +132,25 @@ export class WebhookProcessor extends WorkerHost {}}+ /** The webhook row as it is now, or null when it was deleted, disabled or no longer takes `event`. */+ private async loadDeliverableWebhook(webhookId: string, event: string): Promise<Webhook | null> {+ const row = await this.webhookRepository.findOne({ where: { id: webhookId } });+ return row && row.active && (row.events.includes(event) || row.events.includes('*')) ? row : null;+ }+/*** POST the payload to the receiver through the SSRF-guarded fetch and classify the response:* a non-ok status throws into the failure path. Returns the status and measured response time.*/private async postToReceiver(ctx: WebhookDeliveryContext,+ body: string,requestHeaders: Record<string, string>,): Promise<{ status: number; responseTime: number }> {- const { url, payload, startTime } = ctx;+ const { url, startTime } = ctx;const { status } = await postWebhookPayload(url,- JSON.stringify(payload),+ body,requestHeaders,// Honor WEBHOOK_TIMEOUT on the primary (queued) path too — not just the deprecated direct one.this.configService.get<number>('webhook.timeout', 10000),@@ -247,9 +287,26 @@ export class WebhookProcessor extends WorkerHost {return;}- const { webhookId, url, event, payload } = job.data;+ const { webhookId, event, payload } = job.data;const sessionId = payload.sessionId;+ // Same rule as process(): no dead-letter row or webhook:error for a webhook that is gone, disabled+ // or unsubscribed, and the row records the URL a retry would have used. If the read itself fails,+ // record against the enqueue-time snapshot rather than lose the failure.+ let url = job.data.url;+ try {+ const current = await this.loadDeliverableWebhook(webhookId, event);+ if (!current) {+ return;+ }+ url = current.url;+ } catch (readError) {+ this.logger.warn('Could not re-read webhook for a stalled job; recording the enqueue-time URL', {+ webhookId,+ error: readError instanceof Error ? readError.message : String(readError),+ });+ }+this.logger.error('Webhook job failed after stalling beyond the recovery limit', error.message, {webhookId,event,diff --git a/src/modules/webhook/utils/deliver-once.ts b/src/modules/webhook/utils/deliver-once.tsindex acf475433..96417b1bd 100644--- a/src/modules/webhook/utils/deliver-once.ts+++ b/src/modules/webhook/utils/deliver-once.ts@@ -1,9 +1,60 @@+import * as crypto from 'crypto';import { Repository } from 'typeorm';import { withSafeFetch, redactSsrfError, isSsrfProtectionEnabled } from '../../../common/security/ssrf-guard';import { type LoggerService } from '../../../common/services/logger.service';import { WebhookDeliveryFailure } from '../entities/webhook-delivery-failure.entity';import { recordWebhookDeliveryFailure, statusCodeFromError } from './record-delivery-failure';+/**+ * Drop operator-supplied custom headers that target reserved names (Content-Type or any+ * X-OpenWA-* header) so a webhook config cannot forge the signature/event/idempotency+ * headers. Spread the result BEFORE the system headers so system always wins.+ */+export function sanitizeCustomHeaders(custom: Record<string, string> | null | undefined): Record<string, string> {+ const safe: Record<string, string> = {};+ for (const [key, value] of Object.entries(custom ?? {})) {+ if (!/^(content-type|x-openwa-)/i.test(key)) {+ safe[key] = value;+ }+ }+ return safe;+}++/** HMAC-SHA256 over the exact pre-serialized body, prefixed for receiver-side verification. */+export function generateSignature(payload: string, secret: string): string {+ const hmac = crypto.createHmac('sha256', secret);+ hmac.update(payload);+ return `sha256=${hmac.digest('hex')}`;+}++/**+ * The headers of one delivery attempt: the webhook's custom headers first, then the system headers+ * (which always win), then the signature over `body` when the webhook has a secret. Built from the+ * webhook row in hand, so a caller holding a fresh row sends its current headers and secret.+ */+export function buildDeliveryHeaders(+ webhook: { headers?: Record<string, string> | null; secret?: string | null },+ event: string,+ idempotencyKey: string,+ deliveryId: string,+ body: string,+ retryCount = 0,+): Record<string, string> {+ const headers: Record<string, string> = {+ ...sanitizeCustomHeaders(webhook.headers),+ 'Content-Type': 'application/json',+ 'User-Agent': 'OpenWA-Webhook/1.0.0',+ 'X-OpenWA-Event': event,+ 'X-OpenWA-Idempotency-Key': idempotencyKey,+ 'X-OpenWA-Delivery-Id': deliveryId,+ 'X-OpenWA-Retry-Count': String(retryCount),+ };+ if (webhook.secret) {+ headers['X-OpenWA-Signature'] = generateSignature(body, webhook.secret);+ }+ return headers;+}+/*** One SSRF-guarded POST + response classification: a non-ok status throws `HTTP <status>: <statusText>`,* ok returns the status. This is the byte-level delivery core BOTH paths previously duplicated linediff --git a/src/modules/webhook/webhook-delivery.service.ts b/src/modules/webhook/webhook-delivery.service.tsindex a19282f35..80e15d388 100644--- a/src/modules/webhook/webhook-delivery.service.ts+++ b/src/modules/webhook/webhook-delivery.service.ts@@ -4,13 +4,18 @@ import { Repository } from 'typeorm';import { ConfigService } from '@nestjs/config';import { InjectQueue } from '@nestjs/bullmq';import { Queue } from 'bullmq';-import * as crypto from 'crypto';import { setTimeout } from 'node:timers/promises';import { Webhook } from './entities/webhook.entity';import { WebhookOutboxService } from './webhook-outbox.service';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';import { recordWebhookDeliveryFailure } from './utils/record-delivery-failure';-import { postWebhookPayload, recordTerminalFailure } from './utils/deliver-once';+import {+ buildDeliveryHeaders,+ generateSignature,+ postWebhookPayload,+ recordTerminalFailure,+ sanitizeCustomHeaders,+} from './utils/deliver-once';import { createLogger } from '../../common/services/logger.service';import { DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES, shedInlineMedia } from '../../common/utils/inline-media';import { incrementWebhookDeliveryFailures } from '../../common/metrics/webhook-delivery-metrics';@@ -387,15 +392,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {return null;}- const headers = {- ...this.sanitizeCustomHeaders(webhook.headers),- 'Content-Type': 'application/json',- 'User-Agent': 'OpenWA-Webhook/1.0.0',- 'X-OpenWA-Event': event,- 'X-OpenWA-Idempotency-Key': idempotencyKey,- 'X-OpenWA-Delivery-Id': deliveryId,- 'X-OpenWA-Retry-Count': '0',- };+ const headers = buildDeliveryHeaders(webhook, event, idempotencyKey, deliveryId, body);return { finalPayload, body, headers };} catch (error) {await this.recordUndelivered(@@ -455,15 +452,9 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {): Promise<WebhookDeliveryOutcome> {const { sessionId, event } = ctx;try {- // Sign the exact pre-serialized body from preflight. The processor re-serializes the same- // payload object at delivery time (JSON key order survives the Redis round-trip), so the- // signature stays valid over the bytes the receiver sees.- const signature = webhook.secret ? this.generateSignature(body, webhook.secret) : '';-- if (webhook.secret) {- headers['X-OpenWA-Signature'] = signature;- }-+ // The job's headers are the enqueue-time snapshot. The processor rebuilds them (and the+ // signature) from the current webhook row on every attempt, so a secret or header rotated+ // while the job waits is honoured.const jobData: WebhookJobData = {webhookId: webhook.id,url: webhook.url,@@ -798,26 +789,12 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {}}- /**- * Drop operator-supplied custom headers that target reserved names (Content-Type or any- * X-OpenWA-* header) so a webhook config cannot forge the signature/event/idempotency- * headers. Spread the result BEFORE the system headers so system always wins. Shared with- * WebhookService.test(), which must probe with headers identical to a real delivery's.- */+ /** Shared with WebhookService.test(), which must probe with headers identical to a real delivery's. */sanitizeCustomHeaders(custom: Record<string, string> | null | undefined): Record<string, string> {- const safe: Record<string, string> = {};- for (const [key, value] of Object.entries(custom ?? {})) {- if (!/^(content-type|x-openwa-)/i.test(key)) {- safe[key] = value;- }- }- return safe;+ return sanitizeCustomHeaders(custom);}- /** HMAC-SHA256 over the exact pre-serialized body, prefixed for receiver-side verification. */generateSignature(payload: string, secret: string): string {- const hmac = crypto.createHmac('sha256', secret);- hmac.update(payload);- return `sha256=${hmac.digest('hex')}`;+ return generateSignature(payload, secret);}}