aws-samples / amazon-cloudfront-functions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Functions are not executed when CloudFront returns an error from S3

monken opened this issue · comments

If CloudFront serves files from S3, the CloudFront function is not executed if the file doesn't exist on S3 (404). This is especially harmful in the provided example where security headers such as CSP are set. It basically eliminates all protections provided by the security headers. Any XSS vulnerability that exists on the page can easily be exploited by sending the user to a page that doesn't exist and therefore doesn't include any of the security headers.

This is a very common setup for hosting single page applications on S3 in combination with CloudFront and I assume that most developers are unaware of this behavior. There should be a huge disclaimer on this specific example that the CSP headers are only added to requests to files that exist on the S3 bucket. Any error response (even if it was rewritten to return a 200 status code) will not invoke the function and therefore not include any custom headers.

This is expected behavior. It is documented now
https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/edge-functions-restrictions.html#edge-function-restrictions-all

As a workaround you can configure redirect rules for error pages on S3 static website endpoint side [1]
This will provide response from origin with 3xx instead of 4xx in that particular example.
In order it to work you should use http webstite endpoint as your origin
DOC-EXAMPLE-BUCKET.s3-website-us-east-1.amazonaws.com
Not S3 API endpoint DOC-EXAMPLE-BUCKET.s3.amazonaws.com [2]

It is possible to cover multiple error scenarios
[
{
"Condition": {
"HttpErrorCodeReturnedEquals": "403"
},
"Redirect": {
"HostName": "yourdomain.net",
"HttpRedirectCode": "302",
"Protocol": "http",
"ReplaceKeyWith": "redirectstaticpage.html"
}
},
{
"Condition": {
"HttpErrorCodeReturnedEquals": "404"
},
"Redirect": {
"HostName": "yourdomain.net",
"HttpRedirectCode": "302",
"Protocol": "http",
"ReplaceKeyWith": "redirectstatic2.html"
}
}
]

Consider using CloudFront Response Headers Policies instead of CloudFront Functions.

+1 for having the ability to execute cloud functions on 4xx & 5xx status code. Will help with setting appropriate security headers for error pages as well. The workaround is fine, but may be this on cloud functions can be made configurable.

+1 for having the ability to execute cloud functions on 4xx & 5xx status code. This allows for OAI access control, not having to setup S3 to serve static websites, and allows us to fully control the results with CF functions.

At the very least a very big warning/disclaimer that "viewer return" functions do not execute on 403/404 S3 errors.

+1 for having the ability to execute cloud functions on 4xx & 5xx status code. The simplest strategy S3+Cloudront doesn't work for SPA and now it looks so fragile and over-complicated.