nideveloper / CDK-SPA-Deploy

This is an AWS CDK Construct to make deploying a single page website (Angular/React/Vue) to AWS S3 behind SSL/Cloudfront easier
MIT License
235 stars 40 forks source link

Support for response headers #382

Closed jgreen-linx closed 3 years ago

jgreen-linx commented 3 years ago

Any thought on how you might support adding to the cloud front response for things like X-Frame-Options: Deny ( like how Lambda@Edge is done?

John

jgreen-linx commented 3 years ago

To answer my own question, Yes you can do this already in the code just not documented My example is with Hosted zone site

const originRespLambda = new cf.experimental.EdgeFunction(this, 'lambdaAtEdge', {
  runtime: lambda.Runtime.NODEJS_14_X,
  handler: 'headers.handler',
  code: lambda.Code.fromAsset('lambda')
});

new SPADeploy(this, `spaDeploy_${process.env.APP_ENV}`, { encryptBucket: true })
.createSiteFromHostedZone({
      zoneName: zoneNameStr,
      indexDoc: 'index.html',
      errorDoc: 'index.html',
      websiteFolder: '../www',
      cfBehaviors: [{
        isDefaultBehavior: true,
        pathPattern: '*',
        lambdaFunctionAssociations: [
          {
            eventType: LambdaEdgeEventType.ORIGIN_RESPONSE,
            lambdaFunction: originRespLambda
          }
        ]
      }
      ]
});

Lambda@Edge Code headers.js

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 'none'; img-src 'self'; script-src 'self'; style-src 'self'; 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);
};

Hope this helps someone