Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(api): refuse an array where a DTO takes one object

Yudhi Armyndharis6105c5e9084b
diff --git a/src/common/utils/dto-strict-coercion.spec.ts b/src/common/utils/dto-strict-coercion.spec.ts
index a8d04f86a..67d6c32ab 100644
--- a/src/common/utils/dto-strict-coercion.spec.ts
+++ b/src/common/utils/dto-strict-coercion.spec.ts
@@ -1,5 +1,5 @@
import 'reflect-metadata';
-import { getMetadataStorage, validate } from 'class-validator';
+import { getMetadataStorage, validate, ValidationTypes } from 'class-validator';
import { ClassConstructor, plainToInstance } from 'class-transformer';
import { readdirSync, statSync } from 'fs';
import { join } from 'path';
@@ -116,3 +116,31 @@ describe('DTO input-coercion drift gate', () => {
},
);
});
+
+/**
+ * The same class of drift for a single nested object. It is declared with `@ValidateNested() @Type()`,
+ * and `@ValidateNested` checks an array element by element, so without `@IsObject()` an array (even an
+ * empty one) passed and the handler read the object's fields off it: bulk `options` sent as `[{...}]`
+ * was stored as the defaults with the caller's values dropped.
+ */
+function nestedObjectProps(cls: ValidatedClass): string[] {
+ const metas = getMetadataStorage().getTargetValidationMetadatas(cls, cls.name, true, false);
+ const nested = metas.filter(m => m.type === ValidationTypes.NESTED_VALIDATION && !m.each);
+ return [...new Set(nested.map(m => m.propertyName))];
+}
+
+describe('DTO nested-object drift gate', () => {
+ const targets = registeredClasses().flatMap(cls => nestedObjectProps(cls).map(prop => ({ cls, prop })));
+
+ it('finds the nested object properties to check', () => {
+ expect(targets.length).toBeGreaterThanOrEqual(15);
+ });
+
+ it.each(targets.map(t => [`${t.cls.name}.${t.prop}`, t] as const))('%s refuses an array', async (_label, target) => {
+ const instance = plainToInstance(target.cls, { [target.prop]: [] }, PIPE_TRANSFORM_OPTS);
+ const errors = await validate(instance, PIPE_VALIDATOR_OPTS);
+
+ const refused = errors.some(e => e.property === target.prop);
+ expect(refused || `${target.cls.name}.${target.prop} accepted an array. Add @IsObject().`).toBe(true);
+ });
+});
diff --git a/src/modules/infra/dto/save-config.dto.spec.ts b/src/modules/infra/dto/save-config.dto.spec.ts
index db5c59add..026b63e3e 100644
--- a/src/modules/infra/dto/save-config.dto.spec.ts
+++ b/src/modules/infra/dto/save-config.dto.spec.ts
@@ -88,3 +88,21 @@ describe('SaveConfigDto strict coercion', () => {
expect(instance.database?.poolSize).toBe(25);
});
});
+
+// @ValidateNested checks an array element by element, so a section sent as [] or [{...}] passed validation.
+describe('SaveConfigDto sections refuse an array', () => {
+ const SECTIONS = Object.keys(SECTION_BASE);
+
+ it.each(SECTIONS)('%s as an object is accepted', async section => {
+ const { errors } = await run({ [section]: SECTION_BASE[section] });
+ expect(errors).toHaveLength(0);
+ });
+
+ it.each(SECTIONS.flatMap(section => [[section, []] as const, [section, [SECTION_BASE[section]]] as const]))(
+ '%s as an array (%j) is refused',
+ async (section, value) => {
+ const { errors } = await run({ [section]: value });
+ expect(errors.map(e => e.property)).toEqual([section]);
+ },
+ );
+});
diff --git a/src/modules/infra/dto/save-config.dto.ts b/src/modules/infra/dto/save-config.dto.ts
index 767e0e1b5..ae8e91734 100644
--- a/src/modules/infra/dto/save-config.dto.ts
+++ b/src/modules/infra/dto/save-config.dto.ts
@@ -1,6 +1,6 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
-import { IsBoolean, IsIn, IsNumber, IsOptional, IsString, ValidateNested } from 'class-validator';
+import { IsBoolean, IsIn, IsNumber, IsObject, IsOptional, IsString, ValidateNested } from 'class-validator';
import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';
/**
@@ -180,30 +180,35 @@ export class EngineConfigDto {
export class SaveConfigDto {
@ApiPropertyOptional({ type: () => DatabaseConfigDto })
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => DatabaseConfigDto)
database?: DatabaseConfigDto;
@ApiPropertyOptional({ type: () => RedisConfigDto })
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => RedisConfigDto)
redis?: RedisConfigDto;
@ApiPropertyOptional({ type: () => QueueConfigDto })
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => QueueConfigDto)
queue?: QueueConfigDto;
@ApiPropertyOptional({ type: () => StorageConfigDto })
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => StorageConfigDto)
storage?: StorageConfigDto;
@ApiPropertyOptional({ type: () => EngineConfigDto })
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => EngineConfigDto)
engine?: EngineConfigDto;
diff --git a/src/modules/message/dto/bulk-message.dto.spec.ts b/src/modules/message/dto/bulk-message.dto.spec.ts
index 82a10d919..b2c8ca646 100644
--- a/src/modules/message/dto/bulk-message.dto.spec.ts
+++ b/src/modules/message/dto/bulk-message.dto.spec.ts
@@ -75,6 +75,29 @@ describe('SendBulkMessageDto media url', () => {
});
});
+// @ValidateNested checks an array element by element, so a nested object sent as an array passed. The
+// service then read its fields off the array: options [{...}] was stored as the defaults with the caller's
+// values dropped, and a media object in an array was only refused later, with a message about the text.
+describe('SendBulkMessageDto nested objects refuse an array', () => {
+ const options = { delayBetweenMessages: 60000, randomizeDelay: false, stopOnError: true };
+
+ it('accepts the options as an object', async () => {
+ await accepts({ ...textItem('hi'), options });
+ });
+
+ it.each([[[]], [[{}]], [[options]]])('refuses options given as an array: %j', async value => {
+ await rejects({ ...textItem('hi'), options: value });
+ });
+
+ it('refuses a message content given as an array', async () => {
+ await rejects({ messages: [{ chatId: '[email protected]', type: 'text', content: [{ text: 'hi' }] }] });
+ });
+
+ it.each(['image', 'video', 'audio', 'document'])('refuses %s given as an array', async kind => {
+ await rejects({ messages: [{ chatId: '[email protected]', type: kind, content: { [kind]: [{ base64: 'AAAA' }] } }] });
+ });
+});
+
// @nestjs/swagger does not derive bounds from the validators, so the published schema has to declare
// them itself, or a client generated from it accepts arrays the server answers with a 400.
describe('SendBulkMessageDto published schema', () => {
diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.ts
index b3ef588c4..ca06fa8e4 100644
--- a/src/modules/message/dto/bulk-message.dto.ts
+++ b/src/modules/message/dto/bulk-message.dto.ts
@@ -68,24 +68,28 @@ export class BulkMessageContentDto {
// object pass straight through and are persisted verbatim.
@ApiPropertyOptional({ description: 'Image URL or base64', type: BulkMediaDto })
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => BulkMediaDto)
image?: BulkMediaDto;
@ApiPropertyOptional({ description: 'Video URL or base64', type: BulkMediaDto })
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => BulkMediaDto)
video?: BulkMediaDto;
@ApiPropertyOptional({ description: 'Audio URL or base64', type: BulkMediaDto })
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => BulkMediaDto)
audio?: BulkMediaDto;
@ApiPropertyOptional({ description: 'Document URL or base64', type: BulkMediaDto })
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => BulkMediaDto)
document?: BulkMediaDto;
@@ -127,6 +131,7 @@ class BulkMessageItemDto {
type!: 'text' | 'image' | 'video' | 'audio' | 'document';
@ApiProperty({ description: 'Message content based on type' })
+ @IsObject()
@ValidateNested()
@Type(() => BulkMessageContentDto)
content!: BulkMessageContentDto;
@@ -190,6 +195,7 @@ export class SendBulkMessageDto {
@ApiPropertyOptional({ description: 'Batch processing options' })
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => BulkMessageOptionsDto)
options?: BulkMessageOptionsDto;
diff --git a/src/modules/message/dto/send-message.dto.spec.ts b/src/modules/message/dto/send-message.dto.spec.ts
index 7410d85a6..d27b801ba 100644
--- a/src/modules/message/dto/send-message.dto.spec.ts
+++ b/src/modules/message/dto/send-message.dto.spec.ts
@@ -296,6 +296,25 @@ describe('SendTemplateMessageDto identifiers', () => {
});
});
+describe('SendTextMessageDto customLinkPreview', () => {
+ const base = { chatId: '[email protected]', text: 'hi https://example.com' };
+ const preview = { url: 'https://example.com', title: 'Example' };
+ const previewErrors = async (customLinkPreview: unknown) =>
+ (await validateDto(SendTextMessageDto, { ...base, customLinkPreview })).filter(
+ e => e.property === 'customLinkPreview',
+ );
+
+ it('accepts the preview as an object', async () => {
+ expect(await previewErrors(preview)).toHaveLength(0);
+ });
+
+ // @ValidateNested checks an array element by element, so [] and [{...}] passed and reached the engine as
+ // an array, which Baileys read .url and .title off to send an empty preview without an error.
+ it.each([[[]], [[preview]]])('refuses an array: %j', async value => {
+ expect(await previewErrors(value)).toHaveLength(1);
+ });
+});
+
describe('published schema bounds', () => {
const published = (cls: new () => object, key: string): Record<string, unknown> | undefined =>
Reflect.getMetadata(DECORATORS.API_MODEL_PROPERTIES, cls.prototype as object, key) as
diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.ts
index 9cb6d0ca9..a7da51c9d 100644
--- a/src/modules/message/dto/send-message.dto.ts
+++ b/src/modules/message/dto/send-message.dto.ts
@@ -8,6 +8,7 @@ import {
IsArray,
ArrayMaxSize,
IsBoolean,
+ IsObject,
Validate,
} from 'class-validator';
import { Type } from 'class-transformer';
@@ -165,6 +166,7 @@ export class SendTextMessageDto {
'with `linkPreview: false`, which asks for the opposite.',
})
@IsOptional()
+ @IsObject()
@ValidateNested()
@Type(() => CustomLinkPreviewDto)
customLinkPreview?: CustomLinkPreviewDto;
diff --git a/src/modules/status/dto/send-media-status.dto.spec.ts b/src/modules/status/dto/send-media-status.dto.spec.ts
index 7746648b2..3190b2bd9 100644
--- a/src/modules/status/dto/send-media-status.dto.spec.ts
+++ b/src/modules/status/dto/send-media-status.dto.spec.ts
@@ -1,7 +1,7 @@
import 'reflect-metadata';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
-import { SendImageStatusDto, SendVideoStatusDto } from './send-media-status.dto';
+import { SendImageStatusDto, SendVideoStatusDto, SendVoiceStatusDto } from './send-media-status.dto';
describe('SendImageStatusDto recipients validation', () => {
const valid = { image: { url: 'https://example.com/i.png' }, recipients: ['[email protected]'] };
@@ -87,6 +87,23 @@ describe('SendVideoStatusDto recipients validation', () => {
});
});
+// @ValidateNested checks an array element by element, so a media source sent as [] or [{...}] passed.
+describe('status media sources refuse an array', () => {
+ const source = { url: 'https://example.com/m.bin' };
+
+ it.each([
+ ['image', SendImageStatusDto],
+ ['video', SendVideoStatusDto],
+ ['audio', SendVoiceStatusDto],
+ ] as const)('%s as an object is accepted and as an array is refused', async (key, Dto) => {
+ const failed = async (value: unknown) =>
+ (await validate(plainToInstance(Dto as new () => object, { [key]: value }))).some(e => e.property === key);
+ expect(await failed(source)).toBe(false);
+ expect(await failed([source])).toBe(true);
+ expect(await failed([])).toBe(true);
+ });
+});
+
// Both engines fetch only a string that starts with http(s):// and decode anything else as base64.
describe('status media url', () => {
it('accepts only an absolute http(s) url', async () => {
diff --git a/src/modules/status/dto/send-media-status.dto.ts b/src/modules/status/dto/send-media-status.dto.ts
index 43db21e38..cf0722f2b 100644
--- a/src/modules/status/dto/send-media-status.dto.ts
+++ b/src/modules/status/dto/send-media-status.dto.ts
@@ -6,6 +6,7 @@ import {
ArrayMaxSize,
IsDefined,
IsNotEmpty,
+ IsObject,
Matches,
MaxLength,
ValidateIf,
@@ -46,6 +47,7 @@ class StatusMediaInput {
export class SendImageStatusDto {
@ApiProperty({ description: 'Image source (URL or base64).', type: StatusMediaInput })
@IsDefined()
+ @IsObject()
@ValidateNested()
@Type(() => StatusMediaInput)
image!: StatusMediaInput;
@@ -77,6 +79,7 @@ export class SendImageStatusDto {
export class SendVideoStatusDto {
@ApiProperty({ description: 'Video source (URL or base64).', type: StatusMediaInput })
@IsDefined()
+ @IsObject()
@ValidateNested()
@Type(() => StatusMediaInput)
video!: StatusMediaInput;
@@ -117,6 +120,7 @@ export class SendVoiceStatusDto {
type: StatusMediaInput,
})
@IsDefined()
+ @IsObject()
@ValidateNested()
@Type(() => StatusMediaInput)
audio!: StatusMediaInput;