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 07c37adb03cf9..e00f8e152b2cd 100644 --- a/packages/aws-cdk-lib/aws-cloudfront/README.md +++ b/packages/aws-cdk-lib/aws-cloudfront/README.md @@ -792,6 +792,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 9bed65f41f48e..a8e4989ea6db7 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[] = []; @@ -354,6 +355,9 @@ export class Distribution extends Resource implements IDistribution { this.certificate = props.certificate; this.errorResponses = props.errorResponses ?? []; this.publishAdditionalMetrics = props.publishAdditionalMetrics; + this.httpVersion = props.httpVersion ?? HttpVersion.HTTP2; + + this.validateGrpc(this.defaultBehavior); // Comments have an undocumented limit of 128 characters const trimmedComment = @@ -372,7 +376,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, @@ -724,7 +728,10 @@ export class Distribution extends Resource implements IDistribution { private renderCacheBehaviors(): CfnDistribution.CacheBehaviorProperty[] | undefined { if (this.additionalBehaviors.length === 0) { return undefined; } - return this.additionalBehaviors.map(behavior => behavior._renderBehavior()); + return this.additionalBehaviors.map(behavior => { + this.validateGrpc(behavior); + return behavior._renderBehavior(); + }); } private renderErrorResponses(): CfnDistribution.CustomErrorResponseProperty[] | undefined { @@ -787,6 +794,15 @@ export class Distribution extends Resource implements IDistribution { sslSupportMethod: sslSupportMethod, }; } + + private validateGrpc(cacheBehavior: CacheBehavior) { + if (!cacheBehavior.grpcEnabled) { + return; + } + if (![HttpVersion.HTTP2, HttpVersion.HTTP2_AND_3].includes(this.httpVersion)) { + throw new Error(`'httpVersion' must be HttpVersion.HTTP2 or HttpVersion.HTTP2_AND_3 if 'enableGrpc' in 'defaultBehavior' or 'additionalBehaviors' is true, got ${this.httpVersion}`); + } + } } /** Maximum HTTP version to support */ @@ -1082,6 +1098,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 b4a7e8bd4c483..c197e359748bb 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 @@ -1,7 +1,7 @@ import * as iam from '../../../aws-iam'; 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. @@ -22,10 +22,21 @@ export interface CacheBehaviorProps extends AddBehaviorOptions { * CloudFrontWebDistribution implementation. */ export class CacheBehavior { + public readonly grpcEnabled?: boolean; private readonly originId: string; constructor(originId: string, private readonly props: CacheBehaviorProps) { this.originId = originId; + this.grpcEnabled = props.enableGrpc; + + if (this.grpcEnabled) { + if (props.allowedMethods !== AllowedMethods.ALLOW_ALL) { + throw new Error('\'allowedMethods\' can only be AllowedMethods.ALLOW_ALL if \'enableGrpc\' is true'); + } + if (props.edgeLambdas !== undefined && props.edgeLambdas.length > 0) { + throw new Error('\'edgeLambdas\' cannot be specified if \'enableGrpc\' is true'); + } + } this.validateEdgeLambdas(props.edgeLambdas); this.grantEdgeLambdaFunctionExecutionRole(props.edgeLambdas); @@ -62,6 +73,11 @@ export class CacheBehavior { includeBody: edgeLambda.includeBody, })), trustedKeyGroups: this.props.trustedKeyGroups?.map(keyGroup => keyGroup.keyGroupId), + grpcConfig: this.grpcEnabled !== undefined + ? { + enabled: this.grpcEnabled, + } + : 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 927ba5861b368..011d314d1108e 100644 --- a/packages/aws-cdk-lib/aws-cloudfront/test/distribution.test.ts +++ b/packages/aws-cdk-lib/aws-cloudfront/test/distribution.test.ts @@ -8,6 +8,7 @@ import * as lambda from '../../aws-lambda'; import * as s3 from '../../aws-s3'; import { App, Aws, Duration, Stack } from '../../core'; import { + AllowedMethods, CfnDistribution, Distribution, Endpoint, @@ -1432,5 +1433,57 @@ describe('attachWebAclId', () => { }).toThrow(/WebACL for CloudFront distributions must be created in the us-east-1 region; received ap-northeast-1/); }); }); +}); + +describe('gRPC', () => { + 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 HttpVersion.HTTP2 or HttpVersion.HTTP2_AND_3 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 HttpVersion.HTTP2 or HttpVersion.HTTP2_AND_3 if 'enableGrpc' in 'defaultBehavior' or 'additionalBehaviors' is true, got ${httpVersion}`; + 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, + }, + }, + }); + expect(() => { + app.synth(); + }).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/); + }); +});