yarbsemaj / sveltekit-adapter-lambda

An adapter to build a SvelteKit app into a lambda ready for deployment with lambda proxy via the Serverless Framework or CDK.
https://www.npmjs.com/package/@yarbsemaj/adapter-lambda
MIT License
77 stars 16 forks source link

Origin Access Identity Support #22

Open nlicitra opened 1 year ago

nlicitra commented 1 year ago

This PR is not necessarily intended to be merged in but I wanted to highlight a use case that this fork addresses and see if it's worth discussing further.

In it's current state, the S3 static asset bucket is created with public read permissions, making it possible for anybody to fetch the content directly from S3, bypassing the CloudFront distribution. This is fine for most uses cases but sometimes we might want to lock a bucket down so that it is not public and the content can only be accessed via CloudFront, either with Origin Access Control (OAC), or the now legacy Origin Access Identity (OAI).

According to the AWS Docs for the authMethod property of the Lambda@Edge event structure, OAC is not supported, so we are forced to use OAI by setting the origin.authMethod of the request object to "origin-access-identity". Unfortunately, one of the caveats of this means that we cannot switch from a lambda origin to an S3 origin and maintain OAI authentication.

As it currently works, the default origin behavior of the CF distribution is to default the origin to be the Svelte app server lambda and switch to the static asset S3 origin when necessary, so switching to the S3 origin with OAI access permissions will result in every static asset returning a 403. However, I have found that inverting this logic, and making the S3 bucket the default origin will work with OAI.

In order to get my use case working, I had to do the following:

This method allows OAI authentication to work at the expense of making the logic in the origin request lambda handler a little bit less intuitive.

With all that being said, the app that I am using this for is a prototype so I am more than happy to continue to use this forked version that serves my use case but I wanted to bring it to your attention in case you felt like this was valuable to know.