-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
sdk.ts
255 lines (226 loc) · 7.47 KB
/
sdk.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import { ArnFormat, CfnResource, CustomResource, Lazy, Stack, Aspects, CfnOutput } from 'aws-cdk-lib/core';
import { Construct, IConstruct } from 'constructs';
import { ApiCallBase, IApiCall } from './api-call-base';
import { ExpectedResult } from './common';
import { AssertionsProvider, SDK_RESOURCE_TYPE_PREFIX } from './providers';
import { WaiterStateMachine, WaiterStateMachineOptions } from './waiter-state-machine';
/**
* Options to perform an AWS JavaScript V2 API call
*/
export interface AwsApiCallOptions {
/**
* The AWS service, i.e. S3
*/
readonly service: string;
/**
* The api call to make, i.e. getBucketLifecycle
*/
readonly api: string;
/**
* Any parameters to pass to the api call
*
* @default - no parameters
*/
readonly parameters?: any;
/**
* Restrict the data returned by the API call to specific paths in
* the API response. Use this to limit the data returned by the custom
* resource if working with API calls that could potentially result in custom
* response objects exceeding the hard limit of 4096 bytes.
*
* @default - return all data
*/
readonly outputPaths?: string[];
}
/**
* Construct that creates a custom resource that will perform
* a query using the AWS SDK
*/
export interface AwsApiCallProps extends AwsApiCallOptions { }
/**
* Construct that creates a custom resource that will perform
* a query using the AWS SDK
*/
export class AwsApiCall extends ApiCallBase {
public readonly provider: AssertionsProvider;
/**
* access the AssertionsProvider for the waiter state machine.
* This can be used to add additional IAM policies
* the the provider role policy
*
* @example
* declare const apiCall: AwsApiCall;
* apiCall.waiterProvider?.addToRolePolicy({
* Effect: 'Allow',
* Action: ['s3:GetObject'],
* Resource: ['*'],
* });
*/
public waiterProvider?: AssertionsProvider;
protected readonly apiCallResource: CustomResource;
private readonly name: string;
private _assertAtPath?: string;
private readonly api: string;
private readonly service: string;
constructor(scope: Construct, id: string, props: AwsApiCallProps) {
super(scope, id);
this.provider = new AssertionsProvider(this, 'SdkProvider');
this.provider.addPolicyStatementFromSdkCall(props.service, props.api);
this.name = `${props.service}${props.api}`;
this.api = props.api;
this.service = props.service;
if (props.outputPaths) {
this.outputPaths = [...props.outputPaths];
}
this.apiCallResource = new CustomResource(this, 'Default', {
serviceToken: this.provider.serviceToken,
properties: {
service: props.service,
api: props.api,
expected: Lazy.any({ produce: () => this.expectedResult }),
actualPath: Lazy.string({ produce: () => this._assertAtPath }),
stateMachineArn: Lazy.string({ produce: () => this.stateMachineArn }),
parameters: this.provider.encode(props.parameters),
flattenResponse: Lazy.string({ produce: () => this.flattenResponse }),
outputPaths: Lazy.list({ produce: () => this.outputPaths }),
salt: Date.now().toString(),
},
resourceType: `${SDK_RESOURCE_TYPE_PREFIX}${this.name}`.substring(0, 60),
});
// Needed so that all the policies set up by the provider should be available before the custom resource is provisioned.
this.apiCallResource.node.addDependency(this.provider);
// if expectedResult has been configured then that means
// we are making assertions and we should output the results
Aspects.of(this).add({
visit(node: IConstruct) {
if (node instanceof AwsApiCall) {
if (node.expectedResult) {
const result = node.apiCallResource.getAttString('assertion');
new CfnOutput(node, 'AssertionResults', {
value: result,
}).overrideLogicalId(`AssertionResults${id}`);
}
}
},
});
}
public assertAtPath(path: string, expected: ExpectedResult): IApiCall {
this._assertAtPath = path;
(this.outputPaths ??= []).push(path);
this.expectedResult = expected.result;
this.flattenResponse = 'true';
return this;
}
public waitForAssertions(options?: WaiterStateMachineOptions): IApiCall {
const waiter = new WaiterStateMachine(this, 'WaitFor', {
...options,
});
this.stateMachineArn = waiter.stateMachineArn;
this.provider.addPolicyStatementFromSdkCall('states', 'StartExecution');
waiter.isCompleteProvider.addPolicyStatementFromSdkCall(this.service, this.api);
this.waiterProvider = waiter.isCompleteProvider;
return this;
}
}
/**
* Set to Tail to include the execution log in the response.
* Applies to synchronously invoked functions only.
*/
export enum LogType {
/**
* The log messages are not returned in the response
*/
NONE = 'None',
/**
* The log messages are returned in the response
*/
TAIL = 'Tail',
}
/**
* The type of invocation. Default is REQUEST_RESPONSE
*/
export enum InvocationType {
/**
* Invoke the function asynchronously.
* Send events that fail multiple times to the function's
* dead-letter queue (if it's configured).
* The API response only includes a status code.
*/
EVENT = 'Event',
/**
* Invoke the function synchronously.
* Keep the connection open until the function returns a response or times out.
* The API response includes the function response and additional data.
*/
REQUEST_RESPONSE = 'RequestResponse',
/**
* Validate parameter values and verify that the user
* or role has permission to invoke the function.
*/
DRY_RUN = 'DryRun',
}
/**
* Options to pass to the Lambda invokeFunction API call
*/
export interface LambdaInvokeFunctionProps {
/**
* The name of the function to invoke
*/
readonly functionName: string;
/**
* The type of invocation to use
*
* @default InvocationType.REQUEST_RESPONSE
*/
readonly invocationType?: InvocationType;
/**
* Whether to return the logs as part of the response
*
* @default LogType.NONE
*/
readonly logType?: LogType;
/**
* Payload to send as part of the invoke
*
* @default - no payload
*/
readonly payload?: string;
}
/**
* An AWS Lambda Invoke function API call.
* Use this istead of the generic AwsApiCall in order to
* invoke a lambda function. This will automatically create
* the correct permissions to invoke the function
*/
export class LambdaInvokeFunction extends AwsApiCall {
constructor(scope: Construct, id: string, props: LambdaInvokeFunctionProps) {
super(scope, id, {
api: 'invoke',
service: 'Lambda',
parameters: {
FunctionName: props.functionName,
InvocationType: props.invocationType,
LogType: props.logType,
Payload: props.payload,
},
});
const stack = Stack.of(this);
// need to give the assertion lambda permission to invoke
new CfnResource(this, 'Invoke', {
type: 'AWS::Lambda::Permission',
properties: {
Action: 'lambda:InvokeFunction',
FunctionName: props.functionName,
Principal: this.provider.handlerRoleArn,
},
});
// the api call is 'invoke', but the permission is 'invokeFunction'
// so need to handle it specially
this.provider.addPolicyStatementFromSdkCall('Lambda', 'invokeFunction', [stack.formatArn({
service: 'lambda',
resource: 'function',
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
resourceName: props.functionName,
})]);
}
}