Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(integration): make the per-route ingress body cap non-vacuous

Yudhi Armyndharis1378c9846f89
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c7b1549c2..3f2c950d7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- An ingress route whose manifest omits `maxBodyBytes` is no longer unbounded by its own cap. The check compared a byte length against `undefined`, which is always false, so the per-route 413 the published contract promises was silently inert — and every accepted delivery is persisted with the body stored twice and carried into the queue, turning one forgotten manifest field into a write amplifier with no load-time error and no runtime signal. A route with no usable value now falls back to the process-wide body limit (what it was already bounded by in practice, so nothing accepted today starts failing) and the gap is logged once per route instead of passing in silence.
+
- A `message:sending` plugin handler that returns a payload without a usable `input` no longer turns every outbound send on that session into a 500. The gate read `.input` off the hook chain's reply unchecked, so a malformed envelope handed `undefined` to each caller — or threw inside the gate for a `null` — with nothing in the error naming a plugin. The send is now refused with a message that names the hook, and refused rather than sent: this is a moderation chokepoint, and a handler whose reply cannot be read may have been redacting something. A chain that replies with nothing at all is unchanged and keeps the caller's own input.
- The `openwa_sessions_restricted` gauge now follows a restriction that lapses on its own. It was republished only when a restriction was recorded or cleared, and an expiry is neither — so after a reachout timelock passed its stated end, the gauge kept reporting the pre-expiry count while every read path already reported the session as unrestricted, leaving an alert on `> 0` firing indefinitely and disagreeing with `GET /api/sessions`.
diff --git a/src/modules/integration/ingress.service.spec.ts b/src/modules/integration/ingress.service.spec.ts
index 69cd48b35..66a5c6e71 100644
--- a/src/modules/integration/ingress.service.spec.ts
+++ b/src/modules/integration/ingress.service.spec.ts
@@ -119,6 +119,34 @@ describe('IngressService.handle', () => {
expect(d.events.recordOrSkip).not.toHaveBeenCalled();
});
+ // `Buffer.byteLength(rawBody) > route.maxBodyBytes` is always false when the manifest omits the
+ // field, so a route declaring no cap silently enforced none — the 413 the published contract
+ // promises was inert, and every accepted delivery is persisted with the body stored twice. A
+ // manifest that forgets one field must not turn a route into an unbounded write amplifier.
+ it.each([
+ ['omitted', undefined],
+ ['non-numeric', 'lots' as unknown as number],
+ ['zero', 0],
+ ['negative', -1],
+ ])('falls back to a real cap when maxBodyBytes is %s', async (_label, maxBodyBytes) => {
+ const d = deps({
+ manifestRoute: jest.fn().mockReturnValue({
+ route: 'chatwoot',
+ mode: 'async',
+ verify: 'core',
+ maxBodyBytes,
+ signature: { scheme: 'none' },
+ dedupHeader: 'x-delivery',
+ }),
+ });
+ const svc = new IngressService(d);
+ const huge = { ...req, rawBody: 'x'.repeat(64 * 1024 * 1024) };
+ const res = await svc.handle(huge);
+
+ expect(res.status).toBe(413);
+ expect(d.events.recordOrSkip).not.toHaveBeenCalled();
+ });
+
it('rejects a bad signature with 401 before any dedup or enqueue', async () => {
const d = deps({
manifestRoute: jest.fn().mockReturnValue({
diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.ts
index 4550fae28..e9861dda9 100644
--- a/src/modules/integration/ingress.service.ts
+++ b/src/modules/integration/ingress.service.ts
@@ -5,6 +5,9 @@ import { IngressJobData } from '../queue/processors/ingress.processor';
import type { EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';
import { evaluatePreflight } from './ingress-preflight';
import { renderAck } from './ingress-ack';
+import { parseBodyLimitBytes } from '../../config/inflight-body-budget';
+import { resolveBodyLimit } from '../../config/bootstrap-security';
+import { createLogger } from '../../common/services/logger.service';
export interface IngressRequest {
pluginId: string;
@@ -64,8 +67,28 @@ export interface IngressDeps {
* body → dedup (persist-before-ack) → best-effort conversation id → enqueue (or inline) → 202.
*/
export class IngressService {
+ private readonly logger = createLogger('IngressService');
+
constructor(private readonly deps: IngressDeps) {}
+ /**
+ * The cap to apply when a manifest route declares none. Warned once per route so an incomplete
+ * manifest is visible to the operator rather than silently degrading to the global limit.
+ */
+ private readonly warnedMissingCap = new Set<string>();
+
+ private fallbackMaxBodyBytes(pluginId: string, route: string): number {
+ const key = `${pluginId}:${route}`;
+ if (!this.warnedMissingCap.has(key)) {
+ this.warnedMissingCap.add(key);
+ this.logger.warn(
+ `Ingress route ${key} declares no usable maxBodyBytes; falling back to the process body limit. ` +
+ 'Set a per-route maxBodyBytes in the plugin manifest.',
+ );
+ }
+ return parseBodyLimitBytes(resolveBodyLimit(process.env.BODY_SIZE_LIMIT));
+ }
+
async handle(req: IngressRequest): Promise<{ status: number; body?: string; headers?: Record<string, string> }> {
const instance = await this.deps.instances.resolve(req.pluginId, req.instanceId);
if (!instance || !instance.enabled) return { status: 404, body: 'unknown instance' };
@@ -85,7 +108,21 @@ export class IngressService {
return { status: 403, body: 'challenge failed' };
}
- if (Buffer.byteLength(req.rawBody, 'utf8') > route.maxBodyBytes) return { status: 413, body: 'payload too large' };
+ // `n > undefined` is always false, so a manifest that omits maxBodyBytes — or carries a
+ // non-numeric or non-positive value — left this check inert: the 413 the published contract
+ // promises never fired, and every accepted delivery is persisted with the body stored twice
+ // (payload.body and payload.rawBody) and carried into the queue. A third-party adapter forgetting
+ // one field turned its route into a write amplifier with no load-time error and no runtime signal.
+ //
+ // The fallback is the process-wide body limit, which is what such a route was already bounded by
+ // in practice, so no delivery that is accepted today starts failing. What changes is that the
+ // check can no longer be vacuous, and the gap is now stated in the log instead of being silent.
+ const declaredCap = route.maxBodyBytes;
+ const effectiveCap =
+ typeof declaredCap === 'number' && Number.isFinite(declaredCap) && declaredCap > 0
+ ? declaredCap
+ : this.fallbackMaxBodyBytes(req.pluginId, route.route);
+ if (Buffer.byteLength(req.rawBody, 'utf8') > effectiveCap) return { status: 413, body: 'payload too large' };
const verdict = verifyIngressSignature(route.signature, {
rawBody: req.rawBody,