diff --git a/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/.eslintignore b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/.eslintignore new file mode 100755 index 000000000..910cb0513 --- /dev/null +++ b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/.eslintignore @@ -0,0 +1,4 @@ +lib/*.js +test/*.js +*.d.ts +coverage \ No newline at end of file diff --git a/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/.gitignore b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/.gitignore new file mode 100755 index 000000000..6773cabd2 --- /dev/null +++ b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/.gitignore @@ -0,0 +1,15 @@ +lib/*.js +test/*.js +*.js.map +*.d.ts +node_modules +*.generated.ts +dist +.jsii + +.LAST_BUILD +.nyc_output +coverage +.nycrc +.LAST_PACKAGE +*.snk \ No newline at end of file diff --git a/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/.npmignore b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/.npmignore new file mode 100755 index 000000000..f66791629 --- /dev/null +++ b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/.npmignore @@ -0,0 +1,21 @@ +# Exclude typescript source and config +*.ts +tsconfig.json +coverage +.nyc_output +*.tgz +*.snk +*.tsbuildinfo + +# Include javascript files and typescript declarations +!*.js +!*.d.ts + +# Exclude jsii outdir +dist + +# Include .jsii +!.jsii + +# Include .jsii +!.jsii \ No newline at end of file diff --git a/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/README.md b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/README.md new file mode 100755 index 000000000..9e033fc07 --- /dev/null +++ b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/README.md @@ -0,0 +1,112 @@ +# aws-route53-apigateway module + + +--- + +![Stability: Experimental](https://img.shields.io/badge/stability-Experimental-important.svg?style=for-the-badge) + +> All classes are under active development and subject to non-backward compatible changes or removal in any +> future version. These are not subject to the [Semantic Versioning](https://semver.org/) model. +> This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package. + +--- + + +| **Reference Documentation**:| https://docs.aws.amazon.com/solutions/latest/constructs/| +|:-------------|:-------------| +
+ +| **Language** | **Package** | +|:-------------|-----------------| +|![Python Logo](https://docs.aws.amazon.com/cdk/api/latest/img/python32.png) Python|`aws_solutions_constructs.aws_route53_apigateway`| +|![Typescript Logo](https://docs.aws.amazon.com/cdk/api/latest/img/typescript32.png) Typescript|`@aws-solutions-constructs/aws-route53-apigateway`| +|![Java Logo](https://docs.aws.amazon.com/cdk/api/latest/img/java32.png) Java|`software.amazon.awsconstructs.services.route53apigateway`| + +## Overview + +This AWS Solutions Construct implements an Amazon Route 53 connected to a configured Amazon API Gateway REST API. + +Here is a minimal deployable pattern definition in Typescript: + +``` typescript +import * as api from '@aws-cdk/aws-apigateway'; +import * as lambda from "@aws-cdk/aws-lambda"; +import * as route53 from "@aws-cdk/aws-route53"; +import { Route53ToApigateway } from '@aws-solutions-constructs/aws-route53-apigateway'; + +// The construct requires an existing REST API, this can be created in raw CDK or extracted +// from a previously instantiated construct that created an API Gateway REST API +const existingRestApi = previouslyCreatedApigatewayToLambdaConstruct.apiGateway; + +const ourHostedZone = route53.HostedZone.fromLookup(this, 'HostedZone', { + domainName: "example.com", + }); + +const certificate = acm.Certificate.fromCertificateArn( + stack, + "fake-cert", + "arn:aws:acm:us-east-1:123456789012:certificate/11112222-3333-1234-1234-123456789012" + ); + +// This construct can only be attached to a configured API Gateway. +new Route53ToApigateway(this, 'Route53ToApigatewayPattern', { + existingApiGatewayObj: existingRestApi, + existingHostedZoneInterface: ourHostedZone, + publicApi: true, + existingCertificateInterface: certificate +}); + +``` + +## Initializer + +``` text +new Route53ToApigateway(scope: Construct, id: string, props: Route53ToApigatewayProps); +``` + +_Parameters_ + +* scope [`Construct`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) +* id `string` +* props [`Route53ToApigatewayProps`](#pattern-construct-props) + +## Pattern Construct Props + +This construct cannot create a new Public Hosted Zone, if you are creating a public API you must supply an existing Public Hosted Zone that will be reconfigured with a new Alias record. Public Hosted Zones are configured with public domain names and are not well suited to be launched and torn down dynamically, so this construct will only reconfigure existing Public Hosted Zones. + +This construct can create Private Hosted Zones. If you want a Private Hosted Zone, then you can either provide an existing Private Hosted Zone or a privateHostedZoneProps value with at least the Domain Name defined. If you are using privateHostedZoneProps, an existing wildcard certificate (*.example.com) must be issued from a previous domain to be used in the newly created Private Hosted Zone. New certificate creation and validation do not take place in this construct. A private Rest API already exists in a VPC, so that VPC must be provided in the existingVpc prop. There is no scenario where this construct can create a new VPC (since it can't create a new API), so the vpcProps property is not supported on this construct. + +| **Name** | **Type** | **Description** | +|:-------------|:----------------|-----------------| +| publicApi | boolean | Whether the construct is deploying a private or public API. This has implications for the Hosted Zone and VPC. | +| privateHostedZoneProps? | [route53.PrivateHostedZoneProps](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-route53.PrivateHostedZoneProps.html) | Optional custom properties for a new Private Hosted Zone. Cannot be specified for a public API. Cannot specify a VPC, it will use the VPC in existingVpc or the VPC created by the construct. Providing both this and existingHostedZoneInterface is an error. | +| existingHostedZoneInterface? | [route53.IHostedZone](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-route53.IHostedZone.html) | Existing Public or Private Hosted Zone (type must match publicApi setting). Specifying both this and privateHostedZoneProps is an error. If this is a Private Hosted Zone, the associated VPC must be provided as the existingVpc property.| +| existingVpc? | [ec2.IVpc](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.IVpc.html) | An existing VPC in which to deploy the construct.| +|existingApiGatewayInterface|[api.IRestApi](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.IRestApi.html)|The existing API Gateway instance that will be connected to the Route 53 hosted zone. *Note that Route 53 can only be connected to a configured API Gateway, so this construct only accepts an existing IRestApi and does not accept apiGatewayProps.*| +| existingCertificateInterface |[certificatemanager.ICertificate](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-certificatemanager.ICertificate.html)| An existing AWS Certificate Manager certificate for your custom domain name.| + +## Pattern Properties + +| **Name** | **Type** | **Description** | +|:-------------|:----------------|-----------------| +|hostedZone|[route53.IHostedZone](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-route53.IHostedZone.html)|The hosted zone used by the construct (whether created by the construct or provided by the client) | +| vpc? | [ec2.IVpc](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.IVpc.html) | The VPC used by the construct. | +|apiGateway|[api.RestApi](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.RestApi.html)|Returns an instance of the API Gateway REST API created by the pattern.| +|certificate|[certificatemanager.ICertificate](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-certificatemanager.ICertificate.html)| THe certificate used by the construct (whether create by the construct or provided by the client) + +## Default settings +Out of the box implementation of the Construct without any override will set the following defaults: + +### Amazon Route53 +* Adds an ALIAS record to the new or provided Hosted Zone that routes to the construct's API Gateway + +### Amazon API Gateway +* User provided API Gateway object is used as-is +* Sets up custom domain name mapping to API + +## Architecture + +![Architecture Diagram](architecture.png) + +*** +© Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/architecture.png b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/architecture.png new file mode 100644 index 000000000..f5281ab5b Binary files /dev/null and b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/architecture.png differ diff --git a/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/lib/index.ts b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/lib/index.ts new file mode 100755 index 000000000..cdeaedb41 --- /dev/null +++ b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/lib/index.ts @@ -0,0 +1,143 @@ +/** + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance + * with the License. A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES + * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +// Imports +import * as api from '@aws-cdk/aws-apigateway'; +import * as route53 from "@aws-cdk/aws-route53"; +import * as targets from '@aws-cdk/aws-route53-targets'; +import * as ec2 from '@aws-cdk/aws-ec2'; +import * as defaults from '@aws-solutions-constructs/core'; +import * as certificatemanager from '@aws-cdk/aws-certificatemanager'; +// Note: To ensure CDKv2 compatibility, keep the import statement for Construct separate +import { Construct } from '@aws-cdk/core'; + +/** + * The properties for the Route53ToApiGateway class. + */ +export interface Route53ToApiGatewayProps { + /** + * Whether to create a public or private API. This value has implications + * for the VPC, the type of Hosted Zone and the Application Load Balancer + * + * @default - None + */ + readonly publicApi: boolean + /** + * Optional custom properties for a new Private Hosted Zone. Cannot be specified for a + * public API. Cannot specify a VPC, it will use the VPC in existingVpc or the VPC created by the construct. + * Providing both this and existingHostedZoneInterface is an error. + * + * @default - None + */ + readonly privateHostedZoneProps?: route53.PrivateHostedZoneProps | any, + /** + * Existing Public or Private Hosted Zone. If a Private Hosted Zone, must + * exist in the same VPC specified in existingVpc + * + * @default - None + */ + readonly existingHostedZoneInterface?: route53.IHostedZone, + /** + * An existing VPC. If an existing Private Hosted Zone is provided, + * this value must be the VPC associated with those resources. + * + * @default - None + */ + readonly existingVpc?: ec2.IVpc, + /** + * The existing API Gateway instance that will be protected with the Route 53 hosted zone. + * + * @default - None + */ + readonly existingApiGatewayInterface: api.IRestApi, + /** + * An existing AWS Certificate Manager certificate for your custom domain name. + * + * @defualt - None + */ + readonly existingCertificateInterface: certificatemanager.ICertificate; +} + +/** + * @summary The Route53ToApiGateway class. + */ +export class Route53ToApiGateway extends Construct { + public readonly hostedZone: route53.IHostedZone; + public readonly vpc?: ec2.IVpc; + public readonly apiGateway: api.RestApi; + public readonly certificate: certificatemanager.ICertificate; + /** + * @summary Constructs a new instance of the Route53ToApiGateway class. + * @param {cdk.App} scope - represents the scope for all the resources. + * @param {string} id - this is a a scope-unique id. + * @param {Route53ToApiGatewayProps} props - user provided props for the construct + * @since 0.8.0 + * @access public + */ + constructor(scope: Construct, id: string, props: Route53ToApiGatewayProps) { + super(scope, id); + defaults.CheckProps(props); + + this.certificate = props.existingCertificateInterface; + + if (props.existingVpc) { + this.vpc = props.existingVpc; + } + + // Existing Public or Private Hosted Zone + if (props.existingHostedZoneInterface) { + this.hostedZone = props.existingHostedZoneInterface; + + if (props.existingVpc) { + throw new Error('Cannot provide an existing VPC to an existing Private Hosted Zone.'); + } + if (props.privateHostedZoneProps) { + throw new Error('Must provide either existingHostedZoneInterface or privateHostedZoneProps, but not both.'); + } + } else { // Creating a Private Hosted Zone + if (props.publicApi) { + throw new Error('Public APIs require an existingHostedZone be passed in the Props object.'); + } else { + if (!props.privateHostedZoneProps) { + throw new Error('Must provide either existingHostedZoneInterface or privateHostedZoneProps.'); + } + if (props.privateHostedZoneProps.vpc) { + throw new Error('All VPC specs must be provided at the Construct level in Route53ToApiGatewayProps.'); + } + if (!props.privateHostedZoneProps.zoneName) { + throw new Error('Must supply zoneName for Private Hosted Zone Props.'); + } + if ( !this.vpc ) { + throw new Error('Must specify an existingVPC for the Private Hosted Zone in the construct props.'); + } + const manufacturedProps: route53.PrivateHostedZoneProps = defaults.overrideProps(props.privateHostedZoneProps, { vpc: this.vpc }); + this.hostedZone = new route53.PrivateHostedZone(this, `${id}-zone`, manufacturedProps); + } + } + + // Convert IRestApi to RestApi + this.apiGateway = props.existingApiGatewayInterface as api.RestApi; + + // Add custom domain name in API Gateway + this.apiGateway.addDomainName('CustomDomainName', { + domainName: this.hostedZone.zoneName, + certificate: this.certificate + }); + + // Create A Record in custom domain to route traffic to API Gateway + new route53.ARecord(this, 'CustomDomainAliasRecord', { + zone: this.hostedZone, + target: route53.RecordTarget.fromAlias(new targets.ApiGateway(this.apiGateway)) + }); + } +} \ No newline at end of file diff --git a/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/package.json b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/package.json new file mode 100755 index 000000000..aba7a561b --- /dev/null +++ b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/package.json @@ -0,0 +1,99 @@ +{ + "name": "@aws-solutions-constructs/aws-route53-apigateway", + "version": "0.0.0", + "description": "CDK constructs for connecting an Amazon Route53 domain to an API Gateway.", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/awslabs/aws-solutions-constructs.git", + "directory": "source/patterns/@aws-solutions-constructs/aws-route53-apigateway" + }, + "author": { + "name": "Amazon Web Services", + "url": "https://aws.amazon.com", + "organization": true + }, + "license": "Apache-2.0", + "scripts": { + "build": "tsc -b .", + "lint": "eslint -c ../eslintrc.yml --ext=.js,.ts . && tslint --project .", + "lint-fix": "eslint -c ../eslintrc.yml --ext=.js,.ts --fix .", + "test": "jest --coverage", + "clean": "tsc -b --clean", + "watch": "tsc -b -w", + "integ": "cdk-integ", + "integ-no-clean": "cdk-integ --no-clean", + "integ-assert": "cdk-integ-assert", + "jsii": "jsii", + "jsii-pacmak": "jsii-pacmak", + "build+lint+test": "npm run jsii && npm run lint && npm test && npm run integ-assert", + "snapshot-update": "npm run jsii && npm test -- -u && npm run integ-assert" + }, + "jsii": { + "outdir": "dist", + "targets": { + "java": { + "package": "software.amazon.awsconstructs.services.route53apigateway", + "maven": { + "groupId": "software.amazon.awsconstructs", + "artifactId": "route53apigateway" + } + }, + "dotnet": { + "namespace": "Amazon.SolutionsConstructs.AWS.Route53ApiGateway", + "packageId": "Amazon.SolutionsConstructs.AWS.Route53ApiGateway", + "signAssembly": true, + "iconUrl": "https://raw.githubusercontent.com/aws/aws-cdk/master/logo/default-256-dark.png" + }, + "python": { + "distName": "aws-solutions-constructs.aws-route53-apigateway", + "module": "aws_solutions_constructs.aws_route53_apigateway" + } + } + }, + "dependencies": { + "@aws-cdk/aws-ec2": "0.0.0", + "@aws-cdk/aws-apigateway": "0.0.0", + "@aws-cdk/aws-certificatemanager": "0.0.0", + "@aws-cdk/core": "0.0.0", + "@aws-cdk/aws-route53": "0.0.0", + "@aws-cdk/aws-route53-targets": "0.0.0", + "@aws-solutions-constructs/core": "0.0.0", + "constructs": "^3.2.0" + }, + "devDependencies": { + "@aws-cdk/assert": "0.0.0", + "@types/jest": "^26.0.22", + "@types/node": "^10.3.0", + "prettier": "^2.5.1" + }, + "jest": { + "moduleFileExtensions": [ + "js" + ], + "coverageReporters": [ + "text", + [ + "lcov", + { + "projectRoot": "../../../../" + } + ] + ] + }, + "peerDependencies": { + "@aws-cdk/aws-apigateway": "0.0.0", + "@aws-cdk/core": "0.0.0", + "@aws-solutions-constructs/core": "0.0.0", + "constructs": "^3.2.0" + }, + "keywords": [ + "aws", + "cdk", + "awscdk", + "AWS Solutions Constructs", + "Amazon API Gateway", + "Amazon Route 53" + ] +} \ No newline at end of file diff --git a/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/test/integ.dummyTest.expected.json b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/test/integ.dummyTest.expected.json new file mode 100644 index 000000000..175a173b4 --- /dev/null +++ b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/test/integ.dummyTest.expected.json @@ -0,0 +1,257 @@ +{ + "Description": "Dummy Integration Test for aws-route53-apigateway", + "Resources": { + "ApiAccessLogGroupCEA70788": { + "Type": "AWS::Logs::LogGroup", + "UpdateReplacePolicy": "Retain", + "DeletionPolicy": "Retain", + "Metadata": { + "cfn_nag": { + "rules_to_suppress": [ + { + "id": "W86", + "reason": "Retention period for CloudWatchLogs LogGroups are set to 'Never Expire' to preserve customer data indefinitely" + }, + { + "id": "W84", + "reason": "By default CloudWatchLogs LogGroups data is encrypted using the CloudWatch server-side encryption keys (AWS Managed Keys)" + } + ] + } + } + }, + "RestApi0C43BF4B": { + "Type": "AWS::ApiGateway::RestApi", + "Properties": { + "EndpointConfiguration": { + "Types": [ + "REGIONAL" + ] + }, + "Name": "RestApi" + } + }, + "RestApiDeployment180EC50303f556aa2d7ddf6a650ba4d72f3e85ac": { + "Type": "AWS::ApiGateway::Deployment", + "Properties": { + "RestApiId": { + "Ref": "RestApi0C43BF4B" + }, + "Description": "Automatically created by the RestApi construct" + }, + "DependsOn": [ + "RestApiGET0F59260B" + ], + "Metadata": { + "cfn_nag": { + "rules_to_suppress": [ + { + "id": "W45", + "reason": "ApiGateway has AccessLogging enabled in AWS::ApiGateway::Stage resource, but cfn_nag checkes for it in AWS::ApiGateway::Deployment resource" + } + ] + } + } + }, + "RestApiDeploymentStageprod3855DE66": { + "Type": "AWS::ApiGateway::Stage", + "Properties": { + "RestApiId": { + "Ref": "RestApi0C43BF4B" + }, + "AccessLogSetting": { + "DestinationArn": { + "Fn::GetAtt": [ + "ApiAccessLogGroupCEA70788", + "Arn" + ] + }, + "Format": "{\"requestId\":\"$context.requestId\",\"ip\":\"$context.identity.sourceIp\",\"user\":\"$context.identity.user\",\"caller\":\"$context.identity.caller\",\"requestTime\":\"$context.requestTime\",\"httpMethod\":\"$context.httpMethod\",\"resourcePath\":\"$context.resourcePath\",\"status\":\"$context.status\",\"protocol\":\"$context.protocol\",\"responseLength\":\"$context.responseLength\"}" + }, + "DeploymentId": { + "Ref": "RestApiDeployment180EC50303f556aa2d7ddf6a650ba4d72f3e85ac" + }, + "MethodSettings": [ + { + "DataTraceEnabled": false, + "HttpMethod": "*", + "LoggingLevel": "INFO", + "ResourcePath": "/*" + } + ], + "StageName": "prod", + "TracingEnabled": true + } + }, + "RestApiGET0F59260B": { + "Type": "AWS::ApiGateway::Method", + "Properties": { + "HttpMethod": "GET", + "ResourceId": { + "Fn::GetAtt": [ + "RestApi0C43BF4B", + "RootResourceId" + ] + }, + "RestApiId": { + "Ref": "RestApi0C43BF4B" + }, + "AuthorizationType": "AWS_IAM", + "Integration": { + "Type": "MOCK" + } + } + }, + "RestApiUsagePlan6E1C537A": { + "Type": "AWS::ApiGateway::UsagePlan", + "Properties": { + "ApiStages": [ + { + "ApiId": { + "Ref": "RestApi0C43BF4B" + }, + "Stage": { + "Ref": "RestApiDeploymentStageprod3855DE66" + }, + "Throttle": {} + } + ] + } + }, + "LambdaRestApiCloudWatchRoleF339D4E6": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "apigateway.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:DescribeLogGroups", + "logs:DescribeLogStreams", + "logs:PutLogEvents", + "logs:GetLogEvents", + "logs:FilterLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":logs:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":*" + ] + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "LambdaRestApiCloudWatchRolePolicy" + } + ] + } + }, + "LambdaRestApiAccount": { + "Type": "AWS::ApiGateway::Account", + "Properties": { + "CloudWatchRoleArn": { + "Fn::GetAtt": [ + "LambdaRestApiCloudWatchRoleF339D4E6", + "Arn" + ] + } + }, + "DependsOn": [ + "RestApi0C43BF4B" + ] + } + }, + "Outputs": { + "RestApiEndpoint0551178A": { + "Value": { + "Fn::Join": [ + "", + [ + "https://", + { + "Ref": "RestApi0C43BF4B" + }, + ".execute-api.", + { + "Ref": "AWS::Region" + }, + ".", + { + "Ref": "AWS::URLSuffix" + }, + "/", + { + "Ref": "RestApiDeploymentStageprod3855DE66" + }, + "/" + ] + ] + } + } + }, + "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/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/test/integ.dummyTest.ts b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/test/integ.dummyTest.ts new file mode 100644 index 000000000..cd4e0b97f --- /dev/null +++ b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/test/integ.dummyTest.ts @@ -0,0 +1,36 @@ +/** + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance + * with the License. A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES + * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +// Imports +import { App, Stack } from "@aws-cdk/core"; +import { generateIntegStackName } from '@aws-solutions-constructs/core'; +import * as defaults from '@aws-solutions-constructs/core'; + +// Setup +const app = new App(); +const stack = new Stack(app, generateIntegStackName(__filename), {}); + +stack.templateOptions.description = 'Dummy Integration Test for aws-route53-apigateway'; + +// This is an dummy integ test in order to bypass the CodeBuild integ test scans. +// Route53ToApiGateway construct requires a legitimate DNS and certificate to be deployed. +// If a fake DNS and certificate is provided, the deployment will hang and cause it to fail. +// Legitimate DNS and certificate cannot be provided in integ tests as it is user specific +// and will need to be regenerated. + +// Create dummy integ with at least one resource to pass CFN scan +const [restApi] = defaults.RegionalRestApi(stack); +restApi.root.addMethod('GET'); + +// Synth +app.synth(); diff --git a/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/test/test.route53-apigateway.test.ts b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/test/test.route53-apigateway.test.ts new file mode 100755 index 000000000..7e5c40680 --- /dev/null +++ b/source/patterns/@aws-solutions-constructs/aws-route53-apigateway/test/test.route53-apigateway.test.ts @@ -0,0 +1,360 @@ +/** + * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance + * with the License. A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES + * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +// Imports +import * as cdk from "@aws-cdk/core"; +import { Route53ToApiGateway, Route53ToApiGatewayProps } from "../lib"; +import * as route53 from "@aws-cdk/aws-route53"; +import * as defaults from "@aws-solutions-constructs/core"; +import * as acm from "@aws-cdk/aws-certificatemanager"; +import "@aws-cdk/assert/jest"; + +// Deploying Public/Private Existing Hosted Zones +function deployApi( + stack: cdk.Stack, + publicApi: boolean +) { + const [restApi] = defaults.RegionalRestApi(stack); + restApi.root.addMethod('GET'); + + const domainName = "www.test-example.com"; + + let newZone: route53.PublicHostedZone | route53.PrivateHostedZone; + + if (publicApi) { + newZone = new route53.PublicHostedZone(stack, "new-zone", { + zoneName: domainName, + }); + } else { + const vpc = defaults.buildVpc(stack, { + defaultVpcProps: defaults.DefaultPublicPrivateVpcProps(), + constructVpcProps: { + enableDnsHostnames: true, + enableDnsSupport: true, + cidr: "172.168.0.0/16", + }, + }); + + newZone = new route53.PrivateHostedZone(stack, "new-zone", { + zoneName: domainName, + vpc + }); + } + + const certificate = acm.Certificate.fromCertificateArn( + stack, + "fake-cert", + "arn:aws:acm:us-east-1:123456789012:certificate/11112222-3333-1234-1234-123456789012" + ); + + // Definitions + const props: Route53ToApiGatewayProps = { + publicApi, + existingHostedZoneInterface: newZone, + existingApiGatewayInterface: restApi, + existingCertificateInterface: certificate, + }; + + return new Route53ToApiGateway(stack, "api-stack", props); +} + +// -------------------------------------------------------------- +// Check for pattern props +// -------------------------------------------------------------- +test("Test for default params construct props", () => { + // Initial Setup + const stack = new cdk.Stack(); + const construct = deployApi(stack, false); + + // Assertion + expect(construct.apiGateway).not.toBeNull(); + expect(construct.hostedZone).not.toBeNull(); + expect(construct.vpc).not.toBeNull(); + expect(construct.certificate).not.toBeNull(); +}); + +// -------------------------------------------------------------- +// Check for errors when creating a private hosted zone +// -------------------------------------------------------------- +test("Test for errors when creating a private hosted zone", () => { + // Initial Setup + const stack = new cdk.Stack(); + const [restApi] = defaults.RegionalRestApi(stack); + const domainName = "www.test-example.com"; + + const vpc = defaults.buildVpc(stack, { + defaultVpcProps: defaults.DefaultPublicPrivateVpcProps(), + constructVpcProps: { + enableDnsHostnames: true, + enableDnsSupport: true, + cidr: "172.168.0.0/16", + }, + }); + + const newZone = new route53.PrivateHostedZone(stack, "new-zone", { + zoneName: domainName, + vpc + }); + + const certificate = acm.Certificate.fromCertificateArn( + stack, + "fake-cert", + "arn:aws:acm:us-east-1:123456789012:certificate/11112222-3333-1234-1234-123456789012" + ); + + let app = () => + new Route53ToApiGateway(stack, "api-stack1", { + publicApi: true, + existingApiGatewayInterface: restApi, + existingCertificateInterface: certificate + }); + // Assertion 1 + expect(app).toThrowError( + "Public APIs require an existingHostedZone be passed in the Props object." + ); + + app = () => + new Route53ToApiGateway(stack, "api-stack2", { + publicApi: false, + existingApiGatewayInterface: restApi, + existingCertificateInterface: certificate + }); + + // Assertion 2 + expect(app).toThrowError( + "Must provide either existingHostedZoneInterface or privateHostedZoneProps." + ); + + app = () => + new Route53ToApiGateway(stack, "api-stack3", { + publicApi: false, + privateHostedZoneProps: { + zoneName: "test-example.com", + vpc, + }, + existingApiGatewayInterface: restApi, + existingCertificateInterface: certificate + }); + + // Assertion 3 + expect(app).toThrowError( + "All VPC specs must be provided at the Construct level in Route53ToApiGatewayProps" + ); + + app = () => + new Route53ToApiGateway(stack, "api-stack4", { + publicApi: false, + existingHostedZoneInterface: newZone, + existingVpc: vpc, + existingApiGatewayInterface: restApi, + existingCertificateInterface: certificate + }); + + // Assertion 4 + expect(app).toThrowError( + "Cannot provide an existing VPC to an existing Private Hosted Zone." + ); + + app = () => + new Route53ToApiGateway(stack, "api-stack5", { + publicApi: false, + existingHostedZoneInterface: newZone, + existingApiGatewayInterface: restApi, + privateHostedZoneProps: { + domainName: "test-example.com" + }, + existingCertificateInterface: certificate + }); + + // Assertion 5 + expect(app).toThrowError( + "Must provide either existingHostedZoneInterface or privateHostedZoneProps, but not both." + ); + + app = () => + new Route53ToApiGateway(stack, "api-stack6", { + publicApi: false, + privateHostedZoneProps: { + domainName: "test.example.com" + }, + existingApiGatewayInterface: restApi, + existingCertificateInterface: certificate + }); + + // Assertion 6 + expect(app).toThrowError( + 'Must supply zoneName for Private Hosted Zone Props.' + ); + + app = () => + new Route53ToApiGateway(stack, "api-stack7", { + publicApi: false, + privateHostedZoneProps: { + zoneName: "test.example.com" + }, + existingApiGatewayInterface: restApi, + existingCertificateInterface: certificate + }); + + // Assertion 7 + expect(app).toThrowError( + 'Must specify an existingVPC for the Private Hosted Zone in the construct props.' + ); +}); + +// -------------------------------------------------------------- +// Check for providing private hosted zone props +// -------------------------------------------------------------- +test("Test for providing private hosted zone props", () => { + // Initial Setup + const stack = new cdk.Stack(); + const [restApi] = defaults.RegionalRestApi(stack); + restApi.root.addMethod('GET'); + + const domainName = "www.private-zone.com"; + + const vpc = defaults.buildVpc(stack, { + defaultVpcProps: defaults.DefaultPublicPrivateVpcProps(), + constructVpcProps: { + enableDnsHostnames: true, + enableDnsSupport: true, + cidr: "172.168.0.0/16", + }, + }); + + const certificate = acm.Certificate.fromCertificateArn( + stack, + "fake-cert", + "arn:aws:acm:us-east-1:123456789012:certificate/11112222-3333-1234-1234-123456789012" + ); + + new Route53ToApiGateway(stack, "api-stack1", { + publicApi: false, + existingApiGatewayInterface: restApi, + privateHostedZoneProps: { + zoneName: domainName, + }, + existingVpc: vpc, + existingCertificateInterface: certificate + }); + + expect(stack).toHaveResource("AWS::Route53::HostedZone", { + Name: "www.private-zone.com.", + VPCs: [ + { + VPCId: { + Ref: "Vpc8378EB38", + }, + VPCRegion: { + Ref: "AWS::Region", + }, + }, + ], + }); +}); + +// -------------------------------------------------------------- +// Check for A record creation in Public Hosted Zone +// -------------------------------------------------------------- +test("Integration test for A record creation in Public Hosted Zone ", () => { + // Initial Setup + const stack = new cdk.Stack(); + deployApi(stack, true); + + // Assertions + expect(stack).toHaveResource("AWS::Route53::RecordSet", { + Name: "www.test-example.com.", + Type: "A", + AliasTarget: { + DNSName: { + "Fn::GetAtt": [ + "RestApiCustomDomainName94F28E16", + "RegionalDomainName", + ], + }, + HostedZoneId: { + "Fn::GetAtt": [ + "RestApiCustomDomainName94F28E16", + "RegionalHostedZoneId", + ], + }, + }, + HostedZoneId: { + Ref: "newzone1D011936", + }, + }); + + expect(stack).toHaveResource("AWS::ApiGateway::RestApi", { + EndpointConfiguration: { + Types: [ + "REGIONAL" + ] + }, + Name: "RestApi" + }); +}); + +// -------------------------------------------------------------- +// Check for A record creation in Private Hosted Zone +// -------------------------------------------------------------- +test("Integration test for A record creation in Private Hosted Zone ", () => { + // Initial Setup + const stack = new cdk.Stack(); + deployApi(stack, false); + + // Assertions + expect(stack).toHaveResource("AWS::Route53::RecordSet", { + Name: "www.test-example.com.", + Type: "A", + AliasTarget: { + DNSName: { + "Fn::GetAtt": [ + "RestApiCustomDomainName94F28E16", + "RegionalDomainName", + ], + }, + HostedZoneId: { + "Fn::GetAtt": [ + "RestApiCustomDomainName94F28E16", + "RegionalHostedZoneId", + ], + }, + }, + HostedZoneId: { + Ref: "newzone1D011936", + }, + }); + + expect(stack).toHaveResource("AWS::Route53::HostedZone", { + Name: "www.test-example.com.", + VPCs: [ + { + VPCId: { + Ref: "Vpc8378EB38", + }, + VPCRegion: { + Ref: "AWS::Region", + }, + }, + ], + }); + + expect(stack).toHaveResource("AWS::ApiGateway::RestApi", { + EndpointConfiguration: { + Types: [ + "REGIONAL" + ] + }, + Name: "RestApi" + }); +}); \ No newline at end of file