lambda-middleware icon indicating copy to clipboard operation
lambda-middleware copied to clipboard

CORS middleware fails with an internal error when called with an ill-formatted event

Open dbartholomae opened this issue 8 months ago • 0 comments

Describe the bug

The cors middleware just assumes that it gets an APIGatewayEvent, but in practice middleware is often used without first ensuring a certain input. E.g. a lambda might be tested via the AWS Console with any kind of payload.

To Reproduce

Create a lambda with this middleware and with an allowedOrigin. Then call the lambda with an empty event. It will throw an error "Cannot read properties of null (reading 'Origin')".

Expected behavior

There should be a meaningful error, not "Cannot read properties of null"

Additional context

In the packages/cors middleware, in cors.ts, we assume that the handler gets an APIGatewayEvent as event. Go through all the code called by cors and simplify the expected type so it only contains the parts that are actually required for the code to work and put them into an interface called "CORSableEvent". Then, add a test where the cors function gets an empty object instead and http://localhost:3000 as allowedOrigin. This test will most likely fail with a "Cannot read properties of null" error. Instead, it should fail with a TypeError "Received an event that was not an APIGateway event". Then implement this by writing a typeguard for CORSableEvent and utilising the typeguard in the line before creating runHandler

dbartholomae avatar Apr 29 '25 09:04 dbartholomae