Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(group): refuse a membership action body that was not read

Yudhi Armyndharisf2cc2ccb17f1
diff --git a/src/modules/group/group.controller.http.spec.ts b/src/modules/group/group.controller.http.spec.ts
new file mode 100644
index 000000000..ac04d0618
--- /dev/null
+++ b/src/modules/group/group.controller.http.spec.ts
@@ -0,0 +1,96 @@
+import type { INestApplication } from '@nestjs/common';
+import { Test } from '@nestjs/testing';
+import { request as httpRequest } from 'http';
+import type { AddressInfo } from 'net';
+import request from 'supertest';
+import type { App } from 'supertest/types';
+import { applyGlobalValidation } from '../../config/app-validation';
+import { configureApp } from '../../configure-app';
+import { GroupController } from './group.controller';
+import { GroupService } from './group.service';
+
+// Approve and reject act on every pending request when `participants` is absent. The body parsers read
+// only JSON and form bodies, and an empty array has no property for the whitelist to refuse, so these
+// run through the production parsers and pipe: a controller spec that calls the handler never sees either.
+describe('GroupController membership requests over HTTP: a body that was sent but not read', () => {
+ let app: INestApplication<App>;
+ let port: number;
+ const approve = jest.fn(() => Promise.resolve([]));
+ const reject = jest.fn(() => Promise.resolve([]));
+
+ beforeAll(async () => {
+ const mod = await Test.createTestingModule({
+ controllers: [GroupController],
+ providers: [
+ {
+ provide: GroupService,
+ useValue: { approveGroupMembershipRequests: approve, rejectGroupMembershipRequests: reject },
+ },
+ ],
+ }).compile();
+ app = mod.createNestApplication({ bodyParser: false, logger: false });
+ configureApp(app);
+ applyGlobalValidation(app);
+ await app.listen(0);
+ port = (app.getHttpServer() as { address: () => AddressInfo }).address().port;
+ });
+
+ afterAll(async () => {
+ await app.close();
+ });
+
+ beforeEach(() => jest.clearAllMocks());
+
+ const verbs = [
+ ['approve', approve],
+ ['reject', reject],
+ ] as const;
+ const url = (verb: string) => `/api/sessions/s1/groups/[email protected]/membership-requests/${verb}`;
+
+ describe.each(verbs)('%s', (verb, service) => {
+ it.each([
+ ['an empty JSON array', 'application/json', '[]'],
+ ['a text/plain body', 'text/plain', '{"participants":["[email protected]"]}'],
+ ['a +json body', 'application/vnd.api+json', '{"participants":["[email protected]"]}'],
+ ['a binary body', 'application/octet-stream', '{"participants":["[email protected]"]}'],
+ ])('refuses %s instead of acting on every pending request', async (_name, type, body) => {
+ const res = await request(app.getHttpServer()).post(url(verb)).set('Content-Type', type).send(body);
+
+ expect(res.status).toBe(400);
+ expect(service).not.toHaveBeenCalled();
+ });
+
+ it('refuses a body sent without a Content-Type', async () => {
+ const status = await new Promise<number>((resolve, reject) => {
+ const req = httpRequest({ port, method: 'POST', path: url(verb) }, res => {
+ res.resume();
+ resolve(res.statusCode ?? 0);
+ });
+ req.on('error', reject);
+ req.end('{"participants":["[email protected]"]}');
+ });
+
+ expect(status).toBe(400);
+ expect(service).not.toHaveBeenCalled();
+ });
+
+ it('still acts on every pending request for an empty object and for no body at all', async () => {
+ await request(app.getHttpServer()).post(url(verb)).send({}).expect(200);
+ await request(app.getHttpServer()).post(url(verb)).expect(200);
+
+ expect(service).toHaveBeenNthCalledWith(1, 's1', '[email protected]', undefined);
+ expect(service).toHaveBeenNthCalledWith(2, 's1', '[email protected]', undefined);
+ });
+
+ it('still names the requesters of a JSON or form body', async () => {
+ await request(app.getHttpServer())
+ .post(url(verb))
+ .send({ participants: ['[email protected]'] })
+ .expect(200);
+ await request(app.getHttpServer()).post(url(verb)).type('form').send('participants[][email protected]').expect(200);
+
+ expect(service).toHaveBeenNthCalledWith(1, 's1', '[email protected]', ['[email protected]']);
+ expect(service).toHaveBeenNthCalledWith(2, 's1', '[email protected]', ['[email protected]']);
+ });
+ });
+});
diff --git a/src/modules/group/group.controller.spec.ts b/src/modules/group/group.controller.spec.ts
index 3c05b0fc1..c91150042 100644
--- a/src/modules/group/group.controller.spec.ts
+++ b/src/modules/group/group.controller.spec.ts
@@ -1,6 +1,11 @@
+import type { Request } from 'express';
import { GroupController } from './group.controller';
import { GroupService } from './group.service';
+// The membership routes read the request to tell an empty body from one that was never parsed; the
+// body-shape cases run through real parsers in group.controller.http.spec.ts.
+const noBody = { headers: {}, body: {}, is: () => null } as unknown as Request;
+
describe('GroupController join + settings', () => {
const build = (service: Partial<Record<keyof GroupService, jest.Mock>>) => {
const controller = new GroupController(service as unknown as GroupService);
@@ -115,7 +120,7 @@ describe('GroupController membership requests', () => {
const results = [{ id: '[email protected]', success: true, status: 200 }];
const { controller, service } = build({ [svcMethod]: jest.fn().mockResolvedValue(results) });
- await expect(controller[route]('s1', 'g1', { participants: ['[email protected]'] })).resolves.toEqual({
+ await expect(controller[route]('s1', 'g1', { participants: ['[email protected]'] }, noBody)).resolves.toEqual({
success: true,
message: `Membership requests ${verb}`,
results,
@@ -126,7 +131,7 @@ describe('GroupController membership requests', () => {
it('an empty body approves ALL pending requests (participants passed as undefined)', async () => {
const { controller, service } = build({ approveGroupMembershipRequests: jest.fn().mockResolvedValue([]) });
- await controller.approveMembershipRequests('s1', 'g1', {});
+ await controller.approveMembershipRequests('s1', 'g1', {}, noBody);
expect(service.approveGroupMembershipRequests).toHaveBeenCalledWith('s1', 'g1', undefined);
});
diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.ts
index daccca20c..8db46dfc6 100644
--- a/src/modules/group/group.controller.ts
+++ b/src/modules/group/group.controller.ts
@@ -1,4 +1,18 @@
-import { Controller, Get, Post, Put, Delete, Param, Body, Query, HttpCode, HttpStatus } from '@nestjs/common';
+import {
+ BadRequestException,
+ Controller,
+ Get,
+ Post,
+ Put,
+ Delete,
+ Param,
+ Body,
+ Query,
+ Req,
+ HttpCode,
+ HttpStatus,
+} from '@nestjs/common';
+import type { Request } from 'express';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody, ApiQuery } from '@nestjs/swagger';
import { GroupService } from './group.service';
import {
@@ -70,6 +84,25 @@ const PACED_PARTICIPANT_400 =
// an engine that exists but is not ready. The body variant is for routes that also validate a DTO.
const BODY_OR_SESSION_400 = 'The body failed validation, or the session is not started (no engine is running for it).';
+/**
+ * Approve and reject act on EVERY pending request when `participants` is absent, so a body that was sent but
+ * never became the DTO must not pass for an absent one. The parsers read only application/json and
+ * application/x-www-form-urlencoded and leave the body of any other type unread (a `fetch` with a string body
+ * and no headers sends text/plain), and a bare `[]` carries no property for the whitelist to refuse. Both
+ * reach the handler as an empty object.
+ */
+function assertActionBodyRead(req: Request): void {
+ const hasBody = Number(req.headers['content-length'] ?? 0) > 0 || req.headers['transfer-encoding'] !== undefined;
+ if (hasBody && req.is(['application/json', 'application/x-www-form-urlencoded']) === false) {
+ throw new BadRequestException(
+ 'The request body was not read: send it as application/json, or send no body to act on every request',
+ );
+ }
+ if (Array.isArray(req.body)) {
+ throw new BadRequestException('The body must be a JSON object such as {"participants": [...]}, not a list');
+ }
+}
+
// NOTE: the session→groups LIST lives on the SessionController at GET /sessions/:sessionId/groups (it
// registered first and owns the canonical narrow projection). A bare @Get() here would collide on
// the same path pattern (/sessions/{x}/groups) and be shadowed, so this controller owns only the
@@ -395,7 +428,9 @@ export class GroupController {
@Param('sessionId') sessionId: string,
@Param('groupId') groupId: string,
@Body() dto: MembershipRequestActionDto,
+ @Req() req: Request,
) {
+ assertActionBodyRead(req);
const results = await this.groupService.approveGroupMembershipRequests(sessionId, groupId, dto.participants);
return { success: true, message: 'Membership requests approved', results };
}
@@ -429,7 +464,9 @@ export class GroupController {
@Param('sessionId') sessionId: string,
@Param('groupId') groupId: string,
@Body() dto: MembershipRequestActionDto,
+ @Req() req: Request,
) {
+ assertActionBodyRead(req);
const results = await this.groupService.rejectGroupMembershipRequests(sessionId, groupId, dto.participants);
return { success: true, message: 'Membership requests rejected', results };
}