Skip to content

Commit 9ccd301

Browse files
committed
fix(assertBodySize): disallow both content-length and transfer-encoding headers
1 parent 67716ee commit 9ccd301

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

src/utils/body.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,9 +140,14 @@ async function isBodySizeWithin(
140140
return true;
141141
}
142142

143-
const bodyLen = req.headers.get("content-length");
144-
if (bodyLen !== null && !req.headers.has("transfer-encoding")) {
145-
return +bodyLen <= limit;
143+
const contentLength = req.headers.get("content-length");
144+
if (contentLength) {
145+
const transferEncoding = req.headers.get("transfer-encoding");
146+
if (transferEncoding) {
147+
// https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2
148+
throw new HTTPError({ status: 400 });
149+
}
150+
return +contentLength <= limit;
146151
}
147152

148153
const reader = req.clone().body!.getReader();

test/unit/body-limit.test.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,15 +66,21 @@ describe("body limit (unit)", () => {
6666
const eventMock = mockEvent("/", {
6767
method: "POST",
6868
body: streamBytesFrom(BODY_PARTS),
69-
headers: {
70-
// Should ignore content-length
71-
"content-length": "7",
72-
"transfer-encoding": "chunked",
73-
},
69+
headers: { "transfer-encoding": "chunked" },
7470
});
7571

7672
await expect(assertBodySize(eventMock, 100)).resolves.toBeUndefined();
7773
await expect(assertBodySize(eventMock, 10)).rejects.toThrow(HTTPError);
7874
});
75+
76+
it("both content length and transfer encoding", async () => {
77+
const eventMock = mockEvent("/", {
78+
method: "POST",
79+
body: "test",
80+
headers: { "transfer-encoding": "chunked", "content-length": "4" },
81+
});
82+
await expect(assertBodySize(eventMock, 10)).rejects.toThrow(HTTPError);
83+
await expect(assertBodySize(eventMock, 100)).rejects.toThrow(HTTPError);
84+
});
7985
});
8086
});

0 commit comments

Comments
 (0)