From 1b116b9dd4f387d405160ba7ed6ef128eb3abbbe Mon Sep 17 00:00:00 2001 From: "Kenta Goto (k.goto)" <24818752+go-to-k@users.noreply.github.com> Date: Fri, 21 Feb 2025 03:28:56 +0900 Subject: [PATCH] feat(cloudfront): support gRPC for distribution (#32535) ### Issue # (if applicable) Closes #32534. ### Reason for this change CloudFormation supports `GrpcConfig` property to enable gRPC in `CacheBehavior` and `DefaultCacheBehavior`. https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-grpcconfig.html https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-cachebehavior.html https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html So it would be good to enable gRPC for CloudFront Distribution using L2. ### Description of changes Add `enableGrpc` property in `BehaviorOptions`. ### Description of how you validated changes Both 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* --- ...efaultTestDeployAssertE740300C.assets.json | 19 ++ ...aultTestDeployAssertE740300C.template.json | 36 ++++ .../cdk.out | 1 + .../integ-distribution-grpc.assets.json | 19 ++ .../integ-distribution-grpc.template.json | 91 +++++++++ .../integ.json | 12 ++ .../manifest.json | 113 +++++++++++ .../tree.json | 181 ++++++++++++++++++ .../test/integ.distribution-grpc.ts | 23 +++ packages/aws-cdk-lib/aws-cloudfront/README.md | 23 +++ .../aws-cloudfront/lib/distribution.ts | 30 ++- .../lib/private/cache-behavior.ts | 16 +- .../aws-cloudfront/test/distribution.test.ts | 118 +++++++++++- .../test/private/cache-behavior.test.ts | 50 +++++ 14 files changed, 727 insertions(+), 5 deletions(-) create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/DistributionGrpcDefaultTestDeployAssertE740300C.assets.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/DistributionGrpcDefaultTestDeployAssertE740300C.template.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/cdk.out create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ-distribution-grpc.assets.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ-distribution-grpc.template.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/manifest.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/tree.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.ts diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/DistributionGrpcDefaultTestDeployAssertE740300C.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/DistributionGrpcDefaultTestDeployAssertE740300C.assets.json new file mode 100644 index 0000000000000..6fa597d223ea8 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/DistributionGrpcDefaultTestDeployAssertE740300C.assets.json @@ -0,0 +1,19 @@ +{ + "version": "38.0.1", + "files": { + "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22": { + "source": { + "path": "DistributionGrpcDefaultTestDeployAssertE740300C.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/DistributionGrpcDefaultTestDeployAssertE740300C.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/DistributionGrpcDefaultTestDeployAssertE740300C.template.json new file mode 100644 index 0000000000000..ad9d0fb73d1dd --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/DistributionGrpcDefaultTestDeployAssertE740300C.template.json @@ -0,0 +1,36 @@ +{ + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "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." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/cdk.out b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/cdk.out new file mode 100644 index 0000000000000..c6e612584e352 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/cdk.out @@ -0,0 +1 @@ +{"version":"38.0.1"} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ-distribution-grpc.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ-distribution-grpc.assets.json new file mode 100644 index 0000000000000..5356bef4c69b9 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ-distribution-grpc.assets.json @@ -0,0 +1,19 @@ +{ + "version": "38.0.1", + "files": { + "e92efb368ead4669dc674d1d7d93a51366b7ca4d9527f3521f8f4c890fd96824": { + "source": { + "path": "integ-distribution-grpc.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "e92efb368ead4669dc674d1d7d93a51366b7ca4d9527f3521f8f4c890fd96824.json", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ-distribution-grpc.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ-distribution-grpc.template.json new file mode 100644 index 0000000000000..ca5d14c0bcf54 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ-distribution-grpc.template.json @@ -0,0 +1,91 @@ +{ + "Resources": { + "TestDistribution94EC811C": { + "Type": "AWS::CloudFront::Distribution", + "Properties": { + "DistributionConfig": { + "CacheBehaviors": [ + { + "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + "Compress": true, + "PathPattern": "/second", + "TargetOriginId": "integdistributiongrpcTestDistributionOrigin1C4AE5CE4", + "ViewerProtocolPolicy": "allow-all" + }, + { + "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + "Compress": true, + "PathPattern": "/third", + "TargetOriginId": "integdistributiongrpcTestDistributionOrigin1C4AE5CE4", + "ViewerProtocolPolicy": "allow-all" + } + ], + "DefaultCacheBehavior": { + "AllowedMethods": [ + "GET", + "HEAD", + "OPTIONS", + "PUT", + "PATCH", + "POST", + "DELETE" + ], + "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + "Compress": true, + "GrpcConfig": { + "Enabled": true + }, + "TargetOriginId": "integdistributiongrpcTestDistributionOrigin1C4AE5CE4", + "ViewerProtocolPolicy": "allow-all" + }, + "Enabled": true, + "HttpVersion": "http2", + "IPV6Enabled": true, + "Origins": [ + { + "CustomOriginConfig": { + "OriginProtocolPolicy": "https-only" + }, + "DomainName": "www.example.com", + "Id": "integdistributiongrpcTestDistributionOrigin1C4AE5CE4" + } + ] + } + } + } + }, + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "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." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ.json b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ.json new file mode 100644 index 0000000000000..416c058187293 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/integ.json @@ -0,0 +1,12 @@ +{ + "version": "38.0.1", + "testCases": { + "DistributionGrpc/DefaultTest": { + "stacks": [ + "integ-distribution-grpc" + ], + "assertionStack": "DistributionGrpc/DefaultTest/DeployAssert", + "assertionStackName": "DistributionGrpcDefaultTestDeployAssertE740300C" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/manifest.json b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/manifest.json new file mode 100644 index 0000000000000..5adc0ae7e0e13 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/manifest.json @@ -0,0 +1,113 @@ +{ + "version": "38.0.1", + "artifacts": { + "integ-distribution-grpc.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "integ-distribution-grpc.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "integ-distribution-grpc": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "integ-distribution-grpc.template.json", + "terminationProtection": false, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/e92efb368ead4669dc674d1d7d93a51366b7ca4d9527f3521f8f4c890fd96824.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "integ-distribution-grpc.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-lookup-role-${AWS::AccountId}-${AWS::Region}", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "integ-distribution-grpc.assets" + ], + "metadata": { + "/integ-distribution-grpc/TestDistribution/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "TestDistribution94EC811C" + } + ], + "/integ-distribution-grpc/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/integ-distribution-grpc/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "integ-distribution-grpc" + }, + "DistributionGrpcDefaultTestDeployAssertE740300C.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "DistributionGrpcDefaultTestDeployAssertE740300C.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "DistributionGrpcDefaultTestDeployAssertE740300C": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "DistributionGrpcDefaultTestDeployAssertE740300C.template.json", + "terminationProtection": false, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "DistributionGrpcDefaultTestDeployAssertE740300C.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-lookup-role-${AWS::AccountId}-${AWS::Region}", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "DistributionGrpcDefaultTestDeployAssertE740300C.assets" + ], + "metadata": { + "/DistributionGrpc/DefaultTest/DeployAssert/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/DistributionGrpc/DefaultTest/DeployAssert/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "DistributionGrpc/DefaultTest/DeployAssert" + }, + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/tree.json b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/tree.json new file mode 100644 index 0000000000000..45da45df27be9 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.js.snapshot/tree.json @@ -0,0 +1,181 @@ +{ + "version": "tree-0.1", + "tree": { + "id": "App", + "path": "", + "children": { + "integ-distribution-grpc": { + "id": "integ-distribution-grpc", + "path": "integ-distribution-grpc", + "children": { + "TestDistribution": { + "id": "TestDistribution", + "path": "integ-distribution-grpc/TestDistribution", + "children": { + "Origin1": { + "id": "Origin1", + "path": "integ-distribution-grpc/TestDistribution/Origin1", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + }, + "Resource": { + "id": "Resource", + "path": "integ-distribution-grpc/TestDistribution/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::CloudFront::Distribution", + "aws:cdk:cloudformation:props": { + "distributionConfig": { + "enabled": true, + "origins": [ + { + "domainName": "www.example.com", + "id": "integdistributiongrpcTestDistributionOrigin1C4AE5CE4", + "customOriginConfig": { + "originProtocolPolicy": "https-only" + } + } + ], + "defaultCacheBehavior": { + "pathPattern": "*", + "targetOriginId": "integdistributiongrpcTestDistributionOrigin1C4AE5CE4", + "allowedMethods": [ + "GET", + "HEAD", + "OPTIONS", + "PUT", + "PATCH", + "POST", + "DELETE" + ], + "cachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + "compress": true, + "viewerProtocolPolicy": "allow-all", + "grpcConfig": { + "enabled": true + } + }, + "cacheBehaviors": [ + { + "pathPattern": "/second", + "targetOriginId": "integdistributiongrpcTestDistributionOrigin1C4AE5CE4", + "cachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + "compress": true, + "viewerProtocolPolicy": "allow-all" + }, + { + "pathPattern": "/third", + "targetOriginId": "integdistributiongrpcTestDistributionOrigin1C4AE5CE4", + "cachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + "compress": true, + "viewerProtocolPolicy": "allow-all" + } + ], + "httpVersion": "http2", + "ipv6Enabled": true + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "integ-distribution-grpc/BootstrapVersion", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "integ-distribution-grpc/CheckBootstrapVersion", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + }, + "DistributionGrpc": { + "id": "DistributionGrpc", + "path": "DistributionGrpc", + "children": { + "DefaultTest": { + "id": "DefaultTest", + "path": "DistributionGrpc/DefaultTest", + "children": { + "Default": { + "id": "Default", + "path": "DistributionGrpc/DefaultTest/Default", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + }, + "DeployAssert": { + "id": "DeployAssert", + "path": "DistributionGrpc/DefaultTest/DeployAssert", + "children": { + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "DistributionGrpc/DefaultTest/DeployAssert/BootstrapVersion", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "DistributionGrpc/DefaultTest/DeployAssert/CheckBootstrapVersion", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests-alpha.IntegTestCase", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests-alpha.IntegTest", + "version": "0.0.0" + } + }, + "Tree": { + "id": "Tree", + "path": "Tree", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.4.2" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.ts b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.ts new file mode 100644 index 0000000000000..9c8b89503a894 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-cloudfront/test/integ.distribution-grpc.ts @@ -0,0 +1,23 @@ +import * as cdk from 'aws-cdk-lib'; +import { IntegTest } from '@aws-cdk/integ-tests-alpha'; +import { TestOrigin } from './test-origin'; +import * as cloudfront from 'aws-cdk-lib/aws-cloudfront'; + +const app = new cdk.App(); +const stack = new cdk.Stack(app, 'integ-distribution-grpc'); + +const origin = new TestOrigin('www.example.com'); + +const distribution = new cloudfront.Distribution(stack, 'TestDistribution', { + defaultBehavior: { + origin, + allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL, + enableGrpc: true, + }, +}); +distribution.addBehavior('/second', origin); +distribution.addBehavior('/third', origin); + +new IntegTest(app, 'DistributionGrpc', { + testCases: [stack], +}); diff --git a/packages/aws-cdk-lib/aws-cloudfront/README.md b/packages/aws-cdk-lib/aws-cloudfront/README.md index be5440b79b0b1..b89f17f0f1d93 100644 --- a/packages/aws-cdk-lib/aws-cloudfront/README.md +++ b/packages/aws-cdk-lib/aws-cloudfront/README.md @@ -801,6 +801,29 @@ new cloudfront.Distribution(this, 'myCdn', { }); ``` +### gRPC + +CloudFront supports gRPC, an open-source remote procedure call (RPC) framework built on HTTP/2. gRPC offers bi-directional streaming and +binary protocol that buffers payloads, making it suitable for applications that require low latency communications. + +To enable your distribution to handle gRPC requests, you must include HTTP/2 as one of the supported HTTP versions and allow HTTP methods, +including POST. + +See [Using gRPC with CloudFront distributions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-using-grpc.html) +in the CloudFront User Guide. + +Example: + +```ts +new cloudfront.Distribution(this, 'myCdn', { + defaultBehavior: { + origin: new origins.HttpOrigin('www.example.com'), + allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL, // `AllowedMethods.ALLOW_ALL` is required if `enableGrpc` is true + enableGrpc: true, + }, +}); +``` + ## Migrating from the original CloudFrontWebDistribution to the newer Distribution construct It's possible to migrate a distribution from the original to the modern API. diff --git a/packages/aws-cdk-lib/aws-cloudfront/lib/distribution.ts b/packages/aws-cdk-lib/aws-cloudfront/lib/distribution.ts index de66188a0ee13..f20e8ff6199e8 100644 --- a/packages/aws-cdk-lib/aws-cloudfront/lib/distribution.ts +++ b/packages/aws-cdk-lib/aws-cloudfront/lib/distribution.ts @@ -314,6 +314,7 @@ export class Distribution extends Resource implements IDistribution { public readonly distributionDomainName: string; public readonly distributionId: string; + private readonly httpVersion: HttpVersion; private readonly defaultBehavior: CacheBehavior; private readonly additionalBehaviors: CacheBehavior[] = []; private readonly boundOrigins: BoundOrigin[] = []; @@ -340,6 +341,9 @@ export class Distribution extends Resource implements IDistribution { } } + this.httpVersion = props.httpVersion ?? HttpVersion.HTTP2; + this.validateGrpc(props.defaultBehavior); + const originId = this.addOrigin(props.defaultBehavior.origin); this.defaultBehavior = new CacheBehavior(originId, { pathPattern: '*', ...props.defaultBehavior }); if (props.additionalBehaviors) { @@ -374,7 +378,7 @@ export class Distribution extends Resource implements IDistribution { comment: trimmedComment, customErrorResponses: this.renderErrorResponses(), defaultRootObject: props.defaultRootObject, - httpVersion: props.httpVersion ?? HttpVersion.HTTP2, + httpVersion: this.httpVersion, ipv6Enabled: props.enableIpv6 ?? true, logging: this.renderLogging(props), priceClass: props.priceClass ?? undefined, @@ -615,6 +619,7 @@ export class Distribution extends Resource implements IDistribution { if (pathPattern === '*') { throw new ValidationError('Only the default behavior can have a path pattern of \'*\'', this); } + this.validateGrpc(behaviorOptions); const originId = this.addOrigin(origin); this.additionalBehaviors.push(new CacheBehavior(originId, { pathPattern, ...behaviorOptions })); } @@ -820,6 +825,16 @@ export class Distribution extends Resource implements IDistribution { sslSupportMethod: sslSupportMethod, }; } + + private validateGrpc(behaviorOptions: AddBehaviorOptions) { + if (!behaviorOptions.enableGrpc) { + return; + } + const validHttpVersions = [HttpVersion.HTTP2, HttpVersion.HTTP2_AND_3]; + if (!validHttpVersions.includes(this.httpVersion)) { + throw new ValidationError(`'httpVersion' must be ${validHttpVersions.join(' or ')} if 'enableGrpc' in 'defaultBehavior' or 'additionalBehaviors' is true, got ${this.httpVersion}`, this); + } + } } /** Maximum HTTP version to support */ @@ -1115,6 +1130,19 @@ export interface AddBehaviorOptions { * @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html */ readonly trustedKeyGroups?: IKeyGroup[]; + + /** + * Enables your CloudFront distribution to receive gRPC requests and to proxy them directly to your origins. + * + * If the `enableGrpc` is set to true, the following restrictions apply: + * - The `allowedMethods` property must be `AllowedMethods.ALLOW_ALL` to include POST method because gRPC only supports POST method. + * - The `httpVersion` property must be `HttpVersion.HTTP2` or `HttpVersion.HTTP2_AND_3` because gRPC only supports versions including HTTP/2. + * - The `edgeLambdas` property can't be specified because gRPC is not supported with Lambda@Edge. + * + * @default false + * @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-using-grpc.html + */ + readonly enableGrpc?: boolean; } /** diff --git a/packages/aws-cdk-lib/aws-cloudfront/lib/private/cache-behavior.ts b/packages/aws-cdk-lib/aws-cloudfront/lib/private/cache-behavior.ts index d5bb4875be266..8aaa82a0d39bb 100644 --- a/packages/aws-cdk-lib/aws-cloudfront/lib/private/cache-behavior.ts +++ b/packages/aws-cdk-lib/aws-cloudfront/lib/private/cache-behavior.ts @@ -2,7 +2,7 @@ import * as iam from '../../../aws-iam'; import { UnscopedValidationError } from '../../../core'; import { CachePolicy } from '../cache-policy'; import { CfnDistribution } from '../cloudfront.generated'; -import { AddBehaviorOptions, EdgeLambda, LambdaEdgeEventType, ViewerProtocolPolicy } from '../distribution'; +import { AddBehaviorOptions, AllowedMethods, EdgeLambda, LambdaEdgeEventType, ViewerProtocolPolicy } from '../distribution'; /** * Properties for specifying custom behaviors for origins. @@ -28,6 +28,15 @@ export class CacheBehavior { constructor(originId: string, private readonly props: CacheBehaviorProps) { this.originId = originId; + if (props.enableGrpc) { + if (props.allowedMethods !== AllowedMethods.ALLOW_ALL) { + throw new UnscopedValidationError('\'allowedMethods\' can only be AllowedMethods.ALLOW_ALL if \'enableGrpc\' is true'); + } + if (props.edgeLambdas !== undefined && props.edgeLambdas.length > 0) { + throw new UnscopedValidationError('\'edgeLambdas\' cannot be specified if \'enableGrpc\' is true'); + } + } + this.validateEdgeLambdas(props.edgeLambdas); this.grantEdgeLambdaFunctionExecutionRole(props.edgeLambdas); } @@ -63,6 +72,11 @@ export class CacheBehavior { includeBody: edgeLambda.includeBody, })), trustedKeyGroups: this.props.trustedKeyGroups?.map(keyGroup => keyGroup.keyGroupId), + grpcConfig: this.props.enableGrpc !== undefined + ? { + enabled: this.props.enableGrpc, + } + : undefined, }; } diff --git a/packages/aws-cdk-lib/aws-cloudfront/test/distribution.test.ts b/packages/aws-cdk-lib/aws-cloudfront/test/distribution.test.ts index 0ce94620d2746..50b0e3433bfda 100644 --- a/packages/aws-cdk-lib/aws-cloudfront/test/distribution.test.ts +++ b/packages/aws-cdk-lib/aws-cloudfront/test/distribution.test.ts @@ -1,15 +1,14 @@ import { defaultOrigin, defaultOriginGroup, defaultOriginWithOriginAccessControl } from './test-origin'; import { Annotations, Match, Template } from '../../assertions'; import * as acm from '../../aws-certificatemanager'; -import { HttpOrigin, OriginGroup } from '../../aws-cloudfront-origins'; import * as cloudwatch from '../../aws-cloudwatch'; import * as iam from '../../aws-iam'; import * as kinesis from '../../aws-kinesis'; import * as lambda from '../../aws-lambda'; -import { CfnChannelGroup } from '../../aws-mediapackagev2'; import * as s3 from '../../aws-s3'; import { App, Aws, Duration, Stack } from '../../core'; import { + AllowedMethods, CfnDistribution, Distribution, Endpoint, @@ -20,7 +19,6 @@ import { HttpVersion, IOrigin, LambdaEdgeEventType, - OriginSelectionCriteria, PriceClass, RealtimeLogConfig, SecurityPolicyProtocol, @@ -1436,3 +1434,117 @@ describe('attachWebAclId', () => { }); }); }); + +describe('gRPC', () => { + test.each([ + true, + false, + undefined, + ])('set gRPC to %s in defaultBehavior', (enableGrpc) => { + const origin = defaultOrigin(); + new Distribution(stack, 'MyDist', { + httpVersion: HttpVersion.HTTP2, + defaultBehavior: { + origin, + allowedMethods: AllowedMethods.ALLOW_ALL, + enableGrpc, + }, + }); + + const grpcConfig = enableGrpc !== undefined ? { + Enabled: enableGrpc, + } : Match.absent(); + + Template.fromStack(stack).hasResourceProperties('AWS::CloudFront::Distribution', { + DistributionConfig: { + DefaultCacheBehavior: { + GrpcConfig: grpcConfig, + }, + }, + }); + }); + + test.each([ + true, + false, + undefined, + ])('set gRPC to %s in additionalBehaviors', (enableGrpc) => { + const origin = defaultOrigin(); + new Distribution(stack, 'MyDist', { + httpVersion: HttpVersion.HTTP2, + defaultBehavior: { + origin, + }, + additionalBehaviors: { + '/second': { + origin, + allowedMethods: AllowedMethods.ALLOW_ALL, + enableGrpc, + }, + }, + }); + + const grpcConfig = enableGrpc !== undefined ? { + Enabled: enableGrpc, + } : Match.absent(); + + Template.fromStack(stack).hasResourceProperties('AWS::CloudFront::Distribution', { + DistributionConfig: { + CacheBehaviors: [{ + PathPattern: '/second', + GrpcConfig: grpcConfig, + }], + }, + }); + }); + + test.each([ + HttpVersion.HTTP1_1, + HttpVersion.HTTP3, + ])('throws if httpVersion is %s and enableGrpc in defaultBehavior is true', (httpVersion) => { + const origin = defaultOrigin(); + const msg = `'httpVersion' must be http2 or http2and3 if 'enableGrpc' in 'defaultBehavior' or 'additionalBehaviors' is true, got ${httpVersion}`; + + expect(() => { + new Distribution(stack, 'MyDist', { + httpVersion, + defaultBehavior: { + origin, + enableGrpc: true, + allowedMethods: AllowedMethods.ALLOW_ALL, + }, + }); + }).toThrow(msg); + }); + + test.each([ + HttpVersion.HTTP1_1, + HttpVersion.HTTP3, + ])('throws if httpVersion is %s and enableGrpc in additionalBehaviors is true', (httpVersion) => { + const origin = defaultOrigin(); + const msg = `'httpVersion' must be http2 or http2and3 if 'enableGrpc' in 'defaultBehavior' or 'additionalBehaviors' is true, got ${httpVersion}`; + + expect(() => { + new Distribution(stack, 'MyDist', { + httpVersion, + defaultBehavior: { + origin, + enableGrpc: false, + allowedMethods: AllowedMethods.ALLOW_ALL, + }, + additionalBehaviors: { + '/second': { + origin, + enableGrpc: false, + allowedMethods: AllowedMethods.ALLOW_ALL, + }, + '/third': { + origin, + enableGrpc: true, + allowedMethods: AllowedMethods.ALLOW_ALL, + }, + }, + }); + }).toThrow(msg); + }); +}); diff --git a/packages/aws-cdk-lib/aws-cloudfront/test/private/cache-behavior.test.ts b/packages/aws-cdk-lib/aws-cloudfront/test/private/cache-behavior.test.ts index 71741d3e838e7..76ce9f08b66c6 100644 --- a/packages/aws-cdk-lib/aws-cloudfront/test/private/cache-behavior.test.ts +++ b/packages/aws-cdk-lib/aws-cloudfront/test/private/cache-behavior.test.ts @@ -97,3 +97,53 @@ test('throws if edgeLambda includeBody is set for wrong event type', () => { }], })).toThrow(/'includeBody' can only be true for ORIGIN_REQUEST or VIEWER_REQUEST event types./); }); + +describe('gRPC', () => { + test.each([true, false, undefined])('enableGrpc is %s', (enableGrpc) => { + const behavior = new CacheBehavior('origin_id', { + pathPattern: '*', + allowedMethods: AllowedMethods.ALLOW_ALL, + enableGrpc, + }); + + expect(behavior._renderBehavior()).toEqual({ + targetOriginId: 'origin_id', + cachePolicyId: '658327ea-f89d-4fab-a63d-7e88639e58f6', + compress: true, + pathPattern: '*', + allowedMethods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'PATCH', 'POST', 'DELETE'], + viewerProtocolPolicy: 'allow-all', + grpcConfig: enableGrpc !== undefined + ? { + enabled: enableGrpc, + } + : undefined, + }); + }); + + test.each([ + AllowedMethods.ALLOW_GET_HEAD, + AllowedMethods.ALLOW_GET_HEAD_OPTIONS, + undefined, + ])('throws if allowedMethods is not ALLOW_ALL but %s and enableGrpc is true', (allowedMethods) => { + expect(() => new CacheBehavior('origin_id', { + pathPattern: '*', + allowedMethods, + enableGrpc: true, + })).toThrow(/'allowedMethods' can only be AllowedMethods.ALLOW_ALL if 'enableGrpc' is true/); + }); + + test('throws if edgeLambda is set and enableGrpc is true', () => { + const fnVersion = lambda.Version.fromVersionArn(stack, 'Version', 'arn:aws:lambda:testregion:111111111111:function:myTestFun:v1'); + + expect(() => new CacheBehavior('origin_id', { + pathPattern: '*', + allowedMethods: AllowedMethods.ALLOW_ALL, + enableGrpc: true, + edgeLambdas: [{ + eventType: LambdaEdgeEventType.ORIGIN_RESPONSE, + functionVersion: fnVersion, + }], + })).toThrow(/'edgeLambdas' cannot be specified if 'enableGrpc' is true/); + }); +});