FastifyAdapter绕过全局ValidationPipe致生产构建400白名单验证错误
FastifyAdapter绕过全局ValidationPipe致生产构建400白名单验证错误
问题描述
在生产构建环境(本地及生产服务器)中使用FastifyAdapter时,已正确注册的全局ValidationPipe未在请求中生效。尽管能看到注册日志,但多余的查询参数既未被移除也未被拒绝,且针对tz参数出现400 whitelistValidation错误。
复现步骤
- 使用FastifyAdapter搭建Nest项目
// main.ts import 'reflect-metadata'; import { NestFactory } from '@nestjs/core'; import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'; import { ValidationPipe, Logger } from '@nestjs/common'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create<NestFastifyApplication>( AppModule, new FastifyAdapter({ logger: true }), ); const logger = new Logger('Bootstrap'); logger.log('FastifyAdapter registered'); app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true, transformOptions: { enableImplicitConversion: true }, })); logger.log('ValidationPipe registered'); await app.listen(3000, '0.0.0.0'); logger.log('App is running'); } bootstrap();
- 定义简单DTO和控制器
// dto/simple.dto.ts import { IsOptional, IsString } from 'class-validator'; export class SimpleDto { @IsOptional() @IsString() tz?: string; } // controllers/simple.controller.ts import { Controller, Get, Query } from '@nestjs/common'; import { SimpleDto } from '../dto/simple.dto'; @Controller('simple') export class SimpleController { @Get() test(@Query() dto: SimpleDto) { return dto; } }
- 本地构建并运行生产模式
npm run build # uses tsconfig.build.json NODE_ENV=production node dist/main.js
- 发送带多余查询参数的请求
curl -i 'http://localhost:3000/simple?tz=Europe/Istanbul&foo=bar'
- 观察行为
- 预期结果: 因
foo不在白名单内,请求被拒绝并返回400 Bad Request。 - 实际结果: 请求成功返回200 OK,
tz和foo均被原样返回;或仅tz因whitelistValidation错误被拒绝。
环境信息
- NestJS: 10.x
- @nestjs/platform-fastify: 10.x
- class-validator: 0.14.x
- class-transformer: 0.5.x
- Node.js: 20.x
- tsconfig.build.json:
{ "extends": "./tsconfig.json", "compilerOptions": { "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "ES2021", "module": "CommonJS" }, "exclude": ["node_modules", "test", "dist"] }
错误信息
HTTP/1.1 400 Bad Request Content-Type: application/json; charset=utf-8 { "message": [ { "property": "tz", "constraints": { "whitelistValidation": "property tz should not exist" } } ], "error": "Bad Request", "statusCode": 400 }
补充说明
- 开发模式(
NODE_ENV=development)及本地生产构建下运行正常。 - 可看到FastifyAdapter registered和ValidationPipe registered日志。
- 全局设置
whitelist: false和forbidNonWhitelisted: false无法解决问题。 - 在DTO属性上使用
@Allow()也无效。 - 切换为Express适配器后,验证行为符合预期。
- 仅在Fastify生产构建环境下出现该问题。
内容的提问来源于stack exchange,提问作者user30901179
相关产品推荐
相关产品推荐

