Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(validation): refuse a NUL in a request body or MCP tool input

Yudhi Armyndharisa44eb49cefc4
diff --git a/src/common/validation/no-nul-character.ts b/src/common/validation/no-nul-character.ts
index 00a689346..a3fa28ec7 100644
--- a/src/common/validation/no-nul-character.ts
+++ b/src/common/validation/no-nul-character.ts
@@ -3,3 +3,9 @@ import { NotContains } from 'class-validator';
/** PostgreSQL text and varchar columns cannot store U+0000, so the write would fail as a 500. */
export const NoNulCharacter = (): PropertyDecorator =>
NotContains('\u0000', { message: '$property must not contain a NUL character' });
+
+/** Whether a string anywhere in a parsed request value holds U+0000, which PostgreSQL rejects as a parameter. */
+export const containsNul = (value: unknown): boolean =>
+ typeof value === 'string'
+ ? value.includes('\u0000')
+ : typeof value === 'object' && value !== null && Object.values(value).some(containsNul);
diff --git a/src/config/app-validation.spec.ts b/src/config/app-validation.spec.ts
new file mode 100644
index 000000000..ba9b0cc9c
--- /dev/null
+++ b/src/config/app-validation.spec.ts
@@ -0,0 +1,27 @@
+import { BadRequestException } from '@nestjs/common';
+import { NulBodyPipe } from './app-validation';
+import { ImportDataDto } from '../modules/infra/dto/import-data.dto';
+import { SendBulkMessageDto } from '../modules/message/dto/bulk-message.dto';
+
+// PostgreSQL rejects U+0000 in every text and varchar value and bound parameter, so a body string
+// holding one failed the lookup or write behind the route as a 500.
+describe('NulBodyPipe', () => {
+ const pipe = new NulBodyPipe();
+
+ it('refuses a body holding a NUL character at any depth', () => {
+ const body = { messages: [{ chatId: '[email protected]', variables: { name: 'x\u0000' } }] };
+ expect(() => pipe.transform(body, { type: 'body', metatype: SendBulkMessageDto })).toThrow(BadRequestException);
+ });
+
+ it('passes a body without one, and leaves the path and query to the URL refusal', () => {
+ const body = { messages: [{ chatId: '[email protected]', variables: { name: 'x' } }] };
+ expect(pipe.transform(body, { type: 'body', metatype: SendBulkMessageDto })).toBe(body);
+ expect(pipe.transform('x\u0000', { type: 'param', metatype: String, data: 'id' })).toBe('x\u0000');
+ });
+
+ // The restore writes backup rows verbatim, and a SQLite backup may hold a NUL in a stored message.
+ it('lets a restore body through', () => {
+ const backup = { tables: { messages: [{ body: 'a\u0000b' }] } };
+ expect(pipe.transform(backup, { type: 'body', metatype: ImportDataDto })).toBe(backup);
+ });
+});
diff --git a/src/config/app-validation.ts b/src/config/app-validation.ts
index bd5b48a68..c9c3cef43 100644
--- a/src/config/app-validation.ts
+++ b/src/config/app-validation.ts
@@ -1,5 +1,14 @@
-import { INestApplication, ValidationPipe, ValidationPipeOptions } from '@nestjs/common';
+import {
+ ArgumentMetadata,
+ BadRequestException,
+ INestApplication,
+ PipeTransform,
+ ValidationPipe,
+ ValidationPipeOptions,
+} from '@nestjs/common';
import { isValidationErrorDetailEnabled } from './bootstrap-security';
+import { containsNul } from '../common/validation/no-nul-character';
+import { ImportDataDto } from '../modules/infra/dto/import-data.dto';
/**
* The DTO validation contract itself, without the one option that depends on the environment.
@@ -20,6 +29,20 @@ export const GLOBAL_VALIDATION_OPTIONS: ValidationPipeOptions = {
transformOptions: { enableImplicitConversion: true },
};
+/**
+ * Refuses a request body holding U+0000 anywhere. PostgreSQL rejects it in every text and varchar value
+ * and bound parameter, so it failed the lookup or write behind the route as a 500 while SQLite took it.
+ * The restore is exempt: it writes backup rows verbatim, and a SQLite backup may hold one in a message.
+ */
+export class NulBodyPipe implements PipeTransform {
+ transform(value: unknown, { type, metatype }: ArgumentMetadata): unknown {
+ if (type === 'body' && metatype !== ImportDataDto && containsNul(value)) {
+ throw new BadRequestException('Request body must not contain a NUL character');
+ }
+ return value;
+ }
+}
+
/** Apply the HTTP prefix and DTO validation contract shared by production and e2e applications. */
export function applyGlobalValidation(app: INestApplication): void {
app.setGlobalPrefix('api');
@@ -28,5 +51,6 @@ export function applyGlobalValidation(app: INestApplication): void {
...GLOBAL_VALIDATION_OPTIONS,
disableErrorMessages: !isValidationErrorDetailEnabled(process.env.VALIDATION_ERROR_DETAIL, process.env.NODE_ENV),
}),
+ new NulBodyPipe(),
);
}
diff --git a/src/core/agent-tools/tool-invoker.spec.ts b/src/core/agent-tools/tool-invoker.spec.ts
index fbdd8ec27..3449331f5 100644
--- a/src/core/agent-tools/tool-invoker.spec.ts
+++ b/src/core/agent-tools/tool-invoker.spec.ts
@@ -47,6 +47,21 @@ describe('invokeTool', () => {
);
});
+ // PostgreSQL rejects U+0000 in every text parameter, so an argument holding one failed the tool's
+ // query or write as an internal error.
+ it('refuses a NUL character anywhere in the input before the handler runs', async () => {
+ const handler = jest.fn();
+ const tool: ToolDescriptor = {
+ ...readTool,
+ inputSchema: z.object({ chatId: z.string(), vars: z.record(z.string(), z.string()) }),
+ handler,
+ };
+ await expect(
+ invokeTool(tool, { chatId: '[email protected]', vars: { name: 'x\u0000' } }, 'rawkey', auth() as unknown as AuthService),
+ ).rejects.toBeInstanceOf(BadRequestException);
+ expect(handler).not.toHaveBeenCalled();
+ });
+
it('passes sessionId from input to validateApiKey when sessionScoped', async () => {
const a = auth();
const scoped: ToolDescriptor = {
diff --git a/src/core/agent-tools/tool-invoker.ts b/src/core/agent-tools/tool-invoker.ts
index ec2df94a9..44de96623 100644
--- a/src/core/agent-tools/tool-invoker.ts
+++ b/src/core/agent-tools/tool-invoker.ts
@@ -1,5 +1,6 @@
import { BadRequestException, ForbiddenException, UnauthorizedException } from '@nestjs/common';
import { ZodError } from 'zod';
+import { containsNul } from '../../common/validation/no-nul-character';
import type { AuthService } from '../../modules/auth/auth.service';
import type { AnyToolDescriptor } from './tool-descriptor';
@@ -78,6 +79,8 @@ export async function invokeTool(
}
throw e;
}
+ // PostgreSQL rejects U+0000 in every text parameter; REST refuses the same input in NulBodyPipe.
+ if (containsNul(input)) throw new BadRequestException('Tool input must not contain a NUL character');
// The single cast the erasure needs, placed next to the parse that justifies it: `input` is
// whatever this tool's own `inputSchema` just accepted, which is exactly what its handler declares.
return tool.handler(input as never, apiKey);
diff --git a/test/configure-app.e2e-spec.ts b/test/configure-app.e2e-spec.ts
index 5730ae3ab..e7076f2dd 100644
--- a/test/configure-app.e2e-spec.ts
+++ b/test/configure-app.e2e-spec.ts
@@ -276,6 +276,15 @@ describe('production HTTP surface (configureApp)', () => {
await request(app.getHttpServer()).get('/api/sessions/abc%2500').expect(200);
});
+ it('refuses a body holding a NUL character at any depth', async () => {
+ const res = await request(app.getHttpServer())
+ .post('/api/echo')
+ .set('Content-Type', 'application/json')
+ .send({ items: [{ variables: { name: 'a\u0000b' } }] });
+ expect(res.status).toBe(400);
+ expect(res.body).toMatchObject({ statusCode: 400, error: 'Bad Request' });
+ });
+
it('answers a compressed body with 415 rather than charging the budget its inflated size', async () => {
const res = await request(app.getHttpServer())
.post('/api/echo')