Is it possible to set Content-Security-Policy headers in Amazon S3?

I'm having the same problem (using S3/CloudFront) and it appears there is currently no way to set this up easily.

S3 has a whitelist of the headers permitted, and Content-Security-Policy is not on it. Whilst it is true you can use the prefixed x-amz-meta-Content-Security-Policy, this is unhelpful as there is no browser support for it.

There are two options I can see.

1) you can serve the html content from a webserver on an EC2 instance and set that up as another CloudFront origin. Not really a great solution.

2) include the CSP as a meta tag within your html document:

    <!doctype html>
    <html>
      <head>
        <meta http-equiv="Content-Security-Policy" content="default-src http://*.foobar.com 'self'">
...

This option is not as widely supported by browsers, but it appears to work with both Webkit and Firefox, so the current Chrome, Firefox, Safari (and IOS 7 Safari) seem to support it.

I chose 2 as it was the simpler/cheaper/faster solution and I hope AWS will add the CSP header in the future.


If you are testing through CloudFront, have you made sure you have invalidated the cached objects? Can you try to upload a completely new file and then try accessing it via CF and see if the header is still not there?

Update

Seems like custom metadata will not work as expected as per DOC. Any metadata other than the ones supported by S3 (the ones displayed in the dropdown) will have to be prefixed with x-amz-meta-


S3/CloudFront takes any headers that the origin set and forward those to the client, but you can't set custom headers on you response directly.

You can use Lambda@Edge function that can inject security headers through CloudFront.

Here is how the process works: (reference aws blog)

  • Viewer navigates to website.
  • Before CloudFront serves content from the cache it will trigger any Lambda function associated with the Viewer Request trigger for that behavior.
  • CloudFront serves content from the cache if available, otherwise it goes to step 4.
  • Only after CloudFront cache ‘Miss’, Origin Request trigger is fired for that behavior.
  • S3 Origin returns content.
  • After content is returned from S3 but before being cached in CloudFront, Origin Response trigger is fired.
  • After content is cached in CloudFront, Viewer Response trigger is fired and is the final step before viewer receives content.
  • Viewer receives content.

Below is the blog from aws on how to do this step by step.

https://aws.amazon.com/blogs/networking-and-content-delivery/adding-http-security-headers-using-lambdaedge-and-amazon-cloudfront/