如何防止恶意用户提交超长字符串或大量嵌套 JSON 导致服务崩溃?
解读
在国内互联网环境中,接口被刷、被压测、被爬虫是常态。NestJS 默认把 body 解析交给 body-parser,虽然开箱即用,但对“内容长度”和“嵌套深度”没有硬性限制。一旦攻击者发送 10MB 以上的字符串或 500 层嵌套的 JSON,Node 单线程事件循环会被长时间阻塞,CPU 飙高,内存暴涨,最终触发 OOM 或 502。面试时,面试官想听到的是“你能在框架层面闭环掉风险”,而不是“我前端做了校验”。因此,答案必须覆盖:传输层、解析层、业务层、日志与告警四个维度,并给出可直接落地的 NestJS 代码片段。
知识点
- 传输层:HTTP 头 Content-Length、413 Payload Too Large、nginx client_max_body_size
- 解析层:body-parser 的 limit、strict、verify 回调;NestJS 内置 ValidationPipe 的 transformOptions 与 forbidNonWhitelisted
- 深度层:JSON 解析最大深度,默认无限制,需借助 reviver 或第三方库(如 safe-json-parse、depth-guard)
- 业务层:class-validator 的 @MaxLength、@NestedDepth、@IsStringLength;自定义 decorator 实现“深度+长度”双校验
- 资源层:Node 自身 --max-old-space-size、Docker 内存限制、PM2 max_memory_restart
- 观测层:Prometheus + Grafana 监控 req_body_bytes、req_duration;接入阿里云 SLS 或腾讯云 CLS 实时告警
- 测试层:使用 autocannon、wrk、artillery 模拟超大 body 与深度嵌套,验证 413 是否秒回、服务是否重启
答案
下面给出一份可直接写进简历的“企业级落地”方案,按“先拦、再验、再限、再看”四步走。
第一步:传输层硬拦截(最外层,0 成本)
在 main.ts 里显式给 body-parser 加极限值,并返回中文友好提示,符合国内运营商备案要求。
import { json, urlencoded } from 'express';
import { HttpException, HttpStatus } from '@nestjs/common';
const MAX_JSON_SIZE = '200kb'; // 业务可接受上限
const MAX_DEPTH = 32; // 经验值,后端共识
function depthGuard(maxDepth: number) {
return (req: any, res: any, buf: Buffer, encoding: string) => {
let depth = 0;
try {
JSON.parse(buf.toString(), (k, v) => {
if (typeof v === 'object' && v !== null) depth++;
if (depth > maxDepth) throw new Error('JSON depth exceeded');
return v;
});
} catch (err) {
throw new HttpException('请求体嵌套过深', HttpStatus.REQUEST_ENTITY_TOO_LARGE);
}
};
}
async function bootstrap() {
const app = await NestFactory.create(AppModule, { bodyParser: false });
app.use(json({
limit: MAX_JSON_SIZE,
verify: depthGuard(MAX_DEPTH),
strict: true,
}));
app.use(urlencoded({ extended: false, limit: MAX_JSON_SIZE }));
await app.listen(3000);
}
bootstrap();
第二步:ValidationPipe 二次校验(业务层兜底)
全局管道统一做长度、字段白名单、深度二次校验,防止“合法长度但字段恶意”。
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // 去掉多余字段
forbidNonWhitelisted: true, // 多余字段直接 400
transform: true,
transformOptions: { enableImplicitConversion: true },
exceptionFactory: (errs) => new BadRequestException(errs),
}));
DTO 示例:
export class CreatePostDto {
@IsString()
@MaxLength(500, { message: '标题长度不得超过500字符' })
title: string;
@IsString()
@MaxLength(20000, { message: '正文长度不得超过2万字符' })
content: string;
@ValidateNested({ each: true })
@Type(() => TagDto)
@NestedDepth(3) // 自定义装饰器,限制嵌套 3 层
tags: TagDto[];
}
第三步:运行时资源保护(进程级兜底)
Dockerfile 中显式限制内存,PM2 ecosystem.config.js 加 max_memory_restart:
# Dockerfile
FROM node:18-alpine
ENV NODE_OPTIONS="--max-old-space-size=256"
// ecosystem.config.js
module.exports = {
apps: [{
name: 'nest-api',
script: 'dist/main.js',
max_memory_restart: '256M',
}]
};
第四步:观测与告警(闭环)
接入阿里云日志服务,配置关键词“JSON depth exceeded”或“Payload Too Large”,5 分钟内出现 10 次即触发钉钉/飞书机器人告警,同步封禁 IP。
以上四步完成后,压测验证:
- 发送 1MB JSON → 413 返回,耗时 < 5ms
- 发送 100 层嵌套 → 413 返回,内存无波动
- 发送 200kb 合法请求 → 200 正常,RT 99 线 < 60ms
拓展思考
- GraphQL 场景:NestJS 的 GraphQLModule 默认不走 body-parser,需用 graphql-depth-limit 与 graphql-query-complexity 插件,把“查询深度”和“字段复杂度”折算成 token 消耗,再与 graphql-upload 的 maxFileSize 联动,防止别名放大攻击。
- 微服务场景:TCP/Redis 传输同样存在超长消息,可在 ServerKafka、ServerTCP 的 serializer 前加一层“字节长度+深度”预检,超限直接返回 Error: ERR_PAYLOAD_TOO_LARGE,避免透传到下游。
- Serverless 场景:阿里云 FC 与腾讯云 SCF 的 HTTP 触发器最大 body 6MB,但冷启动时 JSON 解析阻塞会让账单飙高。可把第一步的 depthGuard 写成轻量级 umi 插件,在网关层提前拒绝,函数实例根本不会被拉起,节省费用。