diff --git a/.gitpod.yml b/.gitpod.yml new file mode 100644 index 0000000000000..5491cbd291d9e --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,7 @@ +image: jsii/superchain +tasks: + - init: yarn build --skip-test --no-bail + +vscode: + extensions: + - dbaeumer.vscode-eslint@2.1.5:9Wg0Glx/TwD8ElFBg+FKcQ== diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8600b28cba8f2..b32319c73af1c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -47,7 +47,31 @@ and let us know if it's not up-to-date (even better, submit a PR with your corr ## Getting Started -For day-to-day development and normal contributions, the following SDKs and tools are required: +### Gitpod + +For setting up a local development environment, +we recommend using [Gitpod](http://gitpod.io) - +a service that allows you to spin up an in-browser +Visual Studio Code-compatible editor, +with everything set up and ready to go for CDK development. +Just click the button below to create your private workspace: + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/aws/aws-cdk) + +This will start a new Gitpod workspace, +and immediately kick off a build of the CDK code. +Once it's done (it takes around an hour, unfortunately), +you can work on any package that you want to modify, +as described in ['Quick Iteration'](#quick-iteration) below. + +Gitpod is free for 50 hours per month - +make sure to stop your workspace when you're done +(you can always resume it later, and it won't need to run the build again). + +### Local dependencies + +If you don't want to use Gitpod, +you need to have the following SDKs and tools locally: - [Node.js >= 10.13.0](https://nodejs.org/download/release/latest-v10.x/) - We recommend using a version in [Active LTS](https://nodejs.org/en/about/releases/) diff --git a/README.md b/README.md index 4d7778e5752ca..fce633e49f010 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ ![Build Status](https://codebuild.us-east-1.amazonaws.com/badges?uuid=eyJlbmNyeXB0ZWREYXRhIjoiSy9rWmVENzRDbXBoVlhYaHBsNks4OGJDRXFtV1IySmhCVjJoaytDU2dtVWhhVys3NS9Odk5DbC9lR2JUTkRvSWlHSXZrNVhYQ3ZsaUJFY3o4OERQY1pnPSIsIml2UGFyYW1ldGVyU3BlYyI6IlB3ODEyRW9KdU0yaEp6NDkiLCJtYXRlcmlhbFNldFNlcmlhbCI6MX0%3D&branch=master) [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.svg)](https://gitter.im/awslabs/aws-cdk) +[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/aws/aws-cdk) [![NPM version](https://badge.fury.io/js/aws-cdk.svg)](https://badge.fury.io/js/aws-cdk) [![PyPI version](https://badge.fury.io/py/aws-cdk.core.svg)](https://badge.fury.io/py/aws-cdk.core) [![NuGet version](https://badge.fury.io/nu/Amazon.CDK.svg)](https://badge.fury.io/nu/Amazon.CDK) diff --git a/packages/@aws-cdk/aws-cloudfront/package.json b/packages/@aws-cdk/aws-cloudfront/package.json index 0a7bb14bfb821..bec6bac7a5b35 100644 --- a/packages/@aws-cdk/aws-cloudfront/package.json +++ b/packages/@aws-cdk/aws-cloudfront/package.json @@ -64,7 +64,7 @@ "devDependencies": { "@aws-cdk/assert": "0.0.0", "@types/nodeunit": "^0.0.31", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", "cfn2ts": "0.0.0", diff --git a/packages/@aws-cdk/aws-cloudtrail/package.json b/packages/@aws-cdk/aws-cloudtrail/package.json index 5cc1f63af976d..fbe197aabf380 100644 --- a/packages/@aws-cdk/aws-cloudtrail/package.json +++ b/packages/@aws-cdk/aws-cloudtrail/package.json @@ -64,7 +64,7 @@ "devDependencies": { "@aws-cdk/assert": "0.0.0", "@types/nodeunit": "^0.0.31", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", "cfn2ts": "0.0.0", diff --git a/packages/@aws-cdk/aws-codebuild/package.json b/packages/@aws-cdk/aws-codebuild/package.json index 77829647d1092..dc1cc13f744d8 100644 --- a/packages/@aws-cdk/aws-codebuild/package.json +++ b/packages/@aws-cdk/aws-codebuild/package.json @@ -70,7 +70,7 @@ "@aws-cdk/aws-sns": "0.0.0", "@aws-cdk/aws-sqs": "0.0.0", "@types/nodeunit": "^0.0.31", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", "cfn2ts": "0.0.0", diff --git a/packages/@aws-cdk/aws-codecommit/package.json b/packages/@aws-cdk/aws-codecommit/package.json index 41b634411314f..a62c98e699e6d 100644 --- a/packages/@aws-cdk/aws-codecommit/package.json +++ b/packages/@aws-cdk/aws-codecommit/package.json @@ -70,7 +70,7 @@ "@aws-cdk/assert": "0.0.0", "@aws-cdk/aws-sns": "0.0.0", "@types/nodeunit": "^0.0.31", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", "cfn2ts": "0.0.0", diff --git a/packages/@aws-cdk/aws-dynamodb/package.json b/packages/@aws-cdk/aws-dynamodb/package.json index be0ac34ef307f..694114f8f1a41 100644 --- a/packages/@aws-cdk/aws-dynamodb/package.json +++ b/packages/@aws-cdk/aws-dynamodb/package.json @@ -65,7 +65,7 @@ "devDependencies": { "@aws-cdk/assert": "0.0.0", "@types/jest": "^25.2.2", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "aws-sdk-mock": "^5.1.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", diff --git a/packages/@aws-cdk/aws-eks/package.json b/packages/@aws-cdk/aws-eks/package.json index 0524927557dc9..791a6304f09c5 100644 --- a/packages/@aws-cdk/aws-eks/package.json +++ b/packages/@aws-cdk/aws-eks/package.json @@ -64,7 +64,7 @@ "devDependencies": { "@aws-cdk/assert": "0.0.0", "@types/nodeunit": "^0.0.31", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", "cfn2ts": "0.0.0", diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/.eslintrc.js b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/.eslintrc.js new file mode 100644 index 0000000000000..1b28bad193ceb --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/.eslintrc.js @@ -0,0 +1,2 @@ +const baseConfig = require('../../../tools/cdk-build-tools/config/eslintrc'); +module.exports = baseConfig; diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/.gitignore b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/.gitignore new file mode 100644 index 0000000000000..0c82e8606a62b --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/.gitignore @@ -0,0 +1,19 @@ +*.js +tsconfig.json +*.js.map +*.d.ts +*.generated.ts +dist +lib/generated/resources.ts +.jsii + +.LAST_BUILD +.nyc_output +coverage +nyc.config.js +.LAST_PACKAGE +*.snk +.cdk.staging +!.eslintrc.js + +!jest.config.js \ No newline at end of file diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/.npmignore b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/.npmignore new file mode 100644 index 0000000000000..6112f38ab3d62 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/.npmignore @@ -0,0 +1,22 @@ +# Don't include original .ts files when doing `npm pack` +*.ts +!*.d.ts +coverage +.nyc_output +*.tgz + +dist +.LAST_PACKAGE +.LAST_BUILD +!*.js + +# Include .jsii +!.jsii + +*.snk +*.tsbuildinfo + +tsconfig.json +.eslintrc.js + +jest.config.js \ No newline at end of file diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/LICENSE b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/LICENSE new file mode 100644 index 0000000000000..b71ec1688783a --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018-2020 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. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/NOTICE b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/NOTICE new file mode 100644 index 0000000000000..bfccac9a7f69c --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/NOTICE @@ -0,0 +1,2 @@ +AWS Cloud Development Kit (AWS CDK) +Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/README.md b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/README.md new file mode 100644 index 0000000000000..874938a793b90 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/README.md @@ -0,0 +1,24 @@ +# Actions for AWS Elastic Load Balancing V2 + +--- + +![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge) + +--- + + +This package contains integration actions for ELBv2. See the README of the `@aws-cdk/aws-elasticloadbalancingv2` library. + +## Cognito + +ELB allows for requests to be authenticated against a Cognito user pool using +the `AuthenticateCognitoAction`. For details on the setup's requirements, +read [Prepare to use Amazon +Cognito](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-authenticate-users.html#cognito-requirements). +Here's an example: + +[Example of using AuthenticateCognitoAction](test/integ.cognito.lit.ts) + +> NOTE: this example seems incomplete, I was not able to get the redirect back to the +Load Balancer after authentication working. Would love some pointers on what a full working +setup actually looks like! diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/jest.config.js b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/jest.config.js new file mode 100644 index 0000000000000..c68c147dd5514 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/jest.config.js @@ -0,0 +1,10 @@ +const baseConfig = require('../../../tools/cdk-build-tools/config/jest.config'); +module.exports = { + ...baseConfig, + coverageThreshold: { + global: { + ...baseConfig.coverageThreshold.global, + branches: 70, + }, + }, +}; diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/lib/cognito-action.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/lib/cognito-action.ts new file mode 100644 index 0000000000000..425e8e8f29a31 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/lib/cognito-action.ts @@ -0,0 +1,92 @@ +import * as cognito from '@aws-cdk/aws-cognito'; +import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2'; +import { Duration } from '@aws-cdk/core'; + +/** + * Properties for AuthenticateCognitoAction + */ +export interface AuthenticateCognitoActionProps { + /** + * What action to execute next + * + * Multiple actions form a linked chain; the chain must always terminate in a + * (weighted)forward, fixedResponse or redirect action. + */ + readonly next: elbv2.ListenerAction; + + /** + * The Amazon Cognito user pool. + */ + readonly userPool: cognito.IUserPool; + + /** + * The Amazon Cognito user pool client. + */ + readonly userPoolClient: cognito.IUserPoolClient; + + /** + * The domain prefix or fully-qualified domain name of the Amazon Cognito user pool. + */ + readonly userPoolDomain: cognito.IUserPoolDomain; + + /** + * The query parameters (up to 10) to include in the redirect request to the authorization endpoint. + * + * @default - No extra parameters + */ + readonly authenticationRequestExtraParams?: Record; + + /** + * The behavior if the user is not authenticated. + * + * @default UnauthenticatedAction.AUTHENTICATE + */ + readonly onUnauthenticatedRequest?: elbv2.UnauthenticatedAction; + + /** + * The set of user claims to be requested from the IdP. + * + * To verify which scope values your IdP supports and how to separate multiple values, see the documentation for your IdP. + * + * @default "openid" + */ + readonly scope?: string; + + /** + * The name of the cookie used to maintain session information. + * + * @default "AWSELBAuthSessionCookie" + */ + readonly sessionCookieName?: string; + + /** + * The maximum duration of the authentication session. + * + * @default Duration.days(7) + */ + readonly sessionTimeout?: Duration; +} + +/** + * A Listener Action to authenticate with Cognito + */ +export class AuthenticateCognitoAction extends elbv2.ListenerAction { + /** + * Authenticate using an identity provide (IdP) that is compliant with OpenID Connect (OIDC) + */ + constructor(options: AuthenticateCognitoActionProps) { + super({ + type: 'authenticate-cognito', + authenticateCognitoConfig: { + userPoolArn: options.userPool.userPoolArn, + userPoolClientId: options.userPoolClient.userPoolClientId, + userPoolDomain: options.userPoolDomain.domainName, + authenticationRequestExtraParams: options.authenticationRequestExtraParams, + onUnauthenticatedRequest: options.onUnauthenticatedRequest, + scope: options.scope, + sessionCookieName: options.sessionCookieName, + sessionTimeout: options.sessionTimeout?.toSeconds(), + }, + }, options.next); + } +} diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/lib/index.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/lib/index.ts new file mode 100644 index 0000000000000..8863714d5d908 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/lib/index.ts @@ -0,0 +1 @@ +export * from './cognito-action'; \ No newline at end of file diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/package.json b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/package.json new file mode 100644 index 0000000000000..c1a5a92fb1053 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/package.json @@ -0,0 +1,98 @@ +{ + "name": "@aws-cdk/aws-elasticloadbalancingv2-actions", + "version": "0.0.0", + "description": "Integration actions for AWS ElasticLoadBalancingV2", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "jsii": { + "outdir": "dist", + "targets": { + "java": { + "package": "software.amazon.awscdk.services.elasticloadbalancingv2.actions", + "maven": { + "groupId": "software.amazon.awscdk", + "artifactId": "elasticloadbalancingv2-actions" + } + }, + "dotnet": { + "namespace": "Amazon.CDK.AWS.ElasticLoadBalancingV2.Actions", + "packageId": "Amazon.CDK.AWS.ElasticLoadBalancingV2.Actions", + "signAssembly": true, + "assemblyOriginatorKeyFile": "../../key.snk", + "iconUrl": "https://raw.githubusercontent.com/aws/aws-cdk/master/logo/default-256-dark.png" + }, + "python": { + "distName": "aws-cdk.aws-elasticloadbalancingv2-actions", + "module": "aws_cdk.aws_elasticloadbalancingv2_actions" + } + } + }, + "repository": { + "type": "git", + "url": "https://github.com/aws/aws-cdk.git", + "directory": "packages/@aws-cdk/aws-elasticloadbalancingv2-actions" + }, + "scripts": { + "build": "cdk-build", + "watch": "cdk-watch", + "lint": "cdk-lint", + "test": "cdk-test", + "integ": "cdk-integ", + "pkglint": "pkglint -f", + "package": "cdk-package", + "awslint": "cdk-awslint", + "cfn2ts": "cfn2ts", + "build+test+package": "npm run build+test && npm run package", + "build+test": "npm run build && npm test", + "compat": "cdk-compat" + }, + "keywords": [ + "aws", + "cdk", + "cloudlib", + "aws-cloudlib", + "aws-clib" + ], + "author": { + "name": "Amazon Web Services", + "url": "https://aws.amazon.com", + "organization": true + }, + "license": "Apache-2.0", + "devDependencies": { + "@aws-cdk/assert": "0.0.0", + "cdk-build-tools": "0.0.0", + "cdk-integ-tools": "0.0.0", + "jest": "^25.5.2", + "pkglint": "0.0.0" + }, + "dependencies": { + "@aws-cdk/aws-ec2": "0.0.0", + "@aws-cdk/aws-elasticloadbalancingv2": "0.0.0", + "@aws-cdk/aws-iam": "0.0.0", + "@aws-cdk/aws-cognito": "0.0.0", + "@aws-cdk/core": "0.0.0", + "constructs": "^3.0.2" + }, + "homepage": "https://github.com/aws/aws-cdk", + "peerDependencies": { + "@aws-cdk/aws-ec2": "0.0.0", + "@aws-cdk/aws-elasticloadbalancingv2": "0.0.0", + "@aws-cdk/aws-iam": "0.0.0", + "@aws-cdk/aws-cognito": "0.0.0", + "@aws-cdk/core": "0.0.0", + "constructs": "^3.0.2" + }, + "engines": { + "node": ">= 10.13.0 <13 || >=13.7.0" + }, + "stability": "stable", + "maturity": "stable", + "awslint": {}, + "awscdkio": { + "announce": false + }, + "cdk-build": { + "jest": true + } +} diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/test/cognito.test.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/test/cognito.test.ts new file mode 100644 index 0000000000000..0917c80c5d039 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/test/cognito.test.ts @@ -0,0 +1,60 @@ +import { expect, haveResource } from '@aws-cdk/assert'; +import * as cognito from '@aws-cdk/aws-cognito'; +import * as ec2 from '@aws-cdk/aws-ec2'; +import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2'; +import { Stack } from '@aws-cdk/core'; +import * as actions from '../lib'; + +test('Cognito Action', () => { + // GIVEN + const stack = new Stack(); + const vpc = new ec2.Vpc(stack, 'Stack'); + const lb = new elbv2.ApplicationLoadBalancer(stack, 'LB', { vpc }); + + const userPool = new cognito.UserPool(stack, 'UserPool'); + const userPoolClient = new cognito.UserPoolClient(stack, 'Client', { userPool }); + const userPoolDomain = new cognito.UserPoolDomain(stack, 'Domain', { + userPool, + cognitoDomain: { + domainPrefix: 'prefix', + }, + }); + + // WHEN + lb.addListener('Listener', { + port: 80, + defaultAction: new actions.AuthenticateCognitoAction({ + userPool, + userPoolClient, + userPoolDomain, + next: elbv2.ListenerAction.fixedResponse(200, { + contentType: 'text/plain', + messageBody: 'Authenticated', + }), + }), + }); + + // THEN + expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::Listener', { + DefaultActions: [ + { + AuthenticateCognitoConfig: { + UserPoolArn: { 'Fn::GetAtt': [ 'UserPool6BA7E5F2', 'Arn' ] }, + UserPoolClientId: { Ref: 'Client4A7F64DF' }, + UserPoolDomain: { Ref: 'Domain66AC69E0' }, + }, + Order: 1, + Type: 'authenticate-cognito', + }, + { + FixedResponseConfig: { + ContentType: 'text/plain', + MessageBody: 'Authenticated', + StatusCode: '200', + }, + Order: 2, + Type: 'fixed-response', + }, + ], + })); +}); diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/test/integ.cognito.lit.expected.json b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/test/integ.cognito.lit.expected.json new file mode 100644 index 0000000000000..ca495599afaf6 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/test/integ.cognito.lit.expected.json @@ -0,0 +1,581 @@ +{ + "Resources": { + "Stack8A423254": { + "Type": "AWS::EC2::VPC", + "Properties": { + "CidrBlock": "10.0.0.0/16", + "EnableDnsHostnames": true, + "EnableDnsSupport": true, + "InstanceTenancy": "default", + "Tags": [ + { + "Key": "Name", + "Value": "integ-cognito/Stack" + } + ] + } + }, + "StackPublicSubnet1Subnet0AD81D22": { + "Type": "AWS::EC2::Subnet", + "Properties": { + "CidrBlock": "10.0.0.0/18", + "VpcId": { + "Ref": "Stack8A423254" + }, + "AvailabilityZone": "test-region-1a", + "MapPublicIpOnLaunch": true, + "Tags": [ + { + "Key": "aws-cdk:subnet-name", + "Value": "Public" + }, + { + "Key": "aws-cdk:subnet-type", + "Value": "Public" + }, + { + "Key": "Name", + "Value": "integ-cognito/Stack/PublicSubnet1" + } + ] + } + }, + "StackPublicSubnet1RouteTable5057189D": { + "Type": "AWS::EC2::RouteTable", + "Properties": { + "VpcId": { + "Ref": "Stack8A423254" + }, + "Tags": [ + { + "Key": "Name", + "Value": "integ-cognito/Stack/PublicSubnet1" + } + ] + } + }, + "StackPublicSubnet1RouteTableAssociation74F1C1B6": { + "Type": "AWS::EC2::SubnetRouteTableAssociation", + "Properties": { + "RouteTableId": { + "Ref": "StackPublicSubnet1RouteTable5057189D" + }, + "SubnetId": { + "Ref": "StackPublicSubnet1Subnet0AD81D22" + } + } + }, + "StackPublicSubnet1DefaultRoute16154E3D": { + "Type": "AWS::EC2::Route", + "Properties": { + "RouteTableId": { + "Ref": "StackPublicSubnet1RouteTable5057189D" + }, + "DestinationCidrBlock": "0.0.0.0/0", + "GatewayId": { + "Ref": "StackIGW2F0A1126" + } + }, + "DependsOn": [ + "StackVPCGWFFCB6290" + ] + }, + "StackPublicSubnet1EIPBDAAB2A5": { + "Type": "AWS::EC2::EIP", + "Properties": { + "Domain": "vpc", + "Tags": [ + { + "Key": "Name", + "Value": "integ-cognito/Stack/PublicSubnet1" + } + ] + } + }, + "StackPublicSubnet1NATGatewayD2E1ABF7": { + "Type": "AWS::EC2::NatGateway", + "Properties": { + "AllocationId": { + "Fn::GetAtt": [ + "StackPublicSubnet1EIPBDAAB2A5", + "AllocationId" + ] + }, + "SubnetId": { + "Ref": "StackPublicSubnet1Subnet0AD81D22" + }, + "Tags": [ + { + "Key": "Name", + "Value": "integ-cognito/Stack/PublicSubnet1" + } + ] + } + }, + "StackPublicSubnet2Subnet3C7D2288": { + "Type": "AWS::EC2::Subnet", + "Properties": { + "CidrBlock": "10.0.64.0/18", + "VpcId": { + "Ref": "Stack8A423254" + }, + "AvailabilityZone": "test-region-1b", + "MapPublicIpOnLaunch": true, + "Tags": [ + { + "Key": "aws-cdk:subnet-name", + "Value": "Public" + }, + { + "Key": "aws-cdk:subnet-type", + "Value": "Public" + }, + { + "Key": "Name", + "Value": "integ-cognito/Stack/PublicSubnet2" + } + ] + } + }, + "StackPublicSubnet2RouteTableCD306445": { + "Type": "AWS::EC2::RouteTable", + "Properties": { + "VpcId": { + "Ref": "Stack8A423254" + }, + "Tags": [ + { + "Key": "Name", + "Value": "integ-cognito/Stack/PublicSubnet2" + } + ] + } + }, + "StackPublicSubnet2RouteTableAssociation5E8F73F1": { + "Type": "AWS::EC2::SubnetRouteTableAssociation", + "Properties": { + "RouteTableId": { + "Ref": "StackPublicSubnet2RouteTableCD306445" + }, + "SubnetId": { + "Ref": "StackPublicSubnet2Subnet3C7D2288" + } + } + }, + "StackPublicSubnet2DefaultRoute0319539B": { + "Type": "AWS::EC2::Route", + "Properties": { + "RouteTableId": { + "Ref": "StackPublicSubnet2RouteTableCD306445" + }, + "DestinationCidrBlock": "0.0.0.0/0", + "GatewayId": { + "Ref": "StackIGW2F0A1126" + } + }, + "DependsOn": [ + "StackVPCGWFFCB6290" + ] + }, + "StackPublicSubnet2EIP8CDBC8C2": { + "Type": "AWS::EC2::EIP", + "Properties": { + "Domain": "vpc", + "Tags": [ + { + "Key": "Name", + "Value": "integ-cognito/Stack/PublicSubnet2" + } + ] + } + }, + "StackPublicSubnet2NATGatewayA8E03AB3": { + "Type": "AWS::EC2::NatGateway", + "Properties": { + "AllocationId": { + "Fn::GetAtt": [ + "StackPublicSubnet2EIP8CDBC8C2", + "AllocationId" + ] + }, + "SubnetId": { + "Ref": "StackPublicSubnet2Subnet3C7D2288" + }, + "Tags": [ + { + "Key": "Name", + "Value": "integ-cognito/Stack/PublicSubnet2" + } + ] + } + }, + "StackPrivateSubnet1Subnet47AC2BC7": { + "Type": "AWS::EC2::Subnet", + "Properties": { + "CidrBlock": "10.0.128.0/18", + "VpcId": { + "Ref": "Stack8A423254" + }, + "AvailabilityZone": "test-region-1a", + "MapPublicIpOnLaunch": false, + "Tags": [ + { + "Key": "aws-cdk:subnet-name", + "Value": "Private" + }, + { + "Key": "aws-cdk:subnet-type", + "Value": "Private" + }, + { + "Key": "Name", + "Value": "integ-cognito/Stack/PrivateSubnet1" + } + ] + } + }, + "StackPrivateSubnet1RouteTable8ADA6A0C": { + "Type": "AWS::EC2::RouteTable", + "Properties": { + "VpcId": { + "Ref": "Stack8A423254" + }, + "Tags": [ + { + "Key": "Name", + "Value": "integ-cognito/Stack/PrivateSubnet1" + } + ] + } + }, + "StackPrivateSubnet1RouteTableAssociationFFE38495": { + "Type": "AWS::EC2::SubnetRouteTableAssociation", + "Properties": { + "RouteTableId": { + "Ref": "StackPrivateSubnet1RouteTable8ADA6A0C" + }, + "SubnetId": { + "Ref": "StackPrivateSubnet1Subnet47AC2BC7" + } + } + }, + "StackPrivateSubnet1DefaultRouteFBF81BA5": { + "Type": "AWS::EC2::Route", + "Properties": { + "RouteTableId": { + "Ref": "StackPrivateSubnet1RouteTable8ADA6A0C" + }, + "DestinationCidrBlock": "0.0.0.0/0", + "NatGatewayId": { + "Ref": "StackPublicSubnet1NATGatewayD2E1ABF7" + } + } + }, + "StackPrivateSubnet2SubnetA2F8EDD8": { + "Type": "AWS::EC2::Subnet", + "Properties": { + "CidrBlock": "10.0.192.0/18", + "VpcId": { + "Ref": "Stack8A423254" + }, + "AvailabilityZone": "test-region-1b", + "MapPublicIpOnLaunch": false, + "Tags": [ + { + "Key": "aws-cdk:subnet-name", + "Value": "Private" + }, + { + "Key": "aws-cdk:subnet-type", + "Value": "Private" + }, + { + "Key": "Name", + "Value": "integ-cognito/Stack/PrivateSubnet2" + } + ] + } + }, + "StackPrivateSubnet2RouteTableA5546697": { + "Type": "AWS::EC2::RouteTable", + "Properties": { + "VpcId": { + "Ref": "Stack8A423254" + }, + "Tags": [ + { + "Key": "Name", + "Value": "integ-cognito/Stack/PrivateSubnet2" + } + ] + } + }, + "StackPrivateSubnet2RouteTableAssociation68ACB8C1": { + "Type": "AWS::EC2::SubnetRouteTableAssociation", + "Properties": { + "RouteTableId": { + "Ref": "StackPrivateSubnet2RouteTableA5546697" + }, + "SubnetId": { + "Ref": "StackPrivateSubnet2SubnetA2F8EDD8" + } + } + }, + "StackPrivateSubnet2DefaultRoute22004492": { + "Type": "AWS::EC2::Route", + "Properties": { + "RouteTableId": { + "Ref": "StackPrivateSubnet2RouteTableA5546697" + }, + "DestinationCidrBlock": "0.0.0.0/0", + "NatGatewayId": { + "Ref": "StackPublicSubnet2NATGatewayA8E03AB3" + } + } + }, + "StackIGW2F0A1126": { + "Type": "AWS::EC2::InternetGateway", + "Properties": { + "Tags": [ + { + "Key": "Name", + "Value": "integ-cognito/Stack" + } + ] + } + }, + "StackVPCGWFFCB6290": { + "Type": "AWS::EC2::VPCGatewayAttachment", + "Properties": { + "VpcId": { + "Ref": "Stack8A423254" + }, + "InternetGatewayId": { + "Ref": "StackIGW2F0A1126" + } + } + }, + "LB8A12904C": { + "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer", + "Properties": { + "Scheme": "internet-facing", + "SecurityGroups": [ + { + "Fn::GetAtt": [ + "LBSecurityGroup8A41EA2B", + "GroupId" + ] + } + ], + "Subnets": [ + { + "Ref": "StackPublicSubnet1Subnet0AD81D22" + }, + { + "Ref": "StackPublicSubnet2Subnet3C7D2288" + } + ], + "Type": "application" + }, + "DependsOn": [ + "StackPublicSubnet1DefaultRoute16154E3D", + "StackPublicSubnet2DefaultRoute0319539B" + ] + }, + "LBSecurityGroup8A41EA2B": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "Automatically created Security Group for ELB integcognitoLBFBBBA626", + "SecurityGroupEgress": [ + { + "CidrIp": "255.255.255.255/32", + "Description": "Disallow all traffic", + "FromPort": 252, + "IpProtocol": "icmp", + "ToPort": 86 + } + ], + "SecurityGroupIngress": [ + { + "CidrIp": "0.0.0.0/0", + "Description": "Allow from anyone on port 443", + "FromPort": 443, + "IpProtocol": "tcp", + "ToPort": 443 + } + ], + "VpcId": { + "Ref": "Stack8A423254" + } + } + }, + "LBListener49E825B4": { + "Type": "AWS::ElasticLoadBalancingV2::Listener", + "Properties": { + "DefaultActions": [ + { + "AuthenticateCognitoConfig": { + "UserPoolArn": { + "Fn::GetAtt": [ + "UserPool6BA7E5F2", + "Arn" + ] + }, + "UserPoolClientId": { + "Ref": "Client4A7F64DF" + }, + "UserPoolDomain": { + "Ref": "Domain66AC69E0" + } + }, + "Order": 1, + "Type": "authenticate-cognito" + }, + { + "FixedResponseConfig": { + "ContentType": "text/plain", + "MessageBody": "Authenticated", + "StatusCode": "200" + }, + "Order": 2, + "Type": "fixed-response" + } + ], + "LoadBalancerArn": { + "Ref": "LB8A12904C" + }, + "Port": 443, + "Protocol": "HTTPS", + "Certificates": [ + { + "CertificateArn": "" + } + ] + } + }, + "UserPoolsmsRole4EA729DD": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Condition": { + "StringEquals": { + "sts:ExternalId": "integcognitoUserPool7BB79D76" + } + }, + "Effect": "Allow", + "Principal": { + "Service": "cognito-idp.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sns:Publish", + "Effect": "Allow", + "Resource": "*" + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "sns-publish" + } + ] + } + }, + "UserPool6BA7E5F2": { + "Type": "AWS::Cognito::UserPool", + "Properties": { + "AdminCreateUserConfig": { + "AllowAdminCreateUserOnly": true + }, + "EmailVerificationMessage": "The verification code to your new account is {####}", + "EmailVerificationSubject": "Verify your new account", + "SmsConfiguration": { + "ExternalId": "integcognitoUserPool7BB79D76", + "SnsCallerArn": { + "Fn::GetAtt": [ + "UserPoolsmsRole4EA729DD", + "Arn" + ] + } + }, + "SmsVerificationMessage": "The verification code to your new account is {####}", + "VerificationMessageTemplate": { + "DefaultEmailOption": "CONFIRM_WITH_CODE", + "EmailMessage": "The verification code to your new account is {####}", + "EmailSubject": "Verify your new account", + "SmsMessage": "The verification code to your new account is {####}" + } + } + }, + "Client4A7F64DF": { + "Type": "AWS::Cognito::UserPoolClient", + "Properties": { + "UserPoolId": { + "Ref": "UserPool6BA7E5F2" + }, + "AllowedOAuthFlows": [ + "code" + ], + "AllowedOAuthFlowsUserPoolClient": true, + "AllowedOAuthScopes": [ + "email", + "openid" + ], + "CallbackURLs": [ + { + "Fn::Join": [ + "", + [ + "https://", + { + "Fn::GetAtt": [ + "LB8A12904C", + "DNSName" + ] + }, + "/oauth2/idpresponse" + ] + ] + } + ], + "ExplicitAuthFlows": [ + "ALLOW_USER_PASSWORD_AUTH", + "ALLOW_REFRESH_TOKEN_AUTH" + ], + "GenerateSecret": true, + "RefreshTokenValidity": 1, + "SupportedIdentityProviders": [ + "COGNITO" + ] + } + }, + "Domain66AC69E0": { + "Type": "AWS::Cognito::UserPoolDomain", + "Properties": { + "Domain": "test-cdk-prefix", + "UserPoolId": { + "Ref": "UserPool6BA7E5F2" + } + } + } + }, + "Outputs": { + "DNS": { + "Value": { + "Fn::GetAtt": [ + "LB8A12904C", + "DNSName" + ] + } + } + } +} diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/test/integ.cognito.lit.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/test/integ.cognito.lit.ts new file mode 100644 index 0000000000000..f9ab2c015b382 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2-actions/test/integ.cognito.lit.ts @@ -0,0 +1,80 @@ +import * as cognito from '@aws-cdk/aws-cognito'; +import * as ec2 from '@aws-cdk/aws-ec2'; +import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2'; +import { App, CfnOutput, Construct, Stack } from '@aws-cdk/core'; +import * as actions from '../lib'; + +class CognitoStack extends Stack { + + /// !hide + constructor(scope: Construct, id: string) { + super(scope, id); + + const vpc = new ec2.Vpc(this, 'Stack', { + maxAzs: 2, + }); + + const certificate: elbv2.IListenerCertificate = { + certificateArn: process.env.SELF_SIGNED_CERT_ARN ?? '', + }; + + /// !show + const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', { + vpc, + internetFacing: true, + }); + + const userPool = new cognito.UserPool(this, 'UserPool'); + const userPoolClient = new cognito.UserPoolClient(this, 'Client', { + userPool, + + // Required minimal configuration for use with an ELB + generateSecret: true, + authFlows: { + userPassword: true, + refreshToken: true, + }, + oAuth: { + flows: { + authorizationCodeGrant: true, + }, + scopes: [cognito.OAuthScope.EMAIL], + callbackUrls: [ + `https://${lb.loadBalancerDnsName}/oauth2/idpresponse`, + ], + }, + }); + const cfnClient = userPoolClient.node.defaultChild as cognito.CfnUserPoolClient; + cfnClient.addPropertyOverride('RefreshTokenValidity', 1); + cfnClient.addPropertyOverride('SupportedIdentityProviders', ['COGNITO']); + + const userPoolDomain = new cognito.UserPoolDomain(this, 'Domain', { + userPool, + cognitoDomain: { + domainPrefix: 'test-cdk-prefix', + }, + }); + + lb.addListener('Listener', { + port: 443, + certificates: [certificate], + defaultAction: new actions.AuthenticateCognitoAction({ + userPool, + userPoolClient, + userPoolDomain, + next: elbv2.ListenerAction.fixedResponse(200, { + contentType: 'text/plain', + messageBody: 'Authenticated', + }), + }), + }); + + new CfnOutput(this, 'DNS', { + value: lb.loadBalancerDnsName, + }); + } +} + +const app = new App(); +new CognitoStack(app, 'integ-cognito'); +app.synth(); \ No newline at end of file diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/README.md b/packages/@aws-cdk/aws-elasticloadbalancingv2/README.md index 02c3b45d12286..22764ebe22de1 100644 --- a/packages/@aws-cdk/aws-elasticloadbalancingv2/README.md +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/README.md @@ -34,44 +34,33 @@ const vpc = new ec2.Vpc(...); // Create the load balancer in a VPC. 'internetFacing' is 'false' // by default, which creates an internal load balancer. const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', { - vpc, - internetFacing: true + vpc, + internetFacing: true }); // Add a listener and open up the load balancer's security group // to the world. const listener = lb.addListener('Listener', { - port: 80, + port: 80, - // 'open: true' is the default, you can leave it out if you want. Set it - // to 'false' and use `listener.connections` if you want to be selective - // about who can access the load balancer. - open: true, + // 'open: true' is the default, you can leave it out if you want. Set it + // to 'false' and use `listener.connections` if you want to be selective + // about who can access the load balancer. + open: true, }); // Create an AutoScaling group and add it as a load balancing // target to the listener. const asg = new autoscaling.AutoScalingGroup(...); listener.addTargets('ApplicationFleet', { - port: 8080, - targets: [asg] + port: 8080, + targets: [asg] }); ``` The security groups of the load balancer and the target are automatically updated to allow the network traffic. -Use the `addFixedResponse()` method to add fixed response rules on the listener: - -```ts -listener.addFixedResponse('Fixed', { - pathPattern: '/ok', - contentType: elbv2.ContentType.TEXT_PLAIN, - messageBody: 'OK', - statusCode: '200' -}); -``` - #### Conditions It's possible to route traffic to targets based on conditions in the incoming @@ -82,11 +71,11 @@ requested host in the request is either for `example.com/ok` or ```ts listener.addTargets('Example.Com Fleet', { - priority: 10, - pathPatterns: ['/ok', '/path'], - hostHeader: 'example.com', - port: 8080, - targets: [asg] + priority: 10, + pathPatterns: ['/ok', '/path'], + hostHeader: 'example.com', + port: 8080, + targets: [asg] }); ``` @@ -98,6 +87,67 @@ targets with conditions. The lowest number wins. Every listener must have at least one target without conditions, which is where all requests that didn't match any of the conditions will be sent. +#### Convenience methods and more complex Actions + +Routing traffic from a Load Balancer to a Target involves the following steps: + +- Create a Target Group, register the Target into the Target Group +- Add an Action to the Listener which forwards traffic to the Target Group. + +Various methods on the `Listener` take care of this work for you to a greater +or lesser extent: + +- `addTargets()` performs both steps: automatically creates a Target Group and the + required Action. +- `addTargetGroups()` gives you more control: you create the Target Group (or + Target Groups) yourself and the method creates Action that routes traffic to + the Target Groups. +- `addAction()` gives you full control: you supply the Action and wire it up + to the Target Groups yourself (or access one of the other ELB routing features). + +Using `addAction()` gives you access to some of the features of an Elastic Load +Balancer that the other two convenience methods don't: + +- **Routing stickiness**: use `ListenerAction.forward()` and supply a + `stickinessDuration` to make sure requests are routed to the same target group + for a given duration. +- **Weighted Target Groups**: use `ListenerAction.weightedForward()` + to give different weights to different target groups. +- **Fixed Responses**: use `ListenerAction.fixedResponse()` to serve + a static response (ALB only). +- **Redirects**: use `ListenerAction.redirect()` to serve an HTTP + redirect response (ALB only). +- **Authentication**: use `ListenerAction.authenticateOidc()` to + perform OpenID authentication before serving a request (see the + `@aws-cdk/aws-elasticloadbalancingv2-actions` package for direct authentication + integration with Cognito) (ALB only). + +Here's an example of serving a fixed response at the `/ok` URL: + +```ts +listener.addAction('Fixed', { + pathPatterns: ['/ok'], + priority: 10, + action: ListenerAction.fixedResponse(200, { + contentType: elbv2.ContentType.TEXT_PLAIN, + messageBody: 'OK', + }) +}); +``` + +Here's an example of using OIDC authentication before forwarding to a TargetGroup: + +```ts +listener.addAction('DefaultAction', { + action: ListenerAction.authenticateOidc({ + authorizationEndpoint: 'https://example.com/openid', + // Other OIDC properties here + // ... + next: ListenerAction.forward([myTargetGroup]), + }), +}); +``` + ### Defining a Network Load Balancer Network Load Balancers are defined in a similar way to Application Load @@ -111,19 +161,19 @@ import * as autoscaling from '@aws-cdk/aws-autoscaling'; // Create the load balancer in a VPC. 'internetFacing' is 'false' // by default, which creates an internal load balancer. const lb = new elbv2.NetworkLoadBalancer(this, 'LB', { - vpc, - internetFacing: true + vpc, + internetFacing: true }); // Add a listener on a particular port. const listener = lb.addListener('Listener', { - port: 443, + port: 443, }); // Add targets on a particular port. listener.addTargets('AppFleet', { - port: 443, - targets: [asg] + port: 443, + targets: [asg] }); ``` @@ -152,8 +202,8 @@ and add it to the listener by calling `addTargetGroups` instead of `addTargets`. ```ts const group = listener.addTargets('AppFleet', { - port: 443, - targets: [asg1], + port: 443, + targets: [asg1], }); group.addTarget(asg2); @@ -174,13 +224,13 @@ const lb = new elbv2.ApplicationLoadBalancer(...); const listener = lb.addListener('Listener', { port: 80 }); listener.addTargets('Targets', { - targets: [new targets.LambdaTarget(lambdaFunction)], + targets: [new targets.LambdaTarget(lambdaFunction)], - // For Lambda Targets, you need to explicitly enable health checks if you - // want them. - healthCheck: { - enabled: true, - } + // For Lambda Targets, you need to explicitly enable health checks if you + // want them. + healthCheck: { + enabled: true, + } }); ``` @@ -192,12 +242,12 @@ Health checks are configured upon creation of a target group: ```ts listener.addTargets('AppFleet', { - port: 8080, - targets: [asg], - healthCheck: { - path: '/ping', - interval: cdk.Duration.minutes(1), - } + port: 8080, + targets: [asg], + healthCheck: { + path: '/ping', + interval: cdk.Duration.minutes(1), + } }); ``` @@ -211,11 +261,11 @@ If not, you will have to configure the security groups appropriately: ```ts listener.addTargets('AppFleet', { - port: 8080, - targets: [asg], - healthCheck: { - port: 8088, - } + port: 8080, + targets: [asg], + healthCheck: { + port: 8088, + } }); listener.connections.allowFrom(lb, ec2.Port.tcp(8088)); @@ -247,11 +297,11 @@ load balancing target: ```ts public attachToApplicationTargetGroup(targetGroup: ApplicationTargetGroup): LoadBalancerTargetProps { - targetGroup.registerConnectable(...); - return { - targetType: TargetType.Instance | TargetType.Ip - targetJson: { id: ..., port: ... }, - }; + targetGroup.registerConnectable(...); + return { + targetType: TargetType.Instance | TargetType.Ip + targetJson: { id: ..., port: ... }, + }; } ``` `targetType` should be one of `Instance` or `Ip`. If the target can be diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener-action.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener-action.ts new file mode 100644 index 0000000000000..9b3e713a6115c --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener-action.ts @@ -0,0 +1,444 @@ +import { Construct, Duration, IConstruct, SecretValue, Tokenization } from '@aws-cdk/core'; +import { CfnListener } from '../elasticloadbalancingv2.generated'; +import { IListenerAction } from '../shared/listener-action'; +import { IApplicationListener } from './application-listener'; +import { IApplicationTargetGroup } from './application-target-group'; + +/** + * What to do when a client makes a request to a listener + * + * Some actions can be combined with other ones (specifically, + * you can perform authentication before serving the request). + * + * Multiple actions form a linked chain; the chain must always terminate in a + * *(weighted)forward*, *fixedResponse* or *redirect* action. + * + * If an action supports chaining, the next action can be indicated + * by passing it in the `next` property. + * + * (Called `ListenerAction` instead of the more strictly correct + * `ListenerAction` because this is the class most users interact + * with, and we want to make it not too visually overwhelming). + */ +export class ListenerAction implements IListenerAction { + /** + * Authenticate using an identity provider (IdP) that is compliant with OpenID Connect (OIDC) + * + * @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-authenticate-users.html#oidc-requirements + */ + public static authenticateOidc(options: AuthenticateOidcOptions): ListenerAction { + return new ListenerAction({ + type: 'authenticate-oidc', + authenticateOidcConfig: { + authorizationEndpoint: options.authorizationEndpoint, + clientId: options.clientId, + clientSecret: options.clientSecret.toString(), + issuer: options.issuer, + tokenEndpoint: options.tokenEndpoint, + userInfoEndpoint: options.userInfoEndpoint, + authenticationRequestExtraParams: options.authenticationRequestExtraParams, + onUnauthenticatedRequest: options.onUnauthenticatedRequest, + scope: options.scope, + sessionCookieName: options.sessionCookieName, + sessionTimeout: options.sessionTimeout?.toSeconds(), + }, + }, options.next); + } + + /** + * Forward to one or more Target Groups + * + * @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#forward-actions + */ + public static forward(targetGroups: IApplicationTargetGroup[], options: ForwardOptions = {}): ListenerAction { + if (targetGroups.length === 0) { + throw new Error('Need at least one targetGroup in a ListenerAction.forward()'); + } + if (targetGroups.length === 1 && options.stickinessDuration === undefined) { + // Render a "simple" action for backwards compatibility with old templates + return new TargetGroupListenerAction(targetGroups, { + type: 'forward', + targetGroupArn: targetGroups[0].targetGroupArn, + }); + } + + return new TargetGroupListenerAction(targetGroups, { + type: 'forward', + forwardConfig: { + targetGroups: targetGroups.map(g => ({ targetGroupArn: g.targetGroupArn })), + targetGroupStickinessConfig: options.stickinessDuration ? { + durationSeconds: options.stickinessDuration.toSeconds(), + enabled: true, + } : undefined, + }, + }); + } + + /** + * Forward to one or more Target Groups which are weighted differently + * + * @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#forward-actions + */ + public static weightedForward(targetGroups: WeightedTargetGroup[], options: ForwardOptions = {}): ListenerAction { + if (targetGroups.length === 0) { + throw new Error('Need at least one targetGroup in a ListenerAction.weightedForward()'); + } + + return new TargetGroupListenerAction(targetGroups.map(g => g.targetGroup), { + type: 'forward', + forwardConfig: { + targetGroups: targetGroups.map(g => ({ targetGroupArn: g.targetGroup.targetGroupArn, weight: g.weight })), + targetGroupStickinessConfig: options.stickinessDuration ? { + durationSeconds: options.stickinessDuration.toSeconds(), + enabled: true, + } : undefined, + }, + }); + } + + /** + * Return a fixed response + * + * @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#fixed-response-actions + */ + public static fixedResponse(statusCode: number, options: FixedResponseOptions = {}): ListenerAction { + return new ListenerAction({ + type: 'fixed-response', + fixedResponseConfig: { + statusCode: Tokenization.stringifyNumber(statusCode), + contentType: options.contentType, + messageBody: options.messageBody, + }, + }); + } + + /** + * Redirect to a different URI + * + * A URI consists of the following components: + * protocol://hostname:port/path?query. You must modify at least one of the + * following components to avoid a redirect loop: protocol, hostname, port, or + * path. Any components that you do not modify retain their original values. + * + * You can reuse URI components using the following reserved keywords: + * + * - `#{protocol}` + * - `#{host}` + * - `#{port}` + * - `#{path}` (the leading "/" is removed) + * - `#{query}` + * + * For example, you can change the path to "/new/#{path}", the hostname to + * "example.#{host}", or the query to "#{query}&value=xyz". + * + * @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#redirect-actions + */ + public static redirect(options: RedirectOptions): ListenerAction { + if ([options.host, options.path, options.port, options.protocol, options.query].findIndex(x => x !== undefined) === -1) { + throw new Error('To prevent redirect loops, set at least one of \'protocol\', \'host\', \'port\', \'path\', or \'query\'.'); + } + + return new ListenerAction({ + type: 'redirect', + redirectConfig: { + statusCode: options.permanent ? 'HTTP_301' : 'HTTP_302', + host: options.host, + path: options.path, + port: options.port, + protocol: options.protocol, + query: options.query, + }, + }); + } + + /** + * Create an instance of ListenerAction + * + * The default class should be good enough for most cases and + * should be created by using one of the static factory functions, + * but allow overriding to make sure we allow flexibility for the future. + */ + protected constructor(private readonly actionJson: CfnListener.ActionProperty, protected readonly next?: ListenerAction) { + } + + /** + * Render the actions in this chain + */ + public renderActions(): CfnListener.ActionProperty[] { + return this.renumber([this.actionJson, ...this.next?.renderActions() ?? []]); + } + + /** + * Called when the action is being used in a listener + */ + public bind(scope: Construct, listener: IApplicationListener, associatingConstruct?: IConstruct) { + // Empty on purpose + Array.isArray(scope); + Array.isArray(listener); + Array.isArray(associatingConstruct); + } + + /** + * Renumber the "order" fields in the actions array. + * + * We don't number for 0 or 1 elements, but otherwise number them 1...#actions + * so ELB knows about the right order. + * + * Do this in `ListenerAction` instead of in `Listener` so that we give + * users the opportunity to override by subclassing and overriding `renderActions`. + */ + protected renumber(actions: CfnListener.ActionProperty[]): CfnListener.ActionProperty[] { + if (actions.length < 2) { return actions; } + + return actions.map((action, i) => ({ ...action, order: i + 1 })); + } +} + +/** + * Options for `ListenerAction.forward()` + */ +export interface ForwardOptions { + /** + * For how long clients should be directed to the same target group + * + * Range between 1 second and 7 days. + * + * @default - No stickiness + */ + readonly stickinessDuration?: Duration; +} + +/** + * A Target Group and weight combination + */ +export interface WeightedTargetGroup { + /** + * The target group + */ + readonly targetGroup: IApplicationTargetGroup; + + /** + * The target group's weight + * + * Range is [0..1000). + * + * @default 1 + */ + readonly weight?: number; +} + +/** + * Options for `ListenerAction.fixedResponse()` + */ +export interface FixedResponseOptions { + /** + * Content Type of the response + * + * Valid Values: text/plain | text/css | text/html | application/javascript | application/json + * + * @default - Automatically determined + */ + readonly contentType?: string; + + /** + * The response body + * + * @default - No body + */ + readonly messageBody?: string; +} + +/** + * Options for `ListenerAction.redirect()` + * + * A URI consists of the following components: + * protocol://hostname:port/path?query. You must modify at least one of the + * following components to avoid a redirect loop: protocol, hostname, port, or + * path. Any components that you do not modify retain their original values. + * + * You can reuse URI components using the following reserved keywords: + * + * - `#{protocol}` + * - `#{host}` + * - `#{port}` + * - `#{path}` (the leading "/" is removed) + * - `#{query}` + * + * For example, you can change the path to "/new/#{path}", the hostname to + * "example.#{host}", or the query to "#{query}&value=xyz". + */ +export interface RedirectOptions { + /** + * The hostname. + * + * This component is not percent-encoded. The hostname can contain #{host}. + * + * @default - No change + */ + readonly host?: string; + + /** + * The absolute path, starting with the leading "/". + * + * This component is not percent-encoded. The path can contain #{host}, #{path}, and #{port}. + * + * @default - No change + */ + readonly path?: string; + + /** + * The port. + * + * You can specify a value from 1 to 65535 or #{port}. + * + * @default - No change + */ + readonly port?: string; + + /** + * The protocol. + * + * You can specify HTTP, HTTPS, or #{protocol}. You can redirect HTTP to HTTP, HTTP to HTTPS, and HTTPS to HTTPS. You cannot redirect HTTPS to HTTP. + * + * @default - No change + */ + readonly protocol?: string; + + /** + * The query parameters, URL-encoded when necessary, but not percent-encoded. + * + * Do not include the leading "?", as it is automatically added. You can specify any of the reserved keywords. + * + * @default - No change + */ + readonly query?: string; + + /** + * The HTTP redirect code. + * + * The redirect is either permanent (HTTP 301) or temporary (HTTP 302). + * + * @default false + */ + readonly permanent?: boolean; +} + +/** + * Options for `ListenerAction.authenciateOidc()` + */ +export interface AuthenticateOidcOptions { + /** + * What action to execute next + */ + readonly next: ListenerAction; + + /** + * The query parameters (up to 10) to include in the redirect request to the authorization endpoint. + * + * @default - No extra parameters + */ + readonly authenticationRequestExtraParams?: Record; + + /** + * The authorization endpoint of the IdP. + * + * This must be a full URL, including the HTTPS protocol, the domain, and the path. + */ + readonly authorizationEndpoint: string; + + /** + * The OAuth 2.0 client identifier. + */ + readonly clientId: string; + + /** + * The OAuth 2.0 client secret. + */ + readonly clientSecret: SecretValue; + + /** + * The OIDC issuer identifier of the IdP. + * + * This must be a full URL, including the HTTPS protocol, the domain, and the path. + */ + readonly issuer: string; + + /** + * The behavior if the user is not authenticated. + * + * @default UnauthenticatedAction.AUTHENTICATE + */ + readonly onUnauthenticatedRequest?: UnauthenticatedAction; + + /** + * The set of user claims to be requested from the IdP. + * + * To verify which scope values your IdP supports and how to separate multiple values, see the documentation for your IdP. + * + * @default "openid" + */ + readonly scope?: string; + + /** + * The name of the cookie used to maintain session information. + * + * @default "AWSELBAuthSessionCookie" + */ + readonly sessionCookieName?: string; + + /** + * The maximum duration of the authentication session. + * + * @default Duration.days(7) + */ + readonly sessionTimeout?: Duration; + + /** + * The token endpoint of the IdP. + * + * This must be a full URL, including the HTTPS protocol, the domain, and the path. + */ + readonly tokenEndpoint: string; + + /** + * The user info endpoint of the IdP. + * + * This must be a full URL, including the HTTPS protocol, the domain, and the path. + */ + readonly userInfoEndpoint: string; +} + +/** + * What to do with unauthenticated requests + */ +export enum UnauthenticatedAction { + /** + * Return an HTTP 401 Unauthorized error. + */ + DENY = 'deny', + + /** + * Allow the request to be forwarded to the target. + */ + ALLOW = 'allow', + + /** + * Redirect the request to the IdP authorization endpoint. + */ + AUTHENTICATE = 'authenticate', +} + +/** + * Listener Action that calls "registerListener" on TargetGroups + */ +class TargetGroupListenerAction extends ListenerAction { + constructor(private readonly targetGroups: IApplicationTargetGroup[], actionJson: CfnListener.ActionProperty) { + super(actionJson); + } + + public bind(_scope: Construct, listener: IApplicationListener, associatingConstruct?: IConstruct) { + for (const tg of this.targetGroups) { + tg.registerListener(listener, associatingConstruct); + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener-rule.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener-rule.ts index d041da5d4c3b3..c2eab3160fd6a 100644 --- a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener-rule.ts +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener-rule.ts @@ -1,6 +1,8 @@ import * as cdk from '@aws-cdk/core'; import { CfnListenerRule } from '../elasticloadbalancingv2.generated'; +import { IListenerAction } from '../shared/listener-action'; import { IApplicationListener } from './application-listener'; +import { ListenerAction } from './application-listener-action'; import { IApplicationTargetGroup } from './application-target-group'; /** @@ -17,26 +19,42 @@ export interface BaseApplicationListenerRuleProps { readonly priority: number; /** - * Target groups to forward requests to. Only one of `fixedResponse`, `redirectResponse` or - * `targetGroups` can be specified. + * Target groups to forward requests to. + * + * Only one of `action`, `fixedResponse`, `redirectResponse` or `targetGroups` can be specified. + * + * Implies a `forward` action. * * @default - No target groups. */ readonly targetGroups?: IApplicationTargetGroup[]; /** - * Fixed response to return. Only one of `fixedResponse`, `redirectResponse` or - * `targetGroups` can be specified. + * Action to perform when requests are received + * + * Only one of `action`, `fixedResponse`, `redirectResponse` or `targetGroups` can be specified. + * + * @default - No action + */ + readonly action?: ListenerAction; + + /** + * Fixed response to return. + * + * Only one of `action`, `fixedResponse`, `redirectResponse` or `targetGroups` can be specified. * * @default - No fixed response. + * @deprecated Use `action` instead. */ readonly fixedResponse?: FixedResponse; /** - * Redirect response to return. Only one of `fixedResponse`, `redirectResponse` or - * `targetGroups` can be specified. + * Redirect response to return. + * + * Only one of `action`, `fixedResponse`, `redirectResponse` or `targetGroups` can be specified. * * @default - No redirect response. + * @deprecated Use `action` instead. */ readonly redirectResponse?: RedirectResponse; @@ -171,8 +189,8 @@ export class ApplicationListenerRule extends cdk.Construct { private readonly conditions: {[key: string]: string[] | undefined} = {}; - private readonly actions: any[] = []; private readonly listener: IApplicationListener; + private action?: IListenerAction; constructor(scope: cdk.Construct, id: string, props: ApplicationListenerRuleProps) { super(scope, id); @@ -182,7 +200,7 @@ export class ApplicationListenerRule extends cdk.Construct { throw new Error('At least one of \'hostHeader\', \'pathPattern\' or \'pathPatterns\' is required when defining a load balancing rule.'); } - const possibleActions: Array = ['targetGroups', 'fixedResponse', 'redirectResponse']; + const possibleActions: Array = ['action', 'targetGroups', 'fixedResponse', 'redirectResponse']; const providedActions = possibleActions.filter(action => props[action] !== undefined); if (providedActions.length > 1) { throw new Error(`'${providedActions}' specified together, specify only one`); @@ -198,7 +216,7 @@ export class ApplicationListenerRule extends cdk.Construct { listenerArn: props.listener.listenerArn, priority: props.priority, conditions: cdk.Lazy.anyValue({ produce: () => this.renderConditions() }), - actions: cdk.Lazy.anyValue({ produce: () => this.actions }), + actions: cdk.Lazy.anyValue({ produce: () => this.action ? this.action.renderActions() : [] }), }); if (props.hostHeader) { @@ -213,6 +231,10 @@ export class ApplicationListenerRule extends cdk.Construct { this.setCondition('path-pattern', pathPattern); } + if (props.action) { + this.configureAction(props.action); + } + (props.targetGroups || []).forEach(this.addTargetGroup.bind(this)); if (props.fixedResponse) { @@ -231,46 +253,73 @@ export class ApplicationListenerRule extends cdk.Construct { this.conditions[field] = values; } + /** + * Configure the action to perform for this rule + */ + public configureAction(action: ListenerAction) { + // It might make sense to 'throw' here. + // + // However, programs may already exist out there which configured an action twice, + // in which case the second action accidentally overwrite the initial action, and in some + // way ended up with a program that did what the author intended. If we were to add throw now, + // the previously working program would be broken. + // + // Instead, signal this through a warning. + // @deprecate: upon the next major version bump, replace this with a `throw` + if (this.action) { + this.node.addWarning('An Action already existed on this ListenerRule and was replaced. Configure exactly one default Action.'); + } + + action.bind(this, this.listener, this); + this.action = action; + } + /** * Add a TargetGroup to load balance to + * + * @deprecated Use configureAction instead */ public addTargetGroup(targetGroup: IApplicationTargetGroup) { - this.actions.push({ - targetGroupArn: targetGroup.targetGroupArn, - type: 'forward', - }); - targetGroup.registerListener(this.listener, this); + this.configureAction(ListenerAction.forward([targetGroup])); } /** * Add a fixed response + * + * @deprecated Use configureAction instead */ public addFixedResponse(fixedResponse: FixedResponse) { validateFixedResponse(fixedResponse); - this.actions.push({ - fixedResponseConfig: fixedResponse, - type: 'fixed-response', - }); + this.configureAction(ListenerAction.fixedResponse(cdk.Token.asNumber(fixedResponse.statusCode), { + contentType: fixedResponse.contentType, + messageBody: fixedResponse.messageBody, + })); } /** * Add a redirect response + * + * @deprecated Use configureAction instead */ public addRedirectResponse(redirectResponse: RedirectResponse) { validateRedirectResponse(redirectResponse); - this.actions.push({ - redirectConfig: redirectResponse, - type: 'redirect', - }); + this.configureAction(ListenerAction.redirect({ + host: redirectResponse.host, + path: redirectResponse.path, + permanent: redirectResponse.statusCode === 'HTTP_301', + port: redirectResponse.port, + protocol: redirectResponse.protocol, + query: redirectResponse.query, + })); } /** * Validate the rule */ protected validate() { - if (this.actions.length === 0) { + if (this.action === undefined) { return ['Listener rule needs at least one action']; } return []; diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener.ts index 7dd1b627c5bde..c3560eb519993 100644 --- a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener.ts +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/alb/application-listener.ts @@ -1,10 +1,11 @@ import * as ec2 from '@aws-cdk/aws-ec2'; -import { Construct, Duration, IResource, Lazy, Resource } from '@aws-cdk/core'; +import { Construct, Duration, IResource, Lazy, Resource, Token } from '@aws-cdk/core'; import { BaseListener } from '../shared/base-listener'; import { HealthCheck } from '../shared/base-target-group'; import { ApplicationProtocol, SslPolicy } from '../shared/enums'; import { IListenerCertificate, ListenerCertificate } from '../shared/listener-certificate'; import { determineProtocolAndPort } from '../shared/util'; +import { ListenerAction } from './application-listener-action'; import { ApplicationListenerCertificate } from './application-listener-certificate'; import { ApplicationListenerRule, FixedResponse, RedirectResponse, validateFixedResponse, validateRedirectResponse } from './application-listener-rule'; import { IApplicationLoadBalancer } from './application-load-balancer'; @@ -53,10 +54,30 @@ export interface BaseApplicationListenerProps { /** * Default target groups to load balance to * + * All target groups will be load balanced to with equal weight and without + * stickiness. For a more complex configuration than that, use + * either `defaultAction` or `addAction()`. + * + * Cannot be specified together with `defaultAction`. + * * @default - None. */ readonly defaultTargetGroups?: IApplicationTargetGroup[]; + /** + * Default action to take for requests to this listener + * + * This allows full control of the default action of the load balancer, + * including Action chaining, fixed responses and redirect responses. + * + * See the `ListenerAction` class for all options. + * + * Cannot be specified together with `defaultTargetGroups`. + * + * @default - None. + */ + readonly defaultAction?: ListenerAction; + /** * Allow anyone to connect to this listener * @@ -149,7 +170,17 @@ export class ApplicationListener extends BaseListener implements IApplicationLis defaultPort: ec2.Port.tcp(port), }); - (props.defaultTargetGroups || []).forEach(this.addDefaultTargetGroup.bind(this)); + if (props.defaultAction && props.defaultTargetGroups) { + throw new Error('Specify at most one of \'defaultAction\' and \'defaultTargetGroups\''); + } + + if (props.defaultAction) { + this.setDefaultAction(props.defaultAction); + } + + if (props.defaultTargetGroups) { + this.setDefaultAction(ListenerAction.forward(props.defaultTargetGroups)); + } if (props.open !== false) { this.connections.allowDefaultPortFrom(ec2.Peer.anyIpv4(), `Allow from anyone on port ${port}`); @@ -192,11 +223,47 @@ export class ApplicationListener extends BaseListener implements IApplicationLis } } + /** + * Perform the given default action on incoming requests + * + * This allows full control of the default action of the load balancer, + * including Action chaining, fixed responses and redirect responses. See + * the `ListenerAction` class for all options. + * + * It's possible to add routing conditions to the Action added in this way. + * At least one Action must be added without conditions (which becomes the + * default Action). + */ + public addAction(id: string, props: AddApplicationActionProps): void { + checkAddRuleProps(props); + + if (props.priority !== undefined) { + // New rule + // + // TargetGroup.registerListener is called inside ApplicationListenerRule. + new ApplicationListenerRule(this, id + 'Rule', { + listener: this, + hostHeader: props.hostHeader, + pathPattern: props.pathPattern, + pathPatterns: props.pathPatterns, + priority: props.priority, + action: props.action, + }); + } else { + // New default target with these targetgroups + this.setDefaultAction(props.action); + } + } + /** * Load balance incoming requests to the given target groups. * - * It's possible to add conditions to the TargetGroups added in this way. - * At least one TargetGroup must be added without conditions. + * All target groups will be load balanced to with equal weight and without + * stickiness. For a more complex configuration than that, use `addAction()`. + * + * It's possible to add routing conditions to the TargetGroups added in this + * way. At least one TargetGroup must be added without conditions (which will + * become the default Action for this listener). */ public addTargetGroups(id: string, props: AddApplicationTargetGroupsProps): void { checkAddRuleProps(props); @@ -214,10 +281,8 @@ export class ApplicationListener extends BaseListener implements IApplicationLis targetGroups: props.targetGroups, }); } else { - // New default target(s) - for (const targetGroup of props.targetGroups) { - this.addDefaultTargetGroup(targetGroup); - } + // New default target with these targetgroups + this.setDefaultAction(ListenerAction.forward(props.targetGroups)); } } @@ -225,7 +290,10 @@ export class ApplicationListener extends BaseListener implements IApplicationLis * Load balance incoming requests to the given load balancing targets. * * This method implicitly creates an ApplicationTargetGroup for the targets - * involved. + * involved, and a 'forward' action to route traffic to the given TargetGroup. + * + * If you want more control over the precise setup, create the TargetGroup + * and use `addAction` yourself. * * It's possible to add conditions to the targets added in this way. At least * one set of targets must be added without conditions. @@ -263,6 +331,8 @@ export class ApplicationListener extends BaseListener implements IApplicationLis /** * Add a fixed response + * + * @deprecated Use `addAction()` instead */ public addFixedResponse(id: string, props: AddFixedResponseProps) { checkAddRuleProps(props); @@ -283,15 +353,17 @@ export class ApplicationListener extends BaseListener implements IApplicationLis ...props, }); } else { - this._addDefaultAction({ - fixedResponseConfig: fixedResponse, - type: 'fixed-response', - }); + this.setDefaultAction(ListenerAction.fixedResponse(Token.asNumber(props.statusCode), { + contentType: props.contentType, + messageBody: props.messageBody, + })); } } /** * Add a redirect response + * + * @deprecated Use `addAction()` instead */ public addRedirectResponse(id: string, props: AddRedirectResponseProps) { checkAddRuleProps(props); @@ -314,10 +386,14 @@ export class ApplicationListener extends BaseListener implements IApplicationLis ...props, }); } else { - this._addDefaultAction({ - redirectConfig: redirectResponse, - type: 'redirect', - }); + this.setDefaultAction(ListenerAction.redirect({ + host: props.host, + path: props.path, + port: props.port, + protocol: props.protocol, + query: props.query, + permanent: props.statusCode === 'HTTP_301', + })); } } @@ -342,11 +418,11 @@ export class ApplicationListener extends BaseListener implements IApplicationLis } /** - * Add a default TargetGroup + * Wrapper for _setDefaultAction which does a type-safe bind */ - private addDefaultTargetGroup(targetGroup: IApplicationTargetGroup) { - this._addDefaultTargetGroup(targetGroup); - targetGroup.registerListener(this); + private setDefaultAction(action: ListenerAction) { + action.bind(this, this); + this._setDefaultAction(action); } } @@ -591,6 +667,16 @@ export interface AddApplicationTargetGroupsProps extends AddRuleProps { readonly targetGroups: IApplicationTargetGroup[]; } +/** + * Properties for adding a new action to a listener + */ +export interface AddApplicationActionProps extends AddRuleProps { + /** + * Action to perform + */ + readonly action: ListenerAction; +} + /** * Properties for adding new targets to a listener */ @@ -669,12 +755,16 @@ export interface AddApplicationTargetsProps extends AddRuleProps { /** * Properties for adding a fixed response to a listener + * + * @deprecated Use `ApplicationListener.addAction` instead. */ export interface AddFixedResponseProps extends AddRuleProps, FixedResponse { } /** * Properties for adding a redirect response to a listener + * + * @deprecated Use `ApplicationListener.addAction` instead. */ export interface AddRedirectResponseProps extends AddRuleProps, RedirectResponse { } diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/index.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/index.ts index 898031490fb37..1442972c82a50 100644 --- a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/index.ts +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/index.ts @@ -6,10 +6,12 @@ export * from './alb/application-listener-certificate'; export * from './alb/application-listener-rule'; export * from './alb/application-load-balancer'; export * from './alb/application-target-group'; +export * from './alb/application-listener-action'; export * from './nlb/network-listener'; export * from './nlb/network-load-balancer'; export * from './nlb/network-target-group'; +export * from './nlb/network-listener-action'; export * from './shared/base-listener'; export * from './shared/base-load-balancer'; @@ -17,3 +19,4 @@ export * from './shared/base-target-group'; export * from './shared/enums'; export * from './shared/load-balancer-targets'; export * from './shared/listener-certificate'; +export * from './shared/listener-action'; \ No newline at end of file diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/nlb/network-listener-action.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/nlb/network-listener-action.ts new file mode 100644 index 0000000000000..81b45a5e3b146 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/nlb/network-listener-action.ts @@ -0,0 +1,155 @@ +import { Construct, Duration } from '@aws-cdk/core'; +import { CfnListener } from '../elasticloadbalancingv2.generated'; +import { IListenerAction } from '../shared/listener-action'; +import { INetworkListener } from './network-listener'; +import { INetworkTargetGroup } from './network-target-group'; + +/** + * What to do when a client makes a request to a listener + * + * Some actions can be combined with other ones (specifically, + * you can perform authentication before serving the request). + * + * Multiple actions form a linked chain; the chain must always terminate in a + * *(weighted)forward*, *fixedResponse* or *redirect* action. + * + * If an action supports chaining, the next action can be indicated + * by passing it in the `next` property. + */ +export class NetworkListenerAction implements IListenerAction { + /** + * Forward to one or more Target Groups + */ + public static forward(targetGroups: INetworkTargetGroup[], options: NetworkForwardOptions = {}): NetworkListenerAction { + if (targetGroups.length === 0) { + throw new Error('Need at least one targetGroup in a NetworkListenerAction.forward()'); + } + if (targetGroups.length === 1 && options.stickinessDuration === undefined) { + // Render a "simple" action for backwards compatibility with old templates + return new TargetGroupListenerAction(targetGroups, { + type: 'forward', + targetGroupArn: targetGroups[0].targetGroupArn, + }); + } + + return new TargetGroupListenerAction(targetGroups, { + type: 'forward', + forwardConfig: { + targetGroups: targetGroups.map(g => ({ targetGroupArn: g.targetGroupArn })), + targetGroupStickinessConfig: options.stickinessDuration ? { + durationSeconds: options.stickinessDuration.toSeconds(), + enabled: true, + } : undefined, + }, + }); + } + + /** + * Forward to one or more Target Groups which are weighted differently + */ + public static weightedForward(targetGroups: NetworkWeightedTargetGroup[], options: NetworkForwardOptions = {}): NetworkListenerAction { + if (targetGroups.length === 0) { + throw new Error('Need at least one targetGroup in a NetworkListenerAction.weightedForward()'); + } + + return new TargetGroupListenerAction(targetGroups.map(g => g.targetGroup), { + type: 'forward', + forwardConfig: { + targetGroups: targetGroups.map(g => ({ targetGroupArn: g.targetGroup.targetGroupArn, weight: g.weight })), + targetGroupStickinessConfig: options.stickinessDuration ? { + durationSeconds: options.stickinessDuration.toSeconds(), + enabled: true, + } : undefined, + }, + }); + } + + /** + * Create an instance of NetworkListenerAction + * + * The default class should be good enough for most cases and + * should be created by using one of the static factory functions, + * but allow overriding to make sure we allow flexibility for the future. + */ + protected constructor(private readonly actionJson: CfnListener.ActionProperty, protected readonly next?: NetworkListenerAction) { + } + + /** + * Render the actions in this chain + */ + public renderActions(): CfnListener.ActionProperty[] { + return this.renumber([this.actionJson, ...this.next?.renderActions() ?? []]); + } + + /** + * Called when the action is being used in a listener + */ + public bind(scope: Construct, listener: INetworkListener) { + // Empty on purpose + Array.isArray(scope); + Array.isArray(listener); + } + + /** + * Renumber the "order" fields in the actions array. + * + * We don't number for 0 or 1 elements, but otherwise number them 1...#actions + * so ELB knows about the right order. + * + * Do this in `NetworkListenerAction` instead of in `Listener` so that we give + * users the opportunity to override by subclassing and overriding `renderActions`. + */ + protected renumber(actions: CfnListener.ActionProperty[]): CfnListener.ActionProperty[] { + if (actions.length < 2) { return actions; } + + return actions.map((action, i) => ({ ...action, order: i + 1 })); + } +} + +/** + * Options for `NetworkListenerAction.forward()` + */ +export interface NetworkForwardOptions { + /** + * For how long clients should be directed to the same target group + * + * Range between 1 second and 7 days. + * + * @default - No stickiness + */ + readonly stickinessDuration?: Duration; +} + +/** + * A Target Group and weight combination + */ +export interface NetworkWeightedTargetGroup { + /** + * The target group + */ + readonly targetGroup: INetworkTargetGroup; + + /** + * The target group's weight + * + * Range is [0..1000). + * + * @default 1 + */ + readonly weight?: number; +} + +/** + * Listener Action that calls "registerListener" on TargetGroups + */ +class TargetGroupListenerAction extends NetworkListenerAction { + constructor(private readonly targetGroups: INetworkTargetGroup[], actionJson: CfnListener.ActionProperty) { + super(actionJson); + } + + public bind(_scope: Construct, listener: INetworkListener) { + for (const tg of this.targetGroups) { + tg.registerListener(listener); + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/nlb/network-listener.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/nlb/network-listener.ts index d3b4a3239cf11..f122b7470ce63 100644 --- a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/nlb/network-listener.ts +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/nlb/network-listener.ts @@ -3,6 +3,7 @@ import { BaseListener } from '../shared/base-listener'; import { HealthCheck } from '../shared/base-target-group'; import { Protocol, SslPolicy } from '../shared/enums'; import { IListenerCertificate } from '../shared/listener-certificate'; +import { NetworkListenerAction } from './network-listener-action'; import { INetworkLoadBalancer } from './network-load-balancer'; import { INetworkLoadBalancerTarget, INetworkTargetGroup, NetworkTargetGroup } from './network-target-group'; @@ -18,10 +19,29 @@ export interface BaseNetworkListenerProps { /** * Default target groups to load balance to * + * All target groups will be load balanced to with equal weight and without + * stickiness. For a more complex configuration than that, use + * either `defaultAction` or `addAction()`. + * + * Cannot be specified together with `defaultAction`. + * * @default - None. */ readonly defaultTargetGroups?: INetworkTargetGroup[]; + /** + * Default action to take for requests to this listener + * + * This allows full control of the default Action of the load balancer, + * including weighted forwarding. See the `NetworkListenerAction` class for + * all options. + * + * Cannot be specified together with `defaultTargetGroups`. + * + * @default - None. + */ + readonly defaultAction?: NetworkListenerAction; + /** * Protocol for listener, expects TCP or TLS * @@ -112,25 +132,51 @@ export class NetworkListener extends BaseListener implements INetworkListener { this.loadBalancer = props.loadBalancer; - (props.defaultTargetGroups || []).forEach(this._addDefaultTargetGroup.bind(this)); + if (props.defaultAction && props.defaultTargetGroups) { + throw new Error('Specify at most one of \'defaultAction\' and \'defaultTargetGroups\''); + } + + if (props.defaultAction) { + this.setDefaultAction(props.defaultAction); + } + + if (props.defaultTargetGroups) { + this.setDefaultAction(NetworkListenerAction.forward(props.defaultTargetGroups)); + } } /** * Load balance incoming requests to the given target groups. + * + * All target groups will be load balanced to with equal weight and without + * stickiness. For a more complex configuration than that, use `addAction()`. */ public addTargetGroups(_id: string, ...targetGroups: INetworkTargetGroup[]): void { - // New default target(s) - for (const targetGroup of targetGroups) { - this._addDefaultTargetGroup(targetGroup); - targetGroup.registerListener(this); - } + this.setDefaultAction(NetworkListenerAction.forward(targetGroups)); + } + + /** + * Perform the given Action on incoming requests + * + * This allows full control of the default Action of the load balancer, + * including weighted forwarding. See the `NetworkListenerAction` class for + * all options. + */ + public addAction(_id: string, props: AddNetworkActionProps): void { + this.setDefaultAction(props.action); } /** * Load balance incoming requests to the given load balancing targets. * - * This method implicitly creates an ApplicationTargetGroup for the targets - * involved. + * This method implicitly creates a NetworkTargetGroup for the targets + * involved, and a 'forward' action to route traffic to the given TargetGroup. + * + * If you want more control over the precise setup, create the TargetGroup + * and use `addAction` yourself. + * + * It's possible to add conditions to the targets added in this way. At least + * one set of targets must be added without conditions. * * @returns The newly created target group */ @@ -154,6 +200,14 @@ export class NetworkListener extends BaseListener implements INetworkListener { return group; } + + /** + * Wrapper for _setDefaultAction which does a type-safe bind + */ + private setDefaultAction(action: NetworkListenerAction) { + action.bind(this, this); + this._setDefaultAction(action); + } } /** @@ -167,6 +221,16 @@ export interface INetworkListener extends IResource { readonly listenerArn: string; } +/** + * Properties for adding a new action to a listener + */ +export interface AddNetworkActionProps { + /** + * Action to perform + */ + readonly action: NetworkListenerAction; +} + /** * Properties for adding new network targets to a listener */ diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/shared/base-listener.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/shared/base-listener.ts index 0af15c9f0215c..d9405bff1f729 100644 --- a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/shared/base-listener.ts +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/shared/base-listener.ts @@ -1,6 +1,6 @@ import { Construct, Lazy, Resource } from '@aws-cdk/core'; import { CfnListener } from '../elasticloadbalancingv2.generated'; -import { ITargetGroup } from './base-target-group'; +import { IListenerAction } from './listener-action'; /** * Base class for listeners @@ -11,14 +11,14 @@ export abstract class BaseListener extends Resource { */ public readonly listenerArn: string; - private readonly defaultActions: CfnListener.ActionProperty[] = []; + private defaultAction?: IListenerAction; constructor(scope: Construct, id: string, additionalProps: any) { super(scope, id); const resource = new CfnListener(this, 'Resource', { ...additionalProps, - defaultActions: Lazy.anyValue({ produce: () => this.defaultActions }), + defaultActions: Lazy.anyValue({ produce: () => this.defaultAction ? this.defaultAction.renderActions() : [] }), }); this.listenerArn = resource.ref; @@ -28,28 +28,31 @@ export abstract class BaseListener extends Resource { * Validate this listener */ protected validate(): string[] { - if (this.defaultActions.length === 0) { - return ['Listener needs at least one default target group (call addTargetGroups)']; + if (!this.defaultAction) { + return ['Listener needs at least one default action or target group (call addTargetGroups or addAction)']; } return []; } /** - * Add an action to the list of default actions of this listener + * Configure the default action + * * @internal */ - protected _addDefaultAction(action: CfnListener.ActionProperty) { - this.defaultActions.push(action); - } + protected _setDefaultAction(action: IListenerAction) { + // It might make sense to 'throw' here. + // + // However, programs may already exist out there which configured an action twice, + // in which case the second action accidentally overwrite the initial action, and in some + // way ended up with a program that did what the author intended. If we were to add throw now, + // the previously working program would be broken. + // + // Instead, signal this through a warning. + // @deprecate: upon the next major version bump, replace this with a `throw` + if (this.defaultAction) { + this.node.addWarning('A default Action already existed on this Listener and was replaced. Configure exactly one default Action.'); + } - /** - * Add a TargetGroup to the list of default actions of this listener - * @internal - */ - protected _addDefaultTargetGroup(targetGroup: ITargetGroup) { - this._addDefaultAction({ - targetGroupArn: targetGroup.targetGroupArn, - type: 'forward', - }); + this.defaultAction = action; } } diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/shared/listener-action.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/shared/listener-action.ts new file mode 100644 index 0000000000000..753c08c4755a7 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/lib/shared/listener-action.ts @@ -0,0 +1,11 @@ +import { CfnListener } from '../elasticloadbalancingv2.generated'; + +/** + * Interface for listener actions + */ +export interface IListenerAction { + /** + * Render the actions in this chain + */ + renderActions(): CfnListener.ActionProperty[]; +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/test/alb/test.actions.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/test/alb/test.actions.ts new file mode 100644 index 0000000000000..1921303469968 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/test/alb/test.actions.ts @@ -0,0 +1,185 @@ +import { expect, haveResource } from '@aws-cdk/assert'; +import * as ec2 from '@aws-cdk/aws-ec2'; +import * as cdk from '@aws-cdk/core'; +import { Test } from 'nodeunit'; +import * as elbv2 from '../../lib'; + +let stack: cdk.Stack; +let group1: elbv2.ApplicationTargetGroup; +let group2: elbv2.ApplicationTargetGroup; +let lb: elbv2.ApplicationLoadBalancer; + +export = { + 'setUp'(cb: () => void) { + stack = new cdk.Stack(); + const vpc = new ec2.Vpc(stack, 'Stack'); + group1 = new elbv2.ApplicationTargetGroup(stack, 'TargetGroup1', { vpc, port: 80 }); + group2 = new elbv2.ApplicationTargetGroup(stack, 'TargetGroup2', { vpc, port: 80 }); + lb = new elbv2.ApplicationLoadBalancer(stack, 'LB', { vpc }); + + cb(); + }, + + 'Forward action legacy rendering'(test: Test) { + // WHEN + lb.addListener('Listener', { + port: 80, + defaultAction: elbv2.ListenerAction.forward([group1]), + }); + + // THEN + expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::Listener', { + DefaultActions: [ + { + TargetGroupArn: { Ref: 'TargetGroup1E5480F51' }, + Type: 'forward', + }, + ], + })); + + test.done(); + }, + + 'Forward to multiple targetgroups with an Action and stickiness'(test: Test) { + // WHEN + lb.addListener('Listener', { + port: 80, + defaultAction: elbv2.ListenerAction.forward([group1, group2], { + stickinessDuration: cdk.Duration.hours(1), + }), + }); + + // THEN + expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::Listener', { + DefaultActions: [ + { + ForwardConfig: { + TargetGroupStickinessConfig: { + DurationSeconds: 3600, + Enabled: true, + }, + TargetGroups: [ + { + TargetGroupArn: { Ref: 'TargetGroup1E5480F51' }, + }, + { + TargetGroupArn: { Ref: 'TargetGroup2D571E5D7' }, + }, + ], + }, + Type: 'forward', + }, + ], + })); + + test.done(); + }, + + 'Weighted forward to multiple targetgroups with an Action'(test: Test) { + // WHEN + lb.addListener('Listener', { + port: 80, + defaultAction: elbv2.ListenerAction.weightedForward([ + { targetGroup: group1, weight: 10 }, + { targetGroup: group2, weight: 50 }, + ], { + stickinessDuration: cdk.Duration.hours(1), + }), + }); + + // THEN + expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::Listener', { + DefaultActions: [ + { + ForwardConfig: { + TargetGroupStickinessConfig: { + DurationSeconds: 3600, + Enabled: true, + }, + TargetGroups: [ + { + TargetGroupArn: { Ref: 'TargetGroup1E5480F51' }, + Weight: 10, + }, + { + TargetGroupArn: { Ref: 'TargetGroup2D571E5D7' }, + Weight: 50, + }, + ], + }, + Type: 'forward', + }, + ], + })); + test.done(); + }, + + 'Chaining OIDC authentication action'(test: Test) { + // WHEN + lb.addListener('Listener', { + port: 80, + defaultAction: elbv2.ListenerAction.authenticateOidc({ + authorizationEndpoint: 'A', + clientId: 'B', + clientSecret: cdk.SecretValue.plainText('C'), + issuer: 'D', + tokenEndpoint: 'E', + userInfoEndpoint: 'F', + next: elbv2.ListenerAction.forward([group1]), + }), + }); + + // THEN + expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::Listener', { + DefaultActions: [ + { + AuthenticateOidcConfig: { + AuthorizationEndpoint: 'A', + ClientId: 'B', + ClientSecret: 'C', + Issuer: 'D', + TokenEndpoint: 'E', + UserInfoEndpoint: 'F', + }, + Order: 1, + Type: 'authenticate-oidc', + }, + { + Order: 2, + TargetGroupArn: { Ref: 'TargetGroup1E5480F51' }, + Type: 'forward', + }, + ], + })); + + test.done(); + }, + + 'Add default Action and add Action with conditions'(test: Test) { + // GIVEN + const listener = lb.addListener('Listener', { port: 80 }); + + // WHEN + listener.addAction('Action1', { + action: elbv2.ListenerAction.forward([group1]), + }); + + listener.addAction('Action2', { + hostHeader: 'example.com', + priority: 10, + action: elbv2.ListenerAction.forward([group2]), + }); + + // THEN + expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::ListenerRule', { + Actions: [ + { + TargetGroupArn: { Ref: 'TargetGroup2D571E5D7' }, + Type: 'forward', + }, + ], + })); + + test.done(); + }, +}; \ No newline at end of file diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/test/alb/test.listener.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/test/alb/test.listener.ts index 242dbae69525f..7588119a3762f 100644 --- a/packages/@aws-cdk/aws-elasticloadbalancingv2/test/alb/test.listener.ts +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/test/alb/test.listener.ts @@ -1024,6 +1024,55 @@ export = { test.done(); }, + + 'not allowed to combine action specifiers when instantiating a Rule directly'(test: Test) { + // GIVEN + const stack = new cdk.Stack(); + const vpc = new ec2.Vpc(stack, 'Stack'); + const group = new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, port: 80 }); + const lb = new elbv2.ApplicationLoadBalancer(stack, 'LB', { vpc }); + const listener = lb.addListener('Listener', { port: 80 }); + + const baseProps = { listener, priority: 1, pathPatterns: ['/path1', '/path2'] }; + + // WHEN + test.throws(() => { + new elbv2.ApplicationListenerRule(stack, 'Rule1', { + ...baseProps, + fixedResponse: { statusCode: '200' }, + action: elbv2.ListenerAction.fixedResponse(200), + }); + }, /specify only one/); + + test.throws(() => { + new elbv2.ApplicationListenerRule(stack, 'Rule2', { + ...baseProps, + targetGroups: [group], + action: elbv2.ListenerAction.fixedResponse(200), + }); + }, /specify only one/); + + test.done(); + }, + + 'not allowed to specify defaultTargetGroups and defaultAction together'(test: Test) { + // GIVEN + const stack = new cdk.Stack(); + const vpc = new ec2.Vpc(stack, 'Stack'); + const group = new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, port: 80 }); + const lb = new elbv2.ApplicationLoadBalancer(stack, 'LB', { vpc }); + + // WHEN + test.throws(() => { + lb.addListener('Listener1', { + port: 80, + defaultTargetGroups: [group], + defaultAction: elbv2.ListenerAction.fixedResponse(200), + }); + }, /Specify at most one/); + + test.done(); + }, }; class ResourceWithLBDependency extends cdk.CfnResource { diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/test/nlb/test.actions.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/test/nlb/test.actions.ts new file mode 100644 index 0000000000000..f093cf1df2548 --- /dev/null +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/test/nlb/test.actions.ts @@ -0,0 +1,96 @@ +import { expect, haveResource } from '@aws-cdk/assert'; +import * as ec2 from '@aws-cdk/aws-ec2'; +import * as cdk from '@aws-cdk/core'; +import { Test } from 'nodeunit'; +import * as elbv2 from '../../lib'; + +let stack: cdk.Stack; +let group1: elbv2.NetworkTargetGroup; +let group2: elbv2.NetworkTargetGroup; +let lb: elbv2.NetworkLoadBalancer; + +export = { + 'setUp'(cb: () => void) { + stack = new cdk.Stack(); + const vpc = new ec2.Vpc(stack, 'Stack'); + group1 = new elbv2.NetworkTargetGroup(stack, 'TargetGroup1', { vpc, port: 80 }); + group2 = new elbv2.NetworkTargetGroup(stack, 'TargetGroup2', { vpc, port: 80 }); + lb = new elbv2.NetworkLoadBalancer(stack, 'LB', { vpc }); + + cb(); + }, + + 'Forward to multiple targetgroups with an Action and stickiness'(test: Test) { + // WHEN + lb.addListener('Listener', { + port: 80, + defaultAction: elbv2.NetworkListenerAction.forward([group1, group2], { + stickinessDuration: cdk.Duration.hours(1), + }), + }); + + // THEN + expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::Listener', { + DefaultActions: [ + { + ForwardConfig: { + TargetGroupStickinessConfig: { + DurationSeconds: 3600, + Enabled: true, + }, + TargetGroups: [ + { + TargetGroupArn: { Ref: 'TargetGroup1E5480F51' }, + }, + { + TargetGroupArn: { Ref: 'TargetGroup2D571E5D7' }, + }, + ], + }, + Type: 'forward', + }, + ], + })); + + test.done(); + }, + + 'Weighted forward to multiple targetgroups with an Action'(test: Test) { + // WHEN + lb.addListener('Listener', { + port: 80, + defaultAction: elbv2.NetworkListenerAction.weightedForward([ + { targetGroup: group1, weight: 10 }, + { targetGroup: group2, weight: 50 }, + ], { + stickinessDuration: cdk.Duration.hours(1), + }), + }); + + // THEN + expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::Listener', { + DefaultActions: [ + { + ForwardConfig: { + TargetGroupStickinessConfig: { + DurationSeconds: 3600, + Enabled: true, + }, + TargetGroups: [ + { + TargetGroupArn: { Ref: 'TargetGroup1E5480F51' }, + Weight: 10, + }, + { + TargetGroupArn: { Ref: 'TargetGroup2D571E5D7' }, + Weight: 50, + }, + ], + }, + Type: 'forward', + }, + ], + })); + test.done(); + }, +}; \ No newline at end of file diff --git a/packages/@aws-cdk/aws-elasticloadbalancingv2/test/nlb/test.listener.ts b/packages/@aws-cdk/aws-elasticloadbalancingv2/test/nlb/test.listener.ts index ba9eb7ce61327..a94421e357154 100644 --- a/packages/@aws-cdk/aws-elasticloadbalancingv2/test/nlb/test.listener.ts +++ b/packages/@aws-cdk/aws-elasticloadbalancingv2/test/nlb/test.listener.ts @@ -315,6 +315,25 @@ export = { test.done(); }, + + 'not allowed to specify defaultTargetGroups and defaultAction together'(test: Test) { + // GIVEN + const stack = new cdk.Stack(); + const vpc = new ec2.Vpc(stack, 'Stack'); + const group = new elbv2.NetworkTargetGroup(stack, 'TargetGroup', { vpc, port: 80 }); + const lb = new elbv2.NetworkLoadBalancer(stack, 'LB', { vpc }); + + // WHEN + test.throws(() => { + lb.addListener('Listener1', { + port: 80, + defaultTargetGroups: [group], + defaultAction: elbv2.NetworkListenerAction.forward([group]), + }); + }, /Specify at most one/); + + test.done(); + }, }; class ResourceWithLBDependency extends cdk.CfnResource { diff --git a/packages/@aws-cdk/aws-events-targets/package.json b/packages/@aws-cdk/aws-events-targets/package.json index 3090d038e8a72..8da67c2da5412 100644 --- a/packages/@aws-cdk/aws-events-targets/package.json +++ b/packages/@aws-cdk/aws-events-targets/package.json @@ -68,7 +68,7 @@ "devDependencies": { "@aws-cdk/assert": "0.0.0", "@aws-cdk/aws-codecommit": "0.0.0", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "aws-sdk-mock": "^5.1.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", diff --git a/packages/@aws-cdk/aws-lambda/package.json b/packages/@aws-cdk/aws-lambda/package.json index 1c3f44a954a7e..c981c16f64fb6 100644 --- a/packages/@aws-cdk/aws-lambda/package.json +++ b/packages/@aws-cdk/aws-lambda/package.json @@ -71,7 +71,7 @@ "@types/lodash": "^4.14.151", "@types/nodeunit": "^0.0.31", "@types/sinon": "^9.0.1", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "aws-sdk-mock": "^5.1.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", diff --git a/packages/@aws-cdk/aws-route53/package.json b/packages/@aws-cdk/aws-route53/package.json index d26e7eb3366de..4b8e9a7d04a76 100644 --- a/packages/@aws-cdk/aws-route53/package.json +++ b/packages/@aws-cdk/aws-route53/package.json @@ -64,7 +64,7 @@ "devDependencies": { "@aws-cdk/assert": "0.0.0", "@types/nodeunit": "^0.0.31", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", "cfn2ts": "0.0.0", diff --git a/packages/@aws-cdk/aws-sqs/package.json b/packages/@aws-cdk/aws-sqs/package.json index c510af43a5dad..e95c4edd5984f 100644 --- a/packages/@aws-cdk/aws-sqs/package.json +++ b/packages/@aws-cdk/aws-sqs/package.json @@ -65,7 +65,7 @@ "@aws-cdk/assert": "0.0.0", "@aws-cdk/aws-s3": "0.0.0", "@types/nodeunit": "^0.0.31", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", "cfn2ts": "0.0.0", diff --git a/packages/@aws-cdk/cloudformation-include/README.md b/packages/@aws-cdk/cloudformation-include/README.md index d4f2795b7d6d6..9996c500feb7f 100644 --- a/packages/@aws-cdk/cloudformation-include/README.md +++ b/packages/@aws-cdk/cloudformation-include/README.md @@ -105,7 +105,7 @@ All items unchecked below are currently not supported. - [x] Properties - [ ] Condition -- [ ] DependsOn +- [x] DependsOn - [ ] CreationPolicy - [ ] UpdatePolicy - [x] UpdateReplacePolicy diff --git a/packages/@aws-cdk/cloudformation-include/lib/cfn-include.ts b/packages/@aws-cdk/cloudformation-include/lib/cfn-include.ts index 9807e652dbdaf..d825a7ae24845 100644 --- a/packages/@aws-cdk/cloudformation-include/lib/cfn-include.ts +++ b/packages/@aws-cdk/cloudformation-include/lib/cfn-include.ts @@ -92,7 +92,7 @@ export class CfnInclude extends core.CfnElement { throw new Error(`Unrecognized CloudFormation resource type: '${resourceAttributes.Type}'`); } // fail early for resource attributes we don't support yet - const knownAttributes = ['Type', 'Properties', 'DeletionPolicy', 'UpdateReplacePolicy', 'Metadata']; + const knownAttributes = ['Type', 'Properties', 'DependsOn', 'DeletionPolicy', 'UpdateReplacePolicy', 'Metadata']; for (const attribute of Object.keys(resourceAttributes)) { if (!knownAttributes.includes(attribute)) { throw new Error(`The ${attribute} resource attribute is not supported by cloudformation-include yet. ` + @@ -103,7 +103,19 @@ export class CfnInclude extends core.CfnElement { const [moduleName, ...className] = l1ClassFqn.split('.'); const module = require(moduleName); // eslint-disable-line @typescript-eslint/no-require-imports const jsClassFromModule = module[className.join('.')]; - const l1Instance = jsClassFromModule.fromCloudFormation(this, logicalId, resourceAttributes); + const self = this; + const finder: core.ICfnFinder = { + findResource(lId: string): core.CfnResource | undefined { + if (!(lId in (self.template.Resources || {}))) { + return undefined; + } + return self.getOrCreateResource(lId); + }, + }; + const options: core.FromCloudFormationOptions = { + finder, + }; + const l1Instance = jsClassFromModule.fromCloudFormation(this, logicalId, resourceAttributes, options); if (this.preserveLogicalIds) { // override the logical ID to match the original template diff --git a/packages/@aws-cdk/cloudformation-include/test/invalid-templates.test.ts b/packages/@aws-cdk/cloudformation-include/test/invalid-templates.test.ts index 955d6ff312d87..3e03ed5468de4 100644 --- a/packages/@aws-cdk/cloudformation-include/test/invalid-templates.test.ts +++ b/packages/@aws-cdk/cloudformation-include/test/invalid-templates.test.ts @@ -40,6 +40,12 @@ describe('CDK Include', () => { SynthUtils.synthesize(stack); }).toThrow(/allowedOrigins: required but missing/); }); + + test("throws a validation exception for a template with a DependsOn that doesn't exist", () => { + expect(() => { + includeTestTemplate(stack, 'non-existent-depends-on.json'); + }).toThrow(/Resource 'Bucket2' depends on 'Bucket1' that doesn't exist/); + }); }); function includeTestTemplate(scope: core.Construct, testTemplate: string): inc.CfnInclude { diff --git a/packages/@aws-cdk/cloudformation-include/test/test-templates/invalid/non-existent-depends-on.json b/packages/@aws-cdk/cloudformation-include/test/test-templates/invalid/non-existent-depends-on.json new file mode 100644 index 0000000000000..442e9c70d80c0 --- /dev/null +++ b/packages/@aws-cdk/cloudformation-include/test/test-templates/invalid/non-existent-depends-on.json @@ -0,0 +1,11 @@ +{ + "Resources": { + "Bucket2": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "bucket2" + }, + "DependsOn": "Bucket1" + } + } +} diff --git a/packages/@aws-cdk/cloudformation-include/test/test-templates/resource-attribute-depends-on-array.json b/packages/@aws-cdk/cloudformation-include/test/test-templates/resource-attribute-depends-on-array.json new file mode 100644 index 0000000000000..a456c9a5a6b16 --- /dev/null +++ b/packages/@aws-cdk/cloudformation-include/test/test-templates/resource-attribute-depends-on-array.json @@ -0,0 +1,17 @@ +{ + "Resources": { + "Bucket0": { + "Type": "AWS::S3::Bucket" + }, + "Bucket1": { + "Type": "AWS::S3::Bucket" + }, + "Bucket2": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "bucket2" + }, + "DependsOn": ["Bucket0", "Bucket1"] + } + } +} diff --git a/packages/@aws-cdk/cloudformation-include/test/test-templates/resource-attribute-depends-on.json b/packages/@aws-cdk/cloudformation-include/test/test-templates/resource-attribute-depends-on.json index 82bd4fa42b847..82b049a7fd2ac 100644 --- a/packages/@aws-cdk/cloudformation-include/test/test-templates/resource-attribute-depends-on.json +++ b/packages/@aws-cdk/cloudformation-include/test/test-templates/resource-attribute-depends-on.json @@ -5,6 +5,9 @@ }, "Bucket2": { "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "bucket2" + }, "DependsOn": "Bucket1" } } diff --git a/packages/@aws-cdk/cloudformation-include/test/valid-templates.test.ts b/packages/@aws-cdk/cloudformation-include/test/valid-templates.test.ts index 6bdd001bddb27..121e163fb0ef4 100644 --- a/packages/@aws-cdk/cloudformation-include/test/valid-templates.test.ts +++ b/packages/@aws-cdk/cloudformation-include/test/valid-templates.test.ts @@ -1,3 +1,4 @@ +import { ResourcePart } from '@aws-cdk/assert'; import '@aws-cdk/assert/jest'; import * as iam from '@aws-cdk/aws-iam'; import * as s3 from '@aws-cdk/aws-s3'; @@ -199,6 +200,38 @@ describe('CDK Include', () => { ); }); + test('resolves DependsOn with a single String value to the actual L1 class instance', () => { + const cfnTemplate = includeTestTemplate(stack, 'resource-attribute-depends-on.json'); + const cfnBucket2 = cfnTemplate.getResource('Bucket2'); + + expect(cfnBucket2.node.dependencies).toHaveLength(1); + // we always render dependsOn as an array, even if it's a single string + expect(stack).toHaveResourceLike('AWS::S3::Bucket', { + "Properties": { + "BucketName": "bucket2", + }, + "DependsOn": [ + "Bucket1", + ], + }, ResourcePart.CompleteDefinition); + }); + + test('resolves DependsOn with an array of String values to the actual L1 class instances', () => { + const cfnTemplate = includeTestTemplate(stack, 'resource-attribute-depends-on-array.json'); + const cfnBucket2 = cfnTemplate.getResource('Bucket2'); + + expect(cfnBucket2.node.dependencies).toHaveLength(2); + expect(stack).toHaveResourceLike('AWS::S3::Bucket', { + "Properties": { + "BucketName": "bucket2", + }, + "DependsOn": [ + "Bucket0", + "Bucket1", + ], + }, ResourcePart.CompleteDefinition); + }); + test("throws an exception when encountering a Resource type it doesn't recognize", () => { expect(() => { includeTestTemplate(stack, 'non-existent-resource-type.json'); @@ -217,12 +250,6 @@ describe('CDK Include', () => { }).toThrow(/The Condition resource attribute is not supported by cloudformation-include yet/); }); - test('throws an exception when encountering the DependsOn attribute in a resource', () => { - expect(() => { - includeTestTemplate(stack, 'resource-attribute-depends-on.json'); - }).toThrow(/The DependsOn resource attribute is not supported by cloudformation-include yet/); - }); - test('throws an exception when encountering the CreationPolicy attribute in a resource', () => { expect(() => { includeTestTemplate(stack, 'resource-attribute-creation-policy.json'); diff --git a/packages/@aws-cdk/core/lib/from-cfn.ts b/packages/@aws-cdk/core/lib/from-cfn.ts new file mode 100644 index 0000000000000..25127ad1fefbc --- /dev/null +++ b/packages/@aws-cdk/core/lib/from-cfn.ts @@ -0,0 +1,29 @@ +import { CfnResource } from './cfn-resource'; + +/** + * An interface that represents callbacks into a CloudFormation template. + * Used by the fromCloudFormation methods in the generated L1 classes. + * + * @experimental + */ +export interface ICfnFinder { + /** + * Returns the resource with the given logical ID in the template. + * If a resource with that logical ID was not found in the template, + * returns undefined. + */ + findResource(logicalId: string): CfnResource | undefined; +} + +/** + * The interface used as the last argument to the fromCloudFormation + * static method of the generated L1 classes. + * + * @experimental + */ +export interface FromCloudFormationOptions { + /** + * The finder interface used to resolve references across the template. + */ + readonly finder: ICfnFinder; +} diff --git a/packages/@aws-cdk/core/lib/index.ts b/packages/@aws-cdk/core/lib/index.ts index a4690f41dc898..3c3cf2cd442ad 100644 --- a/packages/@aws-cdk/core/lib/index.ts +++ b/packages/@aws-cdk/core/lib/index.ts @@ -28,6 +28,7 @@ export * from './cfn-tag'; export * from './removal-policy'; export * from './arn'; export * from './duration'; +export * from './from-cfn'; export * from './size'; export * from './stack-trace'; diff --git a/packages/@aws-cdk/custom-resources/package.json b/packages/@aws-cdk/custom-resources/package.json index d93639a313004..7139b16c5e651 100644 --- a/packages/@aws-cdk/custom-resources/package.json +++ b/packages/@aws-cdk/custom-resources/package.json @@ -74,7 +74,7 @@ "@types/aws-lambda": "^8.10.39", "@types/fs-extra": "^8.1.0", "@types/sinon": "^9.0.1", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "aws-sdk-mock": "^5.1.0", "cdk-build-tools": "0.0.0", "cdk-integ-tools": "0.0.0", diff --git a/packages/aws-cdk/package.json b/packages/aws-cdk/package.json index 4946d9178d621..527d0f964f51e 100644 --- a/packages/aws-cdk/package.json +++ b/packages/aws-cdk/package.json @@ -71,7 +71,7 @@ "@aws-cdk/cloud-assembly-schema": "0.0.0", "@aws-cdk/region-info": "0.0.0", "archiver": "^4.0.1", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "camelcase": "^6.0.0", "cdk-assets": "0.0.0", "colors": "^1.4.0", diff --git a/packages/cdk-assets/package.json b/packages/cdk-assets/package.json index 0b5d7c1d9aff2..04a6cdb5c283e 100644 --- a/packages/cdk-assets/package.json +++ b/packages/cdk-assets/package.json @@ -48,7 +48,7 @@ "@aws-cdk/cdk-assets-schema": "0.0.0", "@aws-cdk/cx-api": "0.0.0", "archiver": "^4.0.1", - "aws-sdk": "^2.678.0", + "aws-sdk": "^2.679.0", "glob": "^7.1.6", "yargs": "^15.3.1" }, diff --git a/packages/decdk/package.json b/packages/decdk/package.json index fa81a42631f46..ba005f527185d 100644 --- a/packages/decdk/package.json +++ b/packages/decdk/package.json @@ -177,7 +177,8 @@ "fs-extra": "^8.1.0", "jsii-reflect": "^1.5.0", "jsonschema": "^1.2.6", - "yaml": "1.10.0", + "@aws-cdk/aws-elasticloadbalancingv2-actions": "0.0.0", + "yaml": "1.9.2", "yargs": "^15.3.1" }, "devDependencies": { diff --git a/packages/monocdk-experiment/package.json b/packages/monocdk-experiment/package.json index ab7bbc3ad13b5..cbadf0077116f 100644 --- a/packages/monocdk-experiment/package.json +++ b/packages/monocdk-experiment/package.json @@ -193,7 +193,8 @@ "@aws-cdk/aws-resourcegroups": "0.0.0", "@aws-cdk/aws-detective": "0.0.0", "@aws-cdk/aws-ce": "0.0.0", - "@aws-cdk/aws-synthetics": "0.0.0" + "@aws-cdk/aws-synthetics": "0.0.0", + "@aws-cdk/aws-elasticloadbalancingv2-actions": "0.0.0" }, "peerDependencies": { "constructs": "^3.0.2" diff --git a/tools/cdk-build-tools/package.json b/tools/cdk-build-tools/package.json index 3e69e99dd72f1..b76128847cee0 100644 --- a/tools/cdk-build-tools/package.json +++ b/tools/cdk-build-tools/package.json @@ -39,7 +39,7 @@ "pkglint": "0.0.0" }, "dependencies": { - "@typescript-eslint/eslint-plugin": "^2.33.0", + "@typescript-eslint/eslint-plugin": "^2.34.0", "@typescript-eslint/parser": "^2.19.2", "awslint": "0.0.0", "colors": "^1.4.0", diff --git a/tools/cfn2ts/lib/codegen.ts b/tools/cfn2ts/lib/codegen.ts index 0689be9027ac4..7efe4275f0dc9 100644 --- a/tools/cfn2ts/lib/codegen.ts +++ b/tools/cfn2ts/lib/codegen.ts @@ -232,7 +232,7 @@ export default class CodeGenerator { this.code.line(' *'); this.code.line(' * @experimental'); this.code.line(' */'); - this.code.openBlock(`public static fromCloudFormation(scope: ${CONSTRUCT_CLASS}, id: string, resourceAttributes: any): ` + + this.code.openBlock(`public static fromCloudFormation(scope: ${CONSTRUCT_CLASS}, id: string, resourceAttributes: any, options: ${CORE}.FromCloudFormationOptions): ` + `${resourceName.className}`); this.code.line('resourceAttributes = resourceAttributes || {};'); if (propsType) { @@ -252,11 +252,24 @@ export default class CodeGenerator { this.code.line(`cfnOptions.deletionPolicy = ${CFN_PARSE}.FromCloudFormation.parseDeletionPolicy(resourceAttributes.DeletionPolicy);`); this.code.line(`cfnOptions.updateReplacePolicy = ${CFN_PARSE}.FromCloudFormation.parseDeletionPolicy(resourceAttributes.UpdateReplacePolicy);`); this.code.line(`cfnOptions.metadata = ${CFN_PARSE}.FromCloudFormation.parseValue(resourceAttributes.Metadata);`); + + // handle DependsOn + this.code.line('// handle DependsOn'); + // DependsOn can be either a single string, or an array of strings + this.code.line('resourceAttributes.DependsOn = resourceAttributes.DependsOn ?? [];'); + this.code.line('const dependencies: string[] = Array.isArray(resourceAttributes.DependsOn) ? resourceAttributes.DependsOn : [resourceAttributes.DependsOn];'); + this.code.openBlock('for (const dep of dependencies)'); + this.code.line('const depResource = options.finder.findResource(dep);'); + this.code.openBlock('if (!depResource)'); + this.code.line("throw new Error(`Resource '${id}' depends on '${dep}' that doesn't exist`);"); + this.code.closeBlock(); + this.code.line('ret.node.addDependency(depResource);'); + this.code.closeBlock(); + // ToDo handle: // 1. Condition // 2. CreationPolicy // 3. UpdatePolicy - // 4. DependsOn this.code.line('return ret;'); this.code.closeBlock(); diff --git a/yarn.lock b/yarn.lock index c8ee0e781a7b6..dbd9f39118032 100644 --- a/yarn.lock +++ b/yarn.lock @@ -219,6 +219,13 @@ dependencies: "@babel/helper-plugin-utils" "^7.8.0" +"@babel/runtime@^7.9.2": + version "7.9.6" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.9.6.tgz#a9102eb5cadedf3f31d08a9ecf294af7827ea29f" + integrity sha512-64AF1xY3OAkFHqOb9s4jpgk1Mm5vDZ4L3acHvAml+53nO1XbXLuDodsVpO4OIUsmemlUHMxNdYMNJmsvOwLrvQ== + dependencies: + regenerator-runtime "^0.13.4" + "@babel/template@^7.3.3", "@babel/template@^7.4.0", "@babel/template@^7.7.4", "@babel/template@^7.8.3", "@babel/template@^7.8.6": version "7.8.6" resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.8.6.tgz#86b22af15f828dfb086474f964dcc3e39c43ce2b" @@ -1634,12 +1641,12 @@ resolved "https://registry.yarnpkg.com/@types/yarnpkg__lockfile/-/yarnpkg__lockfile-1.1.3.tgz#38fb31d82ed07dea87df6bd565721d11979fd761" integrity sha512-mhdQq10tYpiNncMkg1vovCud5jQm+rWeRVz6fxjCJlY6uhDlAn9GnMSmBa2DQwqPf/jS5YR0K/xChDEh1jdOQg== -"@typescript-eslint/eslint-plugin@^2.33.0": - version "2.33.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.33.0.tgz#d6c8319d5011b4783bb3d2dadf105d8bdd499bd5" - integrity sha512-QV6P32Btu1sCI/kTqjTNI/8OpCYyvlGjW5vD8MpTIg+HGE5S88HtT1G+880M4bXlvXj/NjsJJG0aGcVh0DdbeQ== +"@typescript-eslint/eslint-plugin@^2.34.0": + version "2.34.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.34.0.tgz#6f8ce8a46c7dea4a6f1d171d2bb8fbae6dac2be9" + integrity sha512-4zY3Z88rEE99+CNvTbXSyovv2z9PNOVffTWD2W8QF5s2prBQtwN2zadqERcrHpcR7O/+KMI3fcTAmUUhK/iQcQ== dependencies: - "@typescript-eslint/experimental-utils" "2.33.0" + "@typescript-eslint/experimental-utils" "2.34.0" functional-red-black-tree "^1.0.1" regexpp "^3.0.0" tsutils "^3.17.1" @@ -1654,13 +1661,13 @@ eslint-scope "^5.0.0" eslint-utils "^2.0.0" -"@typescript-eslint/experimental-utils@2.33.0": - version "2.33.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-2.33.0.tgz#000f1e5f344fbea1323dc91cc174805d75f99a03" - integrity sha512-qzPM2AuxtMrRq78LwyZa8Qn6gcY8obkIrBs1ehqmQADwkYzTE1Pb4y2W+U3rE/iFkSWcWHG2LS6MJfj6SmHApg== +"@typescript-eslint/experimental-utils@2.34.0": + version "2.34.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-2.34.0.tgz#d3524b644cdb40eebceca67f8cf3e4cc9c8f980f" + integrity sha512-eS6FTkq+wuMJ+sgtuNTtcqavWXqsflWcfBnlYhg/nS4aZ1leewkXGbvBhaapn1q6qf4M71bsR1tez5JTRMuqwA== dependencies: "@types/json-schema" "^7.0.3" - "@typescript-eslint/typescript-estree" "2.33.0" + "@typescript-eslint/typescript-estree" "2.34.0" eslint-scope "^5.0.0" eslint-utils "^2.0.0" @@ -1687,10 +1694,10 @@ semver "^6.3.0" tsutils "^3.17.1" -"@typescript-eslint/typescript-estree@2.33.0": - version "2.33.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-2.33.0.tgz#33504c050ccafd38f397a645d4e9534d2eccbb5c" - integrity sha512-d8rY6/yUxb0+mEwTShCQF2zYQdLlqihukNfG9IUlLYz5y1CH6G/9XYbrxQLq3Z14RNvkCC6oe+OcFlyUpwUbkg== +"@typescript-eslint/typescript-estree@2.34.0": + version "2.34.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-2.34.0.tgz#14aeb6353b39ef0732cc7f1b8285294937cf37d5" + integrity sha512-OMAr+nJWKdlVM9LOqCqh3pQQPwxHAN7Du8DR6dmwCrAmxtiXQnhHJ6tBNtf+cggqfo51SG/FCwnKhXCIM7hnVg== dependencies: debug "^4.1.1" eslint-visitor-keys "^1.1.0" @@ -2109,10 +2116,10 @@ aws-sdk-mock@^5.1.0: sinon "^9.0.1" traverse "^0.6.6" -aws-sdk@^2.637.0, aws-sdk@^2.678.0: - version "2.678.0" - resolved "https://registry.yarnpkg.com/aws-sdk/-/aws-sdk-2.678.0.tgz#b16230f4894d40ead50f9e23805c874f4ca62549" - integrity sha512-i8t7+1/C6maQzUYUFRQXPAsUPT0YdpNsf/oHZKmmZrsOX+epnn2jmAGIBTZgUakY8jRrZxCJka+QokUIadUVQg== +aws-sdk@^2.637.0, aws-sdk@^2.679.0: + version "2.679.0" + resolved "https://registry.yarnpkg.com/aws-sdk/-/aws-sdk-2.679.0.tgz#493419ef8cc1a6a4fee0c3be70b512228f4065cf" + integrity sha512-bsbu3Mbwqz2DHpVSSgaSoFYsNrW+54vXN74iG++cCE7AAg9vOgCKzGul8yhR4jxxlOmGlfP9kCNrkCpjQ/Uqkg== dependencies: buffer "4.9.1" events "1.1.1" @@ -5881,7 +5888,7 @@ jest-worker@^25.5.0: merge-stream "^2.0.0" supports-color "^7.0.0" -jest@^25.4.0, jest@^25.5.3, jest@^25.5.4: +jest@^25.4.0, jest@^25.5.2, jest@^25.5.3, jest@^25.5.4: version "25.5.4" resolved "https://registry.yarnpkg.com/jest/-/jest-25.5.4.tgz#f21107b6489cfe32b076ce2adcadee3587acb9db" integrity sha512-hHFJROBTqZahnO+X+PMtT6G2/ztqAZJveGqz//FnWWHurizkD05PQGzRZOhF3XP6z7SJmL+5tCfW8qV06JypwQ== @@ -8115,6 +8122,11 @@ redent@^3.0.0: indent-string "^4.0.0" strip-indent "^3.0.0" +regenerator-runtime@^0.13.4: + version "0.13.5" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.5.tgz#d878a1d094b4306d10b9096484b33ebd55e26697" + integrity sha512-ZS5w8CpKFinUzOwW3c83oPeVXoNsrLsaCoLtJvAClH135j/R77RuymhiSErhm2lKcwSCIpmvIWSbDkIfAqKQlA== + regex-not@^1.0.0, regex-not@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c" @@ -10069,6 +10081,13 @@ yaml@*, yaml@1.10.0, yaml@^1.10.0, yaml@^1.5.0: resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.0.tgz#3b593add944876077d4d683fee01081bd9fff31e" integrity sha512-yr2icI4glYaNG+KWONODapy2/jDdMSDnrONSjblABjD9B4Z5LgiircSt8m8sRZFNi08kG9Sm0uSHtEmP3zaEGg== +yaml@1.9.2: + version "1.9.2" + resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.9.2.tgz#f0cfa865f003ab707663e4f04b3956957ea564ed" + integrity sha512-HPT7cGGI0DuRcsO51qC1j9O16Dh1mZ2bnXwsi0jrSpsLz0WxOLSLXfkABVl6bZO629py3CU+OMJtpNHDLB97kg== + dependencies: + "@babel/runtime" "^7.9.2" + yapool@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/yapool/-/yapool-1.0.0.tgz#f693f29a315b50d9a9da2646a7a6645c96985b6a"