-
Notifications
You must be signed in to change notification settings - Fork 4k
/
aws-sdk-v3-handler.ts
167 lines (147 loc) · 6.47 KB
/
aws-sdk-v3-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
/* eslint-disable @typescript-eslint/no-require-imports */
/* eslint-disable no-console */
import { execSync } from 'child_process';
// eslint-disable-next-line import/no-extraneous-dependencies
import { ApiCall } from '@aws-cdk/sdk-v2-to-v3-adapter';
// 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 type * as AWSLambda from 'aws-lambda';
import type { AwsSdkCall } from './construct-types';
import { decodeCall, decodeSpecialValues, filterKeys, respond, startsWithOneOf } from './shared';
let installedSdk: { [service: string]: boolean } = {};
export function forceSdkInstallation() {
installedSdk = {};
}
/**
* Installs latest AWS SDK v3
*/
function installLatestSdk(packageName: string): void {
console.log(`Installing latest AWS SDK v3: ${packageName}`);
// Both HOME and --prefix are needed here because /tmp is the only writable location
execSync(
`NPM_CONFIG_UPDATE_NOTIFIER=false HOME=/tmp npm install ${JSON.stringify(packageName)} --omit=dev --no-package-lock --no-save --prefix /tmp`,
);
installedSdk = {
...installedSdk,
[packageName]: true,
};
}
interface AwsSdk {
[key: string]: any
}
async function loadAwsSdk(
packageName: string,
installLatestAwsSdk?: 'true' | 'false',
) {
let awsSdk: AwsSdk;
try {
if (!installedSdk[packageName] && installLatestAwsSdk === 'true') {
try {
installLatestSdk(packageName);
// MUST use require here. Dynamic import() do not support importing from directories
// esbuild-disable unsupported-require-call -- not esbuildable but that's fine
awsSdk = require(`/tmp/node_modules/${packageName}`);
} catch (e) {
console.log(`Failed to install latest AWS SDK v3. Falling back to pre-installed version. Error: ${e}`);
// MUST use require as dynamic import() does not support importing from directories
// esbuild-disable unsupported-require-call -- not esbuildable but that's fine
return require(packageName); // Fallback to pre-installed version
}
} else if (installedSdk[packageName]) {
// MUST use require here. Dynamic import() do not support importing from directories
// esbuild-disable unsupported-require-call -- not esbuildable but that's fine
awsSdk = require(`/tmp/node_modules/${packageName}`);
} else {
// esbuild-disable unsupported-require-call -- not esbuildable but that's fine
awsSdk = require(packageName);
}
} catch (error) {
throw Error(`Package ${packageName} does not exist.`);
}
return awsSdk;
}
/* eslint-disable @typescript-eslint/no-require-imports, import/no-extraneous-dependencies */
export async function handler(event: AWSLambda.CloudFormationCustomResourceEvent, context: AWSLambda.Context) {
try {
event.ResourceProperties.Create = decodeCall(event.ResourceProperties.Create);
event.ResourceProperties.Update = decodeCall(event.ResourceProperties.Update);
event.ResourceProperties.Delete = decodeCall(event.ResourceProperties.Delete);
let data: { [key: string]: string } = {};
// 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;
}
const call: AwsSdkCall | undefined = event.ResourceProperties[event.RequestType];
if (call) {
const apiCall = new ApiCall(call.service, call.action);
let awsSdk: AwsSdk | Promise<AwsSdk> = loadAwsSdk(apiCall.v3PackageName, event.ResourceProperties.InstallLatestAwsSdk);
console.log(JSON.stringify({ ...event, ResponseURL: '...' }));
let credentials;
if (call.assumedRoleArn) {
const timestamp = (new Date()).getTime();
const params = {
RoleArn: call.assumedRoleArn,
RoleSessionName: `${timestamp}-${physicalResourceId}`.substring(0, 64),
};
const { fromTemporaryCredentials } = await import('@aws-sdk/credential-providers');
credentials = fromTemporaryCredentials({
params,
clientConfig: call.region !== undefined ? { region: call.region } : undefined,
});
}
awsSdk = await awsSdk;
const flatData: { [key: string]: string } = {};
try {
const response = await apiCall.invoke({
sdkPackage: awsSdk,
apiVersion: call.apiVersion,
credentials: credentials,
region: call.region,
parameters: decodeSpecialValues(call.parameters, physicalResourceId),
flattenResponse: true,
});
console.log('API response', response);
flatData.apiVersion = apiCall.client.config.apiVersion; // For test purposes: check if apiVersion was correctly passed.
flatData.region = await apiCall.client.config.region().catch(() => undefined); // For test purposes: check if region was correctly passed.
Object.assign(flatData, 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) {
// empirecal evidence show e.name is not always set
const exceptionName = e.name ?? e.constructor.name;
if (!call.ignoreErrorCodesMatching || !new RegExp(call.ignoreErrorCodesMatching).test(exceptionName)) {
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, {});
}
}