From f2ff9eb3fccec7d86aa3003e6039b27e86be6eea Mon Sep 17 00:00:00 2001 From: margrop <1731827+margrop@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:22:16 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=98=B2=E6=8A=A4=E5=A4=87=E4=BB=BD?= =?UTF-8?q?=E5=AF=BC=E5=85=A5=E8=A7=A3=E5=8E=8B=E7=82=B8=E5=BC=B9=E4=B8=8E?= =?UTF-8?q?=E7=95=B8=E5=BD=A2=E6=96=87=E4=BB=B6=E5=B9=B6=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=20400?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - gunzipSync 传入 maxOutputLength,解压阶段即拒绝超出体积上限的压缩炸弹 - 无 Content-Length 的 chunked 请求按实际原始体积校验 - 损坏 gzip 与非法 JSON 返回 400,避免落入 500 与错误监控 - 补充集成测试覆盖解压炸弹、原始超限、损坏 gzip 与非法 JSON Refs: https://github.com/margrop/wrong-notebook/issues/165 --- src/__tests__/integration/data-backup.test.ts | 41 ++++++++++++++++++- src/app/api/import/route.ts | 27 +++++++++++- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/src/__tests__/integration/data-backup.test.ts b/src/__tests__/integration/data-backup.test.ts index 73a224fb..9d45409a 100644 --- a/src/__tests__/integration/data-backup.test.ts +++ b/src/__tests__/integration/data-backup.test.ts @@ -1,7 +1,7 @@ // @vitest-environment node import { execFileSync } from 'node:child_process'; import { mkdtempSync, rmSync } from 'node:fs'; -import { gunzipSync } from 'node:zlib'; +import { gunzipSync, gzipSync } from 'node:zlib'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { PrismaClient } from '@prisma/client'; @@ -1268,3 +1268,42 @@ describe('跨账号合并导入', () => { expect(await database.errorItem.count({ where: { userId: 'user-1' } })).toBe(0); }); }); + +describe('备份导入体积与格式防护', () => { + const importRaw = (body: Uint8Array, contentType = 'application/json') => + IMPORT(new Request('http://localhost/api/import', { + method: 'POST', + body, + headers: { 'Content-Type': contentType }, + })); + + it('gzip 解压结果超限时在解压阶段返回 400,不等到长度校验', async () => { + // 高压缩比的 gzip 炸弹:压缩后很小,解压后超过上限 + const bomb = gzipSync(Buffer.alloc(MAX_BACKUP_IMPORT_BYTES + 1024)); + const response = await importRaw(bomb, 'application/gzip'); + + expect(response.status).toBe(400); + expect((await response.json()).message).toContain('after decompression'); + }, 30_000); + + it('没有 Content-Length 的 chunked 原始请求体超限时返回 400', async () => { + const response = await importRaw(Buffer.alloc(MAX_BACKUP_IMPORT_BYTES + 1)); + + expect(response.status).toBe(400); + expect((await response.json()).message).toContain('Request body too large'); + }, 30_000); + + it('损坏的 gzip 返回 400 而非 500', async () => { + const response = await importRaw(Buffer.from([0x1f, 0x8b, 0x00, 0x00, 0x00]), 'application/gzip'); + + expect(response.status).toBe(400); + expect((await response.json()).message).toContain('Invalid gzip'); + }); + + it('非法 JSON 返回 400 而非 500', async () => { + const response = await importRaw(Buffer.from('{"user":')); + + expect(response.status).toBe(400); + expect((await response.json()).message).toContain('Invalid JSON'); + }); +}); diff --git a/src/app/api/import/route.ts b/src/app/api/import/route.ts index f5b9f4da..0f1731ab 100644 --- a/src/app/api/import/route.ts +++ b/src/app/api/import/route.ts @@ -35,12 +35,35 @@ export const POST = withUser(async (req: Request, { user, session }: Authenticat } const raw = Buffer.from(await req.arrayBuffer()); + // chunked 请求没有 Content-Length,按实际收到的原始体积再校验一次 + if (raw.length > MAX_BACKUP_IMPORT_BYTES) { + return badRequest(`Request body too large (max ${MAX_BACKUP_IMPORT_BYTES / (1024 * 1024)}MB)`); + } const gzipped = raw.length > 1 && raw[0] === 0x1f && raw[1] === 0x8b; - const decompressed = gzipped ? gunzipSync(raw) : raw; + let decompressed: Buffer; + if (gzipped) { + try { + // 解压时就限制输出,避免高压缩比的小文件在长度校验前撑爆内存 + decompressed = gunzipSync(raw, { maxOutputLength: MAX_BACKUP_IMPORT_BYTES }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ERR_BUFFER_TOO_LARGE') { + return badRequest(`Import file too large after decompression (max ${MAX_BACKUP_IMPORT_BYTES / (1024 * 1024)}MB)`); + } + logger.warn({ error, userId: user.id }, 'Invalid gzip backup'); + return badRequest("Invalid gzip backup file"); + } + } else { + decompressed = raw; + } if (decompressed.length > MAX_BACKUP_IMPORT_BYTES) { return badRequest(`Import file too large after decompression (max ${MAX_BACKUP_IMPORT_BYTES / (1024 * 1024)}MB)`); } - const rawBody: unknown = JSON.parse(decompressed.toString('utf8')); + let rawBody: unknown; + try { + rawBody = JSON.parse(decompressed.toString('utf8')); + } catch { + return badRequest("Invalid JSON in backup file"); + } const parsed = parseBackupFile(rawBody); if (!parsed.success) { return badRequest("Invalid import data format");