-
Notifications
You must be signed in to change notification settings - Fork 4k
/
aws-sdk-v2-handler.ts
172 lines (154 loc) · 6.41 KB
/
aws-sdk-v2-handler.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
/* 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 { decodeCall, decodeSpecialValues, filterKeys, flatten, respond, startsWithOneOf } from './shared';
import { AwsSdkCall } from '../aws-custom-resource';
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,
stsConfig: { stsRegionalEndpoints: 'regional' },
});
}
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: any) {
if (!call.ignoreErrorCodesMatching || !new RegExp(call.ignoreErrorCodesMatching).test(e.code)) {
throw e;
}
}
if (call.physicalResourceId?.responsePath) {
physicalResourceId = flatData[call.physicalResourceId.responsePath];
}
}
await respond(event, 'SUCCESS', 'OK', physicalResourceId, data);
} catch (e: any) {
console.log(e);
await respond(event, 'FAILED', e.message || 'Internal Error', context.logStreamName, {});
}
}