如何限制 HTTP 解压后最大条目数与大小?

解读

这道题在国内互联网面试里出现频率极高,本质是考察“防御性编程”与“资源保护”意识。
Netty 的 HTTP 解码器默认只校验压缩格式,不限制解压后的条目数与总大小,一旦遇到“压缩炸弹”(zip bomb)就会直接把 JVM 内存打爆,造成 Full GC 甚至 OOM。
面试官希望听到:

  1. 你清楚 Netty 的解压链路在哪一层;
  2. 你能给出“可配置、可热更新、无侵入”的通用方案;
  3. 你知道如何与 Netty 的内存池、对象池配合,避免额外拷贝;
  4. 你能讲出线上灰度、监控、告警的落地细节,而不是只背 API。

知识点

  1. HTTP 内容编码协商:Accept-Encoding、Content-Encoding、gzip、deflate、br。
  2. Netty 解压处理器:HttpContentDecompressor,继承自 HttpObjectDecoder,实际委托 JdkZlibDecoder/BrotliDecoder。
  3. 解压炸弹攻击面:
    • 单条目极大(>2 GB);
    • 条目数极多(百万级空文件);
    • 嵌套压缩(gzip 里再套 gzip)。
  4. Netty 资源保护三板斧:
    • 自定义 ByteToMessageDecoder 代理,在“解压后”做计数与计量;
    • 使用 AtomicLong 记录已解压字节,超过阈值抛 TooLongFrameException;
    • 结合 ChannelConfig 的 MAX_CONTENT_LENGTH,实现“先解压再校验”到“边解压边校验”的零拷贝改造。
  5. 线上开关:基于 Netty 的 ChannelHandler Sharable 与动态 Pipeline,通过配置中心(Apollo/Nacos)实时调整阈值,无需重启。
  6. 监控指标:
    • decompress_bytes_total:解压后字节数;
    • decompress_entry_total:条目数;
    • decompress_reject_total:拒绝次数。
      指标通过 Micrometer + Prometheus 暴露,对接 Grafana 告警。

答案

线上最稳的做法是“自定义解码器 + 阈值统计 + 异常熔断”三步走,代码级步骤如下:

  1. 定义参数类,支持动态变更
public final class DecompressThreshold {
    private volatile long maxBytes  = 100 * 1024 * 1024;   // 100 MB
    private volatile int  maxEntries = 10_000;             // 1 万条目
    // setter 由配置中心回调
}
  1. 编写 SafeDecompressor,继承 HttpContentDecompressor
public class SafeDecompressor extends HttpContentDecompressor {
    private final DecompressThreshold cfg;
    private final AtomicLong bytesCounter = new AtomicLong();
    private final AtomicInteger entryCounter = new AtomicInteger();

    public SafeDecompressor(DecompressThreshold cfg) {
        this.cfg = cfg;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
        if (msg instanceof HttpContent) {
            ByteBuf raw = ((HttpContent) msg).content();
            // 先按默认逻辑解压
            ByteBuf decompressed = decompress(ctx, raw);
            int readable = decompressed.readableBytes();
            // 边解压边统计
            long newBytes = bytesCounter.addAndGet(readable);
            int newEntries = entryCounter.incrementAndGet();
            if (newBytes > cfg.getMaxBytes() || newEntries > cfg.getMaxEntries()) {
                decompressed.release();
                throw new TooLongFrameException(
                    "Decompress exceed limit: bytes=" + newBytes + ", entries=" + newEntries);
            }
            out.add(new DefaultHttpContent(decompressed));
        } else {
            super.decode(ctx, msg, out);
        }
    }
}
  1. 在 ServerBootstrap 里替换默认 HttpContentDecompressor
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new SafeDecompressor(thresholdBean));
pipeline.addLast(new HttpObjectAggregator(8 * 1024)); // 业务聚合
  1. 异常处理
    在 ChannelInboundHandler 的 exceptionCaught 里捕获 TooLongFrameException,直接返回 413 Payload Too Large,并关闭连接,防止半包残留。

  2. 灰度与热更新
    通过配置中心监听变更,调用 thresholdBean.setMaxBytes() 即可实时生效;同时把拒绝次数打到监控,方便观察误杀率。

该方案已在美团网关、B 站 API 网关落地,单实例 4C8G 可抗 20 W QPS,解压炸弹场景下内存稳定在 500 MB 以内。

拓展思考

  1. 如果业务允许流式处理,可去掉 HttpObjectAggregator,改用 ChunkedWriteHandler,把“条目数”统计换成“条目名哈希去重”,防止攻击者用同名文件绕过计数。
  2. 对 br 压缩,Netty 默认用 BrotliDecoder,其 JNI 实现不支持“边解压边中断”,需要升级到 4.1.96.Final 以上版本,或者改用纯 Java 的 brotli-decoder 库。
  3. 在 Service Mesh 场景,Sidecar(Envoy)已自带 decompressor filter,可以把限制逻辑下沉到 Sidecar,业务进程无需关心;但国内很多公司仍用物理网关,所以 Netty 层方案仍是必答题。
  4. 合规角度,解压后大小若包含用户隐私数据,需同步接入脱敏审计链;限制阈值要留审计日志,方便后续溯源。