Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): validate the import-data body with a DTO

Yudhi Armyndharisa7a543f43261
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 75738dc60..0d9de6b68 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `check:sdk-routes` scanned the JavaScript client for backtick-delimited paths only, while its PHP and Python rules already accepted every quote style, so the nine routes that client writes as single-quoted strings were never compared to the contract — `/api/health/ready` among them, which is also the container healthcheck and Kubernetes readiness path. Renaming one of those server-side passed every gate and the JS suite, and the published client would have 404'd with CI green.
- The JavaScript, Python, Go and Java SDKs omitted `contact`, `call` and `ephemeralDuration` from their chat-history message type, so a typed client had to cast to read three fields the endpoint returns; all four now mirror the engine payload.
+- `POST /api/infra/import-data` bound its body to an inline type, which erases at runtime, so on the replace-all restore the global ValidationPipe's `whitelist` and `forbidNonWhitelisted` never ran: a body carrying no `tables` failed as a 500 from inside the import, and a misspelled key was accepted in silence. It now takes a DTO — a missing `tables` answers 400 naming the field, an unknown key is refused, and `force`/`stopOrphans` accept only a real boolean or an exact `'true'`/`'false'`, so an ambiguous spelling cannot open the orphan-engine escape.
### Documentation
diff --git a/openapi.json b/openapi.json
index c356a4354..aee8d6f86 100644
--- a/openapi.json
+++ b/openapi.json
@@ -3938,65 +3938,7 @@
"content": {
"application/json": {
"schema": {
- "type": "object",
- "properties": {
- "force": {
- "type": "boolean",
- "description": "Allow the replace to proceed even while engines are running for sessions the backup does not contain (they keep running until restart; see restartRequired). Prefer stopOrphans, which closes that window inside this request instead."
- },
- "stopOrphans": {
- "type": "boolean",
- "description": "Stop the running engines for sessions the backup does not contain, inside this request and before the replace runs. Supersedes force for the orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so restartRequired stays false on the success path."
- },
- "tables": {
- "type": "object",
- "description": "Every one of the 14 migration tables is emptied before the restore runs, so a key omitted here is restored EMPTY rather than left untouched. Post the whole GET /api/infra/export-data payload, not a hand-built subset.",
- "properties": {
- "sessions": {
- "type": "array"
- },
- "webhooks": {
- "type": "array"
- },
- "messages": {
- "type": "array"
- },
- "messageBatches": {
- "type": "array"
- },
- "templates": {
- "type": "array"
- },
- "baileysStoredMessages": {
- "type": "array"
- },
- "lidMappings": {
- "type": "array"
- },
- "pluginInstances": {
- "type": "array"
- },
- "conversationMappings": {
- "type": "array"
- },
- "ingressEvents": {
- "type": "array"
- },
- "webhookDeliveryFailures": {
- "type": "array"
- },
- "integrationDeliveryFailures": {
- "type": "array"
- },
- "statusUpdates": {
- "type": "array"
- },
- "automationRules": {
- "type": "array"
- }
- }
- }
- }
+ "$ref": "#/components/schemas/ImportDataDto"
}
}
}
@@ -12546,6 +12488,70 @@
"omittedInlineMedia"
]
},
+ "ImportDataDto": {
+ "type": "object",
+ "properties": {
+ "tables": {
+ "type": "object",
+ "description": "Every one of the 14 migration tables is emptied before the restore runs, so a key omitted here is restored EMPTY rather than left untouched. Post the whole GET /api/infra/export-data payload, not a hand-built subset.",
+ "properties": {
+ "sessions": {
+ "type": "array"
+ },
+ "webhooks": {
+ "type": "array"
+ },
+ "messages": {
+ "type": "array"
+ },
+ "messageBatches": {
+ "type": "array"
+ },
+ "templates": {
+ "type": "array"
+ },
+ "baileysStoredMessages": {
+ "type": "array"
+ },
+ "lidMappings": {
+ "type": "array"
+ },
+ "pluginInstances": {
+ "type": "array"
+ },
+ "conversationMappings": {
+ "type": "array"
+ },
+ "ingressEvents": {
+ "type": "array"
+ },
+ "webhookDeliveryFailures": {
+ "type": "array"
+ },
+ "integrationDeliveryFailures": {
+ "type": "array"
+ },
+ "statusUpdates": {
+ "type": "array"
+ },
+ "automationRules": {
+ "type": "array"
+ }
+ }
+ },
+ "force": {
+ "type": "boolean",
+ "description": "Allow the replace to proceed even while engines are running for sessions the backup does not contain (they keep running until restart; see restartRequired). Prefer stopOrphans, which closes that window inside this request instead."
+ },
+ "stopOrphans": {
+ "type": "boolean",
+ "description": "Stop the running engines for sessions the backup does not contain, inside this request and before the replace runs. Supersedes force for the orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so restartRequired stays false on the success path."
+ }
+ },
+ "required": [
+ "tables"
+ ]
+ },
"InfraImportDataResponseDto": {
"type": "object",
"properties": {
diff --git a/src/modules/infra/dto/import-data.dto.spec.ts b/src/modules/infra/dto/import-data.dto.spec.ts
new file mode 100644
index 000000000..d9bf9b170
--- /dev/null
+++ b/src/modules/infra/dto/import-data.dto.spec.ts
@@ -0,0 +1,68 @@
+import 'reflect-metadata';
+import { plainToInstance } from 'class-transformer';
+import { validate } from 'class-validator';
+import { ImportDataDto } from './import-data.dto';
+import { TABLE_IMPORTERS } from '../table-importers';
+
+// Mirrors the real pipe from src/config/app-validation.ts: whitelist + forbidNonWhitelisted, and the
+// enableImplicitConversion transform option. Both halves matter here — the whitelist is the reason
+// this DTO exists, and the implicit conversion is what makes a plain `boolean` property unsafe.
+const PIPE_TRANSFORM_OPTS = { enableImplicitConversion: true };
+const PIPE_VALIDATOR_OPTS = { whitelist: true, forbidNonWhitelisted: true };
+
+async function run(payload: unknown) {
+ const instance = plainToInstance(ImportDataDto, payload as object, PIPE_TRANSFORM_OPTS);
+ const errors = await validate(instance, PIPE_VALIDATOR_OPTS);
+ return { instance, errors };
+}
+
+/** A minimal but complete payload: every table the importer registry knows, each empty. */
+function fullTables(): Record<string, unknown[]> {
+ return Object.fromEntries(TABLE_IMPORTERS.map(importer => [importer.key, []]));
+}
+
+describe('ImportDataDto', () => {
+ it('rejects a body with no tables, naming the field', async () => {
+ const { errors } = await run({ force: true });
+ // Before this DTO the inline `@Body()` type erased, so this body reached the restore and threw
+ // from inside it — a 500 on the replace-all route, with nothing pointing at the missing field.
+ expect(errors.map(e => e.property)).toEqual(['tables']);
+ });
+
+ it('rejects an unknown key', async () => {
+ const { errors } = await run({ tables: fullTables(), stopOrphan: true });
+ expect(errors.map(e => e.property)).toEqual(['stopOrphan']);
+ });
+
+ it('accepts a valid body and leaves every table array intact', async () => {
+ // Load-bearing: whitelist strips undecorated properties from the object it validates, and every
+ // table key omitted from a restore is written EMPTY. If validation reached inside `tables`, a
+ // restore would silently blank the database instead of restoring it.
+ const tables = { ...fullTables(), sessions: [{ id: 's1', name: 'main' }], messages: [{ id: 'm1' }] };
+ const { instance, errors } = await run({ tables, force: false, stopOrphans: false });
+ expect(errors).toEqual([]);
+ expect(instance.tables).toEqual(tables);
+ expect(Object.keys(instance.tables as object)).toHaveLength(TABLE_IMPORTERS.length);
+ });
+
+ it.each(['force', 'stopOrphans'] as const)("maps a form-encoded 'false' on %s to a real false", async flag => {
+ // Both flags only ever OPEN the escape from the orphan-engine refusal. Under implicit conversion
+ // a plain boolean property casts 'false' to true, which would open that escape for a caller who
+ // spelled the opposite — the one direction this change must not introduce.
+ const { instance, errors } = await run({ tables: fullTables(), [flag]: 'false' });
+ expect(errors).toEqual([]);
+ expect(instance[flag]).toBe(false);
+ });
+
+ it.each(['force', 'stopOrphans'] as const)('rejects an ambiguous spelling on %s', async flag => {
+ const { errors } = await run({ tables: fullTables(), [flag]: 'yes' });
+ expect(errors.map(e => e.property)).toEqual([flag]);
+ });
+
+ it('leaves an omitted flag absent, so the default orphan refusal still applies', async () => {
+ const { instance, errors } = await run({ tables: fullTables() });
+ expect(errors).toEqual([]);
+ expect(instance.force).toBeUndefined();
+ expect(instance.stopOrphans).toBeUndefined();
+ });
+});
diff --git a/src/modules/infra/dto/import-data.dto.ts b/src/modules/infra/dto/import-data.dto.ts
new file mode 100644
index 000000000..c49d0d0e7
--- /dev/null
+++ b/src/modules/infra/dto/import-data.dto.ts
@@ -0,0 +1,61 @@
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
+import { IsBoolean, IsObject, IsOptional } from 'class-validator';
+import { ToStrictBoolean } from '../../../common/utils/strict-boolean';
+import type { MigrationTables } from '../migration-tables.types';
+import { TABLE_IMPORTERS } from '../table-importers';
+
+/**
+ * The table keys the restore actually reads, derived from the importer registry rather than restated,
+ * so a table added to TABLE_IMPORTERS cannot go missing from the published body schema.
+ */
+const TABLE_PROPERTIES: Record<string, { type: 'array' }> = Object.fromEntries(
+ TABLE_IMPORTERS.map((importer): [string, { type: 'array' }] => [importer.key, { type: 'array' }]),
+);
+
+/**
+ * Body for POST /infra/import-data, the replace-all restore. A class (not an inline object literal)
+ * so the global ValidationPipe's whitelist/forbidNonWhitelisted actually runs — the same reason
+ * ImportStorageDto is one. An inline `@Body()` type erases at runtime, so on the most destructive
+ * route in the product a body carrying no `tables` reached the handler and failed as a 500 from
+ * inside the restore, and a misspelled key was accepted in silence.
+ *
+ * `tables` is validated as an object and not descended into: without @ValidateNested the fourteen
+ * row arrays are leaf values, so whitelist cannot strip them. That is load-bearing, not incidental —
+ * every key omitted here is restored EMPTY, so a whitelist that reached inside would silently blank
+ * the database it was asked to restore.
+ *
+ * Both flags only ever OPEN an escape from the orphan-engine refusal, so they are kept strict. Under
+ * the pipe's enableImplicitConversion a plain `boolean` property casts every non-empty string —
+ * `'false'` among them — to `true` before @IsBoolean() can object, which would open that escape for
+ * a caller who spelled the opposite. @ToStrictBoolean accepts only a real boolean or an exact
+ * 'true'/'false' and leaves anything else to be refused. An absent flag stays absent, so the default
+ * path is still the visible 409 IMPORT_WOULD_ORPHAN_ENGINES.
+ */
+export class ImportDataDto {
+ @ApiProperty({
+ type: 'object',
+ description:
+ 'Every one of the 14 migration tables is emptied before the restore runs, so a key omitted here is restored EMPTY rather than left untouched. Post the whole GET /api/infra/export-data payload, not a hand-built subset.',
+ properties: TABLE_PROPERTIES,
+ })
+ @IsObject()
+ tables!: Partial<MigrationTables>;
+
+ @ApiPropertyOptional({
+ description:
+ 'Allow the replace to proceed even while engines are running for sessions the backup does not contain (they keep running until restart; see restartRequired). Prefer stopOrphans, which closes that window inside this request instead.',
+ })
+ @ToStrictBoolean()
+ @IsOptional()
+ @IsBoolean()
+ force?: boolean;
+
+ @ApiPropertyOptional({
+ description:
+ 'Stop the running engines for sessions the backup does not contain, inside this request and before the replace runs. Supersedes force for the orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so restartRequired stays false on the success path.',
+ })
+ @ToStrictBoolean()
+ @IsOptional()
+ @IsBoolean()
+ stopOrphans?: boolean;
+}
diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.ts
index 5b7cc9538..ed1f7a05a 100644
--- a/src/modules/infra/infra-data.controller.ts
+++ b/src/modules/infra/infra-data.controller.ts
@@ -1,6 +1,7 @@
import { Controller, Get, Post, Body, ConflictException, HttpCode, HttpStatus, Optional } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';
import { InfraExportDataResponseDto, InfraImportDataResponseDto } from './dto/infra-response.dto';
+import { ImportDataDto } from './dto/import-data.dto';
import { ConfigService } from '@nestjs/config';
import { DataSource, QueryRunner } from 'typeorm';
import { InjectDataSource } from '@nestjs/typeorm';
@@ -474,66 +475,16 @@ export class InfraDataController {
@HttpCode(HttpStatus.OK)
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Import data to Data DB (replaces existing data)' })
- @ApiBody({
- description: 'Exported data from export-data endpoint',
- schema: {
- type: 'object',
- properties: {
- force: {
- type: 'boolean',
- description:
- 'Allow the replace to proceed even while engines are running for sessions the backup does not contain (they keep running until restart; see restartRequired). Prefer stopOrphans, which closes that window inside this request instead.',
- },
- stopOrphans: {
- type: 'boolean',
- description:
- 'Stop the running engines for sessions the backup does not contain, inside this request and before the replace runs. Supersedes force for the orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so restartRequired stays false on the success path.',
- },
- tables: {
- type: 'object',
- description:
- 'Every one of the 14 migration tables is emptied before the restore runs, so a key omitted here is restored EMPTY rather than left untouched. Post the whole GET /api/infra/export-data payload, not a hand-built subset.',
- properties: {
- sessions: { type: 'array' },
- webhooks: { type: 'array' },
- messages: { type: 'array' },
- messageBatches: { type: 'array' },
- templates: { type: 'array' },
- baileysStoredMessages: { type: 'array' },
- lidMappings: { type: 'array' },
- pluginInstances: { type: 'array' },
- conversationMappings: { type: 'array' },
- ingressEvents: { type: 'array' },
- webhookDeliveryFailures: { type: 'array' },
- integrationDeliveryFailures: { type: 'array' },
- statusUpdates: { type: 'array' },
- automationRules: { type: 'array' },
- },
- },
- },
- },
- })
+ // `type` is explicit: an @ApiBody carrying only a description does NOT fall back to the handler's
+ // parameter type — it publishes `{"type": "string"}` for the whole body.
+ @ApiBody({ description: 'Exported data from export-data endpoint', type: ImportDataDto })
@ApiResponse({ status: 200, description: 'Data imported successfully', type: InfraImportDataResponseDto })
@ApiResponse({
status: 409,
description:
'Refused, with the reason in `code`. IMPORT_ALREADY_RUNNING: another import is running — wait for it. IMPORT_NESTED_TRANSACTION: another database transaction holds this connection, so a restore could not be made durable — retry with nothing else in flight. IMPORT_WOULD_ORPHAN_ENGINES: live engines exist for sessions the backup would remove — retry with stopOrphans=true to stop them in-request, or force=true to proceed and restart after. Only the last of these is retryable with stopOrphans; the others leave nothing to decide',
})
- async importData(
- @Body()
- data: {
- tables: Partial<MigrationTables>;
- force?: boolean;
- /**
- * Stop the running engines for sessions the backup does not contain, inside this request and
- * before the replace runs (best-effort, time-bounded per engine). Supersedes force=true for the
- * orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so
- * restartRequired stays false on the success path. Without it the pre-existing behavior holds —
- * refuse with 409, or proceed with force=true and leave the engines running until restart.
- */
- stopOrphans?: boolean;
- },
- ): Promise<{
+ async importData(@Body() data: ImportDataDto): Promise<{
imported: boolean;
counts: TableCounts;
warnings: string[];