-
Notifications
You must be signed in to change notification settings - Fork 4k
/
index.ts
275 lines (247 loc) · 9.12 KB
/
index.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/* eslint-disable no-console */
import { execSync } from 'child_process';
import * as fs from 'fs';
import { join } from 'path';
// import the AWSLambda package explicitly,
// which is globally available in the Lambda runtime,
// as otherwise linking this repository with link-all.sh
// fails in the CDK app executed with ts-node
/* eslint-disable-next-line import/no-extraneous-dependencies,import/no-unresolved */
import * as AWSLambda from 'aws-lambda';
import { AwsSdkCall } from '../aws-custom-resource';
/**
* Serialized form of the physical resource id for use in the operation parameters
*/
export const PHYSICAL_RESOURCE_ID_REFERENCE = 'PHYSICAL:RESOURCEID:';
/**
* Flattens a nested object
*
* @param object the object to be flattened
* @returns a flat object with path as keys
*/
export function flatten(object: object): { [key: string]: any } {
return Object.assign(
{},
...function _flatten(child: any, path: string[] = []): any {
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),
);
}
/**
* Decodes encoded special values (physicalResourceId)
*/
function decodeSpecialValues(object: object, physicalResourceId: string) {
return JSON.parse(JSON.stringify(object), (_k, v) => {
switch (v) {
case PHYSICAL_RESOURCE_ID_REFERENCE:
return physicalResourceId;
default:
return v;
}
});
}
/**
* Filters the keys of an object.
*/
function filterKeys(object: object, pred: (key: string) => boolean) {
return Object.entries(object)
.reduce(
(acc, [k, v]) => pred(k)
? { ...acc, [k]: v }
: acc,
{},
);
}
let latestSdkInstalled = false;
export function forceSdkInstallation() {
latestSdkInstalled = false;
}
/**
* Installs latest AWS SDK v2
*/
function installLatestSdk(): void {
console.log('Installing latest AWS SDK v2');
// Both HOME and --prefix are needed here because /tmp is the only writable location
execSync('HOME=/tmp npm install aws-sdk@2 --production --no-package-lock --no-save --prefix /tmp');
latestSdkInstalled = true;
}
// no currently patched services
const patchedServices: { serviceName: string; apiVersions: string[] }[] = [];
/**
* Patches the AWS SDK by loading service models in the same manner as the actual SDK
*/
function patchSdk(awsSdk: any): any {
const apiLoader = awsSdk.apiLoader;
patchedServices.forEach(({ serviceName, apiVersions }) => {
const lowerServiceName = serviceName.toLowerCase();
if (!awsSdk.Service.hasService(lowerServiceName)) {
apiLoader.services[lowerServiceName] = {};
awsSdk[serviceName] = awsSdk.Service.defineService(lowerServiceName, apiVersions);
} else {
awsSdk.Service.addVersions(awsSdk[serviceName], apiVersions);
}
apiVersions.forEach(apiVersion => {
Object.defineProperty(apiLoader.services[lowerServiceName], apiVersion, {
get: function get() {
const modelFilePrefix = `aws-sdk-patch/${lowerServiceName}-${apiVersion}`;
const model = JSON.parse(fs.readFileSync(join(__dirname, `${modelFilePrefix}.service.json`), 'utf-8'));
model.paginators = JSON.parse(fs.readFileSync(join(__dirname, `${modelFilePrefix}.paginators.json`), 'utf-8')).pagination;
return model;
},
enumerable: true,
configurable: true,
});
});
});
return awsSdk;
}
/* eslint-disable @typescript-eslint/no-require-imports, import/no-extraneous-dependencies */
export async function handler(event: AWSLambda.CloudFormationCustomResourceEvent, context: AWSLambda.Context) {
try {
let AWS: any;
if (!latestSdkInstalled && event.ResourceProperties.InstallLatestAwsSdk === 'true') {
try {
installLatestSdk();
AWS = require('/tmp/node_modules/aws-sdk');
} catch (e) {
console.log(`Failed to install latest AWS SDK v2: ${e}`);
AWS = require('aws-sdk'); // Fallback to pre-installed version
}
} else if (latestSdkInstalled) {
AWS = require('/tmp/node_modules/aws-sdk');
} else {
AWS = require('aws-sdk');
}
try {
AWS = patchSdk(AWS);
} catch (e) {
console.log(`Failed to patch AWS SDK: ${e}. Proceeding with the installed copy.`);
}
console.log(JSON.stringify({ ...event, ResponseURL: '...' }));
console.log('AWS SDK VERSION: ' + AWS.VERSION);
event.ResourceProperties.Create = decodeCall(event.ResourceProperties.Create);
event.ResourceProperties.Update = decodeCall(event.ResourceProperties.Update);
event.ResourceProperties.Delete = decodeCall(event.ResourceProperties.Delete);
// Default physical resource id
let physicalResourceId: string;
switch (event.RequestType) {
case 'Create':
physicalResourceId = event.ResourceProperties.Create?.physicalResourceId?.id ??
event.ResourceProperties.Update?.physicalResourceId?.id ??
event.ResourceProperties.Delete?.physicalResourceId?.id ??
event.LogicalResourceId;
break;
case 'Update':
case 'Delete':
physicalResourceId = event.ResourceProperties[event.RequestType]?.physicalResourceId?.id ?? event.PhysicalResourceId;
break;
}
let flatData: { [key: string]: string } = {};
let data: { [key: string]: string } = {};
const call: AwsSdkCall | undefined = event.ResourceProperties[event.RequestType];
if (call) {
let credentials;
if (call.assumedRoleArn) {
const timestamp = (new Date()).getTime();
const params = {
RoleArn: call.assumedRoleArn,
RoleSessionName: `${timestamp}-${physicalResourceId}`.substring(0, 64),
};
credentials = new AWS.ChainableTemporaryCredentials({
params: params,
});
}
if (!Object.prototype.hasOwnProperty.call(AWS, call.service)) {
throw Error(`Service ${call.service} does not exist in AWS SDK version ${AWS.VERSION}.`);
}
const awsService = new (AWS as any)[call.service]({
apiVersion: call.apiVersion,
credentials: credentials,
region: call.region,
});
try {
const response = await awsService[call.action](
call.parameters && decodeSpecialValues(call.parameters, physicalResourceId)).promise();
flatData = {
apiVersion: awsService.config.apiVersion, // For test purposes: check if apiVersion was correctly passed.
region: awsService.config.region, // For test purposes: check if region was correctly passed.
...flatten(response),
};
let outputPaths: string[] | undefined;
if (call.outputPath) {
outputPaths = [call.outputPath];
} else if (call.outputPaths) {
outputPaths = call.outputPaths;
}
if (outputPaths) {
data = filterKeys(flatData, startsWithOneOf(outputPaths));
} else {
data = flatData;
}
} catch (e) {
if (!call.ignoreErrorCodesMatching || !new RegExp(call.ignoreErrorCodesMatching).test(e.code)) {
throw e;
}
}
if (call.physicalResourceId?.responsePath) {
physicalResourceId = flatData[call.physicalResourceId.responsePath];
}
}
await respond('SUCCESS', 'OK', physicalResourceId, data);
} catch (e) {
console.log(e);
await respond('FAILED', e.message || 'Internal Error', context.logStreamName, {});
}
function respond(responseStatus: string, reason: string, physicalResourceId: string, data: any) {
const responseBody = JSON.stringify({
Status: responseStatus,
Reason: reason,
PhysicalResourceId: physicalResourceId,
StackId: event.StackId,
RequestId: event.RequestId,
LogicalResourceId: event.LogicalResourceId,
NoEcho: false,
Data: data,
});
console.log('Responding', responseBody);
// eslint-disable-next-line @typescript-eslint/no-require-imports
const parsedUrl = require('url').parse(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 {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const request = require('https').request(requestOptions, resolve);
request.on('error', reject);
request.write(responseBody);
request.end();
} catch (e) {
reject(e);
}
});
}
}
function decodeCall(call: string | undefined) {
if (!call) { return undefined; }
return JSON.parse(call);
}
function startsWithOneOf(searchStrings: string[]): (string: string) => boolean {
return function(string: string): boolean {
for (const searchString of searchStrings) {
if (string.startsWith(searchString)) {
return true;
}
}
return false;
};
}