Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): refuse restoring a webhook with malformed events or filters

Yudhi Armyndharis7f3ba2a4b873
diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.ts
index bb3d1242a..7bc7e87a3 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -1715,7 +1715,7 @@ describe('InfraDataController.import/export preserves every data-DB table', () =
headers: {},
active: true,
retryCount: 3,
- filters: { conditions: [{ field: 'sender', operator: 'equals', value: '[email protected]' }] },
+ filters: { conditions: [{ field: 'sender', operator: 'is', value: ['[email protected]'] }] },
}),
);
@@ -1724,7 +1724,7 @@ describe('InfraDataController.import/export preserves every data-DB table', () =
expect(res.imported).toBe(true);
expect((await ds.getRepository(Webhook).findOneByOrFail({ id: 'w1' })).filters).toEqual({
- conditions: [{ field: 'sender', operator: 'equals', value: '[email protected]' }],
+ conditions: [{ field: 'sender', operator: 'is', value: ['[email protected]'] }],
});
// The active flag (exported as integer 1 from SQLite) must round-trip as a real boolean.
expect((await ds.getRepository(Webhook).findOneByOrFail({ id: 'w1' })).active).toBe(true);
diff --git a/src/modules/infra/table-importers.spec.ts b/src/modules/infra/table-importers.spec.ts
index 56e0ab87f..42d238ecc 100644
--- a/src/modules/infra/table-importers.spec.ts
+++ b/src/modules/infra/table-importers.spec.ts
@@ -44,3 +44,36 @@ describe('sessions table importer: desiredState', () => {
expect(mapped({ desiredState: 'bogus' })[12]).toBeNull();
});
});
+
+/**
+ * A restore bypasses CreateWebhookDto. Dispatch reads a filters object without a conditions array as
+ * "no filtering", so a malformed one stored verbatim would deliver every subscribed event; a non-list
+ * events column silently never fires. Both are vetoed with a reason instead.
+ */
+describe('webhooks table importer', () => {
+ const webhooks = TABLE_IMPORTERS.find(importer => importer.key === 'webhooks');
+ const skip = (overrides: Record<string, unknown>) =>
+ webhooks?.skip?.({ id: 'wh-1', events: ['message.received'], filters: null, ...overrides } as never);
+ const chatFilter = { conditions: [{ field: 'isGroup', operator: 'is', value: true }] };
+
+ it('accepts events and filters in either decoded or JSON-text form', () => {
+ expect(skip({})).toBeNull();
+ expect(skip({ events: '["message.received","*"]', filters: JSON.stringify(chatFilter) })).toBeNull();
+ expect(skip({ filters: chatFilter })).toBeNull();
+ expect(skip({ events: undefined, filters: undefined })).toBeNull();
+ });
+
+ it.each([['message.received'], ['not json'], [{ 0: 'message.received' }], [[1]], ['[null]']])(
+ 'skips a row whose events is %j',
+ events => {
+ expect(skip({ events })).toMatch(/events/);
+ },
+ );
+
+ it.each([[{}], [{ conditions: 'x' }], ['not json'], ['{}'], [{ conditions: [{ field: 'nope', operator: 'is' }] }]])(
+ 'skips a row whose filters is %j',
+ filters => {
+ expect(skip({ filters })).toMatch(/filters/);
+ },
+ );
+});
diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.ts
index fb2e60262..c4e0a66e0 100644
--- a/src/modules/infra/table-importers.ts
+++ b/src/modules/infra/table-importers.ts
@@ -1,4 +1,5 @@
import { isSafeSessionName } from '../../common/utils/path-safety';
+import { collectFilterErrors } from '../webhook/filters/filter-validation';
import type {
MigrationTables,
SessionRow,
@@ -54,6 +55,17 @@ function defineTableImporter<K extends keyof MigrationTables>(importer: TableImp
return importer;
}
+// A JSON column arrives decoded from Postgres and as text from SQLite. Text that does not parse is
+// returned as-is, so a validator sees a string and refuses it rather than reading it as absent.
+function decodeJsonColumn(value: unknown): unknown {
+ if (typeof value !== 'string') return value;
+ try {
+ return JSON.parse(value) as unknown;
+ } catch {
+ return value;
+ }
+}
+
// Restore order is FK order: sessions first (webhooks/messages/templates/etc. reference it), the
// standalone cache/DLQ tables after. The per-block comments from the former inline import blocks
// live on their descriptor entries.
@@ -103,6 +115,19 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [
sql: `INSERT INTO webhooks (id, "sessionId", url, events, secret, headers, filters, active, "retryCount", "lastTriggeredAt", "createdAt", "updatedAt")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
id: (webhook: WebhookRow) => webhook.id,
+ // This path bypasses CreateWebhookDto. Dispatch reads a filters value without a conditions array
+ // as "no filtering", so a malformed one stored verbatim would deliver every subscribed event, and
+ // an events value that is not a list never fires at all. Veto the row with a warning, like the
+ // sessions guard; any warning rolls the restore back and names the row.
+ skip: (webhook: WebhookRow) => {
+ const events = decodeJsonColumn(webhook.events ?? []);
+ if (!Array.isArray(events) || !events.every(event => typeof event === 'string')) {
+ return `Skipped webhook ${webhook.id}: events is not a list of event names`;
+ }
+ const filterErrors = collectFilterErrors(decodeJsonColumn(webhook.filters));
+ if (filterErrors.length === 0) return null;
+ return `Skipped webhook ${webhook.id}: invalid filters (${filterErrors.join('; ')})`;
+ },
map: (webhook: WebhookRow) => [
webhook.id,
webhook.sessionId,