I am an Ops person setting up a website that needs to have security headers implemented.
I have created a Lambda@Edge function with the headers I need which works fine, but I want to add a nonce for style-src as we are calling external URL's (google fonts etc). Most of the guides I have found are only using 'self' and not other URL's. There is one other question about this on SO but the response does not work as I am using Origin Request not Origin Response.
Can I add this to the Lambda@Edge function? I have some nodejs code that generates a nonce, but when I try to add it to the style-src section, it ignores it. I do not know JS so this is difficult for me to troubleshoot.
I'm open to any method of using nonces with CSP and Lambda@Edge if this is not the correct/best way.
This is my Lambda@Edge code.
'use strict';
exports.handler = (event, context, callback) => {
//Get contents of response
const response = event.Records[0].cf.response;
const headers = response.headers;
//Set new headers
headers['strict-transport-security'] = [{key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubdomains; preload'}];
headers['content-security-policy'] = [{key: 'Content-Security-Policy', value: "default-src 'self'; frame-ancestors 'none'; connect-src https://dev.example.io https://api.exampleapi.io; img-src 'self' data: https://examplebucket.s3.region.amazonaws.com; script-src 'self'; font-src 'self' https://fonts.example.com; style-src 'self' https://fonts.example.com; object-src 'none'"}];
headers['x-content-type-options'] = [{key: 'X-Content-Type-Options', value: 'nosniff'}];
headers['x-frame-options'] = [{key: 'X-Frame-Options', value: 'DENY'}];
headers['x-xss-protection'] = [{key: 'X-XSS-Protection', value: '1; mode=block'}];
headers['referrer-policy'] = [{key: 'Referrer-Policy', value: 'same-origin'}];
//Return modified response
callback(null, response);
};
This is the code I have for generating a nonce, that works locally.
const crypto = require('crypto');
let nonce = crypto.randomBytes(16).toString('hex');