-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
557 lines (463 loc) · 18 KB
/
index.js
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
'use strict';
const fs = require('fs');
const _ = require('lodash');
const signersMethods = require('./src/SignersMethods');
const cloudFormationGenerator = require('./src/CloudFormationGenerator');
class ServerlessPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
signer: {
usage: 'Signs Lambda code using AWS Signer',
lifecycleEvents: ['sign', 'updateCloudFormation'],
options: {
function: {
usage:
'Specify the function you want to sign ' +
'(e.g. "--function main or "-f secondary")',
required: true,
shortcut: 'f',
},
},
},
};
this.hooks = {
'after:package:createDeploymentArtifacts': () => this.signLambdas().then(this.signLayers.bind(this)),
'before:package:finalize': this.addSigningConfigurationToCloudFormation.bind(this),
'signer:sign': this.signLambdas.bind(this),
'before:remove:remove': this.removeResources.bind(this)
// 'signer:updateCloudFormation': this.addSigningConfigurationToCloudFormation.bind(this)
};
const globalConfigSchemaProperties = {
source: {
type: 'object',
properties: {
s3: {
type: 'object',
properties: {
bucketName: {type: "string"},
key: {type: "string"}
},
required: ["bucketName"]
}
}
},
destination: {
type: 'object',
properties: {
s3: {
type: 'object',
properties: {
bucketName: {type: "string"},
key: {type: "string"}
}
}
}
},
profileName: {"type": "string"},
signingPolicy: {"type": "string"}
};
const functionConfigSchemaProperties = {
// Reserved for the future
};
serverless.configSchemaHandler.defineCustomProperties({
type: 'object',
properties: {
signer: {
'.*': {
type: 'object',
properties: globalConfigSchemaProperties,
additionalProperties: false
},
},
},
});
serverless.configSchemaHandler.defineFunctionProperties('aws', {
properties: {
signer: {
'.*': {
type: 'object',
properties: globalConfigSchemaProperties,
additionalProperties: false
},
},
},
});
}
generateSignerConfiguration() {
var signerProcesses = {};
const defaultConfig = {
source: {
s3: {
key: 'common'+'-'+Math.floor(+new Date() / 1000),
}
},
destination: {
s3: {
prefix: "signed-"
}
},
profileName: this.serverless.service.service,
signingPolicy: "Enforce",
retain: true
}
const lambda_functions = this.serverless.service.functions;
if (this.serverless.service.package.individually === true) {
for (let lambda_function in lambda_functions) {
// Since merge mutates the first object in a set, we need to pass an empty object. Otherwise, it'll rewrite the default configuration
// https://stackoverflow.com/questions/19965844/lodash-difference-between-extend-assign-and-merge#comment57512843_19966511
const mergedConfig = _.merge({}, defaultConfig, this.serverless.service.custom.signer, lambda_functions[lambda_function].signer);
const packagePath = (lambda_functions[lambda_function].package) ? (lambda_functions[lambda_function].package.artifact) : (null)
signerProcesses[lambda_function] = {
signerConfiguration: mergedConfig,
packageArtifact: packagePath
}
try {
// TODO: Remove this check with proper validation
if (!signerProcesses[lambda_function].signerConfiguration.source.s3.bucketName) {
throw new this.serverless.classes.Error("No bucket name was specified");
}
if (!signerProcesses[lambda_function].signerConfiguration.destination.s3.bucketName) {
signerProcesses[lambda_function].signerConfiguration.destination.s3.bucketName = signerProcesses[lambda_function].signerConfiguration.source.s3.bucketName
}
}
// TODO: Remove this check with proper validation
catch {
throw new this.serverless.classes.Error("Incorrect signer plugin configuration");
}
}
}
else {
const lambda_function = "common";
signerProcesses[lambda_function] = {
signerConfiguration: _.merge(defaultConfig, this.serverless.service.custom.signer),
packageArtifact: this.serverless.service.package.artifact
}
try {
// TODO: Remove this check with proper validation
if (!signerProcesses[lambda_function].signerConfiguration.source.s3.bucketName) {
throw new this.serverless.classes.Error("No bucket name was specified");
}
if (!signerProcesses[lambda_function].signerConfiguration.destination.s3.bucketName) {
signerProcesses[lambda_function].signerConfiguration.destination.s3.bucketName = signerProcesses[lambda_function].signerConfiguration.source.s3.bucketName
}
}
// TODO: Remove this check with proper validation
catch {
throw new this.serverless.classes.Error("Incorrect signer plugin configuration");
}
}
return signerProcesses
}
generateLayersConfiguration() {
var signerProcesses = {};
const defaultConfig = {
source: {
s3: {
key: 'common'+'-'+Math.floor(+new Date() / 1000),
}
},
destination: {
s3: {
prefix: "signed-"
}
},
profileName: this.serverless.service.service,
signingPolicy: "Enforce",
retain: true
}
const layers = this.serverless.service.layers;
for (let layer in layers) {
// Since merge mutates the first object in a set, we need to pass an empty object. Otherwise, it'll rewrite the default configuration
// https://stackoverflow.com/questions/19965844/lodash-difference-between-extend-assign-and-merge#comment57512843_19966511
const mergedConfig = _.merge({}, defaultConfig, this.serverless.service.custom.signer, layers[layer].signer);
const packagePath = (layers[layer].package) ? (layers[layer].package.artifact) : (null)
signerProcesses[layer] = {
signerConfiguration: mergedConfig,
packageArtifact: packagePath
}
try {
// TODO: Remove this check with proper validation
if (!signerProcesses[layer].signerConfiguration.source.s3.bucketName) {
throw new this.serverless.classes.Error("No bucket name was specified");
}
if (!signerProcesses[layer].signerConfiguration.destination.s3.bucketName) {
signerProcesses[layer].signerConfiguration.destination.s3.bucketName = signerProcesses[layer].signerConfiguration.source.s3.bucketName
}
}
// TODO: Remove this check with proper validation
catch {
throw new this.serverless.classes.Error("Incorrect signer plugin configuration");
}
}
return signerProcesses
}
async verifyConfiguration(configuration) {
// Check if signingProfile is in place
const profileArn = await signersMethods.getProfileParamByName(configuration.signerConfiguration.profileName, 'profileVersionArn', this.serverless)
if (!profileArn) {
await this.createSigningProfile(configuration.signerConfiguration.profileName);
}
// Check if source bucket is in place
try {
await this.serverless.providers.aws.request("S3", "headBucket", {
Bucket: configuration.signerConfiguration.source.s3.bucketName
})
}
catch (e) {
if (e.providerError.code === "NotFound") {
await this.createS3Bucket(configuration.signerConfiguration.source.s3.bucketName)
}
else {
throw (e)
}
}
// Check if destination bucket is in place
try {
await this.serverless.providers.aws.request("S3", "headBucket", {
Bucket: configuration.signerConfiguration.destination.s3.bucketName
})
}
catch (e) {
if (e.providerError.code === "NotFound") {
await this.createS3Bucket(configuration.signerConfiguration.destination.s3.bucketName)
}
else {
throw (e)
}
}
}
async signLambdas() {
this.serverless.cli.log('Signing functions...');
const signerProcesses = this.generateSignerConfiguration();
for (let lambda in signerProcesses) {
var signItem = signerProcesses[lambda];
await this.verifyConfiguration(signItem);
// Copy deployment artifact to S3
const fileContent = fs.readFileSync(signItem.packageArtifact);
var S3Response = await this.serverless.providers.aws.request('S3', 'upload', {
Bucket: signItem.signerConfiguration.source.s3.bucketName,
Key: signItem.signerConfiguration.source.s3.key,
Body: fileContent
})
// Update configuration with a version of the uploaded S3 object
signItem.signerConfiguration.source.s3.version = S3Response.VersionId
if (signItem.signerConfiguration.signingPolicy) {
delete signItem.signerConfiguration.signingPolicy
delete signItem.signerConfiguration.retain
}
// Start signing job
var signJob = await this.serverless.providers.aws.request('Signer', 'startSigningJob', signItem.signerConfiguration)
// Wait until Signing job successfully completes
var status = ""
while ( status !== "Succeeded" && status !== "Failed" ) {
var jobStatus = await this.serverless.providers.aws.request('Signer', 'describeSigningJob', {jobId: signJob.jobId})
status = jobStatus.status
}
if (status === "Failed") {
throw new Error(`Signing job has failed with ${jobStatus.statusReason} reason`)
}
var signedCodeLocation = jobStatus.signedObject.s3
// Replace current zip archive of deployment archive with the same payload but signed
const { Body } = await this.serverless.providers.aws.request('S3', 'getObject', {
Bucket: signedCodeLocation.bucketName,
Key: signedCodeLocation.key
})
await fs.writeFile(signItem.packageArtifact, Body)
}
}
async signLayers() {
this.serverless.cli.log('Signing layers...');
const signerProcesses = this.generateLayersConfiguration();
for (let layer in signerProcesses) {
var signItem = signerProcesses[layer];
await this.verifyConfiguration(signItem);
// Copy deployment artifact to S3
const fileContent = fs.readFileSync(signItem.packageArtifact);
var S3Response = await this.serverless.providers.aws.request('S3', 'upload', {
Bucket: signItem.signerConfiguration.source.s3.bucketName,
Key: signItem.signerConfiguration.source.s3.key,
Body: fileContent
})
// Update configuration with a version of the uploaded S3 object
signItem.signerConfiguration.source.s3.version = S3Response.VersionId
if (signItem.signerConfiguration.signingPolicy) {
delete signItem.signerConfiguration.signingPolicy
delete signItem.signerConfiguration.retain
}
// Start signing job
var signJob = await this.serverless.providers.aws.request('Signer', 'startSigningJob', signItem.signerConfiguration)
// Wait until Signing job successfully completes
var status = ""
while ( status !== "Succeeded" && status !== "Failed" ) {
var jobStatus = await this.serverless.providers.aws.request('Signer', 'describeSigningJob', {jobId: signJob.jobId})
status = jobStatus.status
}
if (status === "Failed") {
throw new Error(`Signing job has failed with ${jobStatus.statusReason} reason`)
}
var signedCodeLocation = jobStatus.signedObject.s3
// Replace current zip archive of deployment archive with the same payload but signed
const { Body } = await this.serverless.providers.aws.request('S3', 'getObject', {
Bucket: signedCodeLocation.bucketName,
Key: signedCodeLocation.key
})
await fs.writeFile(signItem.packageArtifact, Body)
}
}
async createS3Bucket(bucketName) {
this.serverless.cli.log("Creating S3 bucket...")
// https://github.com/aws/aws-sdk-js/issues/3647
if (this.options.region == "us-east-1") {
await this.serverless.providers.aws.request('S3', 'createBucket', {
Bucket: bucketName
})
}
else {
var bucketConfiguration = {
LocationConstraint: this.options.region
}
await this.serverless.providers.aws.request('S3', 'createBucket', {
Bucket: bucketName,
CreateBucketConfiguration: bucketConfiguration
})
}
await this.serverless.providers.aws.request('S3', 'putBucketVersioning', {
Bucket: bucketName,
VersioningConfiguration: {
MFADelete: "Disabled",
Status: "Enabled"
}
})
}
async createSigningProfile(profileName) {
this.serverless.cli.log("Creating Signing profile...")
// Get Lambda Platform ID for Signing profile
const signingPlatforms = await this.serverless.providers.aws.request("Signer", "listSigningPlatforms", {
partner: "AWSLambda"
})
// TODO: Add support for signing profile configuration
const params = {
platformId: signingPlatforms.platforms[0].platformId,
profileName: profileName
}
await this.serverless.providers.aws.request('Signer', 'putSigningProfile', params)
return
}
async addSigningConfigurationToCloudFormation() {
this.serverless.cli.log('Updating signing configuration...');
var cloudFormationResources = this.serverless.service.provider.compiledCloudFormationTemplate.Resources;
const signerProcesses = this.generateSignerConfiguration();
for (let lambda in signerProcesses) {
const profileName = signerProcesses[lambda].signerConfiguration.profileName;
const signingPolicy = signerProcesses[lambda].signerConfiguration.signingPolicy;
const resourceName = normalizeResourceName(lambda) + "CodeSigningConfig";
// Copy deployment artifact to S3
var profileArn = await signersMethods.getProfileParamByName(profileName, 'profileVersionArn', this.serverless)
// TODO: Remove this check with proper validation
if (!profileArn) {
throw new Error("Signing profile not found")
}
const signingCFTemplate=cloudFormationGenerator.codeSigningConfig(profileArn, signingPolicy)
cloudFormationResources[resourceName] = signingCFTemplate
for (let resource in cloudFormationResources){
if (cloudFormationResources[resource].Type === 'AWS::Lambda::Function') {
cloudFormationResources[resource].Properties.CodeSigningConfigArn = {"Ref": resourceName}
}
}
}
}
async removeResources() {
const signerProcesses = this.generateSignerConfiguration();
for (let lambda in signerProcesses) {
var signItem = signerProcesses[lambda];
if (!signItem.signerConfiguration.retain) {
await this.removeS3Bucket(signItem.signerConfiguration.source.s3.bucketName)
await this.removeS3Bucket(signItem.signerConfiguration.destination.s3.bucketName)
}
}
for (let lambda in signerProcesses) {
var signItem = signerProcesses[lambda];
if (!signItem.signerConfiguration.retain) {
await this.removeSigningProfile(signItem.signerConfiguration.profileName)
}
}
}
async removeSigningProfile(profileName) {
// Make sure signing profile exists and hasn't been revoked yet
try {
const profileVersion = await signersMethods.getProfileParamByName(profileName, 'profileVersion', this.serverless)
if (profileName && profileVersion) {
const params = {
effectiveTime: new Date,
profileName: profileName,
profileVersion: profileVersion,
reason: 'Project removal'
};
await this.serverless.providers.aws.request('Signer', 'revokeSigningProfile', params)
}
}
catch (e) {
if (e.providerError.code !== "ProfileRevoked") {
throw (e)
}
}
return
}
async removeS3Bucket(bucketName) {
// Make sure bucket exists
try {
await this.serverless.providers.aws.request("S3", "headBucket", {
Bucket: bucketName
})
// Cleanup S3 bucket
var s3ObjectsList = [];
// TODO: Use ContinuationToken to go through an array of more than 1000 versions/keys
while (s3ObjectsList) {
s3ObjectsList = [];
var s3Objects = await this.serverless.providers.aws.request('S3', 'listObjectVersions', {
Bucket: bucketName
})
s3Objects.Versions.forEach(item => {s3ObjectsList.push({"Key": item.Key, VersionId: item.VersionId})})
s3Objects.DeleteMarkers.forEach(item => {s3ObjectsList.push({"Key": item.Key, VersionId: item.VersionId})})
if (s3ObjectsList.length > 0) {
var response = await this.serverless.providers.aws.request('S3', 'deleteObjects', {
Bucket: bucketName,
Delete: {
Objects: s3ObjectsList
}
})
}
else {
s3ObjectsList = null
}
}
// Delete S3 bucket
await this.serverless.providers.aws.request('S3', 'deleteBucket', {
Bucket: bucketName
})
}
catch (e) {
if (e.providerError.code !== "NotFound") {
throw (e)
}
}
// // Disable versioning
// await this.serverless.providers.aws.request('S3', 'putBucketVersioning', {
// Bucket: bucketName,
// VersioningConfiguration: {
// MFADelete: "Disabled",
// Status: "Enabled"
// }
// })
}
}
// Making sure the resource's logical ID is alphanumeric.
function normalizeResourceName(name) {
return name.replace(
/[^-_]*[-_]*/g,
txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
).replace(/-/g, 'Dash').replace(/_/g, 'Underscore');
}
module.exports = ServerlessPlugin;