diff --git a/packages/@aws-cdk/aws-events/lib/connection.ts b/packages/@aws-cdk/aws-events/lib/connection.ts index 3908c0915a405..18d0a7fa6fe28 100644 --- a/packages/@aws-cdk/aws-events/lib/connection.ts +++ b/packages/@aws-cdk/aws-events/lib/connection.ts @@ -199,6 +199,7 @@ export abstract class HttpParameter { return { key: name, value, + isValueSecret: false, } as CfnConnection.ParameterProperty; } }(); diff --git a/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/ConnectionTestDefaultTestDeployAssertBA181C0F.assets.json b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/ConnectionTestDefaultTestDeployAssertBA181C0F.assets.json new file mode 100644 index 0000000000000..fe69e9ddecb3d --- /dev/null +++ b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/ConnectionTestDefaultTestDeployAssertBA181C0F.assets.json @@ -0,0 +1,32 @@ +{ + "version": "21.0.0", + "files": { + "84802aa01d2d2c9e7d8d69705ee832c97f1ebad2d73c72be5c32d53f16cf90a7": { + "source": { + "path": "asset.84802aa01d2d2c9e7d8d69705ee832c97f1ebad2d73c72be5c32d53f16cf90a7.bundle", + "packaging": "zip" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "84802aa01d2d2c9e7d8d69705ee832c97f1ebad2d73c72be5c32d53f16cf90a7.zip", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + }, + "b67eb2559673644d8bc867113ad588bb685a8a274e1fcb3b8d226be5d9fd6d2e": { + "source": { + "path": "ConnectionTestDefaultTestDeployAssertBA181C0F.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "b67eb2559673644d8bc867113ad588bb685a8a274e1fcb3b8d226be5d9fd6d2e.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/aws-events/test/connection.integ.snapshot/ConnectionTestDefaultTestDeployAssertBA181C0F.template.json b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/ConnectionTestDefaultTestDeployAssertBA181C0F.template.json new file mode 100644 index 0000000000000..8245b7d7cb8ea --- /dev/null +++ b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/ConnectionTestDefaultTestDeployAssertBA181C0F.template.json @@ -0,0 +1,161 @@ +{ + "Resources": { + "AwsApiCallEventBridgedescribeConnection": { + "Type": "Custom::DeployAssert@SdkCallEventBridgedescribeConnection", + "Properties": { + "ServiceToken": { + "Fn::GetAtt": [ + "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F", + "Arn" + ] + }, + "service": "EventBridge", + "api": "describeConnection", + "parameters": { + "Name": { + "Fn::ImportValue": "IntegConnectionStack:ExportsOutputRefConnection07624BCD5A8A23C8" + } + }, + "flattenResponse": "false", + "salt": "1662113441706" + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "AwsApiCallEventBridgedescribeConnectionAssertEqualsEventBridgedescribeConnection641C4FA0": { + "Type": "Custom::DeployAssert@AssertEquals", + "Properties": { + "ServiceToken": { + "Fn::GetAtt": [ + "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F", + "Arn" + ] + }, + "actual": { + "Fn::GetAtt": [ + "AwsApiCallEventBridgedescribeConnection", + "apiCallResponse" + ] + }, + "expected": "{\"$ObjectLike\":{\"AuthParameters\":{\"ApiKeyAuthParameters\":{\"ApiKeyName\":\"keyname\"},\"InvocationHttpParameters\":{\"HeaderParameters\":[{\"Key\":\"content-type\",\"Value\":\"application/json\",\"IsValueSecret\":false}]}}}}", + "salt": "1662113441706" + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73": { + "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": [ + { + "Action": [ + "eventbridge:DescribeConnection" + ], + "Effect": "Allow", + "Resource": [ + "*" + ] + }, + { + "Action": [ + "events:DescribeConnection" + ], + "Effect": "Allow", + "Resource": [ + "*" + ] + } + ] + } + } + ] + } + }, + "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Runtime": "nodejs14.x", + "Code": { + "S3Bucket": { + "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" + }, + "S3Key": "84802aa01d2d2c9e7d8d69705ee832c97f1ebad2d73c72be5c32d53f16cf90a7.zip" + }, + "Timeout": 120, + "Handler": "index.handler", + "Role": { + "Fn::GetAtt": [ + "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73", + "Arn" + ] + } + } + } + }, + "Outputs": { + "AssertionResultsAssertEqualsEventBridgedescribeConnection": { + "Value": { + "Fn::GetAtt": [ + "AwsApiCallEventBridgedescribeConnectionAssertEqualsEventBridgedescribeConnection641C4FA0", + "data" + ] + } + } + }, + "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/aws-events/test/connection.integ.snapshot/IntegConnectionStack.assets.json b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/IntegConnectionStack.assets.json new file mode 100644 index 0000000000000..44a1d91bfe4ce --- /dev/null +++ b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/IntegConnectionStack.assets.json @@ -0,0 +1,19 @@ +{ + "version": "21.0.0", + "files": { + "e6e22d5747aaa38a1e1cec7566f5ac875bb6a03925a4a9fb46ef2d7315634d7a": { + "source": { + "path": "IntegConnectionStack.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "e6e22d5747aaa38a1e1cec7566f5ac875bb6a03925a4a9fb46ef2d7315634d7a.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/aws-events/test/connection.integ.snapshot/IntegConnectionStack.template.json b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/IntegConnectionStack.template.json new file mode 100644 index 0000000000000..5df0b55622f6e --- /dev/null +++ b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/IntegConnectionStack.template.json @@ -0,0 +1,69 @@ +{ + "Resources": { + "Connection07624BCD": { + "Type": "AWS::Events::Connection", + "Properties": { + "AuthorizationType": "API_KEY", + "AuthParameters": { + "ApiKeyAuthParameters": { + "ApiKeyName": "keyname", + "ApiKeyValue": "keyvalue" + }, + "InvocationHttpParameters": { + "HeaderParameters": [ + { + "IsValueSecret": false, + "Key": "content-type", + "Value": "application/json" + } + ] + } + } + } + } + }, + "Outputs": { + "ExportsOutputRefConnection07624BCD5A8A23C8": { + "Value": { + "Ref": "Connection07624BCD" + }, + "Export": { + "Name": "IntegConnectionStack:ExportsOutputRefConnection07624BCD5A8A23C8" + } + } + }, + "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/aws-events/test/connection.integ.snapshot/asset.84802aa01d2d2c9e7d8d69705ee832c97f1ebad2d73c72be5c32d53f16cf90a7.bundle/index.js b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/asset.84802aa01d2d2c9e7d8d69705ee832c97f1ebad2d73c72be5c32d53f16cf90a7.bundle/index.js new file mode 100644 index 0000000000000..ba956d47f51fe --- /dev/null +++ b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/asset.84802aa01d2d2c9e7d8d69705ee832c97f1ebad2d73c72be5c32d53f16cf90a7.bundle/index.js @@ -0,0 +1,612 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// lib/assertions/providers/lambda-handler/index.ts +var lambda_handler_exports = {}; +__export(lambda_handler_exports, { + handler: () => handler +}); +module.exports = __toCommonJS(lambda_handler_exports); + +// ../assertions/lib/matcher.ts +var Matcher = class { + static isMatcher(x) { + return x && x instanceof Matcher; + } +}; +var MatchResult = class { + constructor(target) { + this.failures = []; + this.captures = /* @__PURE__ */ new Map(); + this.finalized = false; + this.target = target; + } + push(matcher, path, message) { + return this.recordFailure({ matcher, path, message }); + } + recordFailure(failure) { + this.failures.push(failure); + return this; + } + hasFailed() { + return this.failures.length !== 0; + } + get failCount() { + return this.failures.length; + } + compose(id, inner) { + const innerF = inner.failures; + this.failures.push(...innerF.map((f) => { + return { path: [id, ...f.path], message: f.message, matcher: f.matcher }; + })); + inner.captures.forEach((vals, capture) => { + vals.forEach((value) => this.recordCapture({ capture, value })); + }); + return this; + } + finished() { + if (this.finalized) { + return this; + } + if (this.failCount === 0) { + this.captures.forEach((vals, cap) => cap._captured.push(...vals)); + } + this.finalized = true; + return this; + } + toHumanStrings() { + return this.failures.map((r) => { + const loc = r.path.length === 0 ? "" : ` at ${r.path.join("")}`; + return "" + r.message + loc + ` (using ${r.matcher.name} matcher)`; + }); + } + recordCapture(options) { + let values = this.captures.get(options.capture); + if (values === void 0) { + values = []; + } + values.push(options.value); + this.captures.set(options.capture, values); + } +}; + +// ../assertions/lib/private/matchers/absent.ts +var AbsentMatch = class extends Matcher { + constructor(name) { + super(); + this.name = name; + } + test(actual) { + const result = new MatchResult(actual); + if (actual !== void 0) { + result.recordFailure({ + matcher: this, + path: [], + message: `Received ${actual}, but key should be absent` + }); + } + return result; + } +}; + +// ../assertions/lib/private/type.ts +function getType(obj) { + return Array.isArray(obj) ? "array" : typeof obj; +} + +// ../assertions/lib/match.ts +var Match = class { + static absent() { + return new AbsentMatch("absent"); + } + static arrayWith(pattern) { + return new ArrayMatch("arrayWith", pattern); + } + static arrayEquals(pattern) { + return new ArrayMatch("arrayEquals", pattern, { subsequence: false }); + } + static exact(pattern) { + return new LiteralMatch("exact", pattern, { partialObjects: false }); + } + static objectLike(pattern) { + return new ObjectMatch("objectLike", pattern); + } + static objectEquals(pattern) { + return new ObjectMatch("objectEquals", pattern, { partial: false }); + } + static not(pattern) { + return new NotMatch("not", pattern); + } + static serializedJson(pattern) { + return new SerializedJson("serializedJson", pattern); + } + static anyValue() { + return new AnyMatch("anyValue"); + } + static stringLikeRegexp(pattern) { + return new StringLikeRegexpMatch("stringLikeRegexp", pattern); + } +}; +var LiteralMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.partialObjects = options.partialObjects ?? false; + if (Matcher.isMatcher(this.pattern)) { + throw new Error("LiteralMatch cannot directly contain another matcher. Remove the top-level matcher or nest it more deeply."); + } + } + test(actual) { + if (Array.isArray(this.pattern)) { + return new ArrayMatch(this.name, this.pattern, { subsequence: false, partialObjects: this.partialObjects }).test(actual); + } + if (typeof this.pattern === "object") { + return new ObjectMatch(this.name, this.pattern, { partial: this.partialObjects }).test(actual); + } + const result = new MatchResult(actual); + if (typeof this.pattern !== typeof actual) { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected type ${typeof this.pattern} but received ${getType(actual)}` + }); + return result; + } + if (actual !== this.pattern) { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected ${this.pattern} but received ${actual}` + }); + } + return result; + } +}; +var ArrayMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.subsequence = options.subsequence ?? true; + this.partialObjects = options.partialObjects ?? false; + } + test(actual) { + if (!Array.isArray(actual)) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected type array but received ${getType(actual)}` + }); + } + if (!this.subsequence && this.pattern.length !== actual.length) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected array of length ${this.pattern.length} but received ${actual.length}` + }); + } + let patternIdx = 0; + let actualIdx = 0; + const result = new MatchResult(actual); + while (patternIdx < this.pattern.length && actualIdx < actual.length) { + const patternElement = this.pattern[patternIdx]; + const matcher = Matcher.isMatcher(patternElement) ? patternElement : new LiteralMatch(this.name, patternElement, { partialObjects: this.partialObjects }); + const matcherName = matcher.name; + if (this.subsequence && (matcherName == "absent" || matcherName == "anyValue")) { + throw new Error(`The Matcher ${matcherName}() cannot be nested within arrayWith()`); + } + const innerResult = matcher.test(actual[actualIdx]); + if (!this.subsequence || !innerResult.hasFailed()) { + result.compose(`[${actualIdx}]`, innerResult); + patternIdx++; + actualIdx++; + } else { + actualIdx++; + } + } + for (; patternIdx < this.pattern.length; patternIdx++) { + const pattern = this.pattern[patternIdx]; + const element = Matcher.isMatcher(pattern) || typeof pattern === "object" ? " " : ` [${pattern}] `; + result.recordFailure({ + matcher: this, + path: [], + message: `Missing element${element}at pattern index ${patternIdx}` + }); + } + return result; + } +}; +var ObjectMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.partial = options.partial ?? true; + } + test(actual) { + if (typeof actual !== "object" || Array.isArray(actual)) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected type object but received ${getType(actual)}` + }); + } + const result = new MatchResult(actual); + if (!this.partial) { + for (const a of Object.keys(actual)) { + if (!(a in this.pattern)) { + result.recordFailure({ + matcher: this, + path: [`/${a}`], + message: "Unexpected key" + }); + } + } + } + for (const [patternKey, patternVal] of Object.entries(this.pattern)) { + if (!(patternKey in actual) && !(patternVal instanceof AbsentMatch)) { + result.recordFailure({ + matcher: this, + path: [`/${patternKey}`], + message: `Missing key '${patternKey}' among {${Object.keys(actual).join(",")}}` + }); + continue; + } + const matcher = Matcher.isMatcher(patternVal) ? patternVal : new LiteralMatch(this.name, patternVal, { partialObjects: this.partial }); + const inner = matcher.test(actual[patternKey]); + result.compose(`/${patternKey}`, inner); + } + return result; + } +}; +var SerializedJson = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + const result = new MatchResult(actual); + if (getType(actual) !== "string") { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected JSON as a string but found ${getType(actual)}` + }); + return result; + } + let parsed; + try { + parsed = JSON.parse(actual); + } catch (err) { + if (err instanceof SyntaxError) { + result.recordFailure({ + matcher: this, + path: [], + message: `Invalid JSON string: ${actual}` + }); + return result; + } else { + throw err; + } + } + const matcher = Matcher.isMatcher(this.pattern) ? this.pattern : new LiteralMatch(this.name, this.pattern); + const innerResult = matcher.test(parsed); + result.compose(`(${this.name})`, innerResult); + return result; + } +}; +var NotMatch = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + const matcher = Matcher.isMatcher(this.pattern) ? this.pattern : new LiteralMatch(this.name, this.pattern); + const innerResult = matcher.test(actual); + const result = new MatchResult(actual); + if (innerResult.failCount === 0) { + result.recordFailure({ + matcher: this, + path: [], + message: `Found unexpected match: ${JSON.stringify(actual, void 0, 2)}` + }); + } + return result; + } +}; +var AnyMatch = class extends Matcher { + constructor(name) { + super(); + this.name = name; + } + test(actual) { + const result = new MatchResult(actual); + if (actual == null) { + result.recordFailure({ + matcher: this, + path: [], + message: "Expected a value but found none" + }); + } + return result; + } +}; +var StringLikeRegexpMatch = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + const result = new MatchResult(actual); + const regex = new RegExp(this.pattern, "gm"); + if (typeof actual !== "string") { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected a string, but got '${typeof actual}'` + }); + } + if (!regex.test(actual)) { + result.recordFailure({ + matcher: this, + path: [], + message: `String '${actual}' did not match pattern '${this.pattern}'` + }); + } + return result; + } +}; + +// lib/assertions/providers/lambda-handler/base.ts +var https = __toESM(require("https")); +var url = __toESM(require("url")); +var CustomResourceHandler = class { + constructor(event, context) { + this.event = event; + this.context = context; + this.timedOut = false; + this.timeout = setTimeout(async () => { + await this.respond({ + status: "FAILED", + reason: "Lambda Function Timeout", + data: this.context.logStreamName + }); + this.timedOut = true; + }, context.getRemainingTimeInMillis() - 1200); + this.event = event; + this.physicalResourceId = extractPhysicalResourceId(event); + } + async handle() { + try { + console.log(`Event: ${JSON.stringify({ ...this.event, ResponseURL: "..." })}`); + const response = await this.processEvent(this.event.ResourceProperties); + console.log(`Event output : ${JSON.stringify(response)}`); + await this.respond({ + status: "SUCCESS", + reason: "OK", + data: response + }); + } catch (e) { + console.log(e); + await this.respond({ + status: "FAILED", + reason: e.message ?? "Internal Error" + }); + } finally { + clearTimeout(this.timeout); + } + } + respond(response) { + if (this.timedOut) { + return; + } + const cfResponse = { + Status: response.status, + Reason: response.reason, + PhysicalResourceId: this.physicalResourceId, + StackId: this.event.StackId, + RequestId: this.event.RequestId, + LogicalResourceId: this.event.LogicalResourceId, + NoEcho: false, + Data: response.data + }; + const responseBody = JSON.stringify(cfResponse); + console.log("Responding to CloudFormation", responseBody); + const parsedUrl = url.parse(this.event.ResponseURL); + const requestOptions = { + hostname: parsedUrl.hostname, + path: parsedUrl.path, + method: "PUT", + headers: { "content-type": "", "content-length": responseBody.length } + }; + return new Promise((resolve, reject) => { + try { + const request2 = https.request(requestOptions, resolve); + request2.on("error", reject); + request2.write(responseBody); + request2.end(); + } catch (e) { + reject(e); + } + }); + } +}; +function extractPhysicalResourceId(event) { + switch (event.RequestType) { + case "Create": + return event.LogicalResourceId; + case "Update": + case "Delete": + return event.PhysicalResourceId; + } +} + +// lib/assertions/providers/lambda-handler/assertion.ts +var AssertionHandler = class extends CustomResourceHandler { + async processEvent(request2) { + let actual = decodeCall(request2.actual); + const expected = decodeCall(request2.expected); + let result; + const matcher = new MatchCreator(expected).getMatcher(); + console.log(`Testing equality between ${JSON.stringify(request2.actual)} and ${JSON.stringify(request2.expected)}`); + const matchResult = matcher.test(actual); + matchResult.finished(); + if (matchResult.hasFailed()) { + result = { + data: JSON.stringify({ + status: "fail", + message: [ + ...matchResult.toHumanStrings(), + JSON.stringify(matchResult.target, void 0, 2) + ].join("\n") + }) + }; + if (request2.failDeployment) { + throw new Error(result.data); + } + } else { + result = { + data: JSON.stringify({ + status: "success" + }) + }; + } + return result; + } +}; +var MatchCreator = class { + constructor(obj) { + this.parsedObj = { + matcher: obj + }; + } + getMatcher() { + try { + const final = JSON.parse(JSON.stringify(this.parsedObj), function(_k, v) { + const nested = Object.keys(v)[0]; + switch (nested) { + case "$ArrayWith": + return Match.arrayWith(v[nested]); + case "$ObjectLike": + return Match.objectLike(v[nested]); + case "$StringLike": + return Match.stringLikeRegexp(v[nested]); + default: + return v; + } + }); + if (Matcher.isMatcher(final.matcher)) { + return final.matcher; + } + return Match.exact(final.matcher); + } catch { + return Match.exact(this.parsedObj.matcher); + } + } +}; +function decodeCall(call) { + if (!call) { + return void 0; + } + try { + const parsed = JSON.parse(call); + return parsed; + } catch (e) { + return call; + } +} + +// lib/assertions/providers/lambda-handler/utils.ts +function decode(object) { + return JSON.parse(JSON.stringify(object), (_k, v) => { + switch (v) { + case "TRUE:BOOLEAN": + return true; + case "FALSE:BOOLEAN": + return false; + default: + return v; + } + }); +} + +// lib/assertions/providers/lambda-handler/sdk.ts +function flatten(object) { + return Object.assign( + {}, + ...function _flatten(child, path = []) { + return [].concat(...Object.keys(child).map((key) => { + const childKey = Buffer.isBuffer(child[key]) ? child[key].toString("utf8") : child[key]; + return typeof childKey === "object" && childKey !== null ? _flatten(childKey, path.concat([key])) : { [path.concat([key]).join(".")]: childKey }; + })); + }(object) + ); +} +var AwsApiCallHandler = class extends CustomResourceHandler { + async processEvent(request2) { + const AWS = require("aws-sdk"); + console.log(`AWS SDK VERSION: ${AWS.VERSION}`); + const service = new AWS[request2.service](); + const response = await service[request2.api](request2.parameters && decode(request2.parameters)).promise(); + console.log(`SDK response received ${JSON.stringify(response)}`); + delete response.ResponseMetadata; + const respond = { + apiCallResponse: response + }; + const flatData = { + ...flatten(respond) + }; + return request2.flattenResponse === "true" ? flatData : respond; + } +}; + +// lib/assertions/providers/lambda-handler/types.ts +var ASSERT_RESOURCE_TYPE = "Custom::DeployAssert@AssertEquals"; +var SDK_RESOURCE_TYPE_PREFIX = "Custom::DeployAssert@SdkCall"; + +// lib/assertions/providers/lambda-handler/index.ts +async function handler(event, context) { + const provider = createResourceHandler(event, context); + await provider.handle(); +} +function createResourceHandler(event, context) { + if (event.ResourceType.startsWith(SDK_RESOURCE_TYPE_PREFIX)) { + return new AwsApiCallHandler(event, context); + } + switch (event.ResourceType) { + case ASSERT_RESOURCE_TYPE: + return new AssertionHandler(event, context); + default: + throw new Error(`Unsupported resource type "${event.ResourceType}`); + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + handler +}); diff --git a/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/cdk.out b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/cdk.out new file mode 100644 index 0000000000000..8ecc185e9dbee --- /dev/null +++ b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/cdk.out @@ -0,0 +1 @@ +{"version":"21.0.0"} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/integ.json b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/integ.json new file mode 100644 index 0000000000000..9affac6ae40c3 --- /dev/null +++ b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/integ.json @@ -0,0 +1,12 @@ +{ + "version": "21.0.0", + "testCases": { + "ConnectionTest/DefaultTest": { + "stacks": [ + "IntegConnectionStack" + ], + "assertionStack": "ConnectionTest/DefaultTest/DeployAssert", + "assertionStackName": "ConnectionTestDefaultTestDeployAssertBA181C0F" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/manifest.json b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/manifest.json new file mode 100644 index 0000000000000..7189ca97680c6 --- /dev/null +++ b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/manifest.json @@ -0,0 +1,148 @@ +{ + "version": "21.0.0", + "artifacts": { + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } + }, + "IntegConnectionStack.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "IntegConnectionStack.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "IntegConnectionStack": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "IntegConnectionStack.template.json", + "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}/e6e22d5747aaa38a1e1cec7566f5ac875bb6a03925a4a9fb46ef2d7315634d7a.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "IntegConnectionStack.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": [ + "IntegConnectionStack.assets" + ], + "metadata": { + "/IntegConnectionStack/Connection/Connection": [ + { + "type": "aws:cdk:logicalId", + "data": "Connection07624BCD" + } + ], + "/IntegConnectionStack/Exports/Output{\"Ref\":\"Connection07624BCD\"}": [ + { + "type": "aws:cdk:logicalId", + "data": "ExportsOutputRefConnection07624BCD5A8A23C8" + } + ], + "/IntegConnectionStack/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/IntegConnectionStack/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "IntegConnectionStack" + }, + "ConnectionTestDefaultTestDeployAssertBA181C0F.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "ConnectionTestDefaultTestDeployAssertBA181C0F.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "ConnectionTestDefaultTestDeployAssertBA181C0F": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "ConnectionTestDefaultTestDeployAssertBA181C0F.template.json", + "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}/b67eb2559673644d8bc867113ad588bb685a8a274e1fcb3b8d226be5d9fd6d2e.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "ConnectionTestDefaultTestDeployAssertBA181C0F.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": [ + "IntegConnectionStack", + "ConnectionTestDefaultTestDeployAssertBA181C0F.assets" + ], + "metadata": { + "/ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/Default/Default": [ + { + "type": "aws:cdk:logicalId", + "data": "AwsApiCallEventBridgedescribeConnection" + } + ], + "/ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/AssertEqualsEventBridgedescribeConnection/Default/Default": [ + { + "type": "aws:cdk:logicalId", + "data": "AwsApiCallEventBridgedescribeConnectionAssertEqualsEventBridgedescribeConnection641C4FA0" + } + ], + "/ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/AssertEqualsEventBridgedescribeConnection/AssertionResults": [ + { + "type": "aws:cdk:logicalId", + "data": "AssertionResultsAssertEqualsEventBridgedescribeConnection" + } + ], + "/ConnectionTest/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Role": [ + { + "type": "aws:cdk:logicalId", + "data": "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73" + } + ], + "/ConnectionTest/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Handler": [ + { + "type": "aws:cdk:logicalId", + "data": "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F" + } + ], + "/ConnectionTest/DefaultTest/DeployAssert/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/ConnectionTest/DefaultTest/DeployAssert/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "ConnectionTest/DefaultTest/DeployAssert" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/tree.json b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/tree.json new file mode 100644 index 0000000000000..81ac8a7d4ab14 --- /dev/null +++ b/packages/@aws-cdk/aws-events/test/connection.integ.snapshot/tree.json @@ -0,0 +1,260 @@ +{ + "version": "tree-0.1", + "tree": { + "id": "App", + "path": "", + "children": { + "Tree": { + "id": "Tree", + "path": "Tree", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.1.92" + } + }, + "IntegConnectionStack": { + "id": "IntegConnectionStack", + "path": "IntegConnectionStack", + "children": { + "Connection": { + "id": "Connection", + "path": "IntegConnectionStack/Connection", + "children": { + "Connection": { + "id": "Connection", + "path": "IntegConnectionStack/Connection/Connection", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::Events::Connection", + "aws:cdk:cloudformation:props": { + "authorizationType": "API_KEY", + "authParameters": { + "apiKeyAuthParameters": { + "apiKeyName": "keyname", + "apiKeyValue": "keyvalue" + }, + "invocationHttpParameters": { + "headerParameters": [ + { + "key": "content-type", + "value": "application/json", + "isValueSecret": false + } + ] + } + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/aws-events.CfnConnection", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/aws-events.Connection", + "version": "0.0.0" + } + }, + "Exports": { + "id": "Exports", + "path": "IntegConnectionStack/Exports", + "children": { + "Output{\"Ref\":\"Connection07624BCD\"}": { + "id": "Output{\"Ref\":\"Connection07624BCD\"}", + "path": "IntegConnectionStack/Exports/Output{\"Ref\":\"Connection07624BCD\"}", + "constructInfo": { + "fqn": "@aws-cdk/core.CfnOutput", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.1.92" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/core.Stack", + "version": "0.0.0" + } + }, + "ConnectionTest": { + "id": "ConnectionTest", + "path": "ConnectionTest", + "children": { + "DefaultTest": { + "id": "DefaultTest", + "path": "ConnectionTest/DefaultTest", + "children": { + "Default": { + "id": "Default", + "path": "ConnectionTest/DefaultTest/Default", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.1.92" + } + }, + "DeployAssert": { + "id": "DeployAssert", + "path": "ConnectionTest/DefaultTest/DeployAssert", + "children": { + "AwsApiCallEventBridgedescribeConnection": { + "id": "AwsApiCallEventBridgedescribeConnection", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection", + "children": { + "SdkProvider": { + "id": "SdkProvider", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/SdkProvider", + "children": { + "AssertionsProvider": { + "id": "AssertionsProvider", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/SdkProvider/AssertionsProvider", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.1.92" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests.AssertionsProvider", + "version": "0.0.0" + } + }, + "Default": { + "id": "Default", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/Default", + "children": { + "Default": { + "id": "Default", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/Default/Default", + "constructInfo": { + "fqn": "@aws-cdk/core.CfnResource", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/core.CustomResource", + "version": "0.0.0" + } + }, + "AssertEqualsEventBridgedescribeConnection": { + "id": "AssertEqualsEventBridgedescribeConnection", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/AssertEqualsEventBridgedescribeConnection", + "children": { + "AssertionProvider": { + "id": "AssertionProvider", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/AssertEqualsEventBridgedescribeConnection/AssertionProvider", + "children": { + "AssertionsProvider": { + "id": "AssertionsProvider", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/AssertEqualsEventBridgedescribeConnection/AssertionProvider/AssertionsProvider", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.1.92" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests.AssertionsProvider", + "version": "0.0.0" + } + }, + "Default": { + "id": "Default", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/AssertEqualsEventBridgedescribeConnection/Default", + "children": { + "Default": { + "id": "Default", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/AssertEqualsEventBridgedescribeConnection/Default/Default", + "constructInfo": { + "fqn": "@aws-cdk/core.CfnResource", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/core.CustomResource", + "version": "0.0.0" + } + }, + "AssertionResults": { + "id": "AssertionResults", + "path": "ConnectionTest/DefaultTest/DeployAssert/AwsApiCallEventBridgedescribeConnection/AssertEqualsEventBridgedescribeConnection/AssertionResults", + "constructInfo": { + "fqn": "@aws-cdk/core.CfnOutput", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests.EqualsAssertion", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests.AwsApiCall", + "version": "0.0.0" + } + }, + "SingletonFunction1488541a7b23466481b69b4408076b81": { + "id": "SingletonFunction1488541a7b23466481b69b4408076b81", + "path": "ConnectionTest/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81", + "children": { + "Staging": { + "id": "Staging", + "path": "ConnectionTest/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Staging", + "constructInfo": { + "fqn": "@aws-cdk/core.AssetStaging", + "version": "0.0.0" + } + }, + "Role": { + "id": "Role", + "path": "ConnectionTest/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Role", + "constructInfo": { + "fqn": "@aws-cdk/core.CfnResource", + "version": "0.0.0" + } + }, + "Handler": { + "id": "Handler", + "path": "ConnectionTest/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Handler", + "constructInfo": { + "fqn": "@aws-cdk/core.CfnResource", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.1.92" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/core.Stack", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests.IntegTestCase", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests.IntegTest", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/core.App", + "version": "0.0.0" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/aws-events/test/connection.test.ts b/packages/@aws-cdk/aws-events/test/connection.test.ts index ac02334050524..08d12dc9f8a1d 100644 --- a/packages/@aws-cdk/aws-events/test/connection.test.ts +++ b/packages/@aws-cdk/aws-events/test/connection.test.ts @@ -88,6 +88,7 @@ test('oauth connection', () => { HeaderParameters: [{ Key: 'oAuthHeaderKey', Value: 'oAuthHeaderValue', + IsValueSecret: false, }], }, }, @@ -102,3 +103,57 @@ test('oauth connection', () => { Description: 'ConnectionDescription', }); }); + +test('Additional plaintext headers', () => { + // GIVEN + const stack = new Stack(); + + // WHEN + new events.Connection(stack, 'Connection', { + authorization: events.Authorization.apiKey('keyname', SecretValue.unsafePlainText('keyvalue')), + headerParameters: { + 'content-type': events.HttpParameter.fromString('application/json'), + }, + }); + + // THEN + const template = Template.fromStack(stack); + template.hasResourceProperties('AWS::Events::Connection', { + AuthParameters: { + InvocationHttpParameters: { + HeaderParameters: [{ + Key: 'content-type', + Value: 'application/json', + IsValueSecret: false, + }], + }, + }, + }); +}); + +test('Additional secret headers', () => { + // GIVEN + const stack = new Stack(); + + // WHEN + new events.Connection(stack, 'Connection', { + authorization: events.Authorization.apiKey('keyname', SecretValue.unsafePlainText('keyvalue')), + headerParameters: { + 'client-secret': events.HttpParameter.fromSecret(SecretValue.unsafePlainText('apiSecret')), + }, + }); + + // THEN + const template = Template.fromStack(stack); + template.hasResourceProperties('AWS::Events::Connection', { + AuthParameters: { + InvocationHttpParameters: { + HeaderParameters: [{ + Key: 'client-secret', + Value: 'apiSecret', + IsValueSecret: true, + }], + }, + }, + }); +}); \ No newline at end of file diff --git a/packages/@aws-cdk/aws-events/test/integ.connection.ts b/packages/@aws-cdk/aws-events/test/integ.connection.ts new file mode 100644 index 0000000000000..8c000a2e50d75 --- /dev/null +++ b/packages/@aws-cdk/aws-events/test/integ.connection.ts @@ -0,0 +1,41 @@ +import { App, SecretValue, Stack } from '@aws-cdk/core'; +import { AssertionsProvider, ExpectedResult, IntegTest } from '@aws-cdk/integ-tests'; +import { Authorization, Connection, HttpParameter } from '../lib'; + +const app = new App(); + +const stack = new Stack(app, 'IntegConnectionStack'); + +const connection = new Connection(stack, 'Connection', { + authorization: Authorization.apiKey('keyname', SecretValue.unsafePlainText('keyvalue')), + headerParameters: { + 'content-type': HttpParameter.fromString('application/json'), + }, +}); +const testCase = new IntegTest(app, 'ConnectionTest', { + testCases: [stack], +}); + +const deployedConncention = testCase.assertions.awsApiCall('EventBridge', 'describeConnection', { Name: connection.connectionName }); + +deployedConncention.expect(ExpectedResult.objectLike({ + AuthParameters: { + ApiKeyAuthParameters: { + ApiKeyName: 'keyname', + }, + InvocationHttpParameters: { + HeaderParameters: [ + { + Key: 'content-type', + Value: 'application/json', + IsValueSecret: false, + }, + ], + }, + }, +})); + +const assertionProvider = deployedConncention.node.tryFindChild('SdkProvider') as AssertionsProvider; +assertionProvider.addPolicyStatementFromSdkCall('events', 'DescribeConnection'); + +app.synth();