How to enable managed response header policy of SecurityHeaders with CloudFrontWebDistribution in AWS CDK?

Viewed 239

I have a CloudFrontWebDistribution in my AWS CDK infrastructure code in typescript:

const cloudFrontDistribution = new cloudfront.CloudFrontWebDistribution(this, 'distribution', {
            originConfigs: [
                {
                    s3OriginSource: {
                        s3BucketSource: webBucket,
                        originAccessIdentity: originAccessIdentity,
                    },
                    behaviors : [ {
                        isDefaultBehavior: true,
                        defaultTtl: Duration.seconds(1),
                        lambdaFunctionAssociations: [
                            {
                                eventType: LambdaEdgeEventType.VIEWER_REQUEST,
                                lambdaFunction: midwayEdgeFunction.currentVersion,
                            },
                        ]
                    },
                    ]
                }
            ],
            defaultRootObject: 'index.html',
            viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(props.certificate, {
                aliases: [props.stageProps.cloud_front_domain_name],
                sslMethod: cloudfront.SSLMethod.SNI,
                securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2019
            }),
            viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.HTTPS_ONLY,
            loggingConfig: {
                bucket: logBucket,
                includeCookies: true,
                prefix: 'cflogs/'
            }
        });

I want to enable Security Headers managed policy (see here) to this distribution. However I only see aws cdk documentation for doing so for a Distribution object, but not for a CloudFrontWebDistribution object.

How to enable managed response headers policy of Security Headers to a CloudFrontWebDistribution object in AWS CDK?

1 Answers

Get an escape hatch reference to the underlying L1 CfnDistribution construct. Then, manually set the ResponseHeadersPolicyId property on DefaultCacheBehavior, making use of the ResponseHeadersPolicy.SECURITY_HEADERS static method:

const cfnDistribution = cloudFrontDistribution.node.defaultChild as cloudfront.CfnDistribution;

cfnDistribution.addPropertyOverride(
  'DistributionConfig.DefaultCacheBehavior.ResponseHeadersPolicyId',
  cloudfront.ResponseHeadersPolicy.SECURITY_HEADERS.responseHeadersPolicyId
);
Related