Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test(api): validate DTO bounds in the contract specs

Yudhi Armyndharis9c5845e628f5
diff --git a/src/modules/catalog/dto/send-product.dto.spec.ts b/src/modules/catalog/dto/send-product.dto.spec.ts
index e7281e3e7..f0a5426dd 100644
--- a/src/modules/catalog/dto/send-product.dto.spec.ts
+++ b/src/modules/catalog/dto/send-product.dto.spec.ts
@@ -1,6 +1,6 @@
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
-import { PRODUCT_ID_MAX_LENGTH, SendProductDto } from './send-product.dto';
+import { PRODUCT_ID_MAX_LENGTH, ProductQueryDto, SendProductDto } from './send-product.dto';
import { MESSAGE_TEXT_MAX_LENGTH } from '../../message/dto/send-message.dto';
/** The constraints that failed, keyed by property; empty when the payload is valid. */
@@ -37,3 +37,31 @@ describe('SendProductDto', () => {
});
});
});
+
+describe('ProductQueryDto', () => {
+ // The query string arrives as text and the pipe converts it, so the cases go through the same conversion.
+ const queryFailures = async (query: object): Promise<Record<string, string[]>> => {
+ const errors = await validate(plainToInstance(ProductQueryDto, query, { enableImplicitConversion: true }));
+ return Object.fromEntries(errors.map(e => [e.property, Object.keys(e.constraints ?? {})]));
+ };
+
+ const published = (name: string) =>
+ Reflect.getMetadata('swagger/apiModelProperties', ProductQueryDto.prototype, name) as { minimum?: number };
+
+ it('defaults to the first page of 20', () => {
+ const query = plainToInstance(ProductQueryDto, {}, { enableImplicitConversion: true });
+ expect({ page: query.page, limit: query.limit }).toEqual({ page: 1, limit: 20 });
+ });
+
+ it('accepts the first page and a one-item page', async () => {
+ expect(await queryFailures({ page: '1', limit: '1' })).toEqual({});
+ });
+
+ it('refuses a page or limit below 1, as the contract publishes, and a fractional one', async () => {
+ expect(published('page').minimum).toBe(1);
+ expect(published('limit').minimum).toBe(1);
+ expect(await queryFailures({ page: '0' })).toEqual({ page: ['min'] });
+ expect(await queryFailures({ limit: '0' })).toEqual({ limit: ['min'] });
+ expect(await queryFailures({ limit: '1.5' })).toEqual({ limit: ['isInt'] });
+ });
+});
diff --git a/src/modules/channel/dto/create-channel.dto.spec.ts b/src/modules/channel/dto/create-channel.dto.spec.ts
index 24f5c361a..056991ce8 100644
--- a/src/modules/channel/dto/create-channel.dto.spec.ts
+++ b/src/modules/channel/dto/create-channel.dto.spec.ts
@@ -1,15 +1,35 @@
+import { plainToInstance } from 'class-transformer';
+import { validate } from 'class-validator';
import { CreateChannelDto } from './create-channel.dto';
+import { GLOBAL_VALIDATION_OPTIONS } from '../../../config/app-validation';
const property = (name: string) =>
Reflect.getMetadata('swagger/apiModelProperties', CreateChannelDto.prototype, name) as { maxLength?: number };
-// The validator caps both fields; the contract has to publish the same caps, or a generated client
-// accepts input the server then refuses.
+// The options the global ValidationPipe runs with, so a body is judged the way a request is.
+const { transformOptions, ...pipeOptions } = GLOBAL_VALIDATION_OPTIONS;
+
+/** The constraints that failed, keyed by property; empty when the body is valid. */
+const failures = async (body: object): Promise<Record<string, string[]>> => {
+ const errors = await validate(plainToInstance(CreateChannelDto, body, transformOptions), pipeOptions);
+ return Object.fromEntries(errors.map(e => [e.property, Object.keys(e.constraints ?? {})]));
+};
+
+// The validator caps both fields and the contract has to publish the same caps, or a generated client is told
+// one bound while the server enforces another. Each case judges a value at the bound and one past it with the
+// real validator, and reads the published value, so neither side can drift without a failure.
describe('CreateChannelDto contract', () => {
it.each([
['name', 100],
['description', 2048],
- ])('publishes the %s length cap the validator enforces', (name, max) => {
+ ])('%s: the validator and the published contract cap at %d', async (name, max) => {
expect(property(name).maxLength).toBe(max);
+ expect(await failures({ name: 'n', [name]: 'x'.repeat(max) })).toEqual({});
+ expect(await failures({ name: 'n', [name]: 'x'.repeat(max + 1) })).toEqual({ [name]: ['maxLength'] });
+ });
+
+ it('refuses an empty name and lets the description be omitted', async () => {
+ expect(await failures({ name: '' })).toEqual({ name: ['isNotEmpty'] });
+ expect(await failures({ name: 'Product updates' })).toEqual({});
});
});
diff --git a/src/modules/contact/dto/upsert-contact.dto.spec.ts b/src/modules/contact/dto/upsert-contact.dto.spec.ts
index 1f37b8796..82ff2288d 100644
--- a/src/modules/contact/dto/upsert-contact.dto.spec.ts
+++ b/src/modules/contact/dto/upsert-contact.dto.spec.ts
@@ -1,4 +1,7 @@
+import { plainToInstance } from 'class-transformer';
+import { validate } from 'class-validator';
import { ADDRESSBOOK_NAME_MAX_LENGTH, UpsertContactDto } from './upsert-contact.dto';
+import { GLOBAL_VALIDATION_OPTIONS } from '../../../config/app-validation';
const property = (name: string) =>
Reflect.getMetadata('swagger/apiModelProperties', UpsertContactDto.prototype, name) as {
@@ -6,10 +9,34 @@ const property = (name: string) =>
maxLength?: number;
};
-// The validator refuses an empty first name; the contract has to publish the same bound, or a
-// generated client accepts input the server then refuses.
+// The options the global ValidationPipe runs with, so a body is judged the way a request is.
+const { transformOptions, ...pipeOptions } = GLOBAL_VALIDATION_OPTIONS;
+
+/** The constraints that failed, keyed by property; empty when the body is valid. */
+const failures = async (body: object): Promise<Record<string, string[]>> => {
+ const errors = await validate(plainToInstance(UpsertContactDto, body, transformOptions), pipeOptions);
+ return Object.fromEntries(errors.map(e => [e.property, Object.keys(e.constraints ?? {})]));
+};
+
+const MAX = ADDRESSBOOK_NAME_MAX_LENGTH;
+
+// The validator refuses an empty first name and caps both names; the contract has to publish the same bounds,
+// or a generated client accepts input the server then refuses (or the server saves a nameless addressbook
+// entry). Each case judges a value at the bound and one past it with the real validator, and reads the
+// published value, so neither side can drift without a failure.
describe('UpsertContactDto contract', () => {
- it('publishes the firstName length bounds the validator enforces', () => {
- expect(property('firstName')).toMatchObject({ minLength: 1, maxLength: ADDRESSBOOK_NAME_MAX_LENGTH });
+ it('publishes the firstName length bounds the validator enforces', async () => {
+ expect(property('firstName')).toMatchObject({ minLength: 1, maxLength: MAX });
+ expect(await failures({ firstName: '' })).toEqual({ firstName: ['minLength'] });
+ expect(await failures({ firstName: 'x' })).toEqual({});
+ expect(await failures({ firstName: 'x'.repeat(MAX) })).toEqual({});
+ expect(await failures({ firstName: 'x'.repeat(MAX + 1) })).toEqual({ firstName: ['maxLength'] });
+ });
+
+ it('publishes the lastName cap the validator enforces, and lets it be omitted', async () => {
+ expect(property('lastName')).toMatchObject({ maxLength: MAX });
+ expect(await failures({ firstName: 'Ann' })).toEqual({});
+ expect(await failures({ firstName: 'Ann', lastName: 'x'.repeat(MAX) })).toEqual({});
+ expect(await failures({ firstName: 'Ann', lastName: 'x'.repeat(MAX + 1) })).toEqual({ lastName: ['maxLength'] });
});
});
diff --git a/src/modules/group/dto/group.dto.spec.ts b/src/modules/group/dto/group.dto.spec.ts
index f68790d92..ddc577769 100644
--- a/src/modules/group/dto/group.dto.spec.ts
+++ b/src/modules/group/dto/group.dto.spec.ts
@@ -99,6 +99,26 @@ describe('group DTO validation', () => {
expect((await errorsFor(JoinGroupDto, {})).length).toBeGreaterThan(0);
});
+ it('caps the invite code at 128 characters, as the contract publishes', async () => {
+ const published = Reflect.getMetadata('swagger/apiModelProperties', JoinGroupDto.prototype, 'inviteCode') as {
+ maxLength?: number;
+ };
+ expect(published.maxLength).toBe(128);
+ expect(await errorsFor(JoinGroupDto, { inviteCode: 'a'.repeat(128) })).toHaveLength(0);
+ const tooLong = await errorsFor(JoinGroupDto, { inviteCode: 'a'.repeat(129) });
+ expect(tooLong.map(e => e.property)).toEqual(['inviteCode']);
+ });
+
+ it('SetGroupPictureDto accepts only an image mimetype, so a non-image payload is refused with 400', async () => {
+ for (const mimetype of ['image/jpeg', 'image/png']) {
+ expect(await errorsFor(SetGroupPictureDto, { base64: 'QUJD', mimetype })).toHaveLength(0);
+ }
+ for (const mimetype of ['application/pdf', 'text/plain', 'jpeg']) {
+ const errors = await errorsFor(SetGroupPictureDto, { base64: 'QUJD', mimetype });
+ expect(errors.map(e => e.property)).toEqual(['mimetype']);
+ }
+ });
+
it('GroupSettingsDto accepts an empty body and any subset of fields (at-least-one is a service rule)', async () => {
expect(await errorsFor(GroupSettingsDto, {})).toHaveLength(0);
expect(await errorsFor(GroupSettingsDto, { announce: true })).toHaveLength(0);