Return clean 413 on oversize instead of aborting connection
This commit is contained in:
+14
-11
@@ -43,30 +43,33 @@ function sendJson(res, status, obj) {
|
||||
}
|
||||
|
||||
// Read the whole request body, enforcing MAX_BYTES.
|
||||
// On overflow we stop buffering and drain the rest of the stream so we can
|
||||
// still send a clean 413 JSON response (destroying the socket => 502 at proxy).
|
||||
function readBody(req, limit) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
let total = 0;
|
||||
let aborted = false;
|
||||
let over = false;
|
||||
req.on('data', (chunk) => {
|
||||
if (aborted) return;
|
||||
total += chunk.length;
|
||||
if (over) return;
|
||||
if (total > limit) {
|
||||
aborted = true;
|
||||
const err = new Error('too large');
|
||||
err.statusCode = 413;
|
||||
req.destroy();
|
||||
reject(err);
|
||||
over = true;
|
||||
chunks.length = 0;
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
req.on('end', () => {
|
||||
if (!aborted) resolve(Buffer.concat(chunks));
|
||||
});
|
||||
req.on('error', (err) => {
|
||||
if (!aborted) reject(err);
|
||||
if (over) {
|
||||
const err = new Error('too large');
|
||||
err.statusCode = 413;
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve(Buffer.concat(chunks));
|
||||
});
|
||||
req.on('error', (err) => reject(err));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user