Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(ingress): flag header-deduped routes and redact hmac signatures
Yudhi Armyndharis7a77fd6d0f72
diff --git a/docs/25-integration-fabric.md b/docs/25-integration-fabric.mdindex 6773cac69..329bf7fc8 100644--- a/docs/25-integration-fabric.md+++ b/docs/25-integration-fabric.md@@ -182,7 +182,15 @@ Four tables live on the data connection, each created by a hand-authored dual-diso the signature itself expires with the window; the loader warns when a route declares the headerwithout signing it (or signs the token without declaring the header). `standard-webhooks` bindsid + timestamp by spec. A provider that sends no timestamp header at all stays outside the replay- window by construction — dedup and handler idempotency are its only protections.+ window by construction. For such an hmac-sha256 route, and for every `shared-secret` route, the default+ header-keyed dedup does not stop a copy of a delivery: the dedup header is not covered by the+ credential, so a copy with a different header value is accepted as new. `dedupOn: "body"` collapses+ byte-identical copies within `INGRESS_DEDUP_RETENTION_DAYS` (a copy gets the route's ack and is not+ enqueued again); beyond that, handler idempotency is the only protection. The loader logs a warning+ for each such route that keeps the header-keyed default.+ The value of a route's declared signature header (hmac-sha256 or shared-secret) is redacted from the+ persisted and enqueued payload, like the well-known signature headers, so the plugin's handler sees+ `[redacted]` in its place.- **Tenancy scoping.** Every durable ingress artifact — secret, dedup store, and dead-letter row — ispartitioned by instance, and downstream capability calls carry the instance's resolved session scope, soa cross-tenant send is blocked host-side.diff --git a/src/core/plugins/plugin-manifest-ingress.spec.ts b/src/core/plugins/plugin-manifest-ingress.spec.tsindex 71f8a1834..f422f301a 100644--- a/src/core/plugins/plugin-manifest-ingress.spec.ts+++ b/src/core/plugins/plugin-manifest-ingress.spec.ts@@ -253,24 +253,53 @@ describe('warnUnsignedTimestampRoutes', () => {expect(logger.warn).not.toHaveBeenCalled();});- it('stays silent when no timestamp is involved at all', () => {+ const withDedupOnBody = (manifest: ReturnType<typeof hmacRoute>) => ({+ ...manifest,+ ingress: manifest.ingress.map(route => ({ ...route, dedupOn: 'body' })),+ });++ it('warns once when an hmac route binds no timestamp and dedups on its header', () => {const logger = { warn: jest.fn() };warnUnsignedTimestampRoutes(hmacRoute({ scheme: 'hmac-sha256', header: 'X-Sig', contentTemplate: '{rawBody}' }) as never,logger,);- expect(logger.warn).not.toHaveBeenCalled();+ expect(logger.warn).toHaveBeenCalledTimes(1);+ expect(logger.warn).toHaveBeenCalledWith(+ expect.stringMatching(/dedupOn: 'body'/),+ expect.objectContaining({ pluginId: 'p', route: 'r', action: 'ingress_replayable_route' }),+ );});- it('ignores non-hmac schemes (their wire format is not templatable)', () => {+ it('stays silent for an hmac route without a timestamp that dedups on the body', () => {const logger = { warn: jest.fn() };- warnUnsignedTimestampRoutes(hmacRoute({ scheme: 'standard-webhooks', dedupHeader: 'webhook-id' }) as never, logger);warnUnsignedTimestampRoutes(- hmacRoute({ scheme: 'shared-secret', header: 'X-Token', timestampHeader: 'X-Ts' }) as never,+ withDedupOnBody(hmacRoute({ scheme: 'hmac-sha256', header: 'X-Sig', contentTemplate: '{rawBody}' })) as never,logger,);expect(logger.warn).not.toHaveBeenCalled();});++ it('warns for a shared-secret route unless it dedups on the body', () => {+ const logger = { warn: jest.fn() };+ const route = hmacRoute({ scheme: 'shared-secret', header: 'X-Token', timestampHeader: 'X-Ts' });+ warnUnsignedTimestampRoutes(route as never, logger);+ expect(logger.warn).toHaveBeenCalledTimes(1);+ expect(logger.warn).toHaveBeenCalledWith(+ expect.stringMatching(/shared-secret/),+ expect.objectContaining({ pluginId: 'p', route: 'r', action: 'ingress_replayable_route' }),+ );++ logger.warn.mockClear();+ warnUnsignedTimestampRoutes(withDedupOnBody(route) as never, logger);+ expect(logger.warn).not.toHaveBeenCalled();+ });++ it('ignores standard-webhooks (its dedup id and timestamp are signed)', () => {+ const logger = { warn: jest.fn() };+ warnUnsignedTimestampRoutes(hmacRoute({ scheme: 'standard-webhooks', dedupHeader: 'webhook-id' }) as never, logger);+ expect(logger.warn).not.toHaveBeenCalled();+ });});function manifestWithRoute(overrides: Record<string, unknown> = {}) {diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex 7a8e5486a..3d98f988e 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -464,14 +464,31 @@ export function warnUnauthenticatedIngressRoutes(* timestamp and a new delivery id forever. Binding the timestamp (`contentTemplate` containing* `{timestamp}`, e.g. `{timestamp}.{rawBody}`) makes the signed bytes expire with the window. The* inverse declaration — a `{timestamp}` token with no `timestampHeader` — signs the empty string,- * which is equally inert. Warn-only (SDK v1 is additive within a major; a load-time rejection would- * break already-installed manifests). Called from PluginLoaderService.loadPlugin.+ * which is equally inert.+ *+ * It also warns about routes whose default header-keyed dedup is the only thing between a copy of a+ * delivery and a second enqueue: an hmac-sha256 route that binds no timestamp, and a shared-secret+ * route (which binds neither body nor time). The dedup header is not covered by the credential, so a+ * copy sent with a different header value is accepted as new. `dedupOn: 'body'` silences it.+ *+ * Warn-only (SDK v1 is additive within a major; a load-time rejection would break already-installed+ * manifests). Called from PluginLoaderService.loadPlugin.*/export function warnUnsignedTimestampRoutes(manifest: PluginManifest,logger: { warn: (message: string, context?: Record<string, unknown>) => void },): void {for (const r of manifest.ingress ?? []) {+ if (r.signature.scheme === 'shared-secret' && r.dedupOn !== 'body') {+ logger.warn(+ `Ingress route '${r.route}' of plugin '${manifest.id}' uses scheme 'shared-secret', which binds ` ++ `neither the body nor a timestamp, and dedups on a header the secret does not cover: a copy of a ` ++ `delivery sent with a different header value is accepted as new. Prefer an hmac-sha256 scheme ` ++ `with a signed timestamp, or set dedupOn: 'body' if the provider's retries are byte-identical.`,+ { pluginId: manifest.id, route: r.route, action: 'ingress_replayable_route' },+ );+ continue;+ }if (r.signature.scheme !== 'hmac-sha256') continue; // only hmac templates can bind a timestampconst signsTimestamp = (r.signature.contentTemplate ?? '{rawBody}').includes('{timestamp}');if (r.signature.timestampHeader && !signsTimestamp) {@@ -489,6 +506,14 @@ export function warnUnsignedTimestampRoutes(`provider's timestamp header (and optionally toleranceSec) to activate the replay window.`,{ pluginId: manifest.id, route: r.route, action: 'ingress_unsigned_timestamp' },);+ } else if (!r.signature.timestampHeader && r.dedupOn !== 'body') {+ logger.warn(+ `Ingress route '${r.route}' of plugin '${manifest.id}' signs no timestamp and dedups on a header ` ++ `the signature does not cover: a copy of a delivery sent with a different header value is ` ++ `accepted as new. Declare and sign the provider's timestamp (timestampHeader plus {timestamp} ` ++ `in the contentTemplate), or set dedupOn: 'body' if the provider's retries are byte-identical.`,+ { pluginId: manifest.id, route: r.route, action: 'ingress_replayable_route' },+ );}}}diff --git a/src/modules/integration/ingress.service.spec.ts b/src/modules/integration/ingress.service.spec.tsindex e21913f91..ade6995b0 100644--- a/src/modules/integration/ingress.service.spec.ts+++ b/src/modules/integration/ingress.service.spec.ts@@ -68,6 +68,36 @@ describe('redactSensitiveHeaders (persisted ingress payloads)', () => {expect(recorded.payload.headers['x-delivery']).toBe('d1');});+ it("redacts an hmac route's declared signature header in the persisted and enqueued payload", async () => {+ const d = deps({+ manifestRoute: jest.fn().mockReturnValue({+ route: 'shop',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'hmac-sha256', header: 'X-Custom-Sig' },+ dedupHeader: 'x-delivery',+ }),+ });+ const res = await new IngressService(d).handle({+ pluginId: 'shop',+ instanceId: 'acct1',+ route: 'shop',+ method: 'POST',+ headers: { 'x-delivery': 'd1', 'x-custom-sig': createHmac('sha256', 's').update('{}').digest('hex') },+ query: {},+ rawBody: '{}',+ });+ expect(res.status).toBe(202);+ const recorded = (+ d.events.recordOrSkip.mock.calls as unknown as [[{ payload: { headers: Record<string, string> } }]]+ )[0][0];+ expect(recorded.payload.headers['x-custom-sig']).toBe('[redacted]');+ expect(recorded.payload.headers['x-delivery']).toBe('d1');+ const job = (d.enqueue.mock.calls as unknown as [[{ payload: { headers: Record<string, string> } }]])[0][0];+ expect(job.payload.headers['x-custom-sig']).toBe('[redacted]');+ });+it("redacts a shared-secret route's declared credential header in the persisted and enqueued payload", async () => {const d = deps({manifestRoute: jest.fn().mockReturnValue({diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.tsindex 57a4699ba..9ecd14f16 100644--- a/src/modules/integration/ingress.service.ts+++ b/src/modules/integration/ingress.service.ts@@ -176,11 +176,14 @@ export class IngressService {const deliveryId = route.dedupOn === 'body' || !headerId ? deriveDeliveryId(req) : headerId;// Provider request headers persist with the event (redrive/debugging); credentials must not.// Signature headers are re-derivable, auth material is not — redact before the first write.- // A shared-secret route carries the instance secret itself in its declared header.+ // A shared-secret route carries the instance secret itself in its declared header, and an hmac+ // route's declared header carries a signature that is only useful to re-send the same body.const payload = {headers: redactSensitiveHeaders(req.headers,- route.signature.scheme === 'shared-secret' ? route.signature.header : undefined,+ route.signature.scheme === 'shared-secret' || route.signature.scheme === 'hmac-sha256'+ ? route.signature.header+ : undefined,),query: req.query,body: req.rawBody,