Skip to content

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

@dbartholomae

Description

@dbartholomae

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions