Description
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.