Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(bootstrap): cap aggregate in-flight request bodies before the body parser (#936)

Yudhi Armyndharis0e922109ec5b
diff --git a/.env.example b/.env.example
index 49c0e0ceb..e3ee2f1d6 100644
--- a/.env.example
+++ b/.env.example
@@ -400,3 +400,7 @@ API_MASTER_KEY=
# =============================================================================
ENABLE_SWAGGER=true # Enable API documentation at /api/docs (set false to disable on exposed deployments)
BODY_SIZE_LIMIT=25mb # Max request body size (base64 media sends ride in the JSON body)
+# Aggregate cap on request-body bytes buffered across ALL connections. Once exceeded, new requests
+# 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
diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.ts
index 19f5f81dc..a6198cf33 100644
--- a/src/config/configuration.spec.ts
+++ b/src/config/configuration.spec.ts
@@ -140,6 +140,30 @@ describe('configuration — status media cap is fail-safe', () => {
});
});
+describe('configuration — in-flight body budget', () => {
+ const keys = ['INFLIGHT_BODY_BUDGET_BYTES', 'BODY_SIZE_LIMIT'];
+ const orig: Record<string, string | undefined> = {};
+ beforeEach(() => keys.forEach(k => (orig[k] = process.env[k])));
+ afterEach(() =>
+ keys.forEach(k => {
+ if (orig[k] === undefined) delete process.env[k];
+ else process.env[k] = orig[k];
+ }),
+ );
+
+ it('defaults to 4 × the per-request body cap and scales with BODY_SIZE_LIMIT', () => {
+ keys.forEach(k => delete process.env[k]);
+ expect(configuration().http.inflightBodyBudgetBytes).toBe(100 * 1024 * 1024);
+ process.env.BODY_SIZE_LIMIT = '5mb';
+ expect(configuration().http.inflightBodyBudgetBytes).toBe(20 * 1024 * 1024);
+ });
+
+ it('honors an explicit INFLIGHT_BODY_BUDGET_BYTES override', () => {
+ process.env.INFLIGHT_BODY_BUDGET_BYTES = '52428800';
+ expect(configuration().http.inflightBodyBudgetBytes).toBe(52428800);
+ });
+});
+
describe('configuration search namespace', () => {
// Save/restore the SEARCH_* env vars so a CI .env that sets them cannot flake the default-value
// assertions below (mirrors the mutate-and-restore pattern used for PLUGIN_DOWNLOAD_MAX_BYTES etc.).
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index afcd566a7..5033b3d00 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -1,4 +1,5 @@
import { computeFeatureFlags } from './feature-flags';
+import { resolveInflightBodyBudgetBytes } from './inflight-body-budget';
export default () => ({
port: parseInt(process.env.PORT || '2785', 10),
@@ -12,6 +13,13 @@ export default () => ({
requestTimeoutMs: parseInt(process.env.REQUEST_TIMEOUT_MS || '300000', 10),
headersTimeoutMs: parseInt(process.env.HEADERS_TIMEOUT_MS || '65000', 10),
keepAliveTimeoutMs: parseInt(process.env.KEEPALIVE_TIMEOUT_MS || '5000', 10),
+ // Aggregate cap on request-body bytes buffered across ALL connections (the pre-body-parser
+ // budget middleware in main.ts). Defaults to 4 × the per-request BODY_SIZE_LIMIT so the two
+ // scale together; explicit bytes override via INFLIGHT_BODY_BUDGET_BYTES.
+ inflightBodyBudgetBytes: resolveInflightBodyBudgetBytes(
+ process.env.INFLIGHT_BODY_BUDGET_BYTES,
+ process.env.BODY_SIZE_LIMIT,
+ ),
},
// Global message search. Opt-out via SEARCH_ENABLED=false. Provider defaults to 'auto' (the
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.ts
index ba6951eb2..d79503f34 100644
--- a/src/config/env.validation.spec.ts
+++ b/src/config/env.validation.spec.ts
@@ -92,6 +92,13 @@ describe('validateEnv', () => {
expect(() => validateEnv({ RATE_LIMIT_SHORT_LIMIT: '10', WEBHOOK_TIMEOUT: '10000' })).not.toThrow();
});
+ it('rejects a non-positive / non-integer in-flight body budget (0 would refuse every body)', () => {
+ expect(() => validateEnv({ INFLIGHT_BODY_BUDGET_BYTES: '0' })).toThrow(/INFLIGHT_BODY_BUDGET_BYTES/);
+ expect(() => validateEnv({ INFLIGHT_BODY_BUDGET_BYTES: '100mb' })).toThrow(/INFLIGHT_BODY_BUDGET_BYTES/);
+ expect(() => validateEnv({ INFLIGHT_BODY_BUDGET_BYTES: '-5' })).toThrow(/INFLIGHT_BODY_BUDGET_BYTES/);
+ expect(() => validateEnv({ INFLIGHT_BODY_BUDGET_BYTES: '104857600' })).not.toThrow();
+ });
+
it('rejects a non-canonical boolean feature flag instead of silently disabling the feature', () => {
// QUEUE_ENABLED / MCP_ENABLED / SERVE_DASHBOARD are read at module-eval with `=== 'true'` /
// `!== 'false'`, so a typo silently (dis)ables the feature with zero diagnostics. Boot must reject it.
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index 1dffe48b0..11294b99e 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -152,6 +152,8 @@ export function validateEnv(config: EnvConfig): EnvConfig {
'HEADERS_TIMEOUT_MS',
'KEEPALIVE_TIMEOUT_MS',
'WEBHOOK_DISPATCH_CONCURRENCY',
+ // 0 would refuse every request carrying a body (a self-DoS), so the budget is positive-only.
+ 'INFLIGHT_BODY_BUDGET_BYTES',
]) {
checkPositiveInt(key);
}
diff --git a/src/config/inflight-body-budget.spec.ts b/src/config/inflight-body-budget.spec.ts
new file mode 100644
index 000000000..bb2170ae3
--- /dev/null
+++ b/src/config/inflight-body-budget.spec.ts
@@ -0,0 +1,237 @@
+import { EventEmitter } from 'events';
+import { Request, Response } from 'express';
+import {
+ createInflightBodyBudget,
+ parseBodyLimitBytes,
+ resolveInflightBodyBudgetBytes,
+ InflightBodyBudget,
+} from './inflight-body-budget';
+
+const MB = 1024 * 1024;
+
+/** Minimal req/res doubles: real EventEmitters so the middleware's listener accounting runs as-is. */
+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;
+ return req;
+};
+
+const makeRes = () => {
+ const state = { code: 0, payload: undefined as unknown };
+ const headers: Record<string, string> = {};
+ const res = Object.assign(new EventEmitter(), {
+ status(code: number) {
+ state.code = code;
+ return res;
+ },
+ set(name: string, value: string) {
+ headers[name.toLowerCase()] = value;
+ return res;
+ },
+ json(payload: unknown) {
+ state.payload = payload;
+ return res;
+ },
+ }) as unknown as Response & EventEmitter;
+ return { res, headers, state };
+};
+
+const run = (budget: InflightBodyBudget, req: Request & EventEmitter) => {
+ const mock = makeRes();
+ const next = jest.fn();
+ budget.middleware(req, mock.res, next);
+ return { ...mock, next };
+};
+
+describe('parseBodyLimitBytes', () => {
+ it('parses the formats resolveBodyLimit accepts, using binary units like the body parser', () => {
+ expect(parseBodyLimitBytes('25mb')).toBe(25 * MB);
+ expect(parseBodyLimitBytes('1024')).toBe(1024);
+ expect(parseBodyLimitBytes('1.5gb')).toBe(1.5 * 1024 * MB);
+ expect(parseBodyLimitBytes('10MB')).toBe(10 * MB);
+ expect(parseBodyLimitBytes('512kb')).toBe(512 * 1024);
+ });
+
+ it('falls back to the 25 MiB default on an impossible value rather than throwing', () => {
+ expect(parseBodyLimitBytes('not-a-limit')).toBe(25 * MB);
+ });
+});
+
+describe('resolveInflightBodyBudgetBytes', () => {
+ it('defaults to 4 × the default per-request cap (25 MiB → 100 MiB)', () => {
+ expect(resolveInflightBodyBudgetBytes(undefined, undefined)).toBe(100 * MB);
+ expect(resolveInflightBodyBudgetBytes('', '')).toBe(100 * MB);
+ });
+
+ it('scales with BODY_SIZE_LIMIT so tuning the per-request cap tunes the aggregate', () => {
+ expect(resolveInflightBodyBudgetBytes(undefined, '5mb')).toBe(20 * MB);
+ });
+
+ it('uses the default per-request cap when BODY_SIZE_LIMIT is unparseable (matches the parser)', () => {
+ expect(resolveInflightBodyBudgetBytes(undefined, 'unlimited')).toBe(100 * MB);
+ });
+
+ it('lets an explicit INFLIGHT_BODY_BUDGET_BYTES win over the derived default', () => {
+ expect(resolveInflightBodyBudgetBytes('123456', '5mb')).toBe(123456);
+ expect(resolveInflightBodyBudgetBytes(' 2048 ', undefined)).toBe(2048);
+ });
+
+ it('ignores an invalid explicit value (env.validation rejects it at boot anyway)', () => {
+ for (const bad of ['0', '-10', 'abc', '10.5']) {
+ expect(resolveInflightBodyBudgetBytes(bad, undefined)).toBe(100 * MB);
+ }
+ });
+});
+
+describe('createInflightBodyBudget middleware', () => {
+ it('admits a request under budget and reserves its declared Content-Length', () => {
+ const budget = createInflightBodyBudget(1000);
+ const req = makeReq({ 'content-length': '400' });
+ const { next, state } = run(budget, req);
+
+ expect(next).toHaveBeenCalledTimes(1);
+ expect(budget.currentBytes()).toBe(400);
+ expect(state.code).toBe(0); // no response written
+ });
+
+ it('does not attach a data listener when a Content-Length was declared (stream left untouched)', () => {
+ const budget = createInflightBodyBudget(1000);
+ 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);
+ run(budget, makeReq({ 'content-length': '600' }));
+ const { next } = run(budget, makeReq({ 'content-length': '400' }));
+ expect(next).toHaveBeenCalledTimes(1);
+ expect(budget.currentBytes()).toBe(1000);
+ });
+
+ it('rejects with 503 + Retry-After, without reading the body, when the declared size would exceed the budget', () => {
+ const budget = createInflightBodyBudget(1000);
+ run(budget, makeReq({ 'content-length': '800' }));
+
+ const rejected = makeReq({ 'content-length': '300' });
+ const { res, headers, state, next } = run(budget, rejected);
+
+ expect(next).not.toHaveBeenCalled();
+ expect(state.code).toBe(503);
+ expect(headers['retry-after']).toBe('1');
+ expect(headers['connection']).toBe('close');
+ expect((state.payload as { statusCode: number }).statusCode).toBe(503);
+ // Nothing was reserved for the rejected request and its stream was never tapped.
+ expect(budget.currentBytes()).toBe(800);
+ expect(rejected.listenerCount('data')).toBe(0);
+ expect(res.listenerCount('finish')).toBe(0);
+ });
+
+ it('sends the configured Retry-After value', () => {
+ const budget = createInflightBodyBudget(100, { retryAfterSeconds: 5 });
+ 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);
+ 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 req = makeReq({ 'content-length': '400' });
+ const { res } = run(budget, req);
+
+ res.emit('finish');
+ expect(budget.currentBytes()).toBe(0);
+ // Late terminal events from the same request must not double-decrement.
+ res.emit('close');
+ req.emit('close');
+ expect(budget.currentBytes()).toBe(0);
+ });
+
+ it('releases exactly once on a client abort (request close before the response)', () => {
+ const budget = createInflightBodyBudget(1000);
+ const req = makeReq({ 'content-length': '400' });
+ const { res } = run(budget, req);
+
+ req.emit('close');
+ expect(budget.currentBytes()).toBe(0);
+ res.emit('finish');
+ res.emit('close');
+ req.emit('error', new Error('late'));
+ expect(budget.currentBytes()).toBe(0);
+ });
+
+ it('releases on stream errors (request or response side)', () => {
+ const budget = createInflightBodyBudget(1000);
+ const reqA = makeReq({ 'content-length': '400' });
+ run(budget, reqA);
+ reqA.emit('error', new Error('boom'));
+ expect(budget.currentBytes()).toBe(0);
+
+ const reqB = makeReq({ 'content-length': '400' });
+ const { res: resB } = run(budget, reqB);
+ resB.emit('error', new Error('boom'));
+ expect(budget.currentBytes()).toBe(0);
+ });
+
+ it('counts actual bytes for requests without a Content-Length and releases on completion', () => {
+ const budget = createInflightBodyBudget(1000);
+ const req = makeReq(); // chunked / close-delimited: nothing declared
+ const { res, next } = run(budget, req);
+
+ expect(next).toHaveBeenCalledTimes(1);
+ expect(budget.currentBytes()).toBe(0);
+
+ req.emit('data', Buffer.alloc(300));
+ expect(budget.currentBytes()).toBe(300);
+ req.emit('data', Buffer.alloc(300));
+ expect(budget.currentBytes()).toBe(600);
+
+ res.emit('finish');
+ expect(budget.currentBytes()).toBe(0);
+ });
+
+ it('aborts an un-declared upload mid-stream when it pushes the aggregate over budget', () => {
+ const budget = createInflightBodyBudget(1000);
+
+ const reqA = makeReq();
+ const { res: resA } = run(budget, reqA);
+ reqA.emit('data', Buffer.alloc(600));
+ expect(budget.currentBytes()).toBe(600);
+
+ const reqB = makeReq();
+ const { res: resB, headers: headersB, state: stateB } = run(budget, reqB);
+ reqB.emit('data', Buffer.alloc(500)); // 600 + 500 > 1000 → abort B, keep A's accounting
+
+ expect(stateB.code).toBe(503);
+ expect(headersB['retry-after']).toBe('1');
+ expect(budget.currentBytes()).toBe(600);
+
+ // After the abort, B is fully released: more incoming bytes are not counted and B's later
+ // terminal events cannot decrement a second time.
+ reqB.emit('data', Buffer.alloc(100));
+ resB.emit('finish');
+ reqB.emit('close');
+ expect(budget.currentBytes()).toBe(600);
+
+ resA.emit('finish');
+ expect(budget.currentBytes()).toBe(0);
+ });
+
+ it('reuses freed budget for the next request (no leak across a full lifecycle)', () => {
+ const budget = createInflightBodyBudget(1000);
+ for (let i = 0; i < 5; i++) {
+ const req = makeReq({ 'content-length': '900' });
+ const { res, next } = run(budget, req);
+ expect(next).toHaveBeenCalledTimes(1);
+ res.emit('finish');
+ expect(budget.currentBytes()).toBe(0);
+ }
+ });
+});
diff --git a/src/config/inflight-body-budget.ts b/src/config/inflight-body-budget.ts
new file mode 100644
index 000000000..f00648825
--- /dev/null
+++ b/src/config/inflight-body-budget.ts
@@ -0,0 +1,150 @@
+/**
+ * Aggregate in-flight request-body budget.
+ *
+ * The per-request body cap (BODY_SIZE_LIMIT, enforced by the body parser) bounds ONE upload but
+ * says nothing about how many bodies may be buffered at once: N connections each trickling a
+ * near-limit body pin N × limit bytes of memory before any guard ever runs — the Nest throttler /
+ * auth guards sit at the routing layer, AFTER middleware and body buffering, so they cannot see
+ * slow-body memory pinning. With a 25 MiB per-request cap, a hundred slow senders is enough to
+ * push a 2 GiB container out of memory.
+ *
+ * This middleware closes the gap. It tracks the aggregate body bytes currently in flight across
+ * ALL connections — the declared Content-Length where present, the actual received bytes
+ * otherwise — and refuses NEW requests with 503 + Retry-After once the budget is exhausted,
+ * without reading a single byte of the rejected body. Requests with no Content-Length (chunked /
+ * close-delimited) are admitted, counted as their bytes actually arrive, and aborted mid-stream
+ * if they push the aggregate over the budget, so un-declared tricklers cannot bypass the cap.
+ *
+ * Extracted from main.ts so the accounting — notably the exactly-once release across every
+ * terminal path — is unit-tested without booting the app.
+ */
+import { Request, Response, NextFunction } from 'express';
+import { resolveBodyLimit } from './bootstrap-security';
+
+/**
+ * Default budget = 4 × the per-request body cap: a handful of concurrent full-size media uploads
+ * (base64 rides in the JSON body) still fits, while the worst-case aggregate (~100 MiB with the
+ * default 25 MiB cap) stays small next to a 2 GiB container limit and realistic concurrency.
+ */
+const DEFAULT_BUDGET_MULTIPLIER = 4;
+
+/** Binary units, mirroring the semantics of the `bytes` package the body parser uses. */
+const UNIT_BYTES: Record<string, number> = {
+ b: 1,
+ kb: 1024,
+ mb: 1024 ** 2,
+ gb: 1024 ** 3,
+ tb: 1024 ** 4,
+ pb: 1024 ** 5,
+};
+
+const FALLBACK_LIMIT_BYTES = 25 * UNIT_BYTES.mb;
+
+/**
+ * Parse a body-limit string ('25mb', '1024', '1.5gb') into bytes. Only the formats
+ * resolveBodyLimit accepts are supported, which keeps this module self-contained (no extra
+ * dependency); an impossible mismatch falls back to the same 25 MiB default instead of throwing.
+ */
+export function parseBodyLimitBytes(limit: string): number {
+ const match = /^(\d+(?:\.\d+)?)\s?(b|kb|mb|gb|tb|pb)?$/i.exec(limit.trim());
+ if (!match) return FALLBACK_LIMIT_BYTES;
+ return Math.floor(parseFloat(match[1]) * UNIT_BYTES[(match[2] ?? 'b').toLowerCase()]);
+}
+
+/**
+ * Resolve the aggregate budget in bytes. An explicit INFLIGHT_BODY_BUDGET_BYTES (positive integer)
+ * wins; an invalid one falls back to the default — env.validation already rejects it at boot, so
+ * this is the same fail-safe layering as the other byte knobs. The default scales with
+ * BODY_SIZE_LIMIT so tuning the per-request cap keeps the aggregate proportional.
+ */
+export function resolveInflightBodyBudgetBytes(budgetEnv?: string, bodyLimitEnv?: string): number {
+ const raw = budgetEnv?.trim();
+ if (raw) {
+ const explicit = Number(raw);
+ if (Number.isInteger(explicit) && explicit > 0) return explicit;
+ }
+ return DEFAULT_BUDGET_MULTIPLIER * parseBodyLimitBytes(resolveBodyLimit(bodyLimitEnv));
+}
+
+export interface InflightBodyBudgetOptions {
+ /** Retry-After value (seconds) sent with the 503. Default 1 — budget frees as bodies finish. */
+ retryAfterSeconds?: 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;
+}
+
+export function createInflightBodyBudget(budgetBytes: number, options?: InflightBodyBudgetOptions): InflightBodyBudget {
+ let inFlightBytes = 0;
+ const retryAfter = String(options?.retryAfterSeconds ?? 1);
+
+ // The rejected request's body is deliberately NEVER read. 'Connection: close' tells the client
+ // (and Node) this socket dies with the response, so the unread bytes are discarded with the
+ // socket instead of being misread as the next pipelined request on a keep-alive connection.
+ const rejectBusy = (res: Response): void => {
+ res
+ .status(503)
+ .set('Retry-After', retryAfter)
+ .set('Connection', 'close')
+ .json({ statusCode: 503, message: 'Too much request body data in flight; retry later' });
+ };
+
+ const middleware = (req: Request, res: Response, next: NextFunction): void => {
+ const declared = parseDeclaredLength(req.headers['content-length']);
+
+ // Admission control on the DECLARED size: a request that would push the aggregate past the
+ // budget is refused before a single byte of its body is buffered.
+ if (declared !== undefined && inFlightBytes + declared > budgetBytes) {
+ rejectBusy(res);
+ return;
+ }
+
+ let counted = declared ?? 0;
+ inFlightBytes += counted;
+
+ // Exactly-once release: the first terminal event wins — normal completion (res 'finish'),
+ // client/socket abort (req/res 'close'), stream failure (req/res 'error'). An aborted upload
+ // typically fires several of these; the flag guarantees the aggregate is decremented once.
+ let released = false;
+ const release = (): void => {
+ if (released) return;
+ released = true;
+ inFlightBytes -= counted;
+ };
+ res.on('finish', release);
+ res.on('close', release);
+ res.on('error', release);
+ req.on('close', release);
+ req.on('error', release);
+
+ if (declared === undefined) {
+ // No Content-Length (chunked / close-delimited): nothing to reserve up front, so count
+ // bytes as they actually arrive. The mid-stream abort keeps the aggregate bounded even
+ // when every sender avoids declaring a length. The stream stays intact for the downstream
+ // body parser — 'data' listeners observe the same chunks, they do not consume them away.
+ req.on('data', (chunk: Buffer) => {
+ if (released) return; // already aborted below — stop counting, the 503 is on its way
+ counted += chunk.length;
+ inFlightBytes += chunk.length;
+ if (inFlightBytes > budgetBytes) {
+ release();
+ rejectBusy(res);
+ }
+ });
+ }
+
+ next();
+ };
+
+ return { middleware, currentBytes: () => inFlightBytes };
+}
+
+/** A well-formed Content-Length, or undefined when absent/unusable (then count actual bytes). */
+function parseDeclaredLength(raw: string | undefined): number | undefined {
+ if (raw === undefined) return undefined;
+ const n = Number(raw.trim());
+ return Number.isSafeInteger(n) && n >= 0 ? n : undefined;
+}
diff --git a/src/main.ts b/src/main.ts
index 47100d1c7..890f84f8d 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -13,6 +13,7 @@ import { LoggerService, LogLevel, createLogger } from './common/services/logger.
import { createSwaggerConfig, exemptPublicOperations } from './config/swagger.config';
import { registerUncaughtExceptionMonitor } from './config/process-error-monitor';
import { applyHttpTimeouts, HttpTimeoutConfig, HttpTimeoutSink } from './config/http-timeouts';
+import { createInflightBodyBudget, resolveInflightBodyBudgetBytes } from './config/inflight-body-budget';
import { applyGlobalValidation } from './config/app-validation';
import { requestContextMiddleware } from './common/middleware/request-context.middleware';
import { injectDashboardCspNonce } from './config/dashboard-csp';
@@ -83,9 +84,22 @@ async function bootstrap() {
// Disable Nest's default body parser so we can set an explicit size cap below.
const app = await NestFactory.create(AppModule, { bodyParser: false });
+ // Aggregate in-flight body budget (DoS hardening): once too many body bytes are being buffered
+ // across ALL connections, new requests get 503 + Retry-After without their body being read.
+ // This is a deliberate PRE-GUARD: the throttler/auth guards run at the Nest routing layer —
+ // AFTER middleware and body buffering — so they can never stop slow-body memory pinning, and
+ // this must run BEFORE the body parser so a rejected connection never buffers a byte. The
+ // per-request BODY_SIZE_LIMIT below is a separate, unchanged cap on each admitted request.
+ const inflightBudgetBytes = resolveInflightBodyBudgetBytes(
+ process.env.INFLIGHT_BODY_BUDGET_BYTES,
+ process.env.BODY_SIZE_LIMIT,
+ );
+ app.use(createInflightBodyBudget(inflightBudgetBytes).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.
const bodyLimit = resolveBodyLimit(process.env.BODY_SIZE_LIMIT);
+ bootstrapLogger.log(`Request body caps: ${bodyLimit} per request, ${inflightBudgetBytes} bytes aggregate in flight`);
// 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.