Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(config): refuse compressed request bodies at the in-flight body budget
Yudhi Armyndharis015c0132fdea
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1360f65a4..8cedb31ee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **`rmyndharis-openwa` 0.2.0 on PyPI** — the first release through the trusted-publishing workflow, carrying everything the Python SDK gained since 0.1.0 in June.- **`rmyndharis/openwa` 0.2.0 on Packagist** — the first versioned PHP release since June; Composer users on a stable constraint were pinned to 0.1.0 while only `dev-main` moved.+### Changed++- **A request body with a `Content-Encoding` other than `identity` is now refused with `415`** — the aggregate in-flight body cap counts wire bytes, so a compressed body was admitted on its compressed size and then inflated past the memory it was supposed to bound.+## [0.14.2] - 2026-08-06### Addeddiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 935b898bb..13608b556 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -102,6 +102,7 @@ Validation failures (`statusCode: 400`) return `message` as an **array** of fiel| `404` | Not Found | The addressed resource (session, message, webhook, batch, …) does not exist || `409` | Conflict | A uniqueness constraint was violated (e.g. duplicate name), or a credential teardown for the same session name is still in flight on `start`/`delete` (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`) || `413` | Payload Too Large | Base64 media exceeds the media byte cap (see §6.3) |+| `415` | Unsupported Media Type | The request carries a `Content-Encoding` other than `identity`. Compressed request bodies are not accepted: the aggregate body cap counts wire bytes, so an inflated body would exceed the memory it bounds || `500` | Internal Server Error | Send failed at the WhatsApp engine or an unexpected server error |### Timestamp Conventionsdiff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 750979ad2..f32d03fad 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -670,6 +670,10 @@ MEDIA_DOWNLOAD_MAX_BYTES=52428800# Default 25mb.BODY_SIZE_LIMIT=25mb+# Note: send the body uncompressed. A request carrying Content-Encoding: gzip (or deflate/br)+# is refused with 415 — the aggregate in-flight cap counts bytes on the wire, so a compressed+# body would be admitted small and then inflated past the memory that cap exists to bound.+# Supported formats# Images: jpg, jpeg, png, gif, webp# Videos: mp4, 3gpdiff --git a/src/config/inflight-body-budget.spec.ts b/src/config/inflight-body-budget.spec.tsindex 0a4bd850b..129f0deb2 100644--- a/src/config/inflight-body-budget.spec.ts+++ b/src/config/inflight-body-budget.spec.ts@@ -1,5 +1,8 @@import { EventEmitter } from 'events';-import { Request, Response } from 'express';+import { createServer, request as httpRequest, Server } from 'http';+import { AddressInfo } from 'net';+import { gzipSync } from 'zlib';+import express, { Request, Response, json } from 'express';import {createInflightBodyBudget,parseBodyLimitBytes,@@ -390,3 +393,118 @@ describe('stall reaper', () => {expect(destroyMock(emptyReq)).not.toHaveBeenCalled();});});++/**+ * Compressed bodies, exercised over a REAL server with a RAW http client. The doubles above hand the+ * middleware a header bag and never move a byte, so they cannot show what a compressed body costs+ * once the parser inflates it. A raw client (rather than an assertion library) is deliberate: the+ * exact bytes on the wire are the subject here, and a serializer that helpfully re-encodes a Buffer+ * would test itself instead of the middleware.+ */+describe('compressed request bodies', () => {+ const BUDGET = 64 * 1024;+ /** Compresses ~1000:1, so its declared length is a small fraction of what inflating it costs. */+ const INFLATED_PAYLOAD = Buffer.from(JSON.stringify({ data: 'a'.repeat(2 * MB) }));++ let server: Server | undefined;+ let budget: InflightBodyBudget;+ let port = 0;++ const listen = async (): Promise<void> => {+ budget = createInflightBodyBudget(BUDGET);+ const app = express();+ app.use(budget.middleware);+ app.use(json({ limit: '25mb' }));+ app.post('/echo', (_req, res) => {+ res.status(200).json({ ok: true });+ });+ server = createServer(app);+ await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));+ port = (server.address() as AddressInfo).port;+ };++ interface Reply {+ status: number;+ body: string;+ }++ /**+ * Resolves on the response even when the server drops the socket mid-upload — which is exactly+ * what a refusal does here (it answers, sets Connection: close and never reads the body), so a+ * client that treated the reset as fatal could not observe the status it is meant to assert.+ */+ const send = (headers: Record<string, string>, body: Buffer): Promise<Reply> =>+ new Promise((resolve, reject) => {+ let reply: Reply | undefined;+ const req = httpRequest({ host: '127.0.0.1', port, path: '/echo', method: 'POST', headers }, res => {+ const chunks: Buffer[] = [];+ res.on('data', (chunk: Buffer) => chunks.push(chunk));+ res.on('end', () => {+ reply = { status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString() };+ resolve(reply);+ });+ });+ req.on('error', (error: NodeJS.ErrnoException) => {+ if (reply) return;+ if (error.code === 'ECONNRESET' || error.code === 'EPIPE') return;+ reject(error);+ });+ req.end(body);+ });++ beforeEach(() => jest.useRealTimers());+ afterEach(async () => {+ if (server) await new Promise<void>(resolve => server!.close(() => resolve()));+ server = undefined;+ });++ it('refuses a gzip-encoded body with 415 instead of admitting it on its compressed length', async () => {+ await listen();+ const gzipped = gzipSync(INFLATED_PAYLOAD);+ // The premise: compressed, this body is small enough to sail through admission control.+ expect(gzipped.length).toBeLessThan(BUDGET);+ expect(INFLATED_PAYLOAD.length).toBeGreaterThan(BUDGET);++ const reply = await send(+ {+ 'Content-Type': 'application/json',+ 'Content-Encoding': 'gzip',+ 'Content-Length': String(gzipped.length),+ },+ gzipped,+ );++ expect(reply.status).toBe(415);+ expect(JSON.parse(reply.body)).toEqual({+ statusCode: 415,+ message: 'Compressed request bodies are not supported',+ error: 'Unsupported Media Type',+ });+ expect(budget.currentBytes()).toBe(0);+ });++ it('refuses an oversized UNCOMPRESSED body through the budget, not the encoding guard', async () => {+ await listen();+ const plain = Buffer.alloc(BUDGET + 1, 0x20);++ const reply = await send({ 'Content-Type': 'application/json', 'Content-Length': String(plain.length) }, plain);++ expect(reply.status).toBe(503);+ });++ it('admits an ordinary body declaring Content-Encoding: identity', async () => {+ await listen();+ const plain = Buffer.from(JSON.stringify({ data: 'small' }));++ const reply = await send(+ {+ 'Content-Type': 'application/json',+ 'Content-Encoding': 'identity',+ 'Content-Length': String(plain.length),+ },+ plain,+ );++ expect(reply.status).toBe(200);+ });+});diff --git a/src/config/inflight-body-budget.ts b/src/config/inflight-body-budget.tsindex 77b64c01f..e8becfb4c 100644--- a/src/config/inflight-body-budget.ts+++ b/src/config/inflight-body-budget.ts@@ -11,7 +11,16 @@* This middleware closes the gap. It tracks the aggregate body bytes currently in flight across* ALL connections — the declared Content-Length where present, one budget slot otherwise — and* refuses NEW requests with 503 + Retry-After once the budget is exhausted, without reading a- * single byte of the rejected body. A stalled sender (headers, then silence) holds its+ * single byte of the rejected body.+ *+ * The bound is on WIRE bytes, and it holds as heap only while a body is stored as it arrives.+ * A compressed body would break that — admitted at its compressed length, then inflated by the+ * parser into memory nothing accounted for — so a non-identity Content-Encoding is refused with+ * 415 outright rather than priced. The one remaining looseness is deliberate and bounded: a+ * chunked identity body reserves a placeholder and is reconciled against socket.bytesRead on the+ * poll interval, so it can briefly under-report by the bytes that arrive within one interval.+ *+ * A stalled sender (headers, then silence) holds its* reservation only until the stall reaper drops the socket after STALL_TIMEOUT_MS without any* new body bytes, so a handful of silent connections cannot pin the whole budget. The request* stream itself is never tapped — no 'data' listener — so downstream consumers (the body@@ -127,6 +136,19 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflight.json({ statusCode: 503, message: 'Too much request body data in flight; retry later' });};+ /** Same never-read-the-body disposal as rejectBusy; only the reason and status differ. */+ const rejectCompressed = (req: Request, res: Response): void => {+ if (res.headersSent || res.writableEnded) {+ req.destroy();+ return;+ }+ res.status(415).set('Connection', 'close').json({+ statusCode: 415,+ message: 'Compressed request bodies are not supported',+ error: 'Unsupported Media Type',+ });+ };+const middleware = (req: Request, res: Response, next: NextFunction): void => {const declared = parseDeclaredLength(req.headers['content-length']);// A body with no declared length is expected only when the request is chunk-encoded (Node@@ -134,6 +156,19 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflight// health checks, Content-Length: 0 — reserves nothing and is never reaped.let reserved = declared ?? (req.headers['transfer-encoding'] !== undefined ? undeclaredReservation : 0);+ // Every quantity this budget works with — the declared length, and socket.bytesRead in the+ // reconciler below — is a WIRE measurement, while what the budget exists to bound is HEAP. The+ // two are the same size only while the body is stored as it arrives. A compressed body breaks+ // that: it is admitted on its compressed length and then inflated by the parser, so a payload+ // orders of magnitude larger than the whole budget can be buffered without the accounting ever+ // seeing it. Refusing here — before admission, before a byte is read — keeps the invariant+ // true rather than trying to price an expansion that is not knowable in advance.+ const encoding = (req.headers['content-encoding'] ?? '').trim().toLowerCase();+ if (reserved > 0 && encoding !== '' && encoding !== 'identity') {+ rejectCompressed(req, res);+ return;+ }+// Admission control on the RESERVED size: a request that would push the aggregate past the// budget is refused before a single byte of its body is buffered.if (inFlightBytes + reserved > budgetBytes) {diff --git a/src/main.ts b/src/main.tsindex 7fa2ab2c4..7cfc43aa0 100644--- a/src/main.ts+++ b/src/main.ts@@ -124,9 +124,14 @@ async function bootstrap() {// The `verify` callback stashes the EXACT bytes json() received on req.rawBody, byte-identical to// what a provider signed, so the @Public ingress controller can HMAC-verify over the raw body// (JSON.stringify(req.body) is NOT byte-identical). Cheap for every route; non-ingress routes ignore it.+ // `inflate: false` is a backstop, not the guard: the budget middleware above already refuses a+ // compressed body with 415 before a byte is read. It sits here so a future middleware reordering,+ // or a route-level parser mounted past that middleware, cannot silently reopen the gap — an+ // inflated body is charged to the budget at its compressed size and bounded by nothing.app.use(json({limit: bodyLimit,+ inflate: false,verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {req.rawBody = buf;},@@ -136,6 +141,7 @@ async function bootstrap() {urlencoded({extended: true,limit: bodyLimit,+ inflate: false,// Form-encoded webhook providers also sign the exact wire bytes. Use the same capture contract// as json(); other content types remain unsupported rather than installing a global catch-all.verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {