Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(integration): keep an ingress delivery's verified verdict
Yudhi Armyndharis22cfa96afba0
diff --git a/src/core/plugins/ingress-instance-config.spec.ts b/src/core/plugins/ingress-instance-config.spec.tsindex 02c413ef6..1392261ae 100644--- a/src/core/plugins/ingress-instance-config.spec.ts+++ b/src/core/plugins/ingress-instance-config.spec.ts@@ -45,18 +45,24 @@ function instanceRow(instanceId: string, config: Record<string, unknown> | null,};}-function job(instanceId: string): IngressJobData {+/** A job as admission leaves it: the session is the one the instance was bound to. */+function job(+ instanceId: string,+ sessionId: string | null = SHARED_SCOPE,+ admission?: { verified: boolean },+): IngressJobData {return {pluginId: PLUGIN_ID,instanceId,route: '/hook',deliveryId: 'delivery-' + instanceId,- payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ sessionId: sessionId ?? undefined,+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}', ...(admission ? { admission } : {}) },};}-/** The one field of the worker payload these specs assert on. */-type WebhookCall = { config?: Record<string, unknown> };+/** The fields of the worker payload these specs assert on. */+type WebhookCall = { config?: Record<string, unknown>; verified?: boolean; sessionId?: string };/** Builds a bridge whose dispatch path is real; only the worker host and the instance store are fakes. */function makeBridge(opts: {@@ -255,7 +261,7 @@ describe('ingress dispatch resolves config per INSTANCE, not per session scope',manifestOverrides: { sessionScoped: false },});- await bridge.dispatchWebhookForInstance(job('acct-a'));+ await bridge.dispatchWebhookForInstance(job('acct-a', null));expect(calls[0].config).toEqual({ apiToken: 'token-A' });});@@ -278,9 +284,68 @@ describe('ingress dispatch refuses an instance that is disabled or deleted', ()const wildcard = instanceRow('acct-b', { apiToken: 'token-B' }, null);const { bridge, calls } = makeBridge({ rows: [wildcard], baseConfig: { apiToken: 'token-B' } });- await expect(bridge.dispatchWebhookForInstance(job('acct-a'))).rejects.toThrow(+ await expect(bridge.dispatchWebhookForInstance(job('acct-a', null))).rejects.toThrow('instance acct-a of plugin chat-adapter is disabled or deleted',);expect(calls).toHaveLength(0);});});++const route = (scheme: 'none' | 'hmac-sha256') => ({+ route: '/hook',+ mode: 'async' as const,+ verify: 'core' as const,+ maxBodyBytes: 1024,+ signature: scheme === 'none' ? { scheme: 'none' as const } : { scheme: 'hmac-sha256' as const, header: 'x-sig' },+});++describe('ingress dispatch keeps what was decided when the delivery was admitted', () => {+ const row = () => instanceRow('acct-a', { apiToken: 'token-A' }, 'S1');++ it('does not label an unauthenticated delivery verified after its route starts signing', async () => {+ const { bridge, calls } = makeBridge({+ rows: [row()],+ manifestOverrides: { ingress: [route('hmac-sha256')] },+ });++ await bridge.dispatchWebhookForInstance(job('acct-a', 'S1', { verified: false }));++ expect(calls[0].verified).toBe(false);+ });++ it('keeps an authenticated delivery verified after its route stops signing', async () => {+ const { bridge, calls } = makeBridge({+ rows: [row()],+ manifestOverrides: { ingress: [route('none')] },+ });++ await bridge.dispatchWebhookForInstance(job('acct-a', 'S1', { verified: true }));++ expect(calls[0].verified).toBe(true);+ });++ it('still never labels a delivery verified when its route is gone', async () => {+ const { bridge, calls } = makeBridge({ rows: [row()] });++ await bridge.dispatchWebhookForInstance(job('acct-a', 'S1', { verified: true }));++ expect(calls[0].verified).toBe(false);+ });++ it.each([+ ['signing', 'hmac-sha256', true],+ ['unsigned', 'none', false],+ ] as const)(+ 'reads the route for a delivery admitted before the verdict was recorded (%s)',+ async (_l, scheme, want) => {+ const { bridge, calls } = makeBridge({+ rows: [row()],+ manifestOverrides: { ingress: [route(scheme)] },+ });++ await bridge.dispatchWebhookForInstance(job('acct-a', 'S1'));++ expect(calls[0].verified).toBe(want);+ },+ );+});diff --git a/src/core/plugins/plugin-sandbox-bridge.ts b/src/core/plugins/plugin-sandbox-bridge.tsindex 69f86b0bd..b9baf12de 100644--- a/src/core/plugins/plugin-sandbox-bridge.ts+++ b/src/core/plugins/plugin-sandbox-bridge.ts@@ -196,8 +196,10 @@ export class PluginSandboxBridge {const route = plugin?.manifest.ingress?.find(candidate => candidate.route === d.route);// Reaching dispatch means every authenticating scheme already passed host verification. A route// explicitly configured with scheme:none is unauthenticated and must never be labelled verified.- // Missing/hot-swapped route metadata fails closed.- const verified = route ? route.signature.scheme !== 'none' : false;+ // The verdict is the one recorded at admission: a plugin update can change the route's scheme while+ // a delivery waits, and it must not relabel a payload nobody authenticated. A delivery admitted before+ // the verdict was recorded reads the route as it stands. Missing/hot-swapped route metadata fails closed.+ const verified = !!route && (d.payload.admission?.verified ?? route.signature.scheme !== 'none');const instance = await this.hostServices.getPluginInstancePort().resolve(d.pluginId, d.instanceId);// The live door and the reconciler refuse an unknown or disabled instance; a queued job, a retry,// the inline fallback and a redrive all land here instead, so the same rule is enforced once more.diff --git a/src/modules/integration/entities/ingress-event.entity.ts b/src/modules/integration/entities/ingress-event.entity.tsindex 2eb64881f..e1d416da6 100644--- a/src/modules/integration/entities/ingress-event.entity.ts+++ b/src/modules/integration/entities/ingress-event.entity.ts@@ -54,6 +54,9 @@ export class IngressEvent {// and it stays pending until INGRESS_DEDUP_RETENTION_DAYS prunes it.// `method` is the request's HTTP method, so a replay reaches the handler as the live attempt did. Rows// written before it was persisted lack it, and dispatch falls back to 'POST' for them.+ // `admission.verified` is what the host decided when it accepted the request (false on a route that+ // authenticates nothing); a replay or retry hands the handler that verdict, not the route's current scheme.+ // Rows written before it was persisted lack it, and dispatch reads the route as it stands.@Column({ type: jsonColumnType(), nullable: true })payload!: {headers: Record<string, string>;@@ -61,6 +64,7 @@ export class IngressEvent {body: string;rawBody: string;method?: string;+ admission?: { verified: boolean };} | null;// sha256 hex of the rawBody, written at recordOrSkip. Survives payload retirement so operators candiff --git a/src/modules/integration/ingress.service.spec.ts b/src/modules/integration/ingress.service.spec.tsindex 1c5889350..835f75eb5 100644--- a/src/modules/integration/ingress.service.spec.ts+++ b/src/modules/integration/ingress.service.spec.ts@@ -172,6 +172,51 @@ describe('redactSensitiveHeaders (persisted ingress payloads)', () => {});});+describe('IngressService admission verdict', () => {+ it.each([+ {+ label: 'an unauthenticated route',+ signature: { scheme: 'none' },+ headers: {} as Record<string, string>,+ verified: false,+ },+ {+ label: 'a shared-secret route',+ signature: { scheme: 'shared-secret', header: 'X-Provider-Token' },+ headers: { 'x-provider-token': 's' },+ verified: true,+ },+ ])(+ 'records $label as verified: $verified in the stored and queued payload',+ async ({ signature, headers, verified }) => {+ const d = deps({+ manifestRoute: jest.fn().mockReturnValue({+ route: 'chatwoot',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature,+ dedupHeader: 'x-delivery',+ }),+ });+ const res = await new IngressService(d).handle({+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ route: 'chatwoot',+ method: 'POST',+ headers: { 'x-delivery': 'd1', ...headers },+ query: {},+ rawBody: '{}',+ });+ expect(res.status).toBe(202);+ const stored = (d.events.recordOrSkip.mock.calls as unknown as [[{ payload: { admission?: unknown } }]])[0][0];+ const queued = (d.enqueue.mock.calls as unknown as [[{ payload: { admission?: unknown } }]])[0][0];+ expect(stored.payload.admission).toEqual({ verified });+ expect(queued.payload.admission).toEqual({ verified });+ },+ );+});+describe('IngressService.handle', () => {const req = {pluginId: 'chatwoot',diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.tsindex ad904091e..932ead59f 100644--- a/src/modules/integration/ingress.service.ts+++ b/src/modules/integration/ingress.service.ts@@ -50,13 +50,7 @@ export interface IngressDeps {pluginId: string;providerDeliveryId: string;route: string;- payload: {- headers: Record<string, string>;- query: Record<string, string>;- body: string;- rawBody: string;- method?: string;- };+ payload: IngressJobData['payload'] & { method?: string };payloadHash: string;sessionId: string | null;}): Promise<boolean>;@@ -238,6 +232,9 @@ export class IngressService {// 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 = {+ // Every authenticating scheme has passed by here; a `none` route authenticates nothing. Recorded now+ // because a plugin update can change the scheme before a queued or replayed delivery runs.+ admission: { verified: route.signature.scheme !== 'none' },headers: redactSensitiveHeaders(req.headers,route.signature.scheme === 'shared-secret' || route.signature.scheme === 'hmac-sha256'diff --git a/src/modules/queue/processors/ingress.processor.ts b/src/modules/queue/processors/ingress.processor.tsindex 2d258c3e7..a338a18fd 100644--- a/src/modules/queue/processors/ingress.processor.ts+++ b/src/modules/queue/processors/ingress.processor.ts@@ -36,7 +36,14 @@ export interface IngressJobData {// pointer. Undefined when the route declares no pointer — the per-conversation ordering lock then// serializes per instance instead (see orderingKeyFor in ../../integration/ordering-lock).providerConversationId?: string;- payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string };+ payload: {+ headers: Record<string, string>;+ query: Record<string, string>;+ body: string;+ rawBody: string;+ // The host's verdict when it accepted the request; see IngressEvent.payload.+ admission?: { verified: boolean };+ };}// The KeyedAsyncLock wrapping dispatch below guarantees no two dispatches for the SAME conversation