如何在接收 JSON 数据前进行深度校验和限制嵌套层级?

解读

国内一线/二线互联网公司的后端面试里,这道题不是“会不会用 class-validator”那么简单,而是考察候选人能否在 NestJS 体系内把“请求级防御”做成企业级方案。

  1. 必须前置:在 JSON 被反序列化成 JS 对象之前就完成校验,否则大体积嵌套会瞬间打爆 V8 堆栈。
  2. 必须深度:既要校验字段类型,也要校验嵌套深度,还要防止原型污染、循环引用、超大数组等“边缘攻击”。
  3. 必须可维护:校验规则要随 DTO 走,不能散落在中间件;还要支持多语言错误码、灰度开关、性能埋点。
  4. 必须可测试:单元测试里能直接 new 一个 DTO 就触发校验,无需启 HTTP Server。
    面试官常追问:
  • 如果客户端传了 50 MB、深度 200 层的 JSON,你的服务会怎样?
  • 如果业务字段规则变了,你怎样零重启生效?
  • 如果跑在 Serverless 上,冷启动要 100 ms 内完成校验,怎么优化?
    回答时要把方案拆成“拦截层、校验层、策略层、监控层”四层,每层给出代码级落地路径。

知识点

  1. NestJS 请求生命周期:Middleware → Guard → Interceptor → Pipe → Controller。
  2. ValidationPipe:基于 class-validator + class-transformer,支持 skipMissingProperties、whitelist、transform、exceptionFactory。
  3. 自定义 decorator:@MaxDepth(n) 结合 @ValidateNested() 可递归检查层级。
  4. JSON 解析前置:在 Express 层通过 raw-body 拿到 buffer,用流式 JSON Schema(ajv、hyperjump/json-schema)预校验深度与大小。
  5. 内存保护:stream-json、clarinet 等 SAX 风格解析器,深度 > 阈值直接抛 413。
  6. 动态规则:结合 joi 或 ajv 的 “standalone code” 功能,把模式编译成独立 JS 文件,通过配置中心热更新。
  7. 性能优化:
    • 使用 ajv 的 compiled schema 缓存,单进程 100 K QPS 下校验耗时 < 0.1 ms。
    • 在 Serverless 场景把 schema 编译阶段提前到构建时,冷启动只执行 require。
  8. 安全:禁用 proto、constructor、prototype 路径;对数组长度、字符串长度做硬限制。
  9. 监控:通过 ValidationPipe 的 exceptionFactory 把错误码、耗时、字段路径打到 Prometheus + Grafana,方便告警。
  10. 单元测试:使用 nestjs-testing 模块,直接 app.get(ValidationPipe).transform() 触发校验,无需走 supertest。

答案

下面给出可直接落地的“四层防御”代码骨架,兼顾深度校验、层级限制、性能与安全。

  1. 全局启用前置拦截层(main.ts)
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import * as rawBody from 'raw-body';
import * as zlib from 'zlib';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { bodyParser: false });
  // 1. 原生层先挡大体积与深度
  app.use('/api', (req, res, next) => {
    const contentLength = req.headers['content-length'];
    if (+contentLength > 2 * 1024 * 1024) {   // 2 MB
      return res.status(413).json({ code: 413, msg: 'payload too large' });
    }
    const stream = req.headers['content-encoding'] === 'gzip'
      ? req.pipe(zlib.createGunzip())
      : req;
    rawBody(stream, { limit: '2mb', encoding: 'utf8' }, (err, body) => {
      if (err) return res.status(413).json({ code: 413, msg: 'payload too large' });
      let depth = 0;
      try {
        // 轻量级深度检查,无需完整解析
        depth = maxDepthJSON(body);
        if (depth > 20) return res.status(400).json({ code: 400, msg: 'max depth 20 exceeded' });
        req.body = JSON.parse(body);   // 这里才 parse
      } catch {
        return res.status(400).json({ code: 400, msg: 'invalid json' });
      }
      next();
    });
  });
  // 2. 业务级校验
  app.useGlobalPipes(new ValidationPipe({
    whitelist: true,
    forbidNonWhitelisted: true,
    transform: true,
    transformOptions: { enableImplicitConversion: true },
    exceptionFactory: (errors) => {
      // 统一错误码与日志
      return new BadRequestException({
        code: 4001001,
        msg: '参数校验失败',
        fields: errors.map(e => e.property),
      });
    },
  }));
  await app.listen(3000);
}
bootstrap();

function maxDepthJSON(str: string): number {
  let depth = 0, max = 0;
  for (const ch of str) {
    if (ch === '{' || ch === '[') { depth++; max = Math.max(max, depth); }
    if (ch === '}' || ch === ']') depth--;
  }
  return max;
}
  1. DTO 层定义深度规则(create-order.dto.ts)
import { IsString, ValidateNested, IsInt, Min, Max } from 'class-validator';
import { Type } from 'class-transformer';
import { MaxDepth } from '../decorators/max-depth.decorator';

class ItemDto {
  @IsString() sku: string;
  @IsInt() @Min(1) @Max(999) qty: number;
}

export class CreateOrderDto {
  @IsString() userId: string;

  @ValidateNested({ each: true })
  @Type(() => ItemDto)
  @MaxDepth(3)   // 自定义装饰器,保证 items 下嵌套不超过 3 层
  items: ItemDto[];
}
  1. 自定义 MaxDepth 装饰器(max-depth.decorator.ts)
import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';

export function MaxDepth(max: number, validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      name: 'MaxDepth',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [max],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
          const [maxDepth] = args.constraints;
          function calcDepth(obj: any, depth = 0): number {
            if (depth > maxDepth) return Infinity;
            if (Array.isArray(obj)) {
              return obj.reduce((acc, item) => Math.max(acc, calcDepth(item, depth + 1)), depth);
            }
            if (typeof obj === 'object' && obj !== null) {
              return Object.values(obj).reduce((acc, v) => Math.max(acc, calcDepth(v, depth + 1)), depth);
            }
            return depth;
          }
          return calcDepth(value) <= maxDepth;
        },
        defaultMessage(args) {
          return `${args.property} nested depth exceeds ${args.constraints[0]}`;
        },
      },
    });
  };
}
  1. 动态规则热更新(可选,ajv 方案)
import Ajv from 'ajv';
import { readFileSync } from 'fs';

const ajv = new Ajv({ allErrors: true, removeAdditional: true });
let validate = ajv.compile(JSON.parse(readFileSync('./schemas/order.json', 'utf8')));

export function reloadSchema() {
  validate = ajv.compile(JSON.parse(readFileSync('./schemas/order.json', 'utf8')));
}

export function validateOrder(data: any) {
  const valid = validate(data);
  if (!valid) throw new BadRequestException(validate.errors);
}

配置中心监听 order.json 变动后调用 reloadSchema(),进程内无中断。

  1. 单元测试(order.dto.spec.ts)
it('should reject depth > 3', async () => {
  const pipe = new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true });
  const dto = plainToInstance(CreateOrderDto, {
    userId: 'u1',
    items: [{ sku: 's1', qty: 1, extra: { a: { b: { c: { d: 1 } } } } }],
  });
  try {
    await pipe.transform(dto, { metatype: CreateOrderDto, type: 'body' });
    fail('should throw');
  } catch (e) {
    expect(e.response.fields).toContain('items');
  }
});

通过以上四层,面试官可以看到你:

  • 在 JSON 解析前就挡掉了大体积与超深嵌套;
  • 用装饰器把规则下沉到 DTO,零侵入业务;
  • 支持热更新与单元测试;
  • 对内存、CPU、安全、监控都有兜底。

拓展思考

  1. 如果接口同时支持 GraphQL 与 RESTful,怎样复用同一套深度/大小规则?
    可把校验逻辑抽成纯函数,REST 用 ValidationPipe,GraphQL 用 Custom Scalar + directive,两者共享同一份 ajv schema。

  2. 在边缘节点(如 Cloudflare Worker)做轻量级校验,核心节点做严格校验,如何保持规则一致性?
    把 schema 编译成 JSON Schema 2020-12 格式,通过 CDN 分发;边缘节点用 ajv-lite,核心节点用完整 ajv;版本号带在 URL,回滚秒级。

  3. 如果业务需要“动态字段白名单”,即不同租户可配置自己的字段集合,怎样与 class-validator 共存?
    在 ValidationPipe 之前加一层租户拦截器,根据租户 ID 拉取白名单,生成临时的 ajv schema,再调用 validate,原 DTO 只当 TypeScript 类型用,不做白名单校验。

  4. 深度限制与 MongoDB 的嵌套文档 $lookup 性能如何联动?
    把最大深度写进 MongoDB Schema Validation,服务端与数据库双向兜底;同时把深度值作为分片键的一部分,防止深度过大造成 chunk 迁移热点。