Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(http): refuse a request body nested over 100 levels
Yudhi Armyndharise0b59bba3d8f
diff --git a/src/common/validation/body-nesting.spec.ts b/src/common/validation/body-nesting.spec.tsnew file mode 100644index 000000000..d9a94be30--- /dev/null+++ b/src/common/validation/body-nesting.spec.ts@@ -0,0 +1,43 @@+import { exceedsBodyNesting, MAX_BODY_NESTING } from './body-nesting';++// One value holding `levels` nested containers: {} is one level, {a:{}} is two.+const objects = (levels: number): unknown => {+ let value: unknown = {};+ for (let i = 1; i < levels; i++) value = { a: value };+ return value;+};+const arrays = (levels: number): unknown => {+ let value: unknown = [];+ for (let i = 1; i < levels; i++) value = [value];+ return value;+};++describe('exceedsBodyNesting', () => {+ it.each([+ ['objects', objects],+ ['arrays', arrays],+ ])('passes %s nested to the cap and refuses one level more', (_kind, build) => {+ expect(exceedsBodyNesting(build(MAX_BODY_NESTING))).toBe(false);+ expect(exceedsBodyNesting(build(MAX_BODY_NESTING + 1))).toBe(true);+ });++ it('measures the deepest branch, not the breadth or the number of nodes', () => {+ const wide = { items: Array.from({ length: 5000 }, () => ({ tags: ['a', 'b'], meta: { k: [1] } })) };+ expect(exceedsBodyNesting(wide)).toBe(false);+ const oneDeepBranch = { items: [...wide.items, { deep: objects(MAX_BODY_NESTING) }] };+ expect(exceedsBodyNesting(oneDeepBranch)).toBe(true);+ });++ // The recursive readers of a body overflow the stack near 2000 levels. The walk stops descending at the+ // cap, so it must answer for a value far deeper than that instead of overflowing like them.+ it.each([+ ['objects', objects],+ ['arrays', arrays],+ ])('answers for %s nested 100000 levels without overflowing the stack', (_kind, build) => {+ expect(exceedsBodyNesting(build(100_000))).toBe(true);+ });++ it.each([[undefined], [null], ['text'], [5], [true], [{}], [[]]])('passes the flat value %j', value => {+ expect(exceedsBodyNesting(value)).toBe(false);+ });+});diff --git a/src/common/validation/body-nesting.ts b/src/common/validation/body-nesting.tsnew file mode 100644index 000000000..a15468f2f--- /dev/null+++ b/src/common/validation/body-nesting.ts@@ -0,0 +1,13 @@+/**+ * How many levels of objects and arrays a request body may nest. The recursive readers of a parsed body+ * (class-transformer in the validation pipe, the send idempotency fingerprint, the cluster proxy's+ * JSON.stringify) overflow the stack a couple of thousand levels down and answered 500 with a stack trace+ * in the log. A real payload nests a handful of levels; nothing in the API takes one near this.+ */+export const MAX_BODY_NESTING = 100;++/** Whether a parsed request body nests deeper than the cap. It stops descending at the cap, so the walk cannot overflow. */+export const exceedsBodyNesting = (value: unknown, depth = 1): boolean =>+ typeof value === 'object' &&+ value !== null &&+ (depth > MAX_BODY_NESTING || Object.values(value).some(child => exceedsBodyNesting(child, depth + 1)));diff --git a/src/configure-app.ts b/src/configure-app.tsindex a417d466e..cfa5483d1 100644--- a/src/configure-app.ts+++ b/src/configure-app.ts@@ -19,6 +19,7 @@ import { injectDashboardCspNonce } from './config/dashboard-csp';import { resolveCorsPolicy, isUpgradeInsecureRequestsEnabled, resolveBodyLimit } from './config/bootstrap-security';import { resolveRequestTimeoutMs } from './config/http-timeouts';import { parseTrustedProxies } from './common/utils/ip';+import { exceedsBodyNesting, MAX_BODY_NESTING } from './common/validation/body-nesting';/** Where the bundled dashboard documents come from, and whether to serve them at all. */export interface DashboardSource {@@ -45,7 +46,7 @@ export interface AppliedBodyCaps {/*** Everything the production HTTP surface installs on the Express app: request context, the CSP* nonce, helmet, the SPA document handler, CORS, the encoded-NUL refusal, the in-flight body budget,- * the body parsers and the trailing-slash DELETE refusal.+ * the body parsers, the nesting-depth refusal and the trailing-slash DELETE refusal.** It lives here rather than inside bootstrap() so the e2e lane can run the SAME stack. main.ts* boots on import, so a suite cannot import it; the whole stack was therefore executed by nothing,@@ -297,6 +298,19 @@ export function configureApp(app: INestApplication, options: ConfigureAppOptions}),);+ // The recursive readers of a parsed body (class-transformer in the validation pipe, the send idempotency+ // fingerprint, the cluster proxy's JSON.stringify) overflow the stack a couple of thousand levels down+ // and answered 500 with a stack trace in the log. Refused here, once the parsers have run, so every+ // route and /mcp share one bound and one answer, ahead of the guards, interceptors and pipes.+ app.use((req: Request, res: Response, next: NextFunction) => {+ if (!exceedsBodyNesting(req.body)) return next();+ res.status(400).json({+ statusCode: 400,+ message: `Request body must not nest objects or arrays more than ${MAX_BODY_NESTING} levels deep`,+ error: 'Bad Request',+ });+ });+// A DELETE path ending in '/' names no resource. Non-strict routing would still match it to the// route without the slash, so a client that normalises `<parent>/<child>/..` down to `<parent>/`// would delete the parent. Only DELETE under /api/ is refused: a trailing slash on other methodsdiff --git a/test/configure-app.e2e-spec.ts b/test/configure-app.e2e-spec.tsindex 05d14ab3c..683752857 100644--- a/test/configure-app.e2e-spec.ts+++ b/test/configure-app.e2e-spec.ts@@ -27,6 +27,8 @@ import { DASHBOARD_CSP_NONCE_PLACEHOLDER } from '../src/config/dashboard-csp';import { ActiveKeyIndex } from '../src/modules/auth/active-key-index';import { ShutdownService } from '../src/common/services/shutdown.service';import { documentErrorResponses, ERROR_RESPONSE_SCHEMA } from '../src/config/swagger.config';+import { MAX_BODY_NESTING } from '../src/common/validation/body-nesting';+import { SendTextMessageDto } from '../src/modules/message/dto/send-message.dto';/*** The production HTTP surface, run for real. Every other e2e builds a bare Nest app, so the stack@@ -43,6 +45,15 @@ class EchoController {}}+/** A route with a real request DTO, so the global ValidationPipe runs class-transformer over the body. */+@Controller('validated')+class ValidatedController {+ @Post('text')+ text(@Body() dto: SendTextMessageDto) {+ return { chatId: dto.chatId };+ }+}+const deleted: string[] = [];@Controller('sessions')@@ -71,7 +82,7 @@ class IngressStubController {}}-@Module({ controllers: [EchoController, SessionStubController, IngressStubController] })+@Module({ controllers: [EchoController, ValidatedController, SessionStubController, IngressStubController] })class HttpSurfaceModule {}// A stand-in for the bundled document: the real dashboard/index.html carries the placeholder in a@@ -205,6 +216,41 @@ describe('production HTTP surface (configureApp)', () => {expect(res.status).toBe(201);});+ // The recursive readers of a parsed body (class-transformer in the validation pipe, the send+ // idempotency fingerprint, the cluster proxy's JSON.stringify) overflow the stack a couple of thousand+ // levels down and answered 500 with a stack trace in the log. A chain of `levels` nested objects:+ // '{"a":{}}' is two.+ const nestedObjects = (levels: number): string => '{"a":'.repeat(levels - 1) + '{}' + '}'.repeat(levels - 1);++ it('admits a body nested to the cap and refuses one level more with 400', async () => {+ const post = (body: string) => request(app.getHttpServer()).post('/api/echo').type('json').send(body);++ expect((await post(nestedObjects(MAX_BODY_NESTING))).status).toBe(201);++ const res = await request(app.getHttpServer())+ .post('/api/echo')+ .type('json')+ .set('Origin', 'https://allowed.example')+ .send(nestedObjects(MAX_BODY_NESTING + 1))+ .expect(400);+ expect(res.body).toMatchObject({ statusCode: 400, error: 'Bad Request' });+ expect(res.body).toHaveProperty('message', expect.stringContaining(String(MAX_BODY_NESTING)));+ expect(res.headers['x-request-id']).toBeDefined();+ // A browser can read the refusal only if it carries the CORS headers.+ expect(res.headers['access-control-allow-origin']).toBe('https://allowed.example');+ });++ it('answers a DTO route 400, not 500, for a body nested thousands of levels deep', async () => {+ const mentions = '['.repeat(5000) + ']'.repeat(5000);+ const res = await request(app.getHttpServer())+ .post('/api/validated/text')+ .type('json')+ .send(`{"chatId":"[email protected]","text":"hi","mentions":${mentions}}`);++ expect(res.status).toBe(400);+ expect(res.body).toMatchObject({ statusCode: 400, error: 'Bad Request' });+ });+it('refuses a body over the per-request cap with 413', async () => {const res = await request(app.getHttpServer()).post('/api/echo')