middyjs / middy

🛵 The stylish Node.js middleware engine for AWS Lambda 🛵

Home Page:https://middy.js.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

middy/http-cors disable defaults and don't add headers

severien opened this issue · comments

Is your feature request related to a problem? Please describe.

When using @middy/http-cors there is quite an amount of flexibility, but it doesn't have the option to not add the headers. For example when adding a list of origins, if the request origin does not match it returns the header 'Access-Control-Allow-Origin':'*', thus defaulting to allow any origin. This opens up your service to anyone, which is the opposite of what we want.

Describe the solution you'd like

I think an easy way to do this might be to add an option disableDefaults: boolean, which would not fallback to defaults and also not add the Access-Control-* header that would otherwise have a default.

On the other hand, if this is considered a bug, then the middleware could not add the headers when options are provided. Given the above example of adding origins option, then don't add the header when not found. Same with the getOrigin option.

Describe alternatives you've considered

Attempting to do this with the current middleware would require me to not add the middleware in case the origin is not allowed. I would have to check the origin beforehand and only add the .use(cors( )) middleware in case the origin is valid, which adds unecessary logic to the code where at this point I might as well just create my own middleware for that.

Additional context

From the MDN docs there are should be only 3 possible values. The '*', an <origin> or null, but null is not recommended. On the other hand I could possibly return an empty string like '', but that also falls on the same security risk as null. Therefore I guess its safer just not to add the headers in case the origin is not allowed.

See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: <origin>
Access-Control-Allow-Origin: null

Thanks in advance!

Thanks for reporting. I have a change that will be released shortly. Will allow setting origin: null, causing the header to not be attached. Next major release we'll update the default to null.