forked from amplify-education/serverless-domain-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
533 lines (469 loc) · 17.6 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
'use strict';
const chalk = require('chalk');
const DomainResponse = require('./DomainResponse');
const endpointTypes = {
edge: 'EDGE',
regional: 'REGIONAL',
};
class ServerlessCustomDomain {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
// Indicate if variables are initialized to avoid run multiples init
this.initialized = false;
this.commands = {
create_domain: {
usage: 'Creates a domain using the domain name defined in the serverless file',
lifecycleEvents: [
'initialize',
'create',
],
},
delete_domain: {
usage: 'Deletes a domain using the domain name defined in the serverless file',
lifecycleEvents: [
'initialize',
'delete',
],
},
};
this.hooks = {
'delete_domain:delete': this.deleteDomain.bind(this),
'create_domain:create': this.createDomain.bind(this),
'after:package:compileEvents': this.setUpBasePathMapping.bind(this),
'after:deploy:deploy': this.domainSummary.bind(this),
'after:info:info': this.domainSummary.bind(this),
};
}
initializeVariables() {
if (!this.initialized) {
this.enabled = this.evaluateEnabled();
if (this.enabled) {
const credentials = this.serverless.providers.aws.getCredentials();
this.apigateway = new this.serverless.providers.aws.sdk.APIGateway(credentials);
this.route53 = new this.serverless.providers.aws.sdk.Route53(credentials);
this.setGivenDomainName(this.serverless.service.custom.customDomain.domainName);
this.setEndpointType(this.serverless.service.custom.customDomain.endpointType);
this.setAcmRegion();
const acmCredentials = Object.assign({}, credentials, { region: this.acmRegion });
this.acm = new this.serverless.providers.aws.sdk.ACM(acmCredentials);
}
this.initialized = true;
}
}
/**
* Determines whether this plug-in should be enabled.
*
* This method reads the customDomain property "enabled" to see if this plug-in should be enabled.
* If the property's value is undefined, a default value of true is assumed (for backwards
* compatibility).
* If the property's value is provided, this should be boolean, otherwise an exception is thrown.
*/
evaluateEnabled() {
const enabled = this.serverless.service.custom.customDomain.enabled;
if (enabled === undefined) {
return true;
}
if (typeof enabled === 'boolean') {
return enabled;
}
throw new Error(`serverless-domain-manager: Ambiguous enablement boolean: '${enabled}'`);
}
reportDisabled() {
return Promise.resolve()
.then(() => this.serverless.cli.log('serverless-domain-manager: Custom domain is disabled.'));
}
createDomain() {
this.initializeVariables();
if (!this.enabled) {
return this.reportDisabled();
}
let domain = null;
const createDomainName = this.getCertArn().then(data => this.createDomainName(data));
return createDomainName
.catch((err) => {
throw new Error(`Error: '${this.givenDomainName}' was not created in API Gateway.\n${err}`);
})
.then((res) => {
domain = res;
return this.migrateRecordType(domain);
})
.then(() => this.changeResourceRecordSet(domain, 'UPSERT').catch((err) => {
throw new Error(`Error: '${this.givenDomainName}' was not created in Route53.\n${err}`);
}))
.then(() => (this.serverless.cli.log(`'${this.givenDomainName}' was created/updated. New domains may take up to 40 minutes to be initialized.`)));
}
deleteDomain() {
this.initializeVariables();
if (!this.enabled) {
return this.reportDisabled();
}
let domain = null;
return this.getDomain().then((data) => {
domain = data;
return this.migrateRecordType(domain);
})
.then(() => {
const promises = [
this.changeResourceRecordSet(domain, 'DELETE'),
this.clearDomainName(),
];
return (Promise.all(promises).then(() => (this.serverless.cli.log('Domain was deleted.'))));
})
.catch((err) => {
throw new Error(`Error: '${this.givenDomainName}' was not deleted.\n${err}`);
});
}
setGivenDomainName(givenDomainName) {
this.givenDomainName = givenDomainName;
}
setEndpointType(endpointType) {
const endpointTypeWithDefault = endpointType || endpointTypes.edge;
const endpointTypeToUse = endpointTypes[endpointTypeWithDefault.toLowerCase()];
if (!endpointTypeToUse) throw new Error(`${endpointTypeWithDefault} is not supported endpointType, use edge or regional.`);
this.endpointType = endpointTypeToUse;
}
setAcmRegion() {
if (this.endpointType === endpointTypes.regional) {
this.acmRegion = this.serverless.providers.aws.getRegion();
} else {
this.acmRegion = 'us-east-1';
}
}
setUpBasePathMapping() {
this.initializeVariables();
if (!this.enabled) {
return this.reportDisabled();
}
let domain = null;
return this.getDomain().then((data) => {
domain = data;
return this.migrateRecordType(domain);
})
.then(() => {
const deploymentId = this.getDeploymentId();
this.addResources(deploymentId);
this.addOutputs(domain);
})
.catch((err) => {
throw new Error(`Error: Could not set up basepath mapping. Try running sls create_domain first.\n${err}`);
});
}
getRoute53HostedZoneId() {
const specificId = this.serverless.service.custom.customDomain.hostedZoneId;
if (specificId) {
this.serverless.cli.log(`Selected specific hostedZoneId ${specificId}`);
return Promise.resolve(specificId);
}
const hostedZonePromise = this.route53.listHostedZones({}).promise();
return hostedZonePromise
.catch((err) => {
throw new Error(`Error: Unable to list hosted zones in Route53.\n${err}`);
})
.then((data) => {
// Gets the hostzone that is closest match to the custom domain name
const targetHostedZone = data.HostedZones
.filter((hostedZone) => {
const hostedZoneName = hostedZone.Name.endsWith('.') ? hostedZone.Name.slice(0, -1) : hostedZone.Name;
return this.givenDomainName.endsWith(hostedZoneName);
})
.sort((zone1, zone2) => zone2.Name.length - zone1.Name.length)
.shift();
if (targetHostedZone) {
const hostedZoneId = targetHostedZone.Id;
// Extracts the hostzone Id
const startPos = hostedZoneId.indexOf('e/') + 2;
const endPos = hostedZoneId.length;
return hostedZoneId.substring(startPos, endPos);
}
throw new Error(`Error: Could not find hosted zone '${this.givenDomainName}'`);
});
}
/**
* Prints out a summary of all domain manager related info
*/
domainSummary() {
this.initializeVariables();
if (!this.enabled) {
return this.reportDisabled();
}
return this.getDomain().then((data) => {
this.serverless.cli.consoleLog(chalk.yellow.underline('Serverless Domain Manager Summary'));
if (this.serverless.service.custom.customDomain.createRoute53Record !== false) {
this.serverless.cli.consoleLog(chalk.yellow('Domain Name'));
this.serverless.cli.consoleLog(` ${this.givenDomainName}`);
}
this.serverless.cli.consoleLog(chalk.yellow('Distribution Domain Name'));
this.serverless.cli.consoleLog(` ${data.domainName}`);
return true;
}).catch((err) => {
throw new Error(`Error: Domain manager summary logging failed.\n${err}`);
});
}
/**
* Gets the deployment id
*/
getDeploymentId() {
// Searches for the deployment id from the cloud formation template
const cloudTemplate = this.serverless.service.provider.compiledCloudFormationTemplate;
const deploymentId = Object.keys(cloudTemplate.Resources).find((key) => {
const resource = cloudTemplate.Resources[key];
return resource.Type === 'AWS::ApiGateway::Deployment';
});
if (!deploymentId) {
throw new Error('Cannot find AWS::ApiGateway::Deployment');
}
return deploymentId;
}
/**
* Adds the custom domain, stage, and basepath to the resource section
* @param deployId Used to set the timing for creating the basepath
*/
addResources(deployId) {
const service = this.serverless.service;
if (!service.custom.customDomain) {
throw new Error('Error: check that the customDomain section is defined in serverless.yml');
}
let basePath = service.custom.customDomain.basePath;
// Check that basePath is either not set, or set to an empty string
if (basePath == null || basePath.trim() === '') {
basePath = '(none)';
}
let stage = service.custom.customDomain.stage;
/*
If stage is not provided, stage will be set based on the user specified value
or the stage value of the provider section (which defaults to dev if unset)
*/
if (typeof stage === 'undefined') {
stage = this.options.stage || service.provider.stage;
}
const dependsOn = [deployId];
// Verify the cloudFormationTemplate exists
if (!service.provider.compiledCloudFormationTemplate) {
this.serverless.service.provider.compiledCloudFormationTemplate = {};
}
if (!service.provider.compiledCloudFormationTemplate.Resources) {
service.provider.compiledCloudFormationTemplate.Resources = {};
}
// If user define an ApiGatewayStage resources add it into the dependsOn array
if (service.provider.compiledCloudFormationTemplate.Resources.ApiGatewayStage) {
dependsOn.push('ApiGatewayStage');
}
// Creates the pathmapping
const pathmapping = {
Type: 'AWS::ApiGateway::BasePathMapping',
DependsOn: dependsOn,
Properties: {
BasePath: basePath,
DomainName: this.givenDomainName,
RestApiId: {
Ref: 'ApiGatewayRestApi',
},
Stage: stage,
},
};
// Creates and sets the resources
service.provider.compiledCloudFormationTemplate.Resources.pathmapping = pathmapping;
}
/**
* Adds the domain name and distribution domain name to the CloudFormation outputs
*/
addOutputs(data) {
const service = this.serverless.service;
if (!service.provider.compiledCloudFormationTemplate.Outputs) {
service.provider.compiledCloudFormationTemplate.Outputs = {};
}
service.provider.compiledCloudFormationTemplate.Outputs.DomainName = {
Value: data.domainName,
};
if (data.hostedZoneId) {
service.provider.compiledCloudFormationTemplate.Outputs.HostedZoneId = {
Value: data.hostedZoneId,
};
}
}
/*
* Obtains the certification arn
*/
getCertArn() {
const certArn = this.acm.listCertificates().promise();
return certArn.catch((err) => {
throw Error(`Error: Could not list certificates in Certificate Manager.\n${err}`);
}).then((data) => {
// The more specific name will be the longest
let nameLength = 0;
// The arn of the choosen certificate
let certificateArn;
// The certificate name
let certificateName = this.serverless.service.custom.customDomain.certificateName;
// Checks if a certificate name is given
if (certificateName != null) {
const foundCertificate = data.CertificateSummaryList
.find(certificate => (certificate.DomainName === certificateName));
if (foundCertificate != null) {
certificateArn = foundCertificate.CertificateArn;
}
} else {
certificateName = this.givenDomainName;
data.CertificateSummaryList.forEach((certificate) => {
let certificateListName = certificate.DomainName;
// Looks for wild card and takes it out when checking
if (certificateListName[0] === '*') {
certificateListName = certificateListName.substr(1);
}
// Looks to see if the name in the list is within the given domain
// Also checks if the name is more specific than previous ones
if (certificateName.includes(certificateListName)
&& certificateListName.length > nameLength) {
nameLength = certificateListName.length;
certificateArn = certificate.CertificateArn;
}
});
}
if (certificateArn == null) {
throw Error(`Error: Could not find the certificate ${certificateName}.`);
}
return certificateArn;
});
}
/**
* Creates the domain name through the api gateway
* @param certificateArn The certificate needed to create the new domain
*/
createDomainName(givenCertificateArn) {
const createDomainNameParams = {
domainName: this.givenDomainName,
endpointConfiguration: {
types: [this.endpointType],
},
};
if (this.endpointType === endpointTypes.edge) {
createDomainNameParams.certificateArn = givenCertificateArn;
} else if (this.endpointType === endpointTypes.regional) {
createDomainNameParams.regionalCertificateArn = givenCertificateArn;
}
/* This will return the distributionDomainName (used in changeResourceRecordSet)
if the domain name already exists, the distribution domain name will be returned */
return this.getDomain()
.catch(() => this.apigateway.createDomainName(createDomainNameParams).promise()
.then(data => new DomainResponse(data)));
}
/**
* Can create a new A Alias or delete a A Alias
*
* @param domain The domain object contains the domainName and the hostedZoneId
* @param action UPSERT: Creates a A Alias
* DELETE: Deletes the A Alias
* The A Alias is specified in the serverless file under domainName
*/
changeResourceRecordSet(domain, action) {
if (action !== 'DELETE' && action !== 'UPSERT') {
throw new Error(`Error: ${action} is not a valid action. action must be either UPSERT or DELETE`);
}
if (this.serverless.service.custom.customDomain.createRoute53Record !== undefined
&& this.serverless.service.custom.customDomain.createRoute53Record === false) {
return Promise.resolve().then(() => (this.serverless.cli.log('Skipping creation of Route53 record.')));
}
return this.getRoute53HostedZoneId().then((route53HostedZoneId) => {
if (!route53HostedZoneId) return null;
const params = {
ChangeBatch: {
Changes: [
{
Action: action,
ResourceRecordSet: {
Name: this.givenDomainName,
Type: 'A',
AliasTarget: {
DNSName: domain.domainName,
EvaluateTargetHealth: false,
HostedZoneId: domain.hostedZoneId,
},
},
},
],
Comment: 'Record created by serverless-domain-manager',
},
HostedZoneId: route53HostedZoneId,
};
return this.route53.changeResourceRecordSets(params).promise();
}, () => {
if (action === 'CREATE') {
throw new Error(`Record set for ${this.givenDomainName} already exists.`);
}
throw new Error(`Record set for ${this.givenDomainName} does not exist and cannot be deleted.`);
});
}
/**
* Delete any legacy CNAME certificates, replacing them with A Alias records.
* records.
*
* @param domain The domain object contains the domainName and the hostedZoneId
*/
migrateRecordType(domain) {
if (this.serverless.service.custom.customDomain.createRoute53Record !== undefined
&& this.serverless.service.custom.customDomain.createRoute53Record === false) {
return Promise.resolve();
}
return this.getRoute53HostedZoneId().then((route53HostedZoneId) => {
if (!route53HostedZoneId) return null;
const params = {
ChangeBatch: {
Changes: [
{
Action: 'DELETE',
ResourceRecordSet: {
Name: this.givenDomainName,
ResourceRecords: [
{
Value: domain.domainName,
},
],
TTL: 60,
Type: 'CNAME',
},
},
{
Action: 'CREATE',
ResourceRecordSet: {
Name: this.givenDomainName,
Type: 'A',
AliasTarget: {
DNSName: domain.domainName,
EvaluateTargetHealth: false,
HostedZoneId: domain.hostedZoneId,
},
},
},
],
Comment: 'Record created by serverless-domain-manager',
},
HostedZoneId: route53HostedZoneId,
};
const changeRecords = this.route53.changeResourceRecordSets(params).promise();
return changeRecords.then(() => this.serverless.cli.log('Notice: Legacy CNAME record was replaced with an A Alias record'))
.catch(() => { }); // Swallow the error, not an error if it doesn't exist
});
}
/**
* Deletes the domain names specified in the serverless file
*/
clearDomainName() {
return this.apigateway.deleteDomainName({
domainName: this.givenDomainName,
}).promise();
}
/*
* Get information on domain
*/
getDomain() {
const getDomainNameParams = {
domainName: this.givenDomainName,
};
return this.apigateway.getDomainName(getDomainNameParams).promise()
.then(data => new DomainResponse(data), (err) => {
throw new Error(`Error: '${this.givenDomainName}' could not be found in API Gateway.\n${err}`);
});
}
}
module.exports = ServerlessCustomDomain;