From abc78bfa613453185e59d5d9a17e5c5cfb5437b3 Mon Sep 17 00:00:00 2001 From: John Dukewich <37190801+jdukewich@users.noreply.github.com> Date: Wed, 7 Aug 2024 18:00:08 -0400 Subject: [PATCH] feat(ec2): security group lookup via filters (#30625) ### Issue # (if applicable) Closes #30331. ### Reason for this change This will improve the security group lookup functionality for importing existing security groups into a CDK stack. ### Description of changes I added the ability to lookup existing security groups via more filters. Filters are supported by the [DescribeSecurityGroups API](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSecurityGroups.html), and using these filters can be immensely useful for looking up existing security groups, especially if your account or organization follows predictable rules regarding things like security group tags. ### Description of how you validated changes I added unit tests similar to the ones that test the normal lookup by ID or name. ### Checklist - [x] My code adheres to the [CONTRIBUTING GUIDE](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md) and [DESIGN GUIDELINES](https://github.com/aws/aws-cdk/blob/main/docs/DESIGN_GUIDELINES.md) ---- *By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license* --- .../LookupStack.assets.json | 20 + .../LookupStack.template.json | 36 ++ ...efaultTestDeployAssert9466B7BF.assets.json | 19 + ...aultTestDeployAssert9466B7BF.template.json | 36 ++ .../StackWithSg.assets.json | 34 ++ .../StackWithSg.template.json | 233 +++++++++++ .../__entrypoint__.js | 155 +++++++ .../index.js | 1 + .../cdk.out | 1 + .../integ.json | 13 + .../manifest.json | 253 +++++++++++ .../tree.json | 392 ++++++++++++++++++ .../test/integ.security-group-lookup.ts | 56 +++ packages/aws-cdk-lib/aws-ec2/README.md | 12 +- .../aws-cdk-lib/aws-ec2/lib/security-group.ts | 57 ++- .../aws-ec2/test/security-group.test.ts | 24 ++ .../lib/cloud-assembly/context-queries.ts | 28 ++ .../schema/cloud-assembly.schema.json | 22 + .../schema/cloud-assembly.version.json | 2 +- .../lib/context-providers/security-groups.ts | 30 +- .../context-providers/security-groups.test.ts | 87 +++- 21 files changed, 1485 insertions(+), 26 deletions(-) create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/LookupStack.assets.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/LookupStack.template.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.assets.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.template.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.assets.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.template.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/asset.bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1/__entrypoint__.js create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/asset.bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1/index.js create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/cdk.out create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/integ.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/manifest.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/tree.json create mode 100644 packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.ts diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/LookupStack.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/LookupStack.assets.json new file mode 100644 index 0000000000000..fc94649590768 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/LookupStack.assets.json @@ -0,0 +1,20 @@ +{ + "version": "37.0.0", + "files": { + "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22": { + "source": { + "path": "LookupStack.template.json", + "packaging": "file" + }, + "destinations": { + "12345678-test-region": { + "bucketName": "cdk-hnb659fds-assets-12345678-test-region", + "objectKey": "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "region": "test-region", + "assumeRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-file-publishing-role-12345678-test-region" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/LookupStack.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/LookupStack.template.json new file mode 100644 index 0000000000000..ad9d0fb73d1dd --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/LookupStack.template.json @@ -0,0 +1,36 @@ +{ + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.assets.json new file mode 100644 index 0000000000000..e67d33537caf4 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.assets.json @@ -0,0 +1,19 @@ +{ + "version": "37.0.0", + "files": { + "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22": { + "source": { + "path": "SgLookupTestDefaultTestDeployAssert9466B7BF.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.template.json new file mode 100644 index 0000000000000..ad9d0fb73d1dd --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.template.json @@ -0,0 +1,36 @@ +{ + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.assets.json new file mode 100644 index 0000000000000..a65bbb573ca89 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.assets.json @@ -0,0 +1,34 @@ +{ + "version": "37.0.0", + "files": { + "bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1": { + "source": { + "path": "asset.bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1", + "packaging": "zip" + }, + "destinations": { + "12345678-test-region": { + "bucketName": "cdk-hnb659fds-assets-12345678-test-region", + "objectKey": "bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1.zip", + "region": "test-region", + "assumeRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-file-publishing-role-12345678-test-region" + } + } + }, + "e205a0cabbb47f8c8f8f543d0ad04ed8b26973d67ffd51d9583342d4ad69a2a9": { + "source": { + "path": "StackWithSg.template.json", + "packaging": "file" + }, + "destinations": { + "12345678-test-region": { + "bucketName": "cdk-hnb659fds-assets-12345678-test-region", + "objectKey": "e205a0cabbb47f8c8f8f543d0ad04ed8b26973d67ffd51d9583342d4ad69a2a9.json", + "region": "test-region", + "assumeRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-file-publishing-role-12345678-test-region" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.template.json new file mode 100644 index 0000000000000..eefe64d08796d --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.template.json @@ -0,0 +1,233 @@ +{ + "Resources": { + "MyVpcF9F0CA6F": { + "Type": "AWS::EC2::VPC", + "Properties": { + "CidrBlock": "10.0.0.0/16", + "EnableDnsHostnames": true, + "EnableDnsSupport": true, + "InstanceTenancy": "default", + "Tags": [ + { + "Key": "Name", + "Value": "my-vpc-name" + } + ] + } + }, + "MyVpcRestrictDefaultSecurityGroupCustomResourceA4FCCD62": { + "Type": "Custom::VpcRestrictDefaultSG", + "Properties": { + "ServiceToken": { + "Fn::GetAtt": [ + "CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E", + "Arn" + ] + }, + "DefaultSecurityGroupId": { + "Fn::GetAtt": [ + "MyVpcF9F0CA6F", + "DefaultSecurityGroup" + ] + }, + "Account": "12345678" + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + } + ] + }, + "ManagedPolicyArns": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + } + ], + "Policies": [ + { + "PolicyName": "Inline", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "ec2:AuthorizeSecurityGroupIngress", + "ec2:AuthorizeSecurityGroupEgress", + "ec2:RevokeSecurityGroupIngress", + "ec2:RevokeSecurityGroupEgress" + ], + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":ec2:test-region:12345678:security-group/", + { + "Fn::GetAtt": [ + "MyVpcF9F0CA6F", + "DefaultSecurityGroup" + ] + } + ] + ] + } + ] + } + ] + } + } + ] + } + }, + "CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Code": { + "S3Bucket": "cdk-hnb659fds-assets-12345678-test-region", + "S3Key": "bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1.zip" + }, + "Timeout": 900, + "MemorySize": 128, + "Handler": "__entrypoint__.handler", + "Role": { + "Fn::GetAtt": [ + "CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0", + "Arn" + ] + }, + "Runtime": "nodejs18.x", + "Description": "Lambda function for removing all inbound/outbound rules from the VPC default security group" + }, + "DependsOn": [ + "CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0" + ] + }, + "MySgAFDC270F2": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "StackWithSg/MySgA", + "SecurityGroupEgress": [ + { + "CidrIp": "0.0.0.0/0", + "Description": "Allow all outbound traffic by default", + "IpProtocol": "-1" + } + ], + "Tags": [ + { + "Key": "myTag", + "Value": "my-value" + } + ], + "VpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + }, + "MySgB343D3C61": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "StackWithSg/MySgB", + "SecurityGroupEgress": [ + { + "CidrIp": "0.0.0.0/0", + "Description": "Allow all outbound traffic by default", + "IpProtocol": "-1" + } + ], + "Tags": [ + { + "Key": "myTagKey", + "Value": "true" + } + ], + "VpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + }, + "MySgC50C8732C": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "my-description", + "SecurityGroupEgress": [ + { + "CidrIp": "0.0.0.0/0", + "Description": "Allow all outbound traffic by default", + "IpProtocol": "-1" + } + ], + "VpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + }, + "MySgDA51BA0C2": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "ownerId description", + "SecurityGroupEgress": [ + { + "CidrIp": "0.0.0.0/0", + "Description": "Allow all outbound traffic by default", + "IpProtocol": "-1" + } + ], + "VpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + } + }, + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/asset.bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1/__entrypoint__.js b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/asset.bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1/__entrypoint__.js new file mode 100644 index 0000000000000..02033f55cf612 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/asset.bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1/__entrypoint__.js @@ -0,0 +1,155 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.withRetries = exports.handler = exports.external = void 0; +const https = require("https"); +const url = require("url"); +// for unit tests +exports.external = { + sendHttpRequest: defaultSendHttpRequest, + log: defaultLog, + includeStackTraces: true, + userHandlerIndex: './index', +}; +const CREATE_FAILED_PHYSICAL_ID_MARKER = 'AWSCDK::CustomResourceProviderFramework::CREATE_FAILED'; +const MISSING_PHYSICAL_ID_MARKER = 'AWSCDK::CustomResourceProviderFramework::MISSING_PHYSICAL_ID'; +async function handler(event, context) { + const sanitizedEvent = { ...event, ResponseURL: '...' }; + exports.external.log(JSON.stringify(sanitizedEvent, undefined, 2)); + // ignore DELETE event when the physical resource ID is the marker that + // indicates that this DELETE is a subsequent DELETE to a failed CREATE + // operation. + if (event.RequestType === 'Delete' && event.PhysicalResourceId === CREATE_FAILED_PHYSICAL_ID_MARKER) { + exports.external.log('ignoring DELETE event caused by a failed CREATE event'); + await submitResponse('SUCCESS', event); + return; + } + try { + // invoke the user handler. this is intentionally inside the try-catch to + // ensure that if there is an error it's reported as a failure to + // cloudformation (otherwise cfn waits). + // eslint-disable-next-line @typescript-eslint/no-require-imports + const userHandler = require(exports.external.userHandlerIndex).handler; + const result = await userHandler(sanitizedEvent, context); + // validate user response and create the combined event + const responseEvent = renderResponse(event, result); + // submit to cfn as success + await submitResponse('SUCCESS', responseEvent); + } + catch (e) { + const resp = { + ...event, + Reason: exports.external.includeStackTraces ? e.stack : e.message, + }; + if (!resp.PhysicalResourceId) { + // special case: if CREATE fails, which usually implies, we usually don't + // have a physical resource id. in this case, the subsequent DELETE + // operation does not have any meaning, and will likely fail as well. to + // address this, we use a marker so the provider framework can simply + // ignore the subsequent DELETE. + if (event.RequestType === 'Create') { + exports.external.log('CREATE failed, responding with a marker physical resource id so that the subsequent DELETE will be ignored'); + resp.PhysicalResourceId = CREATE_FAILED_PHYSICAL_ID_MARKER; + } + else { + // otherwise, if PhysicalResourceId is not specified, something is + // terribly wrong because all other events should have an ID. + exports.external.log(`ERROR: Malformed event. "PhysicalResourceId" is required: ${JSON.stringify(event)}`); + } + } + // this is an actual error, fail the activity altogether and exist. + await submitResponse('FAILED', resp); + } +} +exports.handler = handler; +function renderResponse(cfnRequest, handlerResponse = {}) { + // if physical ID is not returned, we have some defaults for you based + // on the request type. + const physicalResourceId = handlerResponse.PhysicalResourceId ?? cfnRequest.PhysicalResourceId ?? cfnRequest.RequestId; + // if we are in DELETE and physical ID was changed, it's an error. + if (cfnRequest.RequestType === 'Delete' && physicalResourceId !== cfnRequest.PhysicalResourceId) { + throw new Error(`DELETE: cannot change the physical resource ID from "${cfnRequest.PhysicalResourceId}" to "${handlerResponse.PhysicalResourceId}" during deletion`); + } + // merge request event and result event (result prevails). + return { + ...cfnRequest, + ...handlerResponse, + PhysicalResourceId: physicalResourceId, + }; +} +async function submitResponse(status, event) { + const json = { + Status: status, + Reason: event.Reason ?? status, + StackId: event.StackId, + RequestId: event.RequestId, + PhysicalResourceId: event.PhysicalResourceId || MISSING_PHYSICAL_ID_MARKER, + LogicalResourceId: event.LogicalResourceId, + NoEcho: event.NoEcho, + Data: event.Data, + }; + const parsedUrl = url.parse(event.ResponseURL); + const loggingSafeUrl = `${parsedUrl.protocol}//${parsedUrl.hostname}/${parsedUrl.pathname}?***`; + exports.external.log('submit response to cloudformation', loggingSafeUrl, json); + const responseBody = JSON.stringify(json); + const req = { + hostname: parsedUrl.hostname, + path: parsedUrl.path, + method: 'PUT', + headers: { + 'content-type': '', + 'content-length': Buffer.byteLength(responseBody, 'utf8'), + }, + }; + const retryOptions = { + attempts: 5, + sleep: 1000, + }; + await withRetries(retryOptions, exports.external.sendHttpRequest)(req, responseBody); +} +async function defaultSendHttpRequest(options, requestBody) { + return new Promise((resolve, reject) => { + try { + const request = https.request(options, (response) => { + response.resume(); // Consume the response but don't care about it + if (!response.statusCode || response.statusCode >= 400) { + reject(new Error(`Unsuccessful HTTP response: ${response.statusCode}`)); + } + else { + resolve(); + } + }); + request.on('error', reject); + request.write(requestBody); + request.end(); + } + catch (e) { + reject(e); + } + }); +} +function defaultLog(fmt, ...params) { + // eslint-disable-next-line no-console + console.log(fmt, ...params); +} +function withRetries(options, fn) { + return async (...xs) => { + let attempts = options.attempts; + let ms = options.sleep; + while (true) { + try { + return await fn(...xs); + } + catch (e) { + if (attempts-- <= 0) { + throw e; + } + await sleep(Math.floor(Math.random() * ms)); + ms *= 2; + } + } + }; +} +exports.withRetries = withRetries; +async function sleep(ms) { + return new Promise((ok) => setTimeout(ok, ms)); +} diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/asset.bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1/index.js b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/asset.bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1/index.js new file mode 100644 index 0000000000000..013bcaffd8fe5 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/asset.bde7b5c89cb43285f884c94f0b9e17cdb0f5eb5345005114dd60342e0b8a85a1/index.js @@ -0,0 +1 @@ +"use strict";var I=Object.create;var t=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var G=(r,e)=>{for(var o in e)t(r,o,{get:e[o],enumerable:!0})},n=(r,e,o,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of P(e))!l.call(r,s)&&s!==o&&t(r,s,{get:()=>e[s],enumerable:!(i=y(e,s))||i.enumerable});return r};var R=(r,e,o)=>(o=r!=null?I(g(r)):{},n(e||!r||!r.__esModule?t(o,"default",{value:r,enumerable:!0}):o,r)),S=r=>n(t({},"__esModule",{value:!0}),r);var k={};G(k,{handler:()=>f});module.exports=S(k);var a=R(require("@aws-sdk/client-ec2")),u=new a.EC2({});function c(r,e){return{GroupId:r,IpPermissions:[{UserIdGroupPairs:[{GroupId:r,UserId:e}],IpProtocol:"-1"}]}}function d(r){return{GroupId:r,IpPermissions:[{IpRanges:[{CidrIp:"0.0.0.0/0"}],IpProtocol:"-1"}]}}async function f(r){let e=r.ResourceProperties.DefaultSecurityGroupId,o=r.ResourceProperties.Account;switch(r.RequestType){case"Create":return p(e,o);case"Update":return h(r);case"Delete":return m(e,o)}}async function h(r){let e=r.OldResourceProperties.DefaultSecurityGroupId,o=r.ResourceProperties.DefaultSecurityGroupId;e!==o&&(await m(e,r.ResourceProperties.Account),await p(o,r.ResourceProperties.Account))}async function p(r,e){try{await u.revokeSecurityGroupEgress(d(r))}catch(o){if(o.name!=="InvalidPermission.NotFound")throw o}try{await u.revokeSecurityGroupIngress(c(r,e))}catch(o){if(o.name!=="InvalidPermission.NotFound")throw o}}async function m(r,e){await u.authorizeSecurityGroupIngress(c(r,e)),await u.authorizeSecurityGroupEgress(d(r))}0&&(module.exports={handler}); diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/cdk.out b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/cdk.out new file mode 100644 index 0000000000000..079dd58c72d69 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/cdk.out @@ -0,0 +1 @@ +{"version":"37.0.0"} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/integ.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/integ.json new file mode 100644 index 0000000000000..adc4aec587718 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/integ.json @@ -0,0 +1,13 @@ +{ + "enableLookups": true, + "version": "37.0.0", + "testCases": { + "SgLookupTest/DefaultTest": { + "stacks": [ + "StackWithSg" + ], + "assertionStack": "SgLookupTest/DefaultTest/DeployAssert", + "assertionStackName": "SgLookupTestDefaultTestDeployAssert9466B7BF" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/manifest.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/manifest.json new file mode 100644 index 0000000000000..2f8ff36aefa99 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/manifest.json @@ -0,0 +1,253 @@ +{ + "version": "37.0.0", + "artifacts": { + "StackWithSg.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "StackWithSg.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "StackWithSg": { + "type": "aws:cloudformation:stack", + "environment": "aws://12345678/test-region", + "properties": { + "templateFile": "StackWithSg.template.json", + "terminationProtection": false, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-deploy-role-12345678-test-region", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-cfn-exec-role-12345678-test-region", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-12345678-test-region/e205a0cabbb47f8c8f8f543d0ad04ed8b26973d67ffd51d9583342d4ad69a2a9.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "StackWithSg.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-lookup-role-12345678-test-region", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "StackWithSg.assets" + ], + "metadata": { + "/StackWithSg/MyVpc/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "MyVpcF9F0CA6F" + } + ], + "/StackWithSg/MyVpc/RestrictDefaultSecurityGroupCustomResource/Default": [ + { + "type": "aws:cdk:logicalId", + "data": "MyVpcRestrictDefaultSecurityGroupCustomResourceA4FCCD62" + } + ], + "/StackWithSg/Custom::VpcRestrictDefaultSGCustomResourceProvider/Role": [ + { + "type": "aws:cdk:logicalId", + "data": "CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0" + } + ], + "/StackWithSg/Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler": [ + { + "type": "aws:cdk:logicalId", + "data": "CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E" + } + ], + "/StackWithSg/MySgA/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "MySgAFDC270F2" + } + ], + "/StackWithSg/MySgB/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "MySgB343D3C61" + } + ], + "/StackWithSg/MySgC/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "MySgC50C8732C" + } + ], + "/StackWithSg/MySgD/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "MySgDA51BA0C2" + } + ], + "/StackWithSg/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/StackWithSg/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "StackWithSg" + }, + "LookupStack.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "LookupStack.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "LookupStack": { + "type": "aws:cloudformation:stack", + "environment": "aws://12345678/test-region", + "properties": { + "templateFile": "LookupStack.template.json", + "terminationProtection": false, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-deploy-role-12345678-test-region", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-cfn-exec-role-12345678-test-region", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-12345678-test-region/21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "LookupStack.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-lookup-role-12345678-test-region", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "StackWithSg", + "LookupStack.assets" + ], + "metadata": { + "/LookupStack/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/LookupStack/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "LookupStack" + }, + "SgLookupTestDefaultTestDeployAssert9466B7BF.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "SgLookupTestDefaultTestDeployAssert9466B7BF.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "SgLookupTestDefaultTestDeployAssert9466B7BF": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "SgLookupTestDefaultTestDeployAssert9466B7BF.template.json", + "terminationProtection": false, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "SgLookupTestDefaultTestDeployAssert9466B7BF.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-lookup-role-${AWS::AccountId}-${AWS::Region}", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "SgLookupTestDefaultTestDeployAssert9466B7BF.assets" + ], + "metadata": { + "/SgLookupTest/DefaultTest/DeployAssert/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/SgLookupTest/DefaultTest/DeployAssert/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "SgLookupTest/DefaultTest/DeployAssert" + }, + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } + } + }, + "missing": [ + { + "key": "security-group:account=12345678:region=test-region:tags.myTag.0=my-value", + "provider": "security-group", + "props": { + "account": "12345678", + "region": "test-region", + "tags": { + "myTag": [ + "my-value" + ] + }, + "lookupRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-lookup-role-12345678-test-region" + } + }, + { + "key": "security-group:account=12345678:region=test-region:tagKeys.0=myTagKey", + "provider": "security-group", + "props": { + "account": "12345678", + "region": "test-region", + "tagKeys": [ + "myTagKey" + ], + "lookupRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-lookup-role-12345678-test-region" + } + }, + { + "key": "security-group:account=12345678:description=my-description:region=test-region", + "provider": "security-group", + "props": { + "account": "12345678", + "region": "test-region", + "description": "my-description", + "lookupRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-lookup-role-12345678-test-region" + } + }, + { + "key": "security-group:account=12345678:description=ownerId description:ownerId=12345678:region=test-region", + "provider": "security-group", + "props": { + "account": "12345678", + "region": "test-region", + "description": "ownerId description", + "ownerId": "12345678", + "lookupRoleArn": "arn:${AWS::Partition}:iam::12345678:role/cdk-hnb659fds-lookup-role-12345678-test-region" + } + } + ] +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/tree.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/tree.json new file mode 100644 index 0000000000000..bf8c406b81c9e --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/tree.json @@ -0,0 +1,392 @@ +{ + "version": "tree-0.1", + "tree": { + "id": "App", + "path": "", + "children": { + "StackWithSg": { + "id": "StackWithSg", + "path": "StackWithSg", + "children": { + "MyVpc": { + "id": "MyVpc", + "path": "StackWithSg/MyVpc", + "children": { + "Resource": { + "id": "Resource", + "path": "StackWithSg/MyVpc/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::EC2::VPC", + "aws:cdk:cloudformation:props": { + "cidrBlock": "10.0.0.0/16", + "enableDnsHostnames": true, + "enableDnsSupport": true, + "instanceTenancy": "default", + "tags": [ + { + "key": "Name", + "value": "my-vpc-name" + } + ] + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.CfnVPC", + "version": "0.0.0" + } + }, + "RestrictDefaultSecurityGroupCustomResource": { + "id": "RestrictDefaultSecurityGroupCustomResource", + "path": "StackWithSg/MyVpc/RestrictDefaultSecurityGroupCustomResource", + "children": { + "Default": { + "id": "Default", + "path": "StackWithSg/MyVpc/RestrictDefaultSecurityGroupCustomResource/Default", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnResource", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.CustomResource", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.Vpc", + "version": "0.0.0" + } + }, + "Custom::VpcRestrictDefaultSGCustomResourceProvider": { + "id": "Custom::VpcRestrictDefaultSGCustomResourceProvider", + "path": "StackWithSg/Custom::VpcRestrictDefaultSGCustomResourceProvider", + "children": { + "Staging": { + "id": "Staging", + "path": "StackWithSg/Custom::VpcRestrictDefaultSGCustomResourceProvider/Staging", + "constructInfo": { + "fqn": "aws-cdk-lib.AssetStaging", + "version": "0.0.0" + } + }, + "Role": { + "id": "Role", + "path": "StackWithSg/Custom::VpcRestrictDefaultSGCustomResourceProvider/Role", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnResource", + "version": "0.0.0" + } + }, + "Handler": { + "id": "Handler", + "path": "StackWithSg/Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnResource", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.CustomResourceProviderBase", + "version": "0.0.0" + } + }, + "MySgA": { + "id": "MySgA", + "path": "StackWithSg/MySgA", + "children": { + "Resource": { + "id": "Resource", + "path": "StackWithSg/MySgA/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::EC2::SecurityGroup", + "aws:cdk:cloudformation:props": { + "groupDescription": "StackWithSg/MySgA", + "securityGroupEgress": [ + { + "cidrIp": "0.0.0.0/0", + "description": "Allow all outbound traffic by default", + "ipProtocol": "-1" + } + ], + "tags": [ + { + "key": "myTag", + "value": "my-value" + } + ], + "vpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.CfnSecurityGroup", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.SecurityGroup", + "version": "0.0.0" + } + }, + "MySgB": { + "id": "MySgB", + "path": "StackWithSg/MySgB", + "children": { + "Resource": { + "id": "Resource", + "path": "StackWithSg/MySgB/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::EC2::SecurityGroup", + "aws:cdk:cloudformation:props": { + "groupDescription": "StackWithSg/MySgB", + "securityGroupEgress": [ + { + "cidrIp": "0.0.0.0/0", + "description": "Allow all outbound traffic by default", + "ipProtocol": "-1" + } + ], + "tags": [ + { + "key": "myTagKey", + "value": "true" + } + ], + "vpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.CfnSecurityGroup", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.SecurityGroup", + "version": "0.0.0" + } + }, + "MySgC": { + "id": "MySgC", + "path": "StackWithSg/MySgC", + "children": { + "Resource": { + "id": "Resource", + "path": "StackWithSg/MySgC/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::EC2::SecurityGroup", + "aws:cdk:cloudformation:props": { + "groupDescription": "my-description", + "securityGroupEgress": [ + { + "cidrIp": "0.0.0.0/0", + "description": "Allow all outbound traffic by default", + "ipProtocol": "-1" + } + ], + "vpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.CfnSecurityGroup", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.SecurityGroup", + "version": "0.0.0" + } + }, + "MySgD": { + "id": "MySgD", + "path": "StackWithSg/MySgD", + "children": { + "Resource": { + "id": "Resource", + "path": "StackWithSg/MySgD/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::EC2::SecurityGroup", + "aws:cdk:cloudformation:props": { + "groupDescription": "ownerId description", + "securityGroupEgress": [ + { + "cidrIp": "0.0.0.0/0", + "description": "Allow all outbound traffic by default", + "ipProtocol": "-1" + } + ], + "vpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.CfnSecurityGroup", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.SecurityGroup", + "version": "0.0.0" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "StackWithSg/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "StackWithSg/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" + } + }, + "LookupStack": { + "id": "LookupStack", + "path": "LookupStack", + "children": { + "SgFromLookupTags": { + "id": "SgFromLookupTags", + "path": "LookupStack/SgFromLookupTags", + "constructInfo": { + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" + } + }, + "SgFromLookupTagKeys": { + "id": "SgFromLookupTagKeys", + "path": "LookupStack/SgFromLookupTagKeys", + "constructInfo": { + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" + } + }, + "SgFromLookupDescription": { + "id": "SgFromLookupDescription", + "path": "LookupStack/SgFromLookupDescription", + "constructInfo": { + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" + } + }, + "SgFromLookupOwnerId": { + "id": "SgFromLookupOwnerId", + "path": "LookupStack/SgFromLookupOwnerId", + "constructInfo": { + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "LookupStack/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "LookupStack/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" + } + }, + "SgLookupTest": { + "id": "SgLookupTest", + "path": "SgLookupTest", + "children": { + "DefaultTest": { + "id": "DefaultTest", + "path": "SgLookupTest/DefaultTest", + "children": { + "Default": { + "id": "Default", + "path": "SgLookupTest/DefaultTest/Default", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.3.0" + } + }, + "DeployAssert": { + "id": "DeployAssert", + "path": "SgLookupTest/DefaultTest/DeployAssert", + "children": { + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "SgLookupTest/DefaultTest/DeployAssert/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "SgLookupTest/DefaultTest/DeployAssert/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests-alpha.IntegTestCase", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests-alpha.IntegTest", + "version": "0.0.0" + } + }, + "Tree": { + "id": "Tree", + "path": "Tree", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.3.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.App", + "version": "0.0.0" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.ts b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.ts new file mode 100644 index 0000000000000..1030c57274991 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.ts @@ -0,0 +1,56 @@ +import * as cdk from 'aws-cdk-lib'; +import * as ec2 from 'aws-cdk-lib/aws-ec2'; + +import { IntegTest } from '@aws-cdk/integ-tests-alpha'; + +const app = new cdk.App(); + +const env = { + account: process.env.CDK_INTEG_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_INTEG_REGION || process.env.CDK_DEFAULT_REGION, +}; + +// Deploy the security groups to lookup +const stack = new cdk.Stack(app, 'StackWithSg', { env }); +const testVpc = new ec2.Vpc(stack, 'MyVpc', { + vpcName: 'my-vpc-name', + ipAddresses: ec2.IpAddresses.cidr('10.0.0.0/16'), + subnetConfiguration: [], + natGateways: 0, +}); +const testSgA = new ec2.SecurityGroup(stack, 'MySgA', { vpc: testVpc }); +cdk.Tags.of(testSgA).add('myTag', 'my-value'); +const testSgB = new ec2.SecurityGroup(stack, 'MySgB', { vpc: testVpc }); +cdk.Tags.of(testSgB).add('myTagKey', 'true'); +new ec2.SecurityGroup(stack, 'MySgC', { vpc: testVpc, description: 'my-description' }); +new ec2.SecurityGroup(stack, 'MySgD', { vpc: testVpc, description: 'ownerId description' }); + +// Now perform the lookups +const lookupStack = new cdk.Stack(app, 'LookupStack', { env }); +lookupStack.addDependency(stack); +ec2.SecurityGroup.fromLookupByFilters(lookupStack, 'SgFromLookupTags', { + tags: { + myTag: ['my-value'], + }, +}); + +ec2.SecurityGroup.fromLookupByFilters(lookupStack, 'SgFromLookupTagKeys', { + tagKeys: ['myTagKey'], +}); + +ec2.SecurityGroup.fromLookupByFilters(lookupStack, 'SgFromLookupDescription', { + description: 'my-description', +}); + +ec2.SecurityGroup.fromLookupByFilters(lookupStack, 'SgFromLookupOwnerId', { + description: 'ownerId description', + ownerId: process.env.CDK_INTEG_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, +}); + +new IntegTest(app, 'SgLookupTest', { + testCases: [stack], + enableLookups: true, +}); + +app.synth(); + diff --git a/packages/aws-cdk-lib/aws-ec2/README.md b/packages/aws-cdk-lib/aws-ec2/README.md index 686eb78ed2a3f..86e0fd78ee07c 100644 --- a/packages/aws-cdk-lib/aws-ec2/README.md +++ b/packages/aws-cdk-lib/aws-ec2/README.md @@ -843,13 +843,23 @@ Alternatively, use lookup methods to import security groups if you do not know t const sg = ec2.SecurityGroup.fromLookupByName(this, 'SecurityGroupLookup', 'security-group-name', vpc); ``` +You can perform lookups based on filter conditions detailed in the [API](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSecurityGroups.html). +```ts +const sg = ec2.SecurityGroup.fromLookupByFilters(this, 'SecurityGroupLookup', { + ownerId: "012345678901", + description: "my description", + tagKeys: ["tagA", "tagB"], + tags: { tagC: ["valueC", "otherValueC"], tagD: ["valueD"] } +}); +``` + If the security group ID is known and configuration details are unknown, use method `SecurityGroup.fromLookupById` instead. This method will lookup property `allowAllOutbound` from the current configuration of the security group. ```ts const sg = ec2.SecurityGroup.fromLookupById(this, 'SecurityGroupLookup', 'sg-1234'); ``` -The result of `SecurityGroup.fromLookupByName` and `SecurityGroup.fromLookupById` operations will be written to a file called `cdk.context.json`. You must commit this file to source control so that the lookup values are available in non-privileged environments such as CI build steps, and to ensure your template builds are repeatable. +The result of `SecurityGroup.fromLookupByName`, `SecurityGroup.fromLookupById`, and `SecurityGroup.fromLookupByFilters` operations will be written to a file called `cdk.context.json`. You must commit this file to source control so that the lookup values are available in non-privileged environments such as CI build steps, and to ensure your template builds are repeatable. ### Cross Stack Connections diff --git a/packages/aws-cdk-lib/aws-ec2/lib/security-group.ts b/packages/aws-cdk-lib/aws-ec2/lib/security-group.ts index e774c1f9de3af..b9c75b7589350 100644 --- a/packages/aws-cdk-lib/aws-ec2/lib/security-group.ts +++ b/packages/aws-cdk-lib/aws-ec2/lib/security-group.ts @@ -387,6 +387,13 @@ export class SecurityGroup extends SecurityGroupBase { return this.fromLookupAttributes(scope, id, { securityGroupName, vpc }); } + /** + * Look up a security group by filters + */ + public static fromLookupByFilters(scope: Construct, id: string, filters: SecurityGroupLookupOptions) { + return this.fromLookupAttributes(scope, id, filters); + } + /** * Import an existing security group into this app. * @@ -434,7 +441,15 @@ export class SecurityGroup extends SecurityGroupBase { * Look up a security group. */ private static fromLookupAttributes(scope: Construct, id: string, options: SecurityGroupLookupOptions) { - if (Token.isUnresolved(options.securityGroupId) || Token.isUnresolved(options.securityGroupName) || Token.isUnresolved(options.vpc?.vpcId)) { + if ([ + options.securityGroupId, + options.securityGroupName, + options.vpc?.vpcId, + options.description, + options.ownerId, + options.tagKeys, + options.tags, + ].some(opt => Token.isUnresolved(opt))) { throw new Error('All arguments to look up a security group must be concrete (no Tokens)'); } @@ -444,6 +459,10 @@ export class SecurityGroup extends SecurityGroupBase { securityGroupId: options.securityGroupId, securityGroupName: options.securityGroupName, vpcId: options.vpc?.vpcId, + description: options.description, + ownerId: options.ownerId, + tagKeys: options.tagKeys, + tags: options.tags, }, dummyValue: { securityGroupId: 'sg-12345678', @@ -816,13 +835,13 @@ function isAllTrafficRule(rule: any) { * * Either `securityGroupName` or `securityGroupId` has to be specified. */ -interface SecurityGroupLookupOptions { +export interface SecurityGroupLookupOptions { /** * The name of the security group * * If given, will import the SecurityGroup with this name. * - * @default Don't filter on securityGroupName + * @default - Don't filter on securityGroupName */ readonly securityGroupName?: string; @@ -831,7 +850,7 @@ interface SecurityGroupLookupOptions { * * If given, will import the SecurityGroup with this ID. * - * @default Don't filter on securityGroupId + * @default - Don't filter on securityGroupId */ readonly securityGroupId?: string; @@ -840,7 +859,35 @@ interface SecurityGroupLookupOptions { * * If given, will filter the SecurityGroup based on the VPC. * - * @default Don't filter on VPC + * @default - Don't filter on VPC */ readonly vpc?: IVpc; + + /** + * Security group description + * + * @default - Don't filter on description + */ + readonly description?: string; + + /** + * Account ID of the owner of the security group + * + * @default - Don't filter on owner ID + */ + readonly ownerId?: string; + + /** + * The keys of tags assigned to the security group + * + * @default - Don't filter on tag keys + */ + readonly tagKeys?: string[]; + + /** + * The key/value combination of a tag assigned to the security group + * + * @default - Don't filter on tags + */ + readonly tags?: Record; } diff --git a/packages/aws-cdk-lib/aws-ec2/test/security-group.test.ts b/packages/aws-cdk-lib/aws-ec2/test/security-group.test.ts index 50e7f9ae5f224..cd98bd1689181 100644 --- a/packages/aws-cdk-lib/aws-ec2/test/security-group.test.ts +++ b/packages/aws-cdk-lib/aws-ec2/test/security-group.test.ts @@ -596,6 +596,30 @@ describe('security group lookup', () => { }); + test('can look up a security group by filters', () => { + // GIVEN + const app = new App(); + const stack = new Stack(app, 'stack', { + env: { + account: '1234', + region: 'us-east-1', + }, + }); + + // WHEN + const securityGroup = SecurityGroup.fromLookupByFilters(stack, 'SG1', { + ownerId: '012345678901', + description: 'my description', + tagKeys: ['tagA', 'tagB'], + tags: { tagC: ['valueC', 'otherValueC'], tagD: ['valueD'] }, + }); + + // THEN + expect(securityGroup.securityGroupId).toEqual('sg-12345678'); + expect(securityGroup.allowAllOutbound).toEqual(true); + + }); + test('can look up a security group and use it as a peer', () => { // GIVEN const app = new App(); diff --git a/packages/aws-cdk-lib/cloud-assembly-schema/lib/cloud-assembly/context-queries.ts b/packages/aws-cdk-lib/cloud-assembly-schema/lib/cloud-assembly/context-queries.ts index bd35d023dfe69..92fd11f9ea376 100644 --- a/packages/aws-cdk-lib/cloud-assembly-schema/lib/cloud-assembly/context-queries.ts +++ b/packages/aws-cdk-lib/cloud-assembly-schema/lib/cloud-assembly/context-queries.ts @@ -449,6 +449,34 @@ export interface SecurityGroupContextQuery { * @default - None */ readonly vpcId?: string; + + /** + * Security group description + * + * @default - None + */ + readonly description?: string; + + /** + * Account ID of the owner of the security group + * + * @default - None + */ + readonly ownerId?: string; + + /** + * The keys of tags assigned to the security group + * + * @default - None + */ + readonly tagKeys?: string[]; + + /** + * The key/value combination of a tag assigned to the security group + * + * @default - None + */ + readonly tags?: Record; } /** diff --git a/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.schema.json b/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.schema.json index 279dfbe369073..2dc1ceae0d7d9 100644 --- a/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.schema.json +++ b/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.schema.json @@ -870,6 +870,25 @@ "vpcId": { "description": "VPC ID (Default - None)", "type": "string" + }, + "description": { + "description": "Security group description (Default - None)", + "type": "string" + }, + "ownerId": { + "description": "Account ID of the owner of the security group (Default - None)", + "type": "string" + }, + "tagKeys": { + "description": "The keys of tags assigned to the security group (Default - None)", + "type": "array", + "items": { + "type": "string" + } + }, + "tags": { + "description": "The key/value combination of a tag assigned to the security group (Default - None)", + "$ref": "#/definitions/Record" } }, "required": [ @@ -877,6 +896,9 @@ "region" ] }, + "Record": { + "type": "object" + }, "KeyContextQuery": { "description": "Query input for looking up a KMS Key", "type": "object", diff --git a/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.version.json b/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.version.json index 1f0068d32659a..079dd58c72d69 100644 --- a/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.version.json +++ b/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.version.json @@ -1 +1 @@ -{"version":"36.0.0"} \ No newline at end of file +{"version":"37.0.0"} \ No newline at end of file diff --git a/packages/aws-cdk/lib/context-providers/security-groups.ts b/packages/aws-cdk/lib/context-providers/security-groups.ts index 19372df9af842..fa68fa4129e23 100644 --- a/packages/aws-cdk/lib/context-providers/security-groups.ts +++ b/packages/aws-cdk/lib/context-providers/security-groups.ts @@ -17,10 +17,6 @@ export class SecurityGroupContextProviderPlugin implements ContextProviderPlugin throw new Error('\'securityGroupId\' and \'securityGroupName\' can not be specified both when looking up a security group'); } - if (!args.securityGroupId && !args.securityGroupName) { - throw new Error('\'securityGroupId\' or \'securityGroupName\' must be specified to look up a security group'); - } - const options = { assumeRoleArn: args.lookupRoleArn }; const ec2 = (await this.aws.forEnvironment(cxapi.EnvironmentUtils.make(account, region), Mode.ForReading, options)).sdk.ec2(); @@ -37,6 +33,32 @@ export class SecurityGroupContextProviderPlugin implements ContextProviderPlugin Values: [args.securityGroupName], }); } + if (args.description) { + filters.push({ + Name: 'description', + Values: [args.description], + }); + } + if (args.tagKeys) { + filters.push({ + Name: 'tag-key', + Values: args.tagKeys, + }); + } + if (args.ownerId) { + filters.push({ + Name: 'owner-id', + Values: [args.ownerId], + }); + } + if (args.tags) { + Object.entries(args.tags).forEach(([key, values]) => { + filters.push({ + Name: `tag:${key}`, + Values: values, + }); + }); + } const response = await ec2.describeSecurityGroups({ GroupIds: args.securityGroupId ? [args.securityGroupId] : undefined, diff --git a/packages/aws-cdk/test/context-providers/security-groups.test.ts b/packages/aws-cdk/test/context-providers/security-groups.test.ts index c7bdc586ad7bc..2477336d98b93 100644 --- a/packages/aws-cdk/test/context-providers/security-groups.test.ts +++ b/packages/aws-cdk/test/context-providers/security-groups.test.ts @@ -1,7 +1,9 @@ +import * as AWS from 'aws-sdk-mock'; /* eslint-disable import/order */ import * as aws from 'aws-sdk'; -import * as AWS from 'aws-sdk-mock'; -import { hasAllTrafficEgress, SecurityGroupContextProviderPlugin } from '../../lib/context-providers/security-groups'; + +import { SecurityGroupContextProviderPlugin, hasAllTrafficEgress } from '../../lib/context-providers/security-groups'; + import { MockSdkProvider } from '../util/mock-sdk'; AWS.setSDK(require.resolve('aws-sdk')); @@ -226,6 +228,74 @@ describe('security group context provider plugin', () => { expect(res.allowAllOutbound).toEqual(true); }); + test('looks up by security group description, owner id, tag keys, and tags', async () => { + // GIVEN + const provider = new SecurityGroupContextProviderPlugin(mockSDK); + + AWS.mock('EC2', 'describeSecurityGroups', (_params: aws.EC2.DescribeSecurityGroupsRequest, cb: AwsCallback) => { + expect(_params).toEqual({ + GroupIds: undefined, + Filters: [ + { + Name: 'description', + Values: ['my description'], + }, + { + Name: 'tag-key', + Values: ['tagA', 'tagB'], + }, + { + Name: 'owner-id', + Values: ['012345678901'], + }, + { + Name: 'tag:tagC', + Values: ['valueC', 'otherValueC'], + }, + { + Name: 'tag:tagD', + Values: ['valueD'], + }, + ], + }); + cb(null, { + SecurityGroups: [ + { + GroupId: 'sg-1234', + IpPermissionsEgress: [ + { + IpProtocol: '-1', + IpRanges: [ + { CidrIp: '0.0.0.0/0' }, + ], + }, + { + IpProtocol: '-1', + Ipv6Ranges: [ + { CidrIpv6: '::/0' }, + ], + }, + ], + }, + ], + }); + }); + + // WHEN + const res = await provider.getValue({ + account: '1234', + region: 'us-east-1', + ownerId: '012345678901', + description: 'my description', + tagKeys: ['tagA', 'tagB'], + tags: { tagC: ['valueC', 'otherValueC'], tagD: ['valueD'] }, + }); + + // THEN + expect(res.securityGroupId).toEqual('sg-1234'); + expect(res.allowAllOutbound).toEqual(true); + }); + test('detects non all-outbound egress', async () => { // GIVEN const provider = new SecurityGroupContextProviderPlugin(mockSDK); @@ -319,19 +389,6 @@ describe('security group context provider plugin', () => { ).rejects.toThrow(/\'securityGroupId\' and \'securityGroupName\' can not be specified both when looking up a security group/i); }); - test('errors when neither securityGroupId nor securityGroupName are specified', async () => { - // GIVEN - const provider = new SecurityGroupContextProviderPlugin(mockSDK); - - // WHEN - await expect( - provider.getValue({ - account: '1234', - region: 'us-east-1', - }), - ).rejects.toThrow(/\'securityGroupId\' or \'securityGroupName\' must be specified to look up a security group/i); - }); - test('identifies allTrafficEgress from SecurityGroup permissions', () => { expect( hasAllTrafficEgress({