Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(api): refuse an object where a request field takes a list

Yudhi Armyndharis3c4a29caec3b
diff --git a/src/common/utils/dto-strict-coercion.spec.ts b/src/common/utils/dto-strict-coercion.spec.ts
index 1cd8b77ad..4f57456c2 100644
--- a/src/common/utils/dto-strict-coercion.spec.ts
+++ b/src/common/utils/dto-strict-coercion.spec.ts
@@ -10,7 +10,7 @@ import { join } from 'path';
* The global ValidationPipe runs with `transformOptions.enableImplicitConversion: true`
* (`src/config/app-validation.ts`). That is deliberate — it lets a client send `"5"` for a numeric
* field, which form-encoded bodies and several HTTP clients do by default. But it also means
- * class-transformer rewrites the value BEFORE any `@Is*` validator sees it, and three of its
+ * class-transformer rewrites the value BEFORE any `@Is*` validator sees it, and four of its
* conversions destroy information rather than preserving it:
*
* Boolean — every non-empty string becomes `true`, so `"false"`, `"no"` and `"0"` all arrive as
@@ -20,15 +20,20 @@ import { join } from 'path';
* String - a boolean or object becomes its string form (`true`, `[object Object]`), so `@IsString()`
* accepts it and the route sends text the caller never wrote. A number keeps the conversion,
* because clients that hold a phone number as a number rely on it.
+ * Array - an object becomes an EMPTY array (class-transformer builds `new Array()` and copies the keys
+ * onto it), so `@IsArray()` accepts it. Where an empty list means "no restriction", as in the
+ * key lists `allowedChats`, `allowedSessions` and `allowedIps`, a map sent by mistake created
+ * a key with no restriction at all.
*
- * The first two fail toward the more permissive value, which is how a `forEveryone=false` delete became
- * a delete-for-everyone. `ToStrictBoolean`/`ToStrictNumber`/`ToStrictString` (`./strict-boolean`)
- * restore the rejection while keeping the useful half of the conversion.
+ * The first, second and fourth fail toward the more permissive value, which is how a `forEveryone=false`
+ * delete became a delete-for-everyone. `ToStrictBoolean`/`ToStrictNumber`/`ToStrictString`/`ToStrictArray`
+ * (`./strict-boolean`) restore the rejection while keeping the useful half of the conversion.
*
* This spec asserts the BEHAVIOUR rather than the presence of a decorator, so any future mechanism
* that produces the same guarantee also satisfies it. Every boolean and numeric property that
* carries validation metadata is covered — including classes that are never exported, because
- * discovery walks class-validator's own registry rather than module exports. So is every string one.
+ * discovery walks class-validator's own registry rather than module exports. So is every string one, and
+ * every list. Only `*.dto.ts` files are loaded, so a request class declared in a controller escapes.
*/
const PIPE_TRANSFORM_OPTS = { enableImplicitConversion: true };
@@ -45,6 +50,11 @@ const PROBES: Record<string, { values: unknown[]; reason: string }> = {
values: [true, { order: 42 }, ['a']],
reason: 'implicit conversion rewrites a boolean or an object into its string form, which @IsString accepts',
},
+ // A map is the mistake that matters: {"[email protected]":true} sent for a list of chats.
+ Array: {
+ values: [{}, { '[email protected]': true }],
+ reason: 'class-transformer turns an object into an empty array, which @IsArray accepts',
+ },
};
function dtoFiles(dir: string, out: string[] = []): string[] {
@@ -102,10 +112,11 @@ describe('DTO input-coercion drift gate', () => {
expect(names.length).toBeGreaterThanOrEqual(40);
});
- it('finds a boolean, a numeric and a string property to check', () => {
+ it('finds a boolean, a numeric, a string and a list property to check', () => {
expect(targets.some(t => t.type === 'Boolean')).toBe(true);
expect(targets.some(t => t.type === 'Number')).toBe(true);
expect(targets.some(t => t.type === 'String')).toBe(true);
+ expect(targets.some(t => t.type === 'Array')).toBe(true);
expect(targets.length).toBeGreaterThanOrEqual(15);
// Most request fields are text, so a scan that came up with none of them would report a clean result.
expect(targets.filter(t => t.type === 'String').length).toBeGreaterThanOrEqual(100);
@@ -139,6 +150,24 @@ describe('DTO input-coercion drift gate', () => {
expect((instance as Record<string, unknown>)[target.prop]).toBe('628123456789');
},
);
+
+ // The verdict above can pass vacuously where a list also needs a minimum size: the empty list an object
+ // turns into is refused by ArrayNotEmpty, and that guard is one edit from gone. So the value reaching the
+ // validators is checked as well: an object stays an object, and a real list stays a list.
+ const listTargets = targets.filter(t => t.type === 'Array');
+
+ it.each(listTargets.map(t => [`${t.cls.name}.${t.prop}`, t] as const))(
+ '%s does not turn an object into a list, and still reads a list as a list',
+ (_label, target) => {
+ const read = (value: unknown) =>
+ (plainToInstance(target.cls, { [target.prop]: value }, PIPE_TRANSFORM_OPTS) as Record<string, unknown>)[
+ target.prop
+ ];
+ expect(Array.isArray(read({ '[email protected]': true }))).toBe(false);
+ expect(read([])).toEqual([]);
+ expect(Array.isArray(read([]))).toBe(true);
+ },
+ );
});
/**
diff --git a/src/common/utils/strict-boolean.spec.ts b/src/common/utils/strict-boolean.spec.ts
index a312c32b5..2f1db5834 100644
--- a/src/common/utils/strict-boolean.spec.ts
+++ b/src/common/utils/strict-boolean.spec.ts
@@ -1,9 +1,9 @@
import 'reflect-metadata';
-import { plainToInstance } from 'class-transformer';
+import { plainToInstance, Type } from 'class-transformer';
import { validate } from 'class-validator';
import { IsBoolean, ValidateIf } from 'class-validator';
-import { IsInt, IsString } from 'class-validator';
-import { ToStrictBoolean, ToStrictNumber, ToStrictString } from './strict-boolean';
+import { IsArray, IsInt, IsOptional, IsString, ValidateNested } from 'class-validator';
+import { ToStrictArray, ToStrictBoolean, ToStrictNumber, ToStrictString } from './strict-boolean';
// Mirrors the real pipe: whitelist + forbidNonWhitelisted from src/main.ts, and the
// enableImplicitConversion transform option from src/config/app-validation.ts. Leaving the
@@ -192,3 +192,92 @@ describe('ToStrictString', () => {
}
});
});
+
+class Item {
+ @IsString()
+ name!: string;
+}
+
+class ArraySubject {
+ @ToStrictArray()
+ @IsOptional()
+ @IsArray()
+ @IsString({ each: true })
+ list?: string[];
+
+ @ToStrictArray()
+ @IsOptional()
+ @IsArray()
+ @ValidateNested({ each: true })
+ @Type(() => Item)
+ items?: Item[];
+}
+
+class UnguardedArray {
+ @IsOptional()
+ @IsArray()
+ @IsString({ each: true })
+ list?: string[];
+
+ @IsOptional()
+ @IsArray()
+ @ValidateNested({ each: true })
+ @Type(() => Item)
+ items?: Item[];
+}
+
+describe('ToStrictArray', () => {
+ // A JSON array behaves exactly as it does without the decorator: same converted value, same verdict.
+ it.each([
+ [{ list: [] }],
+ [{ list: ['a'] }],
+ [{ list: ['a', 'b'] }],
+ [{ list: [1, 2] }],
+ [{ list: [{ a: 1 }] }],
+ [{ items: [] }],
+ [{ items: [{ name: 'x' }] }],
+ [{ items: [{ name: 5 }, { other: true }] }],
+ ])('reads %j as the unguarded pipe does', async payload => {
+ const guarded = await run(ArraySubject, payload);
+ const unguarded = await run(UnguardedArray, payload);
+ expect(guarded.instance).toEqual(unguarded.instance);
+ expect(guarded.errors.map(e => e.property)).toEqual(unguarded.errors.map(e => e.property));
+ });
+
+ it('still builds the elements of a nested list', async () => {
+ const { instance, errors } = await run(ArraySubject, { items: [{ name: 'x' }] });
+ expect(errors).toHaveLength(0);
+ expect(instance.items?.[0]).toBeInstanceOf(Item);
+ });
+
+ it.each([[{}], [{ a: 1 }], [{ '[email protected]': true }], ['abc'], [5], [true]])(
+ 'rejects %j instead of storing an empty list',
+ async value => {
+ const { instance, errors } = await run(ArraySubject, { list: value });
+ expect(instance.list).toEqual(value);
+ expect(Array.isArray(instance.list)).toBe(false);
+ expect(errors.map(e => e.property)).toEqual(['list']);
+ },
+ );
+
+ it('leaves an absent property absent and a null one null', async () => {
+ const absent = await run(ArraySubject, {});
+ expect(absent.instance.list).toBeUndefined();
+ expect(absent.errors).toHaveLength(0);
+
+ const nulled = await run(ArraySubject, { list: null });
+ expect(nulled.instance.list).toBeNull();
+ expect(nulled.errors).toHaveLength(0);
+ });
+
+ // The behaviour the decorator exists to prevent: an object becoming an empty list, which an access
+ // restriction read as "no restriction".
+ it('documents the unguarded behaviour it replaces: an object becomes an empty list', async () => {
+ for (const value of [{}, { a: 1 }, { '[email protected]': true }]) {
+ const { instance, errors } = await run(UnguardedArray, { list: value });
+ expect(Array.isArray(instance.list)).toBe(true);
+ expect(instance.list).toHaveLength(0);
+ expect(errors).toHaveLength(0);
+ }
+ });
+});
diff --git a/src/common/utils/strict-boolean.ts b/src/common/utils/strict-boolean.ts
index 5035d8192..a992a361d 100644
--- a/src/common/utils/strict-boolean.ts
+++ b/src/common/utils/strict-boolean.ts
@@ -75,3 +75,20 @@ export function coerceStrictString({ obj, key }: Pick<TransformFnParams, 'obj' |
/** Property decorator form of {@link coerceStrictString}. Pair it with `@IsString()`. */
export const ToStrictString = (): PropertyDecorator => Transform(coerceStrictString);
+
+/**
+ * The array counterpart. For an `Array`-typed property class-transformer builds `new Array()` and copies
+ * the keys of an object onto it, so `{"[email protected]":true}` arrives as an EMPTY array that `@IsArray()`
+ * accepts. Where an empty list means "no restriction" (the key lists `allowedChats`, `allowedSessions` and
+ * `allowedIps`), a map sent by mistake created a key with no restriction at all.
+ *
+ * A JSON array keeps the converted value class-transformer built, element types and all, so it reads
+ * exactly as before. Anything else is kept as the caller sent it, so `@IsArray()` refuses it.
+ */
+export function coerceStrictArray({ value, obj, key }: Pick<TransformFnParams, 'value' | 'obj' | 'key'>): unknown {
+ const raw = (obj as Record<string, unknown> | undefined)?.[key];
+ return Array.isArray(raw) ? value : raw;
+}
+
+/** Property decorator form of {@link coerceStrictArray}. Pair it with `@IsArray()`. */
+export const ToStrictArray = (): PropertyDecorator => Transform(coerceStrictArray);
diff --git a/src/modules/auth/dto/api-key.dto.spec.ts b/src/modules/auth/dto/api-key.dto.spec.ts
index 3f32058b2..c9f97c9bf 100644
--- a/src/modules/auth/dto/api-key.dto.spec.ts
+++ b/src/modules/auth/dto/api-key.dto.spec.ts
@@ -60,4 +60,24 @@ describe('API key DTO contract', () => {
expect(await errors(ALLOWED_CHATS_MAX)).toEqual([]);
expect(await errors(ALLOWED_CHATS_MAX + 1)).toEqual(['allowedChats']);
});
+
+ // An empty list is "no restriction" for these three fields, and class-transformer turned an object into an
+ // empty list, so a map sent by mistake created a key that reached every chat, session and address.
+ it.each([CreateApiKeyDto, UpdateApiKeyDto])('refuses a restriction list of %p given as an object', async dto => {
+ for (const field of ['allowedChats', 'allowedSessions', 'allowedIps']) {
+ for (const value of [{}, { '[email protected]': true }]) {
+ const errors = (await validate(plainToInstance(dto, { name: 'probe', [field]: value }))).map(e => e.property);
+ expect(errors).toEqual([field]);
+ }
+ }
+ });
+
+ it.each([CreateApiKeyDto, UpdateApiKeyDto])(
+ 'still takes the restriction lists of %p as lists, empty ones too',
+ async dto => {
+ const body = { name: 'probe', allowedChats: ['[email protected]'], allowedSessions: [], allowedIps: ['10.0.0.0/8'] };
+ expect(await validate(plainToInstance(dto, body))).toEqual([]);
+ expect(plainToInstance(dto, body).allowedSessions).toEqual([]);
+ },
+ );
});
diff --git a/src/modules/auth/dto/api-key.dto.ts b/src/modules/auth/dto/api-key.dto.ts
index 63fb3dd65..5f6730e55 100644
--- a/src/modules/auth/dto/api-key.dto.ts
+++ b/src/modules/auth/dto/api-key.dto.ts
@@ -10,7 +10,7 @@ import {
Validate,
} from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
-import { ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictArray, ToStrictString } from '../../../common/utils/strict-boolean';
import { MaxCodePoints } from '../../../common/validation/max-code-points';
import { ApiKeyRole } from '../entities/api-key.entity';
import { IsIpOrCidrConstraint } from './is-ip-or-cidr.validator';
@@ -52,6 +52,7 @@ export class CreateApiKeyDto {
example: ['192.168.1.1', '10.0.0.0/8'],
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@IsString({ each: true })
@Validate(IsIpOrCidrConstraint, { each: true })
@@ -65,6 +66,7 @@ export class CreateApiKeyDto {
example: ['0a941dac-a965-45e7-b318-74ae8be134f0', '8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a'],
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@IsString({ each: true })
@ArrayUnique()
@@ -83,6 +85,7 @@ export class CreateApiKeyDto {
maxItems: ALLOWED_CHATS_MAX,
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(ALLOWED_CHATS_MAX)
@IsString({ each: true })
@@ -184,6 +187,7 @@ export class UpdateApiKeyDto {
@ApiPropertyOptional()
@IsOptional()
+ @ToStrictArray()
@IsArray()
@IsString({ each: true })
@Validate(IsIpOrCidrConstraint, { each: true })
@@ -191,6 +195,7 @@ export class UpdateApiKeyDto {
@ApiPropertyOptional()
@IsOptional()
+ @ToStrictArray()
@IsArray()
@IsString({ each: true })
@ArrayUnique()
@@ -199,6 +204,7 @@ export class UpdateApiKeyDto {
@ApiPropertyOptional({ maxItems: ALLOWED_CHATS_MAX })
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(ALLOWED_CHATS_MAX)
@IsString({ each: true })
diff --git a/src/modules/group/dto/group.dto.ts b/src/modules/group/dto/group.dto.ts
index e2f263dc4..336c2660d 100644
--- a/src/modules/group/dto/group.dto.ts
+++ b/src/modules/group/dto/group.dto.ts
@@ -14,7 +14,7 @@ import {
Matches,
ValidateIf,
} from 'class-validator';
-import { ToStrictBoolean, ToStrictNumber, ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictArray, ToStrictBoolean, ToStrictNumber, ToStrictString } from '../../../common/utils/strict-boolean';
import type { GroupMemberAddMode } from '../../../engine/interfaces/whatsapp-engine.interface';
import { IsMediaUrl } from '../../../common/media/media-url';
import { stripBase64DataUri } from '../../message/media-cap.util';
@@ -46,6 +46,7 @@ export class CreateGroupDto {
type: [String],
maxItems: GROUP_PARTICIPANTS_MAX,
})
+ @ToStrictArray()
@IsArray()
@ArrayNotEmpty()
@ArrayMaxSize(GROUP_PARTICIPANTS_MAX)
@@ -59,6 +60,7 @@ export class ParticipantsDto {
type: [String],
maxItems: GROUP_PARTICIPANTS_MAX,
})
+ @ToStrictArray()
@IsArray()
@ArrayNotEmpty()
@ArrayMaxSize(GROUP_PARTICIPANTS_MAX)
@@ -79,6 +81,7 @@ export class MembershipRequestActionDto {
maxItems: GROUP_PARTICIPANTS_MAX,
})
@ValidateIf(o => (o as MembershipRequestActionDto).participants !== undefined)
+ @ToStrictArray()
@IsArray()
@ArrayNotEmpty()
@ArrayMaxSize(GROUP_PARTICIPANTS_MAX)
diff --git a/src/modules/infra/dto/restart.dto.ts b/src/modules/infra/dto/restart.dto.ts
new file mode 100644
index 000000000..87ce82fca
--- /dev/null
+++ b/src/modules/infra/dto/restart.dto.ts
@@ -0,0 +1,20 @@
+import { ApiPropertyOptional } from '@nestjs/swagger';
+import { IsArray, IsOptional, IsString } from 'class-validator';
+import { ToStrictArray } from '../../../common/utils/strict-boolean';
+
+/** Body for POST /infra/restart. */
+export class RestartDto {
+ @ApiPropertyOptional({ type: [String] })
+ @IsOptional()
+ @ToStrictArray()
+ @IsArray()
+ @IsString({ each: true })
+ profiles?: string[];
+
+ @ApiPropertyOptional({ type: [String] })
+ @IsOptional()
+ @ToStrictArray()
+ @IsArray()
+ @IsString({ each: true })
+ profilesToRemove?: string[];
+}
diff --git a/src/modules/infra/infra-config.controller.ts b/src/modules/infra/infra-config.controller.ts
index e52aec7c8..ef3fe077f 100644
--- a/src/modules/infra/infra-config.controller.ts
+++ b/src/modules/infra/infra-config.controller.ts
@@ -10,9 +10,9 @@ import {
HttpStatus,
Optional,
} from '@nestjs/common';
-import { ApiTags, ApiOperation, ApiResponse, ApiBody, ApiPropertyOptional } from '@nestjs/swagger';
+import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';
import { InfraConfigResponseDto, InfraConfigSaveResponseDto, InfraRestartResponseDto } from './dto/infra-response.dto';
-import { IsArray, IsOptional, IsString } from 'class-validator';
+import { RestartDto } from './dto/restart.dto';
import { RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
import { writeSecretFile } from '../../common/utils/secret-file';
@@ -39,24 +39,11 @@ import {
ConfigSectionContext,
} from './config-sections';
-// The PUT /infra/config body DTOs live in ./dto/save-config.dto.ts: as *.dto.ts classes they are
-// covered by the input-coercion drift gate (src/common/utils/dto-strict-coercion.spec.ts), which
-// controller-local classes escape, and their boolean/numeric fields carry the @ToStrictBoolean /
-// @ToStrictNumber transforms that keep a form-encoded 'false' from being coerced to `true`.
-
-class RestartDto {
- @ApiPropertyOptional({ type: [String] })
- @IsOptional()
- @IsArray()
- @IsString({ each: true })
- profiles?: string[];
-
- @ApiPropertyOptional({ type: [String] })
- @IsOptional()
- @IsArray()
- @IsString({ each: true })
- profilesToRemove?: string[];
-}
+// The PUT /infra/config body DTOs live in ./dto/save-config.dto.ts and the restart body in
+// ./dto/restart.dto.ts: as *.dto.ts classes they are covered by the input-coercion drift gate
+// (src/common/utils/dto-strict-coercion.spec.ts), which controller-local classes escape, and their
+// boolean/numeric fields carry the @ToStrictBoolean / @ToStrictNumber transforms that keep a form-encoded
+// 'false' from being coerced to `true`.
// The env key and value that point the app at each bundled service, as /infra/status detects them.
const BUNDLED_SERVICE_ENV: Record<string, [string, string]> = {
diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.ts
index 2bf78e2fd..6c69f899f 100644
--- a/src/modules/message/dto/bulk-message.dto.ts
+++ b/src/modules/message/dto/bulk-message.dto.ts
@@ -16,7 +16,7 @@ import {
} from 'class-validator';
import { Type } from 'class-transformer';
import { Validate } from 'class-validator';
-import { ToStrictBoolean, ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictArray, ToStrictBoolean, ToStrictString } from '../../../common/utils/strict-boolean';
import {
BATCH_ID_MAX_LENGTH,
CHAT_ID_MAX_LENGTH,
@@ -117,6 +117,7 @@ export class BulkMessageContentDto {
items: { type: 'string', maxLength: MENTION_WID_MAX_LENGTH },
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(MENTIONS_MAX)
@IsString({ each: true })
@@ -195,6 +196,7 @@ export class SendBulkMessageDto {
type: [BulkMessageItemDto],
maxItems: BULK_MESSAGES_MAX,
})
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(BULK_MESSAGES_MAX)
@ValidateNested({ each: true })
diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.ts
index 400aa4cb2..2ca74a819 100644
--- a/src/modules/message/dto/message-actions.dto.ts
+++ b/src/modules/message/dto/message-actions.dto.ts
@@ -13,7 +13,7 @@ import {
IsIn,
Validate,
} from 'class-validator';
-import { ToStrictBoolean, ToStrictNumber, ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictArray, ToStrictBoolean, ToStrictNumber, ToStrictString } from '../../../common/utils/strict-boolean';
import {
CHAT_ID_MAX_LENGTH,
MENTIONS_DESCRIPTION,
@@ -134,6 +134,7 @@ export class SendPollDto {
items: { type: 'string', maxLength: 100 },
example: ['Park', 'Beach', 'Downtown'],
})
+ @ToStrictArray()
@IsArray()
@ArrayMinSize(2)
@ArrayMaxSize(12)
@@ -189,6 +190,7 @@ export class ReplyMessageDto {
items: { type: 'string', maxLength: MENTION_WID_MAX_LENGTH },
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(MENTIONS_MAX)
@IsString({ each: true })
@@ -328,6 +330,7 @@ export class VotePollDto {
type: [String],
maxItems: POLL_VOTE_MAX_OPTIONS,
})
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(POLL_VOTE_MAX_OPTIONS)
@IsString({ each: true })
@@ -443,6 +446,7 @@ export class EditMessageDto {
items: { type: 'string', maxLength: MENTION_WID_MAX_LENGTH },
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(MENTIONS_MAX)
@IsString({ each: true })
diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.ts
index 3e7d58049..4fbd867d7 100644
--- a/src/modules/message/dto/send-message.dto.ts
+++ b/src/modules/message/dto/send-message.dto.ts
@@ -13,7 +13,7 @@ import {
} from 'class-validator';
import { Type } from 'class-transformer';
import { IsMentionWidConstraint } from './is-mention-wid.validator';
-import { ToStrictBoolean, ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictArray, ToStrictBoolean, ToStrictString } from '../../../common/utils/strict-boolean';
import { IsMediaUrl } from '../../../common/media/media-url';
import { stripBase64DataUri } from '../media-cap.util';
@@ -140,6 +140,7 @@ export class SendTextMessageDto {
items: { type: 'string', maxLength: MENTION_WID_MAX_LENGTH },
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(MENTIONS_MAX)
@IsString({ each: true })
@@ -284,6 +285,7 @@ export class SendMediaMessageDto {
items: { type: 'string', maxLength: MENTION_WID_MAX_LENGTH },
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(MENTIONS_MAX)
@IsString({ each: true })
diff --git a/src/modules/message/dto/send-template.dto.ts b/src/modules/message/dto/send-template.dto.ts
index 96d8ab1a4..fd6474d75 100644
--- a/src/modules/message/dto/send-template.dto.ts
+++ b/src/modules/message/dto/send-template.dto.ts
@@ -10,7 +10,7 @@ import {
IsBoolean,
Validate,
} from 'class-validator';
-import { ToStrictBoolean, ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictArray, ToStrictBoolean, ToStrictString } from '../../../common/utils/strict-boolean';
import { CHAT_ID_MAX_LENGTH, MENTIONS_DESCRIPTION, MENTIONS_MAX, MENTION_WID_MAX_LENGTH } from './send-message.dto';
import { IsMentionWidConstraint } from './is-mention-wid.validator';
@@ -65,6 +65,7 @@ export class SendTemplateMessageDto {
items: { type: 'string', maxLength: MENTION_WID_MAX_LENGTH },
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(MENTIONS_MAX)
@IsString({ each: true })
diff --git a/src/modules/plugins/dto/plugin.dto.ts b/src/modules/plugins/dto/plugin.dto.ts
index 92ee96b1e..9299b29d2 100644
--- a/src/modules/plugins/dto/plugin.dto.ts
+++ b/src/modules/plugins/dto/plugin.dto.ts
@@ -2,7 +2,7 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsArray, IsObject, IsString, IsUrl } from 'class-validator';
import type { PluginConfigSchema, PluginI18n } from '../../../core/plugins';
import { PluginType, PluginStatus } from '../../../core/plugins';
-import { ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictArray, ToStrictString } from '../../../common/utils/strict-boolean';
export class PluginDto {
@ApiProperty({ description: 'Plugin ID' })
@@ -78,6 +78,7 @@ export class PluginSessionsDto {
example: ['*'],
type: [String],
})
+ @ToStrictArray()
@IsArray()
@IsString({ each: true })
sessions!: string[];
diff --git a/src/modules/session/dto/mark-chat-read.dto.ts b/src/modules/session/dto/mark-chat-read.dto.ts
index d7909ae87..73f7d8a38 100644
--- a/src/modules/session/dto/mark-chat-read.dto.ts
+++ b/src/modules/session/dto/mark-chat-read.dto.ts
@@ -10,7 +10,7 @@ import {
MaxLength,
} from 'class-validator';
import { CHAT_ID_MAX_LENGTH, CHAT_JID_MESSAGE, CHAT_JID_PATTERN } from '../../message/dto/send-message.dto';
-import { ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictString, ToStrictArray } from '../../../common/utils/strict-boolean';
/**
* Ceiling on one request's receipt batch, so a single call cannot hand the engine an unbounded key
@@ -66,6 +66,7 @@ export class MarkChatReadDto {
// `"messageIds": null` reached the engine unchecked and dereferenced there as a 500. Absent stays
// absent; present-but-null falls through to @IsArray and answers 400.
@ValidateIf((_object, value) => value !== undefined)
+ @ToStrictArray()
@IsArray()
// An empty array asks for nothing to be acknowledged. Rejected rather than accepted, because the
// engine reads a missing list as "the newest message" and the two must not collapse: a caller that
diff --git a/src/modules/status/dto/send-media-status.dto.ts b/src/modules/status/dto/send-media-status.dto.ts
index c4d0df4fc..855e34b6c 100644
--- a/src/modules/status/dto/send-media-status.dto.ts
+++ b/src/modules/status/dto/send-media-status.dto.ts
@@ -15,7 +15,7 @@ import { Type } from 'class-transformer';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsMediaUrl } from '../../../common/media/media-url';
import { stripBase64DataUri } from '../../message/media-cap.util';
-import { ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictArray, ToStrictString } from '../../../common/utils/strict-boolean';
class StatusMediaInput {
@ApiPropertyOptional({
@@ -74,6 +74,7 @@ export class SendImageStatusDto {
maxItems: 256,
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(256)
@IsString({ each: true })
@@ -107,6 +108,7 @@ export class SendVideoStatusDto {
maxItems: 256,
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(256)
@IsString({ each: true })
@@ -154,6 +156,7 @@ export class SendVoiceStatusDto {
maxItems: 256,
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(256)
@IsString({ each: true })
diff --git a/src/modules/status/dto/send-text-status.dto.ts b/src/modules/status/dto/send-text-status.dto.ts
index f4a6aa68b..4d69dd8fb 100644
--- a/src/modules/status/dto/send-text-status.dto.ts
+++ b/src/modules/status/dto/send-text-status.dto.ts
@@ -1,6 +1,6 @@
import { IsString, IsOptional, IsInt, IsIn, Matches, MaxLength, IsArray, ArrayMaxSize } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
-import { ToStrictNumber, ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictArray, ToStrictNumber, ToStrictString } from '../../../common/utils/strict-boolean';
export class SendTextStatusDto {
@ApiProperty({
@@ -47,6 +47,7 @@ export class SendTextStatusDto {
maxItems: 256,
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(256)
@IsString({ each: true })
diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.ts
index 852c834b7..8d33e3102 100644
--- a/src/modules/webhook/dto/webhook.dto.ts
+++ b/src/modules/webhook/dto/webhook.dto.ts
@@ -21,7 +21,7 @@ import { MAX_CONDITIONS } from '../filters/filter-types';
import type { FilterOperator, WebhookFilters } from '../filters/filter-types';
import { IsValidWebhookFilters } from '../filters/filter-validation';
import { IsHeaderMap } from './is-header-map.validator';
-import { ToStrictBoolean, ToStrictNumber, ToStrictString } from '../../../common/utils/strict-boolean';
+import { ToStrictArray, ToStrictBoolean, ToStrictNumber, ToStrictString } from '../../../common/utils/strict-boolean';
import { MaxCodePoints } from '../../../common/validation/max-code-points';
/**
@@ -132,6 +132,7 @@ export class CreateWebhookDto {
minItems: 1,
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMinSize(1)
// Must include '*' (wildcard subscribe-all) alongside the known events.
@@ -221,6 +222,7 @@ export class UpdateWebhookDto {
minItems: 1,
})
@ValidateIf((_: UpdateWebhookDto, v: unknown) => v !== undefined)
+ @ToStrictArray()
@IsArray()
@ArrayMinSize(1)
@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })
@@ -461,6 +463,7 @@ export class RedriveWebhookDeliveriesDto {
items: { type: 'string', maxLength: 128 },
})
@IsOptional()
+ @ToStrictArray()
@IsArray()
@ArrayMaxSize(500)
@IsString({ each: true })
diff --git a/test/session-scope.e2e-spec.ts b/test/session-scope.e2e-spec.ts
index 4e77dd4b5..9d1a70a22 100644
--- a/test/session-scope.e2e-spec.ts
+++ b/test/session-scope.e2e-spec.ts
@@ -245,6 +245,51 @@ describe('Session-scoped query endpoints (e2e)', () => {
await request(app.getHttpServer()).delete(`/api/auth/api-keys/${id}`).set('X-API-Key', adminKey).expect(204);
});
+ // An object given for a list used to become an empty array, which a key stores as no restriction at all:
+ // {"allowedChats":{"[email protected]":true}} created a key that reached every chat. It is refused instead.
+ describe.each(['allowedChats', 'allowedSessions', 'allowedIps'])('%s given as an object', field => {
+ const asObject = { [field]: { '[email protected]': true } };
+
+ it('is refused on create, and nothing is stored', async () => {
+ const name = `e2e-object-${field}`;
+ await request(app.getHttpServer())
+ .post('/api/auth/api-keys')
+ .set('X-API-Key', adminKey)
+ .send({ name, role: 'operator', ...asObject })
+ .expect(400);
+ const listed = await request(app.getHttpServer()).get('/api/auth/api-keys').set('X-API-Key', adminKey);
+ expect((listed.body as Array<{ name: string }>).some(key => key.name === name)).toBe(false);
+ });
+
+ it('is refused on update, and the stored restriction is kept', async () => {
+ const created = await request(app.getHttpServer())
+ .post('/api/auth/api-keys')
+ .set('X-API-Key', adminKey)
+ .send({ name: `e2e-keep-${field}`, role: 'operator', allowedChats: ['[email protected]'] })
+ .expect(201);
+ const { id } = created.body as { id: string };
+ await request(app.getHttpServer())
+ .put(`/api/auth/api-keys/${id}`)
+ .set('X-API-Key', adminKey)
+ .send(asObject)
+ .expect(400);
+ const read = await request(app.getHttpServer()).get(`/api/auth/api-keys/${id}`).set('X-API-Key', adminKey);
+ expect((read.body as { allowedChats?: string[] }).allowedChats).toEqual(['[email protected]']);
+ await request(app.getHttpServer()).delete(`/api/auth/api-keys/${id}`).set('X-API-Key', adminKey).expect(204);
+ });
+ });
+
+ it('still stores allowedChats given as a list', async () => {
+ const created = await request(app.getHttpServer())
+ .post('/api/auth/api-keys')
+ .set('X-API-Key', adminKey)
+ .send({ name: 'e2e-list-chats', role: 'operator', allowedChats: ['[email protected]'] })
+ .expect(201);
+ const { id } = created.body as { id: string; allowedChats?: string[] };
+ expect((created.body as { allowedChats?: string[] }).allowedChats).toEqual(['[email protected]']);
+ await request(app.getHttpServer()).delete(`/api/auth/api-keys/${id}`).set('X-API-Key', adminKey).expect(204);
+ });
+
it('audits the scoped denial as a failed-auth event', async () => {
await request(app.getHttpServer()).get('/api/auth/api-keys').set('X-API-Key', scopedKey).expect(403);
// The audit write is fire-and-forget; poll briefly for it to land.