Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(integration): scope DLQ redrive by session provenance

Yudhi Armyndharis60b113a95f15
diff --git a/src/modules/integration/ingress-reconciler.service.spec.ts b/src/modules/integration/ingress-reconciler.service.spec.ts
index da03903a3..cf098eaa5 100644
--- a/src/modules/integration/ingress-reconciler.service.spec.ts
+++ b/src/modules/integration/ingress-reconciler.service.spec.ts
@@ -295,7 +295,7 @@ describe('IngressReconcilerService.sweep', () => {
);
const redrive = new RedriveService(failures, events, { enqueue } as unknown as IngressEnqueueService);
- const res = await redrive.redriveInstance('plug', 'inst');
+ const res = await redrive.redriveInstance('plug', 'inst', null);
expect(res.redriven).toBe(1);
expect((await stored(id)).dispatchState).toBe('dispatched');
diff --git a/src/modules/integration/redrive.controller.spec.ts b/src/modules/integration/redrive.controller.spec.ts
index 6dfac2c41..3dc194d36 100644
--- a/src/modules/integration/redrive.controller.spec.ts
+++ b/src/modules/integration/redrive.controller.spec.ts
@@ -40,12 +40,15 @@ describe('RedriveController session-scope fence', () => {
return { controller, redrive, audit };
}
- it('lets a scoped key redrive an instance bound to one of its sessions', async () => {
+ it('lets a scoped key redrive an instance bound to one of its sessions, passing the current binding as a provenance filter', async () => {
+ // A scoped key is authorized against the instance's CURRENT sessionScope, but the DLQ also holds
+ // historical rows from prior bindings. The controller must thread that authorized binding down so
+ // the service can filter by it — otherwise the key replays foreign (sess-old) rows.
const { controller, redrive } = build('sess-1');
await controller.redriveInstance('chatwoot', 'acct1', scopedKey);
- expect(redrive.redriveInstance).toHaveBeenCalledWith('chatwoot', 'acct1');
+ expect(redrive.redriveInstance).toHaveBeenCalledWith('chatwoot', 'acct1', 'sess-1');
});
it('answers 404 when a scoped key redrives an out-of-scope instance (and never dispatches)', async () => {
@@ -65,12 +68,15 @@ describe('RedriveController session-scope fence', () => {
expect(redrive.redriveInstance).not.toHaveBeenCalled();
});
- it('lets an unrestricted key redrive a missing instance (drains retained DLQ rows for cleanup)', async () => {
+ it('lets an unrestricted key redrive a missing instance (drains retained DLQ rows for cleanup), passing null as an unrestricted provenance filter', async () => {
+ // An unrestricted key has no session fence, so it drains every retained row regardless of
+ // sessionId. null signals "caller-decided unrestricted" to the service — never undefined, which
+ // would silently fail open if a caller forgot the argument.
const { controller, redrive } = build(undefined);
await controller.redriveInstance('chatwoot', 'acct1', { allowedSessions: null } as unknown as ApiKey);
- expect(redrive.redriveInstance).toHaveBeenCalledWith('chatwoot', 'acct1');
+ expect(redrive.redriveInstance).toHaveBeenCalledWith('chatwoot', 'acct1', null);
});
it('answers 404 when a scoped key redrives an all-sessions (null scope) instance', async () => {
@@ -80,12 +86,12 @@ describe('RedriveController session-scope fence', () => {
expect(redrive.redriveInstance).not.toHaveBeenCalled();
});
- it('lets an unrestricted key redrive any instance', async () => {
+ it('lets an unrestricted key redrive any instance, passing null as an unrestricted provenance filter', async () => {
const { controller, redrive } = build('sess-2');
await controller.redriveInstance('chatwoot', 'acct1', { allowedSessions: null } as unknown as ApiKey);
- expect(redrive.redriveInstance).toHaveBeenCalledWith('chatwoot', 'acct1');
+ expect(redrive.redriveInstance).toHaveBeenCalledWith('chatwoot', 'acct1', null);
});
it('audits a successful redrive with its outcome counts (a redrive can cause real sends)', async () => {
diff --git a/src/modules/integration/redrive.controller.ts b/src/modules/integration/redrive.controller.ts
index 3f8a87151..fe8a246a5 100644
--- a/src/modules/integration/redrive.controller.ts
+++ b/src/modules/integration/redrive.controller.ts
@@ -40,7 +40,14 @@ export class RedriveController {
if (scoped && (!inst || !sessionScopeVisible(apiKey?.allowedSessions, inst.sessionScope))) {
throw new NotFoundException('instance not found');
}
- const result = await this.redrive.redriveInstance(pluginId, instanceId);
+ // Thread the authorized binding down as an explicit DLQ provenance filter. A scoped key is
+ // authorized against the instance's CURRENT sessionScope, but retained DLQ rows still carry the
+ // sessionId of whatever binding wrote them; without this filter a rebind sess-old -> sess-current
+ // lets a sess-current key replay historical sess-old rows. The filter is derived from the
+ // PERSISTED current instance (not the request body), and null means an unrestricted caller may
+ // drain every retained row — never undefined, which would silently fail open.
+ const sessionIdFilter = scoped ? inst!.sessionScope : null;
+ const result = await this.redrive.redriveInstance(pluginId, instanceId, sessionIdFilter);
// A redrive can trigger real downstream sends, so every successful batch is audited with its
// outcome counts (no payload content — the DLQ rows themselves hold those).
void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_REDRIVEN, {
diff --git a/src/modules/integration/redrive.service.spec.ts b/src/modules/integration/redrive.service.spec.ts
index af6e23e8f..37d571b6e 100644
--- a/src/modules/integration/redrive.service.spec.ts
+++ b/src/modules/integration/redrive.service.spec.ts
@@ -53,7 +53,7 @@ describe('RedriveService', () => {
(repo.find as jest.Mock).mockResolvedValue(rows);
const svc = makeSvc();
- const res = await svc.redriveInstance('p', 'i');
+ const res = await svc.redriveInstance('p', 'i', null);
expect(res.redriven).toBe(2);
expect(res).toEqual({ redriven: 2, remaining: 0, batchSize: 100 });
@@ -94,7 +94,7 @@ describe('RedriveService', () => {
(repo.find as jest.Mock).mockResolvedValue(rows);
const svc = makeSvc();
- const res = await svc.redriveInstance('p', 'i');
+ const res = await svc.redriveInstance('p', 'i', null);
expect(res.redriven).toBe(1);
expect(events.update).toHaveBeenCalledTimes(1);
@@ -126,7 +126,7 @@ describe('RedriveService', () => {
(ingressEnqueue.enqueue as jest.Mock).mockResolvedValue({ outcome: 'failed' });
const svc = makeSvc();
- const res = await svc.redriveInstance('p', 'i');
+ const res = await svc.redriveInstance('p', 'i', null);
expect(res.redriven).toBe(0);
expect(ingressEnqueue.enqueue).toHaveBeenCalledTimes(1);
@@ -138,7 +138,7 @@ describe('RedriveService', () => {
(repo.find as jest.Mock).mockResolvedValue([]);
const svc = makeSvc();
- const res = await svc.redriveInstance('p', 'i');
+ const res = await svc.redriveInstance('p', 'i', null);
expect(repo.find).toHaveBeenCalledWith({
where: { pluginId: 'p', instanceId: 'i', direction: 'inbound', redriven: false },
@@ -150,6 +150,49 @@ describe('RedriveService', () => {
expect(repo.update).not.toHaveBeenCalled();
});
+ it('filters the DLQ batch by the session provenance so a rebind cannot replay foreign historical rows', async () => {
+ // After an instance is rebound sess-old -> sess-current, a key scoped to sess-current must NOT
+ // replay retained rows that still carry sessionId 'sess-old'. The authorized binding is threaded
+ // in as a concrete filter that enters BOTH the find() and count() query — foreign rows neither
+ // consume the batch nor leak through `remaining`.
+ (repo.find as jest.Mock).mockResolvedValue([]);
+ const svc = makeSvc();
+
+ await svc.redriveInstance('p', 'i', 'sess-current');
+
+ expect(repo.find).toHaveBeenCalledWith({
+ where: {
+ pluginId: 'p',
+ instanceId: 'i',
+ direction: 'inbound',
+ redriven: false,
+ sessionId: 'sess-current',
+ },
+ order: { attempts: 'ASC', createdAt: 'ASC' },
+ take: 100,
+ });
+ const [countCall] = (repo.count as jest.Mock).mock.calls[0] as [{ where: Record<string, unknown> }];
+ expect(countCall.where).toMatchObject({ sessionId: 'sess-current' });
+ });
+
+ it('leaves the sessionId predicate ABSENT for an unrestricted (null) caller so legacy/null-session rows stay replayable', async () => {
+ // null means the caller is unrestricted: the DLQ is drained across every sessionId, including
+ // legacy rows written before sessionId provenance existed (sessionId null). The where object must
+ // NOT carry a sessionId key at all — emitting `sessionId: null` would exclude those legacy rows.
+ (repo.find as jest.Mock).mockResolvedValue([]);
+ const svc = makeSvc();
+
+ await svc.redriveInstance('p', 'i', null);
+
+ expect(repo.find).toHaveBeenCalledWith({
+ where: { pluginId: 'p', instanceId: 'i', direction: 'inbound', redriven: false },
+ order: { attempts: 'ASC', createdAt: 'ASC' },
+ take: 100,
+ });
+ const [countArg] = (repo.count as jest.Mock).mock.calls[0] as [{ where: Record<string, unknown> }];
+ expect(countArg.where).not.toHaveProperty('sessionId');
+ });
+
it('falls back to the failure row id as deliveryId when deliveryId is null', async () => {
const rows = [
{
@@ -166,7 +209,7 @@ describe('RedriveService', () => {
(repo.find as jest.Mock).mockResolvedValue(rows);
const svc = makeSvc();
- await svc.redriveInstance('p', 'i');
+ await svc.redriveInstance('p', 'i', null);
expect(ingressEnqueue.enqueue).toHaveBeenCalledWith(
expect.objectContaining({ deliveryId: 'f3', sessionId: undefined }),
diff --git a/src/modules/integration/redrive.service.ts b/src/modules/integration/redrive.service.ts
index 743c32ea6..d6d4fce12 100644
--- a/src/modules/integration/redrive.service.ts
+++ b/src/modules/integration/redrive.service.ts
@@ -32,15 +32,25 @@ export class RedriveService {
redriveInstance(
pluginId: string,
instanceId: string,
+ sessionIdFilter: string | null,
): Promise<{ redriven: number; remaining: number; batchSize: number }> {
- return this.lock.run(`redrive:${pluginId}:${instanceId}`, () => this.redriveBatch(pluginId, instanceId));
+ return this.lock.run(`redrive:${pluginId}:${instanceId}`, () =>
+ this.redriveBatch(pluginId, instanceId, sessionIdFilter),
+ );
}
private async redriveBatch(
pluginId: string,
instanceId: string,
+ sessionIdFilter: string | null,
): Promise<{ redriven: number; remaining: number; batchSize: number }> {
- const where = { pluginId, instanceId, direction: 'inbound' as const, redriven: false };
+ const where = {
+ pluginId,
+ instanceId,
+ direction: 'inbound' as const,
+ redriven: false,
+ ...(sessionIdFilter === null ? {} : { sessionId: sessionIdFilter }),
+ };
const rows = await this.repo.find({
where,
// Failed replays increment attempts and move behind never-retried rows, preventing one permanent
diff --git a/test/integration-instance.e2e-spec.ts b/test/integration-instance.e2e-spec.ts
index 49fdbc825..1ca1b5dec 100644
--- a/test/integration-instance.e2e-spec.ts
+++ b/test/integration-instance.e2e-spec.ts
@@ -8,6 +8,8 @@ process.env.BASE_URL = 'https://api.example.com';
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+import { Repository } from 'typeorm';
import request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from '../src/app.module';
@@ -15,6 +17,7 @@ import { applyGlobalValidation } from '../src/config/app-validation';
import { PluginLoaderService } from '../src/core/plugins/plugin-loader.service';
import { AuthService } from '../src/modules/auth/auth.service';
import { ApiKeyRole } from '../src/modules/auth/entities/api-key.entity';
+import { IntegrationDeliveryFailure } from '../src/modules/integration/entities/integration-delivery-failure.entity';
// A stub ingress-capable plugin so the capability check passes without a real plugin on disk. The
// configSchema carries a NESTED secret field so the masking tests can prove a `secret:true` config
@@ -54,6 +57,10 @@ describe('IntegrationInstanceController (e2e)', () => {
let app: INestApplication<App>;
const key = 'dev-admin-key';
const base = '/api/integration/plugins';
+ // Hoisted so the redrive-provenance test can clear it before the POST and assert exactly which
+ // delivery was dispatched inline (the e2e runs with QUEUE_ENABLED unset, so redrive dispatches
+ // inline through this mock rather than enqueuing to BullMQ).
+ const dispatchWebhookForInstance = jest.fn();
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
@@ -61,7 +68,7 @@ describe('IntegrationInstanceController (e2e)', () => {
.useValue({
getPlugin: (id: string) =>
id === 'chatwoot' ? INGRESS_PLUGIN : id === 'plain' ? NON_INGRESS_PLUGIN : undefined,
- dispatchWebhookForInstance: jest.fn(),
+ dispatchWebhookForInstance,
// EngineFactory.onModuleInit registers the built-in whatsapp-web.js/baileys engine plugins
// and auto-enables the configured one through these at boot; no-ops keep app boot working
// without a real plugin registry (enablePlugin failing is caught+logged, not fatal, but a
@@ -340,4 +347,113 @@ describe('IntegrationInstanceController (e2e)', () => {
.expect(201);
});
});
+
+ /**
+ * F-02 regression: the controller authorizes a scoped key against the instance's CURRENT
+ * sessionScope, but the DLQ also retains rows written under PRIOR bindings. After a rebind
+ * sess-old -> sess-current, a key scoped to sess-current would otherwise replay the historical
+ * sess-old row. The redrive must filter the DLQ by the authorized current binding (provenance),
+ * not just by {pluginId, instanceId}.
+ */
+ describe('redrive session provenance (rebind replay fence)', () => {
+ let scopedCurrentKey: string; // ADMIN, allowedSessions: ['sess-current']
+ let failures: Repository<IntegrationDeliveryFailure>;
+ let oldRowId: string;
+ let currentRowId: string;
+
+ beforeAll(async () => {
+ const authService = app.get(AuthService);
+ scopedCurrentKey = (
+ await authService.createApiKey({
+ name: 'e2e-redrive-sess-current',
+ role: ApiKeyRole.ADMIN,
+ allowedSessions: ['sess-current'],
+ })
+ ).rawKey;
+ failures = app.get(getRepositoryToken(IntegrationDeliveryFailure, 'data'));
+
+ // 1. Create the instance bound to sess-old with the unrestricted key.
+ await request(app.getHttpServer())
+ .post(`${base}/chatwoot/instances`)
+ .set('X-API-Key', key)
+ .send({ instanceId: 'rebound-redrive', sessionScope: 'sess-old' })
+ .expect(201);
+
+ // 2. Seed a non-redriven inbound DLQ row carrying the OLD binding's sessionId (the historical
+ // payload that must NOT be replayable by a sess-current key after the rebind).
+ const oldRow = await failures.save(
+ failures.create({
+ direction: 'inbound',
+ pluginId: 'chatwoot',
+ instanceId: 'rebound-redrive',
+ sessionId: 'sess-old',
+ deliveryId: 'dlv-old',
+ attempts: 1,
+ lastError: 'inline dispatch failed',
+ payload: {
+ route: 'chatwoot',
+ method: 'POST',
+ ingress: { headers: {}, query: {}, body: '{}', rawBody: '{}' },
+ },
+ redriven: false,
+ }),
+ );
+ oldRowId = oldRow.id;
+
+ // 3. Rebind the instance to sess-current (the new authorized binding).
+ await request(app.getHttpServer())
+ .patch(`${base}/chatwoot/instances/rebound-redrive`)
+ .set('X-API-Key', key)
+ .send({ sessionScope: 'sess-current' })
+ .expect(200);
+
+ // 4. Seed a second non-redriven inbound DLQ row carrying the CURRENT binding's sessionId —
+ // this is the only row a sess-current key should be able to replay.
+ const currentRow = await failures.save(
+ failures.create({
+ direction: 'inbound',
+ pluginId: 'chatwoot',
+ instanceId: 'rebound-redrive',
+ sessionId: 'sess-current',
+ deliveryId: 'dlv-current',
+ attempts: 0,
+ lastError: 'inline dispatch failed',
+ payload: {
+ route: 'chatwoot',
+ method: 'POST',
+ ingress: { headers: {}, query: {}, body: '{}', rawBody: '{}' },
+ },
+ redriven: false,
+ }),
+ );
+ currentRowId = currentRow.id;
+ });
+
+ it('redrives only the current-binding DLQ row, never the historical sess-old one', async () => {
+ // 5. POST redrive as a key scoped to sess-current (the instance's current binding).
+ dispatchWebhookForInstance.mockClear();
+ const res = await request(app.getHttpServer())
+ .post('/api/integration/instances/chatwoot/rebound-redrive/redrive')
+ .set('X-API-Key', scopedCurrentKey)
+ // 6. Exactly one row (the sess-current one) is redriven; the sess-old row neither consumes
+ // the batch nor leaks through `remaining`.
+ .expect(201)
+ .then(r => r.body as { redriven: number; remaining: number; batchSize: number });
+
+ expect(res).toEqual({ redriven: 1, remaining: 0, batchSize: 100 });
+
+ // 7. Only the current delivery was dispatched inline; the historical sess-old row was not.
+ expect(dispatchWebhookForInstance).toHaveBeenCalledTimes(1);
+ expect(dispatchWebhookForInstance).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'dlv-current' }));
+ expect(dispatchWebhookForInstance).not.toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'dlv-old' }));
+
+ // Re-read both rows: the current one is retired, the sess-old one stays redrivable (unchanged).
+ const [currentAfter, oldAfter] = await Promise.all([
+ failures.findOneByOrFail({ id: currentRowId }),
+ failures.findOneByOrFail({ id: oldRowId }),
+ ]);
+ expect(currentAfter.redriven).toBe(true);
+ expect(oldAfter.redriven).toBe(false);
+ });
+ });
});