From 21c492b52444c5c95db2913d7429e281384a469f Mon Sep 17 00:00:00 2001 From: Justin Wind Date: Sat, 12 Mar 2022 13:08:55 -0800 Subject: [PATCH] support maximum request body size --- lib/dingus.js | 13 +++++++++++-- lib/enum.js | 4 ++++ test/lib/dingus.js | 11 +++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/dingus.js b/lib/dingus.js index 84c1d14..11bdf99 100644 --- a/lib/dingus.js +++ b/lib/dingus.js @@ -337,12 +337,21 @@ class Dingus { /** * Return all body data from a request. * @param {http.ClientRequest} req + * @param {Number=} maximumBodySize */ - async bodyData(req) { + async bodyData(req, maximumBodySize) { const _scope = _fileScope('bodyData'); return new Promise((resolve, reject) => { const body = []; - req.on('data', (chunk) => body.push(chunk)); + let length = 0; + req.on('data', (chunk) => { + body.push(chunk); + length += Buffer.byteLength(chunk); + if (maximumBodySize && length > maximumBodySize) { + this.logger.debug(_scope, 'body data exceeded limit', { length, maximumBodySize }); + reject(new ResponseError(Enum.ErrorResponse.RequestEntityTooLarge)); + } + }); req.on('end', () => resolve(Buffer.concat(body).toString())); req.on('error', (e) => { this.logger.error(_scope, 'failed', { error: e }); diff --git a/lib/enum.js b/lib/enum.js index ef8e773..e24ed6f 100644 --- a/lib/enum.js +++ b/lib/enum.js @@ -56,6 +56,10 @@ const ErrorResponse = { statusCode: 410, errorMessage: 'Gone', }, + RequestEntityTooLarge: { + statusCode: 413, + errorMessage: 'Request Entity Too Large', + }, UnsupportedMediaType: { statusCode: 415, errorMessage: 'Unsupported Media Type', diff --git a/test/lib/dingus.js b/test/lib/dingus.js index 519feb0..23b7e8c 100644 --- a/test/lib/dingus.js +++ b/test/lib/dingus.js @@ -514,6 +514,17 @@ describe('Dingus', function () { assert.strictEqual(e, 'foo'); } }); + it('limits size', async function () { + const p = dingus.bodyData(res, 8); + resEvents['data'](Buffer.from('foobar')); + resEvents['data'](Buffer.from('bazquux')); + try { + await p; + assert.fail(noExpectedException); + } catch (e) { + assert.strictEqual(e.statusCode, 413); + } + }); }); // bodyData describe('ingestBody', function () { -- 2.43.2