Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(security): bound the in-flight body budget per client IP
Yudhi Armyndharisb7f191b7cd8a
diff --git a/.env.example b/.env.exampleindex 67d5baa34..627122055 100644--- a/.env.example+++ b/.env.example@@ -740,3 +740,5 @@ PLUGINS_DIR=./data/plugins # Plugin directory (default: ./data/plugins)# get 503 + Retry-After without their body being read (protects against slow-body memory pinning).# Keep it >= BODY_SIZE_LIMIT. Default: 4 x BODY_SIZE_LIMIT (100 MiB with the default 25mb cap).# INFLIGHT_BODY_BUDGET_BYTES=104857600+# # Each client IP gets half the budget as its own share (no one+# # uploader/attacker can pin more), keyed via TRUSTED_PROXIES.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6759861bf..5f281da1c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- The in-flight body budget gives each client IP its own share (half the aggregate by default, keyed through TRUSTED_PROXIES): four trickle connections from one source now exhaust only that source's share instead of 503ing every body-bearing request for everyone.- The lifecycle fences (teardown chaining, fail-closed 409, identity-checked initial-status waits, force-destroy eviction) and the status broadcaster (persist-then-mirror, transition de-dup, clear-on-delete) carry their own unit specs instead of being reachable only through the session-service suite's white-box pokes.- Follow-ups: the transient-launch classifier rejects every HttpException up front (the 504 no-retry no longer rests on message wording) and recognizes ECONNRESET; the sendTemplate 404 description names only the template; import-status normalization comments and the parity-fence failure messages state their exact scope.- GET /contacts/:id/phone keeps its documented 400/409 answers (not-started, not-ready) and nulls only genuine lookup failures, logging them at debug; the boundary swallow had absorbed the deliberate errors too.diff --git a/src/config/inflight-body-budget.spec.ts b/src/config/inflight-body-budget.spec.tsindex 76b152583..01230d6d2 100644--- a/src/config/inflight-body-budget.spec.ts+++ b/src/config/inflight-body-budget.spec.ts@@ -18,7 +18,10 @@ const MB = 1024 * 1024;const makeReq = (headers: Record<string, string> = {}): Request & EventEmitter => {const req = new EventEmitter() as unknown as Request & EventEmitter;(req as unknown as { headers: Record<string, string> }).headers = headers;- (req as unknown as { socket: { bytesRead: number } }).socket = { bytesRead: 0 };+ (req as unknown as { socket: { bytesRead: number; remoteAddress: string } }).socket = {+ bytesRead: 0,+ remoteAddress: '203.0.113.7',+ };(req as unknown as { destroy: jest.Mock }).destroy = jest.fn();return req;};@@ -94,7 +97,7 @@ describe('resolveInflightBodyBudgetBytes', () => {describe('createInflightBodyBudget middleware', () => {it('admits a request under budget and reserves its declared Content-Length', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'content-length': '400' });const { next, state } = run(budget, req);@@ -104,14 +107,14 @@ describe('createInflightBodyBudget middleware', () => {});it('does not attach a data listener when a Content-Length was declared (stream left untouched)', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'content-length': '400' });run(budget, req);expect(req.listenerCount('data')).toBe(0);});it('admits a request that lands exactly on the budget', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });run(budget, makeReq({ 'content-length': '600' }));const { next } = run(budget, makeReq({ 'content-length': '400' }));expect(next).toHaveBeenCalledTimes(1);@@ -119,7 +122,7 @@ describe('createInflightBodyBudget middleware', () => {});it('rejects with 503 + Retry-After, without reading the body, when the declared size would exceed the budget', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });run(budget, makeReq({ 'content-length': '800' }));const rejected = makeReq({ 'content-length': '300' });@@ -137,21 +140,21 @@ describe('createInflightBodyBudget middleware', () => {});it('sends the configured Retry-After value', () => {- const budget = createInflightBodyBudget(100, { retryAfterSeconds: 5 });+ const budget = createInflightBodyBudget(100, { retryAfterSeconds: 5, perClientShare: 1 });run(budget, makeReq({ 'content-length': '100' }));const { headers } = run(budget, makeReq({ 'content-length': '1' }));expect(headers['retry-after']).toBe('5');});it('admits a zero-length body even when the budget is fully used', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });run(budget, makeReq({ 'content-length': '1000' }));const { next } = run(budget, makeReq({ 'content-length': '0' }));expect(next).toHaveBeenCalledTimes(1);});it('releases the reservation exactly once on normal completion', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'content-length': '400' });const { res } = run(budget, req);@@ -164,7 +167,7 @@ describe('createInflightBodyBudget middleware', () => {});it('releases exactly once on a client abort (request close before the response)', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'content-length': '400' });const { res } = run(budget, req);@@ -177,7 +180,7 @@ describe('createInflightBodyBudget middleware', () => {});it('releases on stream errors (request or response side)', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const reqA = makeReq({ 'content-length': '400' });run(budget, reqA);reqA.emit('error', new Error('boom'));@@ -190,7 +193,7 @@ describe('createInflightBodyBudget middleware', () => {});it('takes only an opening placeholder for chunk-encoded bodies and releases it on completion', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'transfer-encoding': 'chunked' });const { res, next } = run(budget, req);@@ -209,7 +212,7 @@ describe('createInflightBodyBudget middleware', () => {it('does not price a small chunked body at a whole per-request slot', () => {// Regression: reserving budget/4 up front turned the byte budget into a concurrency limit of 4// for chunked senders — four 6-byte uploads refused every further body-carrying request.- const budget = createInflightBodyBudget(64 * 1024 * 1024);+ const budget = createInflightBodyBudget(64 * 1024 * 1024, { perClientShare: 1 });for (let i = 0; i < 8; i++) {const { next } = run(budget, makeReq({ 'transfer-encoding': 'chunked' }));expect(next).toHaveBeenCalledTimes(1);@@ -218,7 +221,7 @@ describe('createInflightBodyBudget middleware', () => {});it('still refuses an un-declared body once the aggregate is exhausted', () => {- const budget = createInflightBodyBudget(2 * 1024 * 1024);+ const budget = createInflightBodyBudget(2 * 1024 * 1024, { perClientShare: 1 });for (let i = 0; i < 2; i++) {expect(run(budget, makeReq({ 'transfer-encoding': 'chunked' })).next).toHaveBeenCalledTimes(1);}@@ -228,7 +231,7 @@ describe('createInflightBodyBudget middleware', () => {});it('reserves nothing for requests with neither Content-Length nor Transfer-Encoding', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });run(budget, makeReq({ 'content-length': '1000' }));// No body expected (health checks, GETs): admitted even with the budget fully reserved.const req = makeReq();@@ -239,7 +242,7 @@ describe('createInflightBodyBudget middleware', () => {});it('drops the socket instead of writing a 503 when the response is already flushing', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });run(budget, makeReq({ 'content-length': '800' }));const req = makeReq({ 'content-length': '300' });@@ -255,7 +258,7 @@ describe('createInflightBodyBudget middleware', () => {});it('reuses freed budget for the next request (no leak across a full lifecycle)', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });for (let i = 0; i < 5; i++) {const req = makeReq({ 'content-length': '900' });const { res, next } = run(budget, req);@@ -273,7 +276,7 @@ describe('stall reaper', () => {const destroyMock = (req: Request): jest.Mock => (req as unknown as { destroy: jest.Mock }).destroy;it('reaps a stalled declared-length connection and releases its reservation', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'content-length': '400' });run(budget, req);expect(budget.currentBytes()).toBe(400);@@ -290,7 +293,7 @@ describe('stall reaper', () => {});it('reaps a stalled chunk-encoded connection the same way', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'transfer-encoding': 'chunked' });run(budget, req);expect(budget.currentBytes()).toBe(1000);@@ -301,7 +304,7 @@ describe('stall reaper', () => {});it('does not reap a connection that keeps making progress, however slow', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'content-length': '400' });run(budget, req);const socket = (req as unknown as { socket: { bytesRead: number } }).socket;@@ -316,7 +319,7 @@ describe('stall reaper', () => {});it('stops reaping once the declared body has fully arrived', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'content-length': '400' });const { res } = run(budget, req);(req as unknown as { socket: { bytesRead: number } }).socket.bytesRead = 400;@@ -330,7 +333,7 @@ describe('stall reaper', () => {});it('stops reaping once the downstream consumer finished reading (end)', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'transfer-encoding': 'chunked' });const { res } = run(budget, req);@@ -344,7 +347,7 @@ describe('stall reaper', () => {});it('reconciles a chunked reservation with the bytes that actually arrive', () => {- const budget = createInflightBodyBudget(64 * 1024 * 1024);+ const budget = createInflightBodyBudget(64 * 1024 * 1024, { perClientShare: 1 });const req = makeReq({ 'transfer-encoding': 'chunked' });run(budget, req);expect(budget.currentBytes()).toBe(1024 * 1024); // opening placeholder@@ -356,7 +359,7 @@ describe('stall reaper', () => {});it('aborts an un-declared body that streams past the aggregate budget', () => {- const budget = createInflightBodyBudget(2 * 1024 * 1024);+ const budget = createInflightBodyBudget(2 * 1024 * 1024, { perClientShare: 1 });const req = makeReq({ 'transfer-encoding': 'chunked' });run(budget, req);@@ -366,11 +369,94 @@ describe('stall reaper', () => {expect(budget.currentBytes()).toBe(0);});+ // The per-client share: the DoS bound is per ATTACKER, not per deployment. The spec doubles+ // share one remoteAddress, so every request here comes from the same client.+ describe('per-client share of the budget', () => {+ const runFrom = (budget: InflightBodyBudget, ip: string, headers: Record<string, string>) => {+ const req = makeReq(headers);+ (req as unknown as { socket: { bytesRead: number; remoteAddress: string } }).socket = {+ bytesRead: 0,+ remoteAddress: ip,+ };+ return run(budget, req);+ };++ it('refuses a SECOND client request once that client holds its share, while a different client is still admitted', () => {+ const budget = createInflightBodyBudget(1000); // default share 0.5 -> cap 500+ const { next: firstOk } = runFrom(budget, '198.51.100.1', { 'content-length': '400' });+ expect(firstOk).toHaveBeenCalledTimes(1);++ // Same client, over its 500-byte share now.+ const { next: refused, state } = runFrom(budget, '198.51.100.1', { 'content-length': '200' });+ expect(refused).not.toHaveBeenCalled();+ expect(state.code).toBe(503);++ // A different client sails through - the whole aggregate is still theirs to use.+ const { next: other } = runFrom(budget, '198.51.100.2', { 'content-length': '400' });+ expect(other).toHaveBeenCalledTimes(1);+ });++ it('releases the client ledger exactly once: a finished body frees the share', () => {+ const budget = createInflightBodyBudget(1000);+ const { res } = runFrom(budget, '198.51.100.1', { 'content-length': '400' });+ res.emit('finish');+ const { next } = runFrom(budget, '198.51.100.1', { 'content-length': '400' });+ expect(next).toHaveBeenCalledTimes(1);+ expect(budget.clientBytes(makeReq() as never)).toBe(0);+ });++ it('X-Forwarded-For is IGNORED without trusted proxies (share keys on the socket address)', () => {+ const budget = createInflightBodyBudget(1000);+ const reqA = makeReq({ 'content-length': '400', 'x-forwarded-for': '192.0.2.1' });+ const a = run(budget, reqA);+ const reqB = makeReq({ 'content-length': '400', 'x-forwarded-for': '192.0.2.2' });+ const b = run(budget, reqB);+ // Both share one socket address -> one share -> the second is over the cap.+ expect(a.next).toHaveBeenCalledTimes(1);+ expect(b.next).not.toHaveBeenCalled();+ });++ it('X-Forwarded-For keys the share when the proxy is trusted', () => {+ const budget = createInflightBodyBudget(1000, { trustedProxies: ['127.0.0.1'] });+ const base = { 'x-forwarded-for': '', 'content-length': '400' };+ const reqA = makeReq({ ...base, 'x-forwarded-for': '192.0.2.1' });+ (reqA as unknown as { socket: { bytesRead: number; remoteAddress: string } }).socket = {+ bytesRead: 0,+ remoteAddress: '127.0.0.1',+ };+ const reqB = makeReq({ ...base, 'x-forwarded-for': '192.0.2.2' });+ (reqB as unknown as { socket: { bytesRead: number; remoteAddress: string } }).socket = {+ bytesRead: 0,+ remoteAddress: '127.0.0.1',+ };+ expect(run(budget, reqA).next).toHaveBeenCalledTimes(1);+ expect(run(budget, reqB).next).toHaveBeenCalledTimes(1);+ });++ it('perClientShare: 1 restores single-client use of the whole budget', () => {+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });+ expect(runFrom(budget, '198.51.100.1', { 'content-length': '600' }).next).toHaveBeenCalledTimes(1);+ expect(runFrom(budget, '198.51.100.1', { 'content-length': '400' }).next).toHaveBeenCalledTimes(1);+ });++ it('aborts a chunked body that crosses its client share mid-stream', () => {+ const budget = createInflightBodyBudget(10 * 1024 * 1024); // cap 5 MiB+ const req = makeReq({ 'transfer-encoding': 'chunked' });+ run(budget, req);++ (req as unknown as { socket: { bytesRead: number } }).socket.bytesRead = 6 * 1024 * 1024;+ jest.advanceTimersByTime(5_000);+ expect(destroyMock(req)).toHaveBeenCalledTimes(1);+ expect(budget.currentBytes()).toBe(0);+ expect(budget.clientBytes(req as never)).toBe(0);+ });+ });+it('does not reap a fully-received request whose body no parser consumed', () => {// The body can arrive in the same segment as the headers, so socket.bytesRead never moves again// and 'end' never fires when no parser reads the stream. Killing that request at the stall// timeout would drop a healthy connection mid-handler.- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const req = makeReq({ 'content-length': '400' });const { res } = run(budget, req);(req as unknown as { complete: boolean }).complete = true;@@ -384,7 +470,7 @@ describe('stall reaper', () => {});it('never arms the reaper for requests without a body', () => {- const budget = createInflightBodyBudget(1000);+ const budget = createInflightBodyBudget(1000, { perClientShare: 1 });const getReq = makeReq();const emptyReq = makeReq({ 'content-length': '0' });run(budget, getReq);diff --git a/src/config/inflight-body-budget.ts b/src/config/inflight-body-budget.tsindex d8b8e112b..c857aa956 100644--- a/src/config/inflight-body-budget.ts+++ b/src/config/inflight-body-budget.ts@@ -34,6 +34,7 @@*/import { Request, Response, NextFunction } from 'express';import { resolveBodyLimit } from './bootstrap-security';+import { resolveClientIp } from '../common/utils/ip';/*** Default budget = 4 × the per-request body cap: a handful of concurrent full-size media uploads@@ -103,17 +104,43 @@ export function resolveInflightBodyBudgetBytes(budgetEnv?: string, bodyLimitEnv?export interface InflightBodyBudgetOptions {/** Retry-After value (seconds) sent with the 503. Default 1 — budget frees as bodies finish. */retryAfterSeconds?: number;+ /**+ * Trusted proxies for client-IP resolution (TRUSTED_PROXIES). Untrusted by default: with no+ * proxy named, the X-Forwarded-For header is ignored and every connection keys on its socket+ * address - which behind an unconfigured reverse proxy is ONE address, i.e. one shared share.+ * That is the same trade the API-key allowlists and the throttler make; the boot-time proxy+ * warning covers the operator half.+ */+ trustedProxies?: string[];+ /**+ * Per-client share of the aggregate budget as a fraction in (0, 1]. Default 0.5: no single+ * client can pin more than half the budget, so two independent heavy uploaders still coexist;+ * a legitimate bulk uploader above the share gets 503 + Retry-After, not a hang.+ */+ perClientShare?: number;}export interface InflightBodyBudget {middleware: (req: Request, res: Response, next: NextFunction) => void;/** Aggregate bytes currently attributed to in-flight request bodies (observability/tests). */currentBytes: () => number;+ /** Bytes currently attributed to one client's in-flight bodies (observability/tests). */+ clientBytes: (req: Request) => number;}export function createInflightBodyBudget(budgetBytes: number, options?: InflightBodyBudgetOptions): InflightBodyBudget {let inFlightBytes = 0;const retryAfter = String(options?.retryAfterSeconds ?? 1);+ const trustedProxies = options?.trustedProxies ?? [];+ const share = Math.min(1, Math.max(Number.EPSILON, options?.perClientShare ?? 0.5));+ const perClientCap = Math.max(1, Math.floor(budgetBytes * share));+ // Per-client in-flight bytes. The key is the resolved client IP; entries are created lazily and+ // deleted by the same exactly-once release that decrements the aggregate, so the map cannot+ // leak a client that finished. A cap on the MAP itself guards the pathological many-spoofed-IPs+ // case: past it, a NEW client key is treated as busiest (refused) rather than evicting a live+ // one - refusing beats corrupting another client's accounting.+ const clientInFlight = new Map<string, number>();+ const MAX_TRACKED_CLIENTS = 10_000;// Opening reservation for a body with no declared length (chunked). It is only a placeholder:// the poller below reconciles it against the bytes that actually arrive, so a small chunked// request ends up costing what it really weighs. Reserving a whole per-request cap up front@@ -184,14 +211,21 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflightreturn;}- // 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) {+ // Admission control on the RESERVED size: a request that would push the aggregate OR ITS+ // CLIENT'S SHARE past the budget is refused before a single byte of its body is buffered.+ // The per-client check is what makes the DoS bounded per attacker rather than per deployment:+ // four trickle connections from one source exhaust only that source's share, and every other+ // client's uploads still land.+ const clientKey = resolveClientIp(req, trustedProxies);+ const clientBusy = clientInFlight.get(clientKey) ?? 0;+ const mapAtCapacity = clientInFlight.size >= MAX_TRACKED_CLIENTS && !clientInFlight.has(clientKey);+ if (inFlightBytes + reserved > budgetBytes || clientBusy + reserved > perClientCap || mapAtCapacity) {rejectBusy(req, res);return;}inFlightBytes += reserved;+ if (!mapAtCapacity) clientInFlight.set(clientKey, clientBusy + reserved);let released = false;let stallTimer: ReturnType<typeof setInterval> | undefined;@@ -209,6 +243,11 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflightreleased = true;disarmStallReaper();inFlightBytes -= reserved;+ if (!mapAtCapacity) {+ const busy = (clientInFlight.get(clientKey) ?? reserved) - reserved;+ if (busy > 0) clientInFlight.set(clientKey, busy);+ else clientInFlight.delete(clientKey);+ }};res.on('finish', release);res.on('close', release);@@ -234,8 +273,21 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflightconst reconcileUndeclared = (readNow: number): void => {const actual = Math.max(undeclaredReservation, readNow - startBytes);if (actual === reserved) return;- inFlightBytes += actual - reserved;+ const delta = actual - reserved;+ inFlightBytes += delta;reserved = actual;+ if (!mapAtCapacity) {+ // Crossing the per-client cap mid-stream aborts too: the share bound applies to what is+ // actually arriving, not only to what was declared. reserved is updated BEFORE release()+ // so the exactly-once decrement subtracts the reconciled size, not the placeholder.+ const busy = (clientInFlight.get(clientKey) ?? 0) + delta;+ clientInFlight.set(clientKey, busy);+ if (busy > perClientCap) {+ release();+ req.destroy();+ return;+ }+ }if (inFlightBytes > budgetBytes) {release();req.destroy();@@ -272,7 +324,11 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflightnext();};- return { middleware, currentBytes: () => inFlightBytes };+ return {+ middleware,+ currentBytes: () => inFlightBytes,+ clientBytes: req => clientInFlight.get(resolveClientIp(req, trustedProxies)) ?? 0,+ };}/** A well-formed Content-Length, or undefined when absent/unusable (then reserve one slot if chunk-encoded). */diff --git a/src/main.ts b/src/main.tsindex 467fe0969..66f35762d 100644--- a/src/main.ts+++ b/src/main.ts@@ -128,7 +128,14 @@ async function bootstrap() {process.env.INFLIGHT_BODY_BUDGET_BYTES,process.env.BODY_SIZE_LIMIT,);- app.use(createInflightBodyBudget(inflightBudgetBytes).middleware);+ app.use(+ createInflightBodyBudget(inflightBudgetBytes, {+ trustedProxies: (process.env.TRUSTED_PROXIES || '')+ .split(',')+ .map(p => p.trim())+ .filter(Boolean),+ }).middleware,+ );// Cap request body size (DoS hardening). Media sends carry base64 in the JSON body,// so the default is generous; tune with BODY_SIZE_LIMIT.