-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathutils.js
1041 lines (916 loc) · 30.2 KB
/
utils.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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const AWS = require('@serverless/aws-sdk-extra')
const fs = require('fs')
const path = require('path')
const klawSync = require('klaw-sync')
const mime = require('mime-types')
const https = require('https')
const { parseDomain } = require('parse-domain')
const agent = new https.Agent({
keepAlive: true
})
const log = (msg) => console.log(msg) // eslint-disable-line
const sleep = async (wait) => new Promise((resolve) => setTimeout(() => resolve(), wait))
const generateId = () =>
Math.random()
.toString(36)
.substring(6)
const getClients = (credentials, region) => {
// this error message assumes that the user is running via the CLI though...
if (!credentials || !credentials.accessKeyId || !credentials.secretAccessKey) {
const msg = `AWS credentials not found. Make sure you have a .env file in the cwd. - Docs: https://git.io/JvArp`
throw new Error(msg)
}
AWS.config.update({
httpOptions: {
agent
}
})
const params = {
region,
credentials
}
return {
s3: {
// we need two S3 clients because creating/deleting buckets
// is not available with the acceleration feature.
regular: new AWS.S3(params),
accelerated: new AWS.S3({ ...params, endpoint: `s3-accelerate.amazonaws.com` })
},
cf: new AWS.CloudFront(params),
route53: new AWS.Route53(params),
extras: new AWS.Extras(params),
acm: new AWS.ACM({
credentials,
region: 'us-east-1' // ACM must be in us-east-1
})
}
}
const getNakedDomain = (domain) => {
const parsedDomain = parseDomain(domain)
if (!parsedDomain.topLevelDomains) {
throw new Error(`"${domain}" is not a valid domain.`)
}
const nakedDomain = `${parsedDomain.domain}.${parsedDomain.topLevelDomains.join('.')}`
return nakedDomain
}
const shouldConfigureNakedDomain = (domain) => {
if (!domain) {
return false
}
if (domain.startsWith('www')) {
return true
}
return false
}
const getConfig = (inputs, state) => {
const config = {}
config.indexDocument = inputs.indexDocument || 'index.html'
config.errorDocument = inputs.errorDocument || 'index.html'
config.bucketName = inputs.bucketName || state.bucketName || `website-${generateId()}`
config.region = inputs.region || state.region || 'us-east-1'
config.bucketUrl = `http://${config.bucketName}.s3-website-${config.region}.amazonaws.com`
config.src = inputs.src
config.distributionId = state.distributionId
config.distributionUrl = state.distributionUrl
config.distributionArn = state.distributionArn
config.distributionOrigins = [config.bucketUrl] // todo remove this as it's no longer used. Just saved to state.
config.distributionDescription =
inputs.distributionDescription || `Website distribution for bucket ${config.bucketName}`
config.distributionDefaults = inputs.distributionDefaults
// in case user specified protocol
config.domain = inputs.domain
? inputs.domain.replace('https://', '').replace('http://', '')
: null
config.nakedDomain = config.domain ? getNakedDomain(config.domain) : null
config.domainHostedZoneId = config.domain ? state.domainHostedZoneId : null
config.certificateArn = state.certificateArn
// for alternate cloudfront CNAME domains
config.alternateDomainNames = inputs.alternateDomainNames
? inputs.alternateDomainNames.split(',')
: null
// if user input example.com, make sure we also setup www.example.com
if (config.domain && config.domain === config.nakedDomain) {
config.domain = `www.${config.domain}`
}
return config
}
const accelerateBucket = async (clients, bucketName) => {
try {
await clients.s3.regular
.putBucketAccelerateConfiguration({
AccelerateConfiguration: {
Status: 'Enabled'
},
Bucket: bucketName
})
.promise()
// sleep for a a second for propagation
// otherwise we'd get "S3 Transfer Acceleration is not configured on this bucket" error
await sleep(1000)
} catch (e) {
if (e.code === 'NoSuchBucket') {
await sleep(2000)
return accelerateBucket(clients, bucketName)
}
throw e
}
}
const bucketCreation = async (clients, Bucket) => {
try {
await clients.s3.regular.headBucket({ Bucket }).promise()
} catch (e) {
if (e.code === 'NotFound' || e.code === 'NoSuchBucket') {
await sleep(2000)
return bucketCreation(clients, Bucket)
}
throw new Error(e)
}
}
const ensureBucket = async (clients, bucketName, instance) => {
try {
log(`Checking if bucket ${bucketName} exists.`)
await clients.s3.regular.headBucket({ Bucket: bucketName }).promise()
} catch (e) {
if (e.code === 'NotFound') {
log(`Bucket ${bucketName} does not exist. Creating...`)
await clients.s3.regular.createBucket({ Bucket: bucketName }).promise()
// there's a race condition when using acceleration
// so we need to sleep for a couple seconds. See this issue:
// https://github.com/serverless/components/issues/428
log(`Bucket ${bucketName} created. Confirming it's ready...`)
await bucketCreation(clients, bucketName)
// only accelerate if bucketName does not contain dots due to DNS limits
if (!bucketName.includes('.')) {
log(`Bucket ${bucketName} creation confirmed. Accelerating...`)
await accelerateBucket(clients, bucketName)
}
} else if (e.code === 'Forbidden' && e.message === null) {
throw Error(`Forbidden: Invalid credentials or this AWS S3 bucket name may already be taken`)
} else if (e.code === 'Forbidden') {
throw Error(`Bucket name "${bucketName}" is already taken.`)
} else {
throw e
}
}
}
// Attempts to call S3 method with "accelerated" and falls back
// onto "regular", if bucket is not accelerated.
const callAcceleratedOrRegular = async (clients, method, params) => {
return new Promise(async (resolve, reject) => {
try {
const result = await clients.s3.accelerated[method](params).promise()
resolve(result)
} catch (e) {
// if acceleration settings are still not ready
// use the regular client
if (
e.message.includes('Transfer Acceleration is not configured') ||
e.message.includes('Inaccessible host: `s3-accelerate.amazonaws.com')
) {
const result = await clients.s3.regular[method](params).promise()
resolve(result)
}
reject(e)
}
})
}
const upload = async (clients, params) => {
return callAcceleratedOrRegular(clients, 'upload', params)
}
const uploadDir = async (clients, bucketName, zipPath, instance) => {
// upload a simple website by default
let dirPath = path.join(__dirname, '_src')
// but if user provided src code, upload that instead
if (zipPath) {
dirPath = await instance.unzip(zipPath)
}
const items = await new Promise((resolve, reject) => {
try {
resolve(klawSync(dirPath))
} catch (error) {
reject(error)
}
})
const uploadItems = []
items.forEach((item) => {
if (item.stats.isDirectory()) {
return
}
let key = path.relative(dirPath, item.path)
// convert backslashes to forward slashes on windows
if (path.sep === '\\') {
key = key.replace(/\\/g, '/')
}
const itemParams = {
Bucket: bucketName,
Key: key,
Body: fs.readFileSync(item.path),
ContentType: mime.lookup(path.basename(item.path)) || 'application/octet-stream'
}
uploadItems.push(upload(clients, itemParams))
})
await Promise.all(uploadItems)
}
const configureBucketForHosting = async (clients, bucketName, indexDocument, errorDocument) => {
const s3BucketPolicy = {
Version: '2012-10-17',
Statement: [
{
Sid: 'PublicReadGetObject',
Effect: 'Allow',
Principal: {
AWS: '*'
},
Action: ['s3:GetObject'],
Resource: [`arn:aws:s3:::${bucketName}/*`]
}
]
}
const staticHostParams = {
Bucket: bucketName,
WebsiteConfiguration: {
ErrorDocument: {
Key: errorDocument
},
IndexDocument: {
Suffix: indexDocument
}
}
}
const putPostDeleteHeadRule = {
AllowedMethods: ['PUT', 'POST', 'DELETE', 'HEAD'],
AllowedOrigins: ['https://*.amazonaws.com'],
AllowedHeaders: ['*'],
MaxAgeSeconds: 0
}
const getRule = {
AllowedMethods: ['GET'],
AllowedOrigins: ['*'],
AllowedHeaders: ['*'],
MaxAgeSeconds: 0
}
try {
await clients.s3.regular
.putBucketPolicy({
Bucket: bucketName,
Policy: JSON.stringify(s3BucketPolicy)
})
.promise()
await clients.s3.regular
.putBucketCors({
Bucket: bucketName,
CORSConfiguration: {
CORSRules: [putPostDeleteHeadRule, getRule]
}
})
.promise()
await clients.s3.regular.putBucketWebsite(staticHostParams).promise()
} catch (e) {
if (e.code === 'NoSuchBucket') {
await sleep(2000)
return configureBucketForHosting(clients, bucketName)
}
throw e
}
}
const clearBucket = async (clients, bucketName) => {
try {
const data = await callAcceleratedOrRegular(clients, 'listObjects', { Bucket: bucketName })
const items = data.Contents
const promises = []
for (var i = 0; i < items.length; i += 1) {
var deleteParams = { Bucket: bucketName, Key: items[i].Key }
const delObj = callAcceleratedOrRegular(clients, 'deleteObject', deleteParams)
promises.push(delObj)
}
await Promise.all(promises)
} catch (error) {
if (error.code !== 'NoSuchBucket') {
throw error
}
}
}
const deleteBucket = async (clients, bucketName) => {
try {
await clients.s3.regular.deleteBucket({ Bucket: bucketName }).promise()
} catch (error) {
if (error.code !== 'NoSuchBucket') {
throw error
}
}
}
const getDomainHostedZoneId = async (clients, config) => {
const hostedZonesRes = await clients.route53.listHostedZonesByName().promise()
const hostedZone = hostedZonesRes.HostedZones.find(
// Name has a period at the end, so we're using includes rather than equals
(zone) => zone.Name.includes(config.nakedDomain)
)
if (!hostedZone) {
log(`Domain ${config.nakedDomain} was not found in your AWS account. Skipping DNS operations.`)
return
}
return hostedZone.Id.replace('/hostedzone/', '') // hosted zone id is always prefixed with this :(
}
const getCertificateArnByDomain = async (clients, config) => {
const listRes = await clients.acm.listCertificates().promise()
const certificate = listRes.CertificateSummaryList.find(
(cert) => cert.DomainName === config.nakedDomain
)
return certificate && certificate.CertificateArn ? certificate.CertificateArn : null
}
const getCertificateValidationRecord = (certificate, domain) => {
if (!certificate.DomainValidationOptions) {
return null
}
const domainValidationOption = certificate.DomainValidationOptions.find(
(option) => option.DomainName === domain
)
return domainValidationOption.ResourceRecord
}
const describeCertificateByArn = async (clients, certificateArn, domain) => {
const res = await clients.acm.describeCertificate({ CertificateArn: certificateArn }).promise()
const certificate = res && res.Certificate ? res.Certificate : null
if (
certificate.Status === 'PENDING_VALIDATION' &&
!getCertificateValidationRecord(certificate, domain)
) {
await sleep(1000)
return describeCertificateByArn(clients, certificateArn, domain)
}
return certificate
}
const ensureCertificate = async (clients, config, instance) => {
const wildcardSubDomain = `*.${config.nakedDomain}`
const params = {
DomainName: config.nakedDomain,
SubjectAlternativeNames: [config.nakedDomain, wildcardSubDomain],
ValidationMethod: 'DNS'
}
log(`Checking if a certificate for the ${config.nakedDomain} domain exists`)
let certificateArn = await getCertificateArnByDomain(clients, config)
if (!certificateArn) {
log(`Certificate for the ${config.nakedDomain} domain does not exist. Creating...`)
certificateArn = (await clients.acm.requestCertificate(params).promise()).CertificateArn
}
const certificate = await describeCertificateByArn(clients, certificateArn, config.nakedDomain)
log(`Certificate for ${config.nakedDomain} is in a "${certificate.Status}" status`)
if (certificate.Status === 'PENDING_VALIDATION') {
const certificateValidationRecord = getCertificateValidationRecord(
certificate,
config.nakedDomain
)
// only validate if domain/hosted zone is found in this account
if (config.domainHostedZoneId) {
log(`Validating the certificate for the ${config.nakedDomain} domain.`)
const recordParams = {
HostedZoneId: config.domainHostedZoneId,
ChangeBatch: {
Changes: [
{
Action: 'UPSERT',
ResourceRecordSet: {
Name: certificateValidationRecord.Name,
Type: certificateValidationRecord.Type,
TTL: 300,
ResourceRecords: [
{
Value: certificateValidationRecord.Value
}
]
}
}
]
}
}
await clients.route53.changeResourceRecordSets(recordParams).promise()
log(
`Your certificate was created and is being validated. It may take a few mins to validate.`
)
log(
`Please deploy again after few mins to use your newly validated certificate and activate your domain.`
)
} else {
// if domain is not in account, let the user validate manually
log(
`Certificate for the ${config.nakedDomain} domain was created, but not validated. Please validate it manually.`
)
log(`Certificate Validation Record Name: ${certificateValidationRecord.Name} `)
log(`Certificate Validation Record Type: ${certificateValidationRecord.Type} `)
log(`Certificate Validation Record Value: ${certificateValidationRecord.Value} `)
}
} else if (certificate.Status === 'ISSUED') {
// if certificate status is ISSUED, mark it a as valid for CloudFront to use
config.certificateValid = true
} else if (certificate.Status === 'SUCCESS') {
// nothing to do here. We just need to wait a min until the status changes to ISSUED
} else if (certificate.Status === 'VALIDATION_TIMED_OUT') {
// if 72 hours passed and the user did not validate the certificate
// it will timeout and the user will need to recreate and validate the certificate manulaly
log(
`Certificate validation timed out after 72 hours. Please recreate and validate the certifcate manually.`
)
log(`Your domain will not work until your certificate is created and validated .`)
} else {
// something else happened?!
throw new Error(
`Failed to validate ACM certificate. Unsupported ACM certificate status ${certificate.Status}`
)
}
return certificateArn
}
const createCloudFrontDistribution = async (clients, config) => {
const params = {
DistributionConfig: {
CallerReference: String(Date.now()),
DefaultRootObject: 'index.html',
CustomErrorResponses: {
Quantity: 2,
Items: [
{
ErrorCode: 404,
ErrorCachingMinTTL: 300,
ResponseCode: '200',
ResponsePagePath: '/index.html'
},
{
ErrorCode: 403,
ErrorCachingMinTTL: 300,
ResponseCode: '200',
ResponsePagePath: '/index.html'
}
]
},
Comment: config.distributionDescription,
Aliases: {
Quantity: 0,
Items: []
},
Origins: {
Quantity: 0,
Items: []
},
PriceClass: 'PriceClass_All',
Enabled: true,
HttpVersion: 'http2',
Origins: {
Quantity: 1,
Items: [
{
Id: config.bucketName,
DomainName: `${config.bucketName}.s3.${config.region}.amazonaws.com`,
CustomHeaders: {
Quantity: 0,
Items: []
},
OriginPath: '',
S3OriginConfig: {
OriginAccessIdentity: ''
}
}
]
},
DefaultCacheBehavior: {
TargetOriginId: config.bucketName,
ForwardedValues: {
QueryString: false,
Cookies: {
Forward: 'none'
},
Headers: {
Quantity: 0,
Items: []
},
QueryStringCacheKeys: {
Quantity: 0,
Items: []
}
},
TrustedSigners: {
Enabled: false,
Quantity: 0,
Items: []
},
ViewerProtocolPolicy: 'redirect-to-https',
MinTTL: 0,
AllowedMethods: {
Quantity: 2,
Items: ['HEAD', 'GET'],
CachedMethods: {
Quantity: 2,
Items: ['HEAD', 'GET']
}
},
SmoothStreaming: false,
DefaultTTL: 0,
MaxTTL: 31536000,
Compress: false,
LambdaFunctionAssociations: {
Quantity: 0,
Items: []
},
FieldLevelEncryptionId: ''
},
CacheBehaviors: {
Quantity: 0,
Items: []
}
}
}
const distributionConfig = params.DistributionConfig
// add domain and certificate config if certificate is valid and ISSUED
if (config.certificateValid) {
log(`Adding "${config.nakedDomain}" certificate to CloudFront distribution`)
distributionConfig.ViewerCertificate = {
ACMCertificateArn: config.certificateArn,
SSLSupportMethod: 'sni-only',
MinimumProtocolVersion: 'TLSv1.1_2016',
Certificate: config.certificateArn,
CertificateSource: 'acm'
}
log(`Adding domain "${config.domain}" to CloudFront distribution`)
distributionConfig.Aliases = {
Quantity: 1,
Items: [config.domain]
}
if (shouldConfigureNakedDomain(config.domain)) {
log(`Adding domain "${config.nakedDomain}" to CloudFront distribution`)
distributionConfig.Aliases.Quantity = 2
distributionConfig.Aliases.Items.push(config.nakedDomain)
}
if (Array.isArray(config.alternateDomainNames)) {
config.alternateDomainNames.forEach((domain) => {
distributionConfig.Aliases.Quantity += 1
distributionConfig.Aliases.Items.push(domain)
})
}
}
try {
const res = await clients.cf.createDistribution(params).promise()
return {
distributionId: res.Distribution.Id,
distributionArn: res.Distribution.ARN,
distributionUrl: res.Distribution.DomainName,
distributionOrigins: config.distributionOrigins,
distributionDefaults: config.distributionDefaults,
distributionDescription: config.distributionDescription
}
} catch (e) {
// throw a friendly error if trying to use an existing domain
if (e.message.includes('One or more of the CNAMEs')) {
throw new Error(
`The domain "${config.domain}" is already in use by another website or CloudFront Distribution.`
)
}
throw e
}
}
const updateCloudFrontDistribution = async (clients, config) => {
try {
// Update logic is a bit weird...
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudFront.html#updateDistribution-property
// 1. we gotta get the config first...
// todo what if id does not exist?
const params = await clients.cf.getDistributionConfig({ Id: config.distributionId }).promise()
// 2. then add this property
params.IfMatch = params.ETag
// 3. then delete this property
delete params.ETag
// 4. then set this property
params.Id = config.distributionId
// 5. then make our changes
params.DistributionConfig.Enabled = true // make sure it's enabled
params.DistributionConfig.Comment = config.distributionDescription
// add domain and certificate config if certificate is valid and ISSUED
if (config.certificateValid) {
log(`Adding "${config.nakedDomain}" certificate to CloudFront distribution`)
params.DistributionConfig.ViewerCertificate = {
ACMCertificateArn: config.certificateArn,
SSLSupportMethod: 'sni-only',
MinimumProtocolVersion: 'TLSv1.1_2016',
Certificate: config.certificateArn,
CertificateSource: 'acm'
}
log(`Adding domain "${config.domain}" to CloudFront distribution`)
params.DistributionConfig.Aliases = {
Quantity: 1,
Items: [config.domain]
}
if (shouldConfigureNakedDomain(config.domain)) {
log(`Adding domain "${config.nakedDomain}" to CloudFront distribution`)
params.DistributionConfig.Aliases.Quantity = 2
params.DistributionConfig.Aliases.Items.push(config.nakedDomain)
}
if (Array.isArray(config.alternateDomainNames)) {
config.alternateDomainNames.forEach((domain) => {
params.DistributionConfig.Aliases.Quantity += 1
params.DistributionConfig.Aliases.Items.push(domain)
})
}
}
// 6. then finally update!
const res = await clients.cf.updateDistribution(params).promise()
return {
distributionId: res.Distribution.Id,
distributionArn: res.Distribution.ARN,
distributionUrl: res.Distribution.DomainName,
distributionOrigins: config.distributionOrigins,
distributionDefaults: config.distributionDefaults,
distributionDescription: config.distributionDescription
}
} catch (e) {
if (e.code === 'NoSuchDistribution') {
return null
}
if (e.message.includes('One or more of the CNAMEs')) {
throw new Error(
`The domain "${config.domain}" is already in use by another website or CloudFront Distribution.`
)
}
throw e
}
}
const invalidateCloudfrontDistribution = async (clients, config) => {
const params = {
DistributionId: config.distributionId,
InvalidationBatch: {
CallerReference: String(Date.now()),
Paths: {
Quantity: 3,
Items: ['/', '/index.html', '/*']
}
}
}
await clients.cf.createInvalidation(params).promise()
}
const configureDnsForCloudFrontDistribution = async (clients, config) => {
const dnsRecordParams = {
HostedZoneId: config.domainHostedZoneId,
ChangeBatch: {
Changes: [
{
Action: 'UPSERT',
ResourceRecordSet: {
Name: config.domain,
Type: 'A',
AliasTarget: {
HostedZoneId: 'Z2FDTNDATAQYW2', // this is a constant that you can get from here https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region
DNSName: config.distributionUrl,
EvaluateTargetHealth: false
}
}
}
]
}
}
if (shouldConfigureNakedDomain(config.domain)) {
dnsRecordParams.ChangeBatch.Changes.push({
Action: 'UPSERT',
ResourceRecordSet: {
Name: config.nakedDomain,
Type: 'A',
AliasTarget: {
HostedZoneId: 'Z2FDTNDATAQYW2', // this is a constant that you can get from here https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region
DNSName: config.distributionUrl,
EvaluateTargetHealth: false
}
}
})
}
return clients.route53.changeResourceRecordSets(dnsRecordParams).promise()
}
const disableCloudFrontDistribution = async (clients, distributionId) => {
const params = await clients.cf.getDistributionConfig({ Id: distributionId }).promise()
params.IfMatch = params.ETag
delete params.ETag
params.Id = distributionId
params.DistributionConfig.Enabled = false
const res = await clients.cf.updateDistribution(params).promise()
return {
id: res.Distribution.Id,
arn: res.Distribution.ARN,
url: `https://${res.Distribution.DomainName}`
}
}
const deleteCloudFrontDistribution = async (clients, distributionId) => {
try {
const res = await clients.cf.getDistributionConfig({ Id: distributionId }).promise()
const params = { Id: distributionId, IfMatch: res.ETag }
await clients.cf.deleteDistribution(params).promise()
} catch (e) {
if (e.code === 'DistributionNotDisabled') {
await disableCloudFrontDistribution(clients, distributionId)
} else if (e.code === 'NoSuchDistribution') {
return
} else {
throw e
}
}
}
const removeDomainFromCloudFrontDistribution = async (clients, config) => {
try {
const params = await clients.cf.getDistributionConfig({ Id: config.distributionId }).promise()
params.IfMatch = params.ETag
delete params.ETag
params.Id = config.distributionId
params.DistributionConfig.Aliases = {
Quantity: 0,
Items: []
}
params.DistributionConfig.ViewerCertificate = {
SSLSupportMethod: 'sni-only',
MinimumProtocolVersion: 'TLSv1.1_2016'
}
const res = await clients.cf.updateDistribution(params).promise()
return {
distributionId: res.Distribution.Id,
distributionArn: res.Distribution.ARN,
distributionUrl: res.Distribution.DomainName,
distributionOrigins: config.distributionOrigins,
distributionDefaults: config.distributionDefaults,
distributionDescription: config.distributionDescription
}
} catch (e) {
if (e.code === 'NoSuchDistribution') {
return null
}
throw e
}
}
const removeCloudFrontDomainDnsRecords = async (clients, config) => {
const params = {
HostedZoneId: config.domainHostedZoneId,
ChangeBatch: {
Changes: [
{
Action: 'DELETE',
ResourceRecordSet: {
Name: config.domain,
Type: 'A',
AliasTarget: {
HostedZoneId: 'Z2FDTNDATAQYW2', // this is a constant that you can get from here https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region
DNSName: config.distributionUrl,
EvaluateTargetHealth: false
}
}
}
]
}
}
if (shouldConfigureNakedDomain(config.domain)) {
params.ChangeBatch.Changes.push({
Action: 'UPSERT',
ResourceRecordSet: {
Name: config.nakedDomain,
Type: 'A',
AliasTarget: {
HostedZoneId: 'Z2FDTNDATAQYW2', // this is a constant that you can get from here https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region
DNSName: config.distributionUrl,
EvaluateTargetHealth: false
}
}
})
}
try {
await clients.route53.changeResourceRecordSets(params).promise()
} catch (e) {
if (e.code !== 'InvalidChangeBatch' && e.code !== 'NoSuchHostedZone') {
throw e
}
}
}
/*
* Ensure the Meta IAM Role exists
*/
const createOrUpdateMetaRole = async (instance, inputs, clients, serverlessAccountId) => {
// Create or update Meta Role for monitoring and more, if option is enabled. It's enabled by default.
if (inputs.monitoring || typeof inputs.monitoring === 'undefined') {
console.log('Creating or updating the meta IAM Role...');
const roleName = `${instance.name}-meta-role`;
const assumeRolePolicyDocument = {
Version: '2012-10-17',
Statement: {
Effect: 'Allow',
Principal: {
AWS: `arn:aws:iam::${serverlessAccountId}:root`, // Serverless's Components account
},
Action: 'sts:AssumeRole',
},
};
// Create a policy that only can access APIGateway and Lambda metrics, logs from CloudWatch...
const policy = {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Resource: '*',
Action: [
'cloudwatch:Describe*',
'cloudwatch:Get*',
'cloudwatch:List*',
'logs:Get*',
'logs:List*',
'logs:Describe*',
'logs:TestMetricFilter',
'logs:FilterLogEvents',
],
},
],
};
const roleDescription = `The Meta Role for the Serverless Framework App: ${instance.name} Stage: ${instance.stage}`;
const result = await clients.extras.deployRole({
roleName,
roleDescription,
policy,
assumeRolePolicyDocument,
});
instance.state.metaRoleName = roleName;
instance.state.metaRoleArn = result.roleArn;
console.log(`Meta IAM Role created or updated with ARN ${instance.state.metaRoleArn}`);
}
};
/*
* Removes the Function & Meta Roles from aws according to the provided config
*
* @param ${object} clients - an object containing aws sdk clients
* @param ${object} config - the component config
*/
const removeAllRoles = async (instance, clients) => {
// Delete Meta Role
if (instance.state.metaRoleName) {
console.log('Deleting the Meta Role...');
await clients.extras.removeRole({
roleName: instance.state.metaRoleName,
});
}
};
/**
* Get metrics from cloudwatch
* @param {*} clients
* @param {*} rangeStart MUST be a moment() object
* @param {*} rangeEnd MUST be a moment() object
*/
const getMetrics = async (
region,
metaRoleArn,
distributionId,
rangeStart,
rangeEnd
) => {
/**
* Create AWS STS Token via the meta role that is deployed with the Express Component
*/
// Assume Role
const assumeParams = {};
assumeParams.RoleSessionName = `session${Date.now()}`;
assumeParams.RoleArn = metaRoleArn;
assumeParams.DurationSeconds = 900;
const sts = new AWS.STS({ region })
const resAssume = await sts.assumeRole(assumeParams).promise();
const roleCreds = {};
roleCreds.accessKeyId = resAssume.Credentials.AccessKeyId;
roleCreds.secretAccessKey = resAssume.Credentials.SecretAccessKey;
roleCreds.sessionToken = resAssume.Credentials.SessionToken;
/**
* Instantiate a new Extras instance w/ the temporary credentials
*/
const extras = new AWS.Extras({
credentials: roleCreds,
region,