Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(release): 2.169.0 #32224

Merged
merged 14 commits into from
Nov 21, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat(cloudfront): add attachWebAclId method for Distribution (#30567)
### Reason for this change

I often create a custom construct for a WAF only. I also create resources (such as API Gateway, ALB, etc...) that attach the WAF in separate constructs. Instead of attaching the WAF in the target resource's construct, I create a method for attaching it in the WAF's construct.

In this way, the constructs can be loosely coupled, and the target resource's constructs can be more simply. The WAF can also be attached to multiple resources at once later.

```ts
export class Waf extends Construct {
  public readonly webAcl: CfnWebACL;

  constructor(scope: Construct, id: string, props: WafProps) {
    super(scope, id);
    this.webAcl = new CfnWebACL(this, 'WebAcl', {
      // ...
    },
  });

  public attachToRegionalResource(id: string, resourceArn: string) {
    new CfnWebACLAssociation(this, `${id}Association`, {
      resourceArn: resourceArn,
      webAclArn: this.webAcl.attrArn,
    });
  }
}

const waf = new Waf(this, 'Waf', { /* props */ });
waf.attachToRegionalResource('A', resourceA);
waf.attachToRegionalResource('B', resourceB);
waf.attachToRegionalResource('C', resourceC);
```

However, when attaching a WAF to a CloudFront, the WAF attaching configuration needs to be defined through CloudFront props, rather than using CfnWebACLAssociation.
To do this with the above WAF construct, a method is needed to pass a pre-defined CloudFront and override the properties of that definition with an escape hatch. This is a bit complicated.

```ts
  public attachToCloudFront(distribution: Distribution) {
    // override the webAcl using escape hatch
  }
```

In other words, it would be good if CloudFront also had a mechanism (like CfnWebACLAssociation) to attach WAF after defining resources.
This would allow WAF custom constructs to be more generic.

### Description of changes

Add `attachWebAclId` method for Distribution.

```ts
declare const bucketOrigin: origins.S3Origin;
declare const webAcl: wafv2.CfnWebACL;

const distribution = new cloudfront.Distribution(stack, 'Distribution', {
  defaultBehavior: { origin: bucketOrigin },
});

distribution.attachWebAclId(webAcl.attrArn);
```

### Description of how you validated changes

Both of unit and integ tests.

### Checklist
- [x] My code adheres to the [CONTRIBUTING GUIDE](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md) and [DESIGN GUIDELINES](https://github.com/aws/aws-cdk/blob/main/docs/DESIGN_GUIDELINES.md)

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
go-to-k authored Nov 21, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
commit cbe2bec488ff9b9823eacf6de14dff1dcb3033a1

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
{
"Resources": {
"WebAcl": {
"Type": "AWS::WAFv2::WebACL",
"Properties": {
"DefaultAction": {
"Allow": {}
},
"Scope": "CLOUDFRONT",
"VisibilityConfig": {
"CloudWatchMetricsEnabled": false,
"MetricName": "webAclMetric",
"SampledRequestsEnabled": false
}
}
},
"Distribution830FAC52": {
"Type": "AWS::CloudFront::Distribution",
"Properties": {
"DistributionConfig": {
"DefaultCacheBehavior": {
"CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
"Compress": true,
"TargetOriginId": "awscdkcloudfrontwithwebaclDistributionOrigin11CAC3663",
"ViewerProtocolPolicy": "allow-all"
},
"Enabled": true,
"HttpVersion": "http2",
"IPV6Enabled": true,
"Origins": [
{
"CustomOriginConfig": {
"OriginProtocolPolicy": "https-only"
},
"DomainName": "www.example.com",
"Id": "awscdkcloudfrontwithwebaclDistributionOrigin11CAC3663"
}
],
"WebACLId": {
"Fn::GetAtt": [
"WebAcl",
"Arn"
]
}
}
}
}
},
"Parameters": {
"BootstrapVersion": {
"Type": "AWS::SSM::Parameter::Value<String>",
"Default": "/cdk-bootstrap/hnb659fds/version",
"Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]"
}
},
"Rules": {
"CheckBootstrapVersion": {
"Assertions": [
{
"Assert": {
"Fn::Not": [
{
"Fn::Contains": [
[
"1",
"2",
"3",
"4",
"5"
],
{
"Ref": "BootstrapVersion"
}
]
}
]
},
"AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI."
}
]
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import * as cdk from 'aws-cdk-lib';
import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';
import { IntegTest } from '@aws-cdk/integ-tests-alpha';
import { TestOrigin } from './test-origin';
import { CfnWebACL } from 'aws-cdk-lib/aws-wafv2';

const app = new cdk.App();

const stack = new cdk.Stack(app, 'aws-cdk-cloudfront-with-webacl', {
env: {
region: 'us-east-1',
},
});

const webAcl = new CfnWebACL(stack, 'WebAcl', {
defaultAction: {
allow: {},
},
scope: 'CLOUDFRONT',
visibilityConfig: {
cloudWatchMetricsEnabled: false,
metricName: 'webAclMetric',
sampledRequestsEnabled: false,
},
});

const distribution = new cloudfront.Distribution(stack, 'Distribution', {
defaultBehavior: { origin: new TestOrigin('www.example.com') },
});

distribution.attachWebAclId(webAcl.attrArn);

new IntegTest(app, 'integ-cloudfront-with-webacl', {
testCases: [stack],
});
31 changes: 31 additions & 0 deletions packages/aws-cdk-lib/aws-cloudfront/README.md
Original file line number Diff line number Diff line change
@@ -217,6 +217,37 @@ new cloudfront.Distribution(this, 'myDist', {
});
```

### Attaching WAF Web Acls

You can attach the AWS WAF web ACL to a CloudFront distribution.

To specify a web ACL created using the latest version of AWS WAF, use the ACL ARN, for example
`arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a`.
The web ACL must be in the `us-east-1` region.

To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example `473e64fd-f30b-4765-81a0-62ad96dd167a`.

```ts
declare const bucketOrigin: origins.S3Origin;
declare const webAcl: wafv2.CfnWebACL;
const distribution = new cloudfront.Distribution(this, 'Distribution', {
defaultBehavior: { origin: bucketOrigin },
webAclId: webAcl.attrArn,
});
```

You can also attach a web ACL to a distribution after creation.

```ts
declare const bucketOrigin: origins.S3Origin;
declare const webAcl: wafv2.CfnWebACL;
const distribution = new cloudfront.Distribution(this, 'Distribution', {
defaultBehavior: { origin: bucketOrigin },
});

distribution.attachWebAclId(webAcl.attrArn);
```

### Customizing Cache Keys and TTLs with Cache Policies

You can use a cache policy to improve your cache hit ratio by controlling the values (URL query strings, HTTP headers, and cookies)
16 changes: 15 additions & 1 deletion packages/aws-cdk-lib/aws-cloudfront/lib/distribution.ts
Original file line number Diff line number Diff line change
@@ -312,6 +312,7 @@ export class Distribution extends Resource implements IDistribution {
private readonly errorResponses: ErrorResponse[];
private readonly certificate?: acm.ICertificate;
private readonly publishAdditionalMetrics?: boolean;
private webAclId?: string;

constructor(scope: Construct, id: string, props: DistributionProps) {
super(scope, id);
@@ -338,6 +339,7 @@ export class Distribution extends Resource implements IDistribution {
this.certificate = props.certificate;
this.errorResponses = props.errorResponses ?? [];
this.publishAdditionalMetrics = props.publishAdditionalMetrics;
this.webAclId = props.webAclId;

// Comments have an undocumented limit of 128 characters
const trimmedComment =
@@ -363,7 +365,7 @@ export class Distribution extends Resource implements IDistribution {
restrictions: this.renderRestrictions(props.geoRestriction),
viewerCertificate: this.certificate ? this.renderViewerCertificate(this.certificate,
props.minimumProtocolVersion, props.sslSupportMethod) : undefined,
webAclId: props.webAclId,
webAclId: Lazy.string({ produce: () => this.webAclId }),
},
});

@@ -601,6 +603,18 @@ export class Distribution extends Resource implements IDistribution {
return this.grant(identity, 'cloudfront:CreateInvalidation');
}

/**
* Attach WAF WebACL to this CloudFront distribution
*
* @param webAclId The WAF WebACL to associate with this distribution
*/
public attachWebAclId(webAclId: string) {
if (this.webAclId) {
throw new Error('A WebACL has already been attached to this distribution');
}
this.webAclId = webAclId;
}

private addOrigin(origin: IOrigin, isFailoverOrigin: boolean = false): string {
const ORIGIN_ID_MAX_LENGTH = 128;

31 changes: 31 additions & 0 deletions packages/aws-cdk-lib/aws-cloudfront/test/distribution.test.ts
Original file line number Diff line number Diff line change
@@ -1334,3 +1334,34 @@ describe('Distribution metrics tests', () => {
}).toThrow(new RegExp(`${metric.errorMetricName} metric is only available if 'publishAdditionalMetrics' is set 'true'`));
});
});

describe('attachWebAclId', () => {
test('can attach WebAcl to the distribution by the method', () => {
const origin = defaultOrigin();

const distribution = new Distribution(stack, 'MyDist', {
defaultBehavior: { origin },
});

distribution.attachWebAclId('473e64fd-f30b-4765-81a0-62ad96dd167a');

Template.fromStack(stack).hasResourceProperties('AWS::CloudFront::Distribution', {
DistributionConfig: {
WebACLId: '473e64fd-f30b-4765-81a0-62ad96dd167a',
},
});
});

test('throws if a WebAcl is already attached to the distribution', () => {
const origin = defaultOrigin();

const distribution = new Distribution(stack, 'MyDist', {
defaultBehavior: { origin },
webAclId: '473e64fd-f30b-4765-81a0-62ad96dd167a',
});

expect(() => {
distribution.attachWebAclId('473e64fd-f30b-4765-81a0-62ad96dd167b');
}).toThrow(/A WebACL has already been attached to this distribution/);
});
});
Original file line number Diff line number Diff line change
@@ -6,6 +6,7 @@ import * as s3 from 'aws-cdk-lib/aws-s3';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as wafv2 from 'aws-cdk-lib/aws-wafv2';
import * as path from 'path';

class Context extends Stack {