Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(http): answer 413 for a body the in-flight budget can never admit

Yudhi Armyndharis26739eb5cde7
diff --git a/src/config/inflight-body-budget.spec.ts b/src/config/inflight-body-budget.spec.ts
index d55d802ed..1e5a5d288 100644
--- a/src/config/inflight-body-budget.spec.ts
+++ b/src/config/inflight-body-budget.spec.ts
@@ -143,6 +143,32 @@ describe('createInflightBodyBudget middleware', () => {
expect(res.listenerCount('finish')).toBe(0);
});
+ it('answers 413 without Retry-After, on an idle server, for a declared body that could never be admitted', () => {
+ // Default share 0.5 -> a 500-byte per-client cap: 600 bytes would never fit, however long the client waits.
+ const budget = createInflightBodyBudget(1000);
+ const rejected = makeReq({ 'content-length': '600' });
+ const { res, headers, state, next } = run(budget, rejected);
+
+ expect(next).not.toHaveBeenCalled();
+ expect(state.code).toBe(413);
+ expect(headers['retry-after']).toBeUndefined();
+ expect(headers['connection']).toBe('close');
+ expect(state.payload).toEqual({
+ statusCode: 413,
+ message: 'Request body exceeds what this server can accept',
+ error: 'Payload Too Large',
+ });
+ expect(budget.currentBytes()).toBe(0);
+ expect(res.listenerCount('finish')).toBe(0);
+ });
+
+ it('answers 413 for an unkeyed body declared above the whole budget', () => {
+ const budget = createInflightBodyBudget(1000, { classify: () => undefined, bodyLimitBytes: 250 });
+ const { state, headers } = run(budget, makeReq({ 'content-length': '1001' }));
+ expect(state.code).toBe(413);
+ expect(headers['retry-after']).toBeUndefined();
+ });
+
it('sends the configured Retry-After value', () => {
const budget = createInflightBodyBudget(100, { retryAfterSeconds: 5, perClientShare: 1 });
run(budget, makeReq({ 'content-length': '100' }));
@@ -929,7 +955,8 @@ describe('compressed request bodies', () => {
const reply = await send({ 'Content-Type': 'application/json', 'Content-Length': String(plain.length) }, plain);
- expect(reply.status).toBe(503);
+ // Larger than the whole budget, so it could never be admitted: 413, not a retryable 503.
+ expect(reply.status).toBe(413);
});
it('refuses a compressed body whose Content-Length is zero', async () => {
diff --git a/src/config/inflight-body-budget.ts b/src/config/inflight-body-budget.ts
index 62ea3318b..121992238 100644
--- a/src/config/inflight-body-budget.ts
+++ b/src/config/inflight-body-budget.ts
@@ -11,7 +11,8 @@
* 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.
+ * single byte of the rejected body. A declared body too large to fit even on an idle server gets
+ * 413 instead, since retrying it cannot help.
*
* 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
@@ -121,7 +122,8 @@ export interface InflightBodyBudgetOptions {
/**
* 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.
+ * a legitimate bulk uploader above the share gets 503 + Retry-After, not a hang (a single declared
+ * body larger than the share gets 413).
*/
perClientShare?: number;
/**
@@ -226,6 +228,19 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflight
});
};
+ /** Same disposal again, for a body that could not be admitted even with nothing else in flight. */
+ const rejectTooLarge = (req: Request, res: Response): void => {
+ if (res.headersSent || res.writableEnded) {
+ req.destroy();
+ return;
+ }
+ res.status(413).set('Connection', 'close').json({
+ statusCode: 413,
+ message: 'Request body exceeds what this server can accept',
+ error: 'Payload Too Large',
+ });
+ };
+
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
@@ -282,6 +297,13 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflight
keyId === undefined && clientInFlight.size >= MAX_TRACKED_CLIENTS && !clientInFlight.has(clientKey);
// The aggregate check uses the full declared size; the tier and share checks the charged size.
const charge = Math.min(reserved, ceiling);
+ // A declared body that would be refused on an idle server can never be admitted, so a retryable
+ // 503 would only invite the client (and the SDKs, which retry a 503) to send it again. A chunked
+ // body is refused on its placeholder, not its size, so it keeps the 503.
+ if (declared !== undefined && (declared > budgetBytes || charge > shareCap || (anonymous && charge > anonPool))) {
+ rejectTooLarge(req, res);
+ return;
+ }
if (
inFlightBytes + reserved > budgetBytes ||
clientBusy + charge > shareCap ||
diff --git a/src/config/swagger.config.ts b/src/config/swagger.config.ts
index 5ef55b560..111d50f37 100644
--- a/src/config/swagger.config.ts
+++ b/src/config/swagger.config.ts
@@ -182,18 +182,21 @@ export function createSwaggerConfig(): Omit<OpenAPIObject, 'paths'> {
return (
new DocumentBuilder()
.setTitle('OpenWA API')
- // Two refusals are issued by middleware BEFORE routing, so they apply to every operation
+ // Three refusals are issued by middleware BEFORE routing, so they apply to every operation
// below and cannot be expressed as a per-operation @ApiResponse without repeating them 187
// times. Documenting them here keeps the contract honest for clients that would otherwise
// meet an undocumented status.
.setDescription(
'Open Source WhatsApp API Gateway - Free, Self-Hosted HTTP API\n\n' +
- '**Gateway-wide responses.** Two statuses are returned by middleware before routing, ' +
+ '**Gateway-wide responses.** Three statuses are returned by middleware before routing, ' +
'so any operation can emit them:\n\n' +
'- `415 Unsupported Media Type` — the request body carries a `Content-Encoding` other ' +
'than `identity`. The aggregate in-flight body cap counts wire bytes, so a compressed ' +
'body would be admitted on its compressed size and then inflated past the memory it is ' +
'meant to bound. Send the body uncompressed.\n' +
+ '- `413 Payload Too Large`: the declared `Content-Length` is more than the gateway could ' +
+ 'hold in flight for this caller even when idle. The body is not read; retrying it unchanged ' +
+ 'cannot succeed.\n' +
'- `503 Service Unavailable` with `Retry-After` — the gateway already has too much ' +
'request body data in flight. The body is not read; retry after the given delay.\n\n' +
'Every operation that takes an API key can also answer `429 Too Many Requests` (the per-IP ' +