fix(bridge): close two binary-size cap gaps flagged by review

Follow-up on the previous highway commit, addressing two real holes the
Copilot review caught:

* loadBinarySource HTTP path was buffering the entire response via
  `await resp.arrayBuffer()` BEFORE length-checking. A server that omits
  or understates `Content-Length` (chunked transfer, malicious upstream,
  proxy stripping headers) bypassed the cap entirely. Switch to a
  streaming reader: accumulate chunks, abort + reject as soon as the
  running total exceeds `maxBytes`. The Content-Length precheck still
  short-circuits the obvious case before we read a byte.
* video-upload `stageVideoSource` has its own local-path fast-path that
  never went through `loadBinarySource`, so the 100 MB MAX_VIDEO_SIZE
  guard ran AFTER `fs.readFileSync` had already allocated the entire
  file. A 10 GiB local-file pointer would OOM the bot before the check
  fired. Add an `fs.statSync` precheck on the local branch, and pass
  `MAX_VIDEO_SIZE` explicitly when the source falls through to
  `loadBinarySource` so the HTTP / base64 cap matches the on-disk one.

Update the DEFAULT_MAX_BINARY_SIZE comment to stop claiming video paths
are bounded by it — they're bounded by the smaller MAX_VIDEO_SIZE,
enforced inside video-upload.

Adds five regression tests:
  - chunked streamed download (no Content-Length) over cap → throws
  - Content-Length over cap → throws before reading body
  - streamed download inside cap → returns full bytes
  - local file over cap (statSync precheck) → throws
  - base64 over cap → throws
This commit is contained in:
时瑾 authored and DrSmoothl committed 2026-05-16 21:31:54 +08:00
1 parent b3df633c87
commit b40cee18cc
3 files changed
+125 -10

No files matched your search

+42 -8
View File
@@ -12,10 +12,13 @@ export interface LoadedBinary {
}
/**
* Default cap on a single binary load. Image/voice/video paths use this
* to defend against an authenticated OneBot client triggering a multi-GB
* read into memory. Group/private file uploads override this cap because
* QQ's file protocol legitimately supports up to 4 GiB.
* Default cap on a single binary load issued through this helper. Callers
* that route here (image / voice via base64+HTTP, group/private file
* uploads, avatar) get bounded reads. Not all callers route through here
* — in particular `video-upload.stageVideoSource` reads local-video files
* directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private
* file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's
* file protocol legitimately supports up to 4 GiB.
*/
const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
/** Hard ceiling QQ's file protocol supports — used by group/private files. */
@@ -87,11 +90,42 @@ export async function loadBinarySource(
if (Number.isFinite(declared) && declared > maxBytes) {
throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`);
}
const bytes = new Uint8Array(await resp.arrayBuffer());
if (bytes.length > maxBytes) {
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
}
const fileName = guessFileNameFromUrl(source);
// Stream the body incrementally so a server that omits or
// understates Content-Length can't make us buffer a chunked response
// past maxBytes — `await resp.arrayBuffer()` would happily allocate
// the entire payload before we get a chance to length-check it.
const reader = resp.body?.getReader();
if (!reader) {
const bytes = new Uint8Array(await resp.arrayBuffer());
if (bytes.length > maxBytes) {
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
}
return { bytes, fileName };
}
const chunks: Uint8Array[] = [];
let total = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!value) continue;
total += value.byteLength;
if (total > maxBytes) {
await reader.cancel().catch(() => { /* ignore */ });
throw new Error(`${resourceName} too large: > ${maxBytes}`);
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const bytes = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return { bytes, fileName };
}
@@ -280,6 +280,14 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
const local = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
// Pre-check on disk size BEFORE reading bytes into memory. The later
// `staged.bytes.length > MAX_VIDEO_SIZE` guard would otherwise only
// run after we'd already allocated the entire file (so a 10 GiB
// local path still OOMs us before the check fires).
const stat = fs.statSync(local);
if (stat.size > MAX_VIDEO_SIZE) {
throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB`);
}
return {
bytes: new Uint8Array(fs.readFileSync(local)),
filePath: local,
@@ -287,7 +295,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
};
}
const loaded = await loadBinarySource(source, 'video');
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE);
const fileName = element.fileName || loaded.fileName || '';
const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`);
fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes));
+74 -1
View File
@@ -2,7 +2,7 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import { pathToFileURL } from 'url';
import { describe, expect, it } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { loadBinarySource, resolveLocalFilePath } from '../src/bridge/highway/utils';
describe('highway source paths', () => {
@@ -26,3 +26,76 @@ describe('highway source paths', () => {
}
});
});
describe('loadBinarySource maxBytes enforcement', () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
vi.restoreAllMocks();
});
it('rejects HTTP downloads larger than maxBytes via streaming, even without Content-Length', async () => {
// Streamed chunk-encoded response: no Content-Length, totals > cap.
const chunkSize = 4 * 1024;
const totalChunks = 16;
const stream = new ReadableStream<Uint8Array>({
start(controller) {
for (let i = 0; i < totalChunks; i++) controller.enqueue(new Uint8Array(chunkSize));
controller.close();
},
});
globalThis.fetch = vi.fn(async () => new Response(stream, {
status: 200,
headers: { /* no content-length */ },
})) as typeof fetch;
// Cap below total: 16*4096 = 65536, cap 32 KiB → should throw mid-stream.
await expect(
loadBinarySource('https://example.test/big.bin', 'test', 32 * 1024),
).rejects.toThrow(/too large/);
});
it('rejects HTTP downloads when Content-Length already exceeds maxBytes', async () => {
globalThis.fetch = vi.fn(async () => new Response(new Uint8Array(0), {
status: 200,
headers: { 'content-length': String(10 * 1024 * 1024) },
})) as typeof fetch;
await expect(
loadBinarySource('https://example.test/big.bin', 'test', 1024),
).rejects.toThrow(/too large: 10485760/);
});
it('accepts a streamed download that fits inside maxBytes', async () => {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.enqueue(new Uint8Array([4, 5]));
controller.close();
},
});
globalThis.fetch = vi.fn(async () => new Response(stream, { status: 200 })) as typeof fetch;
const loaded = await loadBinarySource('https://example.test/small.bin', 'test', 1024);
expect(Array.from(loaded.bytes)).toEqual([1, 2, 3, 4, 5]);
});
it('rejects oversized local files via fs.stat before reading them', async () => {
const filePath = path.join(os.tmpdir(), `snowluma-binary-cap-${process.pid}-${Date.now()}.bin`);
fs.writeFileSync(filePath, Buffer.alloc(128));
try {
await expect(
loadBinarySource(filePath, 'test', 64),
).rejects.toThrow(/too large: 128 > 64/);
} finally {
try { fs.unlinkSync(filePath); } catch { /* ignore */ }
}
});
it('rejects oversized base64 payloads', async () => {
const big = Buffer.alloc(128).toString('base64');
await expect(
loadBinarySource(`base64://${big}`, 'test', 64),
).rejects.toThrow(/too large: 128 > 64/);
});
});