Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(queue): hash ingress job ids BullMQ refuses instead of degrading to inline dispatch
Yudhi Armyndharisb8ff79f89a72
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d7333222a..0f1c2673b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- Ingress delivery ids BullMQ refuses at enqueue (numeric, `redrive:<uuid>`, `0:`-led) are hashed to a legal job id, namespaced by plugin/instance; the old refusal read as a Redis failure and silently degraded the delivery to inline dispatch with no retry.+### Security- `PUT /sessions/{sessionId}/webhooks/{id}` now enforces the same 16-character webhook-secret floor as create; an empty string still clears signing.diff --git a/src/modules/integration/ingress-enqueue.service.spec.ts b/src/modules/integration/ingress-enqueue.service.spec.tsindex 1d1146d91..3760d7d49 100644--- a/src/modules/integration/ingress-enqueue.service.spec.ts+++ b/src/modules/integration/ingress-enqueue.service.spec.ts@@ -1,4 +1,9 @@-import { IngressEnqueueService, resolveIngressJobOptions, buildIngressDeadLetterRow } from './ingress-enqueue.service';+import {+ IngressEnqueueService,+ resolveIngressJobOptions,+ buildIngressDeadLetterRow,+ sanitizeIngressJobId,+} from './ingress-enqueue.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { ConfigService } from '@nestjs/config';@@ -36,6 +41,66 @@ describe('IngressEnqueueService', () => {expect(loader.dispatchWebhookForInstance).not.toHaveBeenCalled();});+ // BullMQ refuses integer jobIds and colon ids that do not split into exactly 3 parts; before the+ // sanitizer those throws read as "Redis unreachable" in the catch-all and silently degraded the+ // delivery to inline dispatch (no retry, no backoff, blocked redrive loop).+ describe('sanitizeIngressJobId', () => {+ it('passes safe ids through unchanged (BullMQ accepts them as-is)', () => {+ expect(sanitizeIngressJobId('d1')).toBe('d1');+ expect(sanitizeIngressJobId('evt_abc-123')).toBe('evt_abc-123');+ expect(sanitizeIngressJobId('a:b:c')).toBe('a:b:c'); // exactly 3 parts is BullMQ-legal+ expect(sanitizeIngressJobId('0abc')).toBe('0abc'); // zero-PREFIXED is fine; only '0:'-leading is not+ });++ it('hashes the shapes BullMQ refuses, deterministically', () => {+ const integer = sanitizeIngressJobId('12345');+ const redrive = sanitizeIngressJobId('redrive:3f8e2a1b-9c4d-4e6f-8a2b-7d1c0e5f9a3b');+ const twoPart = sanitizeIngressJobId('a:b');+ const zeroLedThreePart = sanitizeIngressJobId('0:tenant:123'); // Queue.addJob: "cannot start with '0:'"+ for (const hashed of [integer, redrive, twoPart, zeroLedThreePart]) {+ expect(hashed).toMatch(/^ing-[0-9a-f]{40}$/);+ expect(hashed).not.toContain(':');+ }+ expect(sanitizeIngressJobId('12345')).toBe(integer);+ expect(sanitizeIngressJobId('redrive:3f8e2a1b-9c4d-4e6f-8a2b-7d1c0e5f9a3b')).toBe(redrive);+ expect(sanitizeIngressJobId('0')).toMatch(/^ing-/); // Queue.addJob rejects the literal '0' too+ });++ it('coerces a non-string id (a duplicated header can surface as string[]) instead of throwing', () => {+ const coerced = sanitizeIngressJobId(['0:tenant', '123'] as unknown as string);+ expect(coerced).toMatch(/^ing-[0-9a-f]{40}$/);+ });++ it('namespaces the hash by plugin/instance so two instances sharing a numeric id do not collide', () => {+ // BullMQ dedups jobIds across the whole shared queue while the DB dedup is+ // (pluginId, instanceId, providerDeliveryId); numeric provider ids are per-account sequences.+ const a = sanitizeIngressJobId('12345', 'chatwoot\u0000acct-1');+ const b = sanitizeIngressJobId('12345', 'chatwoot\u0000acct-2');+ expect(a).toMatch(/^ing-[0-9a-f]{40}$/);+ expect(a).not.toBe(b);+ expect(sanitizeIngressJobId('12345', 'chatwoot\u0000acct-1')).toBe(a); // stable for replays+ });++ it.each([+ ['a numeric provider dedup header', '12345'],+ ['the redrive replay id', 'redrive:3f8e2a1b-9c4d-4e6f-8a2b-7d1c0e5f9a3b'],+ ['a two-part colon id', 'a:b'],+ ['a zero-led three-part colon id', '0:tenant:123'],+ ])('still queues (%s) instead of tripping the inline fallback', async (_label, jobId) => {+ (config.get as jest.Mock).mockReturnValue(true);+ const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, queue as never);++ expect(await svc.enqueue(data, jobId)).toEqual({ outcome: 'queued' });++ expect(queue.add).toHaveBeenCalledWith('ingress', data, {+ jobId: sanitizeIngressJobId(jobId, `${data.pluginId}\u0000${data.instanceId}`),+ attempts: 3,+ backoff: { type: 'exponential', delay: 5000 },+ });+ expect(loader.dispatchWebhookForInstance).not.toHaveBeenCalled();+ });+ });+it('dispatches inline when queueing is disabled, even if a queue instance is present', async () => {(config.get as jest.Mock).mockReturnValue(false);const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, queue as never);diff --git a/src/modules/integration/ingress-enqueue.service.ts b/src/modules/integration/ingress-enqueue.service.tsindex 387fee479..4af0c66fb 100644--- a/src/modules/integration/ingress-enqueue.service.ts+++ b/src/modules/integration/ingress-enqueue.service.ts@@ -2,6 +2,7 @@ import { Injectable, OnApplicationBootstrap, Optional } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { InjectQueue } from '@nestjs/bullmq';import { Queue } from 'bullmq';+import { createHash } from 'crypto';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { IngressJobData } from '../queue/processors/ingress.processor';import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';@@ -35,6 +36,35 @@ export function resolveIngressJobOptions(): { attempts: number; backoff: { type:};}+/**+ * BullMQ refuses several jobId shapes outright, at two validation sites: Job.validateOptions rejects+ * an exact integer string ("Custom Id cannot be integers") and a colon id that does not split into+ * exactly 3 parts ("Custom Id cannot contain :"); Queue.addJob additionally rejects '0' and any+ * '0:'-prefixed id ("JobId cannot be '0' or start with '0:'"). Providers send numeric dedup headers+ * (`svix-Id: 12345`), and the redrive path mints `redrive:<uuid>`, so these refusals happen in+ * practice, and because enqueue()'s catch-all treats ANY add() throw as "Redis unreachable", the job+ * silently degraded to inline dispatch with no retry, no backoff, and a blocked redrive loop. Map the+ * refused shapes to a deterministic sha256 prefix: BullMQ's exactly-once dedup only needs the id+ * STABLE per delivery, not recognizable, and the reconciler replays through this same function so+ * its dedup against an earlier enqueue is preserved.+ *+ * The hash input is namespaced with the plugin/instance pair. BullMQ dedups jobIds across the WHOLE+ * shared ingress queue, while the database dedup is (pluginId, instanceId, providerDeliveryId), and+ * numeric provider ids are exactly the short, per-account sequence style that two instances of one+ * provider can share. Without the namespace, the second instance's delivery would collide with the+ * first's job id and BullMQ would silently discard it (resolved as the existing job, no DLQ row);+ * with it, the queue-level dedup matches the database-level scope. A non-string id (a duplicated+ * header can surface as string[]) is coerced rather than trusted to reach BullMQ's own checks.+ */+export function sanitizeIngressJobId(jobId: string, namespace = ''): string {+ const raw = typeof jobId === 'string' ? jobId : String(jobId);+ const looksInteger = `${parseInt(raw, 10)}` === raw;+ const badColon = raw.includes(':') && raw.split(':').length !== 3;+ const zeroPrefixed = raw === '0' || raw.startsWith('0:');+ if (!looksInteger && !badColon && !zeroPrefixed) return raw;+ return `ing-${createHash('sha256').update(`${namespace}\u0000${raw}`).digest('hex').slice(0, 40)}`;+}+/*** Build the dead-letter row for an ingress delivery whose inline-dispatch fallback failed. The shape* mirrors the row IngressProcessor writes on a final-attempt failure (direction / pluginId / instanceId@@ -101,8 +131,13 @@ export class IngressEnqueueService implements OnApplicationBootstrap {if (useQueue && this.ingressQueue) {try {// jobId = deliveryId gives BullMQ exactly-once enqueue semantics; the retry policy adds bounded- // exponential-backoff attempts so a transient failure retries before landing in the DLQ.- await this.ingressQueue.add('ingress', data, { jobId, ...resolveIngressJobOptions() });+ // exponential-backoff attempts so a transient failure retries before landing in the DLQ. The id+ // is sanitized because BullMQ refuses several id shapes at add() (see sanitizeIngressJobId),+ // which would otherwise read as a Redis failure here and fall through to inline dispatch.+ await this.ingressQueue.add('ingress', data, {+ jobId: sanitizeIngressJobId(jobId, `${data.pluginId}\u0000${data.instanceId}`),+ ...resolveIngressJobOptions(),+ });return { outcome: 'queued' };} catch (err) {// Redis unreachable (enableOfflineQueue:false makes add() reject) — fall through to inline