Skip to content

Commit ddc2449

Browse files
authored
Make the request body limit configurable, and bump its default value to 1mb (#1048)
1 parent 105511d commit ddc2449

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

src/functions/index.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ describe(__filename, () => {
5858
_console,
5959
apiKey = 'valid api key',
6060
apiKeyEnvVarName = 'API_KEY',
61+
maxRequestBodySize,
6162
}: Partial<
6263
FunctionConfig & { apiKey: string; allowedOrigin: string }
6364
> = {}) => {
@@ -67,6 +68,7 @@ describe(__filename, () => {
6768
_console,
6869
_process,
6970
apiKeyEnvVarName,
71+
maxRequestBodySize,
7072
});
7173

7274
return (handler: express.Handler) => ({
@@ -268,5 +270,15 @@ describe(__filename, () => {
268270

269271
expect(response.status).toEqual(200);
270272
});
273+
274+
it('returns a 413 when the request body exceeds the configured limit', async () => {
275+
const { app, sendApiKey } = _createExpressApp({ maxRequestBodySize: 1 })(
276+
okHandler,
277+
);
278+
279+
const response = await sendApiKey(request(app).post('/'));
280+
281+
expect(response.status).toEqual(413);
282+
});
271283
});
272284
});

src/functions/index.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,15 @@ export type RequestWithExtraProps = Request & {
2828
* @property _process - Process object for environment variables (for testing
2929
* purposes)
3030
* @property apiKeyEnvVarName - Environment variable name for the API key
31+
* @property maxRequestBodySize - Controls the maximum request body size. If
32+
* this is a number, then the value specifies the number of bytes; if it is a
33+
* string, the value is passed to the bytes library for parsing.
3134
*/
3235
export type FunctionConfig = {
3336
_console?: typeof console;
3437
_process?: typeof process;
3538
apiKeyEnvVarName?: string;
39+
maxRequestBodySize?: string | number;
3640
};
3741

3842
/**
@@ -62,6 +66,7 @@ export const createExpressApp =
6266
_console = console,
6367
_process = process,
6468
apiKeyEnvVarName = 'LAMBDA_API_KEY',
69+
maxRequestBodySize = '1mb',
6570
}: FunctionConfig = {}) =>
6671
(handler: RequestHandler) => {
6772
const app = express();
@@ -75,6 +80,7 @@ export const createExpressApp =
7580

7681
// This is the options we pass to the `json()` middleware.
7782
const jsonOptions = {
83+
limit: maxRequestBodySize,
7884
// This is a hack to retain the raw body on the request object. We need
7985
// this to verify the signature of the request.
8086
verify(

0 commit comments

Comments
 (0)