-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
389 lines (344 loc) · 12.7 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
const path = require("path");
const _ = require("lodash");
const chalk = require("chalk");
const yaml = require("js-yaml");
const fs = require("fs");
const certStatuses = ["PENDING_VALIDATION", "ISSUED", "INACTIVE"];
class ServerlessAppSyncCloudFrontPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.hooks = {
"package:createDeploymentArtifacts": this.createDeploymentArtifacts.bind(
this
),
"aws:info:displayStackOutputs": this.printSummary.bind(this),
};
}
async createDeploymentArtifacts() {
if (this.getConfig("enabled", true) !== false) {
const credentials = this.serverless.providers.aws.getCredentials();
const acmCredentials = Object.assign({}, credentials, {
region: "us-east-1",
});
this.acm = new this.serverless.providers.aws.sdk.ACM(acmCredentials);
this.route53 = new this.serverless.providers.aws.sdk.Route53(credentials);
const baseResources = this.serverless.service.provider
.compiledCloudFormationTemplate;
const filename = path.resolve(__dirname, "resources.yml");
const content = fs.readFileSync(filename, "utf-8");
const resources = yaml.safeLoad(content, { filename });
await this.prepareResources(resources);
return _.merge(baseResources, resources);
}
}
async printSummary() {
const awsInfo = _.find(
this.serverless.pluginManager.getPlugins(),
(plugin) => plugin.constructor.name === "AwsInfo"
);
if (!awsInfo || !awsInfo.gatheredData) {
return;
}
const { outputs } = awsInfo.gatheredData;
const apiDistributionDomain = _.find(
outputs,
(output) => output.OutputKey === "AppSyncApiDistribution"
);
if (!apiDistributionDomain || !apiDistributionDomain.OutputValue) {
return;
}
const cnameDomain = this.getConfig("domainName");
this.serverless.cli.consoleLog(chalk.yellow("CloudFront domain name"));
this.serverless.cli.consoleLog(
` ${apiDistributionDomain.OutputValue} (CNAME: ${cnameDomain || "-"})`
);
if (cnameDomain) {
this.serverless.cli.consoleLog(
`AppSync: ${chalk.yellow(
`Creating Route53 records for ${cnameDomain}...`
)}`
);
await this.changeResourceRecordSet(
"UPSERT",
apiDistributionDomain.OutputValue
);
}
}
/**
* Gets Certificate ARN that most closely matches domain name OR given Cert ARN if provided
*/
async getCertArn() {
let certificateArn; // The arn of the choosen certificate
let certificateName = this.getConfig("certificateName");
if (!certificateName && !this.getConfig("domainName")) return;
try {
const certData = await this.acm
.listCertificates({ CertificateStatuses: certStatuses })
.promise();
// The more specific name will be the longest
let nameLength = 0;
const certificates = certData.CertificateSummaryList;
// Checks if a certificate name is given
if (certificateName != null) {
const foundCertificate = certificates.find(
(certificate) => certificate.DomainName === certificateName
);
if (foundCertificate != null) {
certificateArn = foundCertificate.CertificateArn;
}
} else {
certificateName = this.getConfig("domainName");
certificates.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;
}
});
}
} catch (err) {
throw Error(
`Error: Could not list certificates in Certificate Manager.\n${err}`
);
}
if (certificateArn == null) {
throw Error(`Error: Could not find the certificate ${certificateName}.`);
}
return certificateArn;
}
/**
* Change A Alias record through Route53 based on given action
* @param action: String descriptor of change to be made. Valid actions are ['UPSERT', 'DELETE']
* @param domain: DomainInfo object containing info about custom domain
*/
async changeResourceRecordSet(action, domain) {
if (action !== "UPSERT" && action !== "DELETE") {
throw new Error(`Error: Invalid action "${action}" when changing Route53 Record.
Action must be either UPSERT or DELETE.\n`);
}
const createRoute53Record = this.getConfig("createRoute53Record");
if (createRoute53Record !== undefined && createRoute53Record === false) {
this.serverless.cli.log("Skipping creation of Route53 record.");
return;
}
// Set up parameters
const route53HostedZoneId = await this.getRoute53HostedZoneId();
const Changes = ["A", "AAAA"].map((Type) => ({
Action: action,
ResourceRecordSet: {
AliasTarget: {
DNSName: domain,
EvaluateTargetHealth: false,
HostedZoneId: "Z2FDTNDATAQYW2", // CloudFront HZID is always Z2FDTNDATAQYW2
},
Name: this.getConfig("domainName"),
Type,
},
}));
const params = {
ChangeBatch: {
Changes,
Comment: "Record created by serverless-appsync-cloudfront",
},
HostedZoneId: route53HostedZoneId,
};
// Make API call
try {
await this.route53.changeResourceRecordSets(params).promise();
} catch (err) {
throw new Error(
`Error: Failed to ${action} A Alias for ${this.getConfig(
"domainName"
)}\n`
);
}
}
/**
* Gets Route53 HostedZoneId from user or from AWS
*/
async getRoute53HostedZoneId() {
if (this.serverless.service.custom.appSyncCloudFront.hostedZoneId) {
this.serverless.cli.log(
`Selected specific hostedZoneId ${this.serverless.service.custom.appSyncCloudFront.hostedZoneId}`
);
return this.serverless.service.custom.appSyncCloudFront.hostedZoneId;
}
const filterZone = this.hostedZonePrivate !== undefined;
if (filterZone && this.hostedZonePrivate) {
this.serverless.cli.log("Filtering to only private zones.");
} else if (filterZone && !this.hostedZonePrivate) {
this.serverless.cli.log("Filtering to only public zones.");
}
let hostedZoneData;
const givenDomainName = this.getConfig("domainName", "");
const givenDomainNameReverse = givenDomainName.split(".").reverse();
try {
hostedZoneData = await this.route53.listHostedZones({}).promise();
const targetHostedZone = hostedZoneData.HostedZones.filter(
(hostedZone) => {
let hostedZoneName;
if (hostedZone.Name.endsWith(".")) {
hostedZoneName = hostedZone.Name.slice(0, -1);
} else {
hostedZoneName = hostedZone.Name;
}
if (
!filterZone ||
this.hostedZonePrivate === hostedZone.Config.PrivateZone
) {
const hostedZoneNameReverse = hostedZoneName.split(".").reverse();
if (
givenDomainNameReverse.length === 1 ||
givenDomainNameReverse.length >= hostedZoneNameReverse.length
) {
for (let i = 0; i < hostedZoneNameReverse.length; i += 1) {
if (givenDomainNameReverse[i] !== hostedZoneNameReverse[i]) {
return false;
}
}
return true;
}
}
return false;
}
)
.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);
}
} catch (err) {
throw new Error(`Error: Unable to list hosted zones in Route53.\n${err}`);
}
throw new Error(
`Error: Could not find hosted zone "${this.getConfig("domainName")}"`
);
}
async prepareResources(resources) {
const distributionConfig =
resources.Resources.AppSyncApiDistribution.Properties.DistributionConfig;
this.prepareLogging(distributionConfig);
this.prepareDomain(distributionConfig);
this.preparePriceClass(distributionConfig);
this.prepareCookies(distributionConfig);
this.prepareHeaders(distributionConfig);
this.prepareQueryString(distributionConfig);
this.prepareComment(distributionConfig);
await this.prepareCertificate(distributionConfig);
this.prepareWaf(distributionConfig);
this.prepareCompress(distributionConfig);
this.prepareMinimumProtocolVersion(distributionConfig);
}
prepareLogging(distributionConfig) {
const loggingBucket = this.getConfig("logging.bucket");
if (loggingBucket !== null) {
distributionConfig.Logging.Bucket = loggingBucket;
distributionConfig.Logging.Prefix = this.getConfig("logging.prefix", "");
} else {
delete distributionConfig.Logging;
}
}
prepareDomain(distributionConfig) {
const domain = this.getConfig("domainName");
if (domain !== null) {
distributionConfig.Aliases = Array.isArray(domain) ? domain : [domain];
} else {
delete distributionConfig.Aliases;
}
}
preparePriceClass(distributionConfig) {
const priceClass = this.getConfig("priceClass", "PriceClass_All");
distributionConfig.PriceClass = priceClass;
}
// prepareOrigins(distributionConfig) {
// distributionConfig.Origins[0].OriginPath = `/${this.options.stage}`;
// }
prepareCookies(distributionConfig) {
const forwardCookies = this.getConfig("cookies", "all");
distributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.Forward = Array.isArray(
forwardCookies
)
? "whitelist"
: forwardCookies;
if (Array.isArray(forwardCookies)) {
distributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames = forwardCookies;
}
}
prepareHeaders(distributionConfig) {
const forwardHeaders = this.getConfig("headers", "none");
if (Array.isArray(forwardHeaders)) {
distributionConfig.DefaultCacheBehavior.ForwardedValues.Headers = forwardHeaders;
} else {
distributionConfig.DefaultCacheBehavior.ForwardedValues.Headers =
forwardHeaders === "none" ? [] : ["*"];
}
}
prepareQueryString(distributionConfig) {
const forwardQueryString = this.getConfig("querystring", "all");
if (Array.isArray(forwardQueryString)) {
distributionConfig.DefaultCacheBehavior.ForwardedValues.QueryString = true;
distributionConfig.DefaultCacheBehavior.ForwardedValues.QueryStringCacheKeys = forwardQueryString;
} else {
distributionConfig.DefaultCacheBehavior.ForwardedValues.QueryString =
forwardQueryString === "all";
}
}
prepareComment(distributionConfig) {
const name = this.serverless.getProvider("aws").naming.getApiGatewayName();
distributionConfig.Comment = `Serverless Managed ${name}`;
}
async prepareCertificate(distributionConfig) {
const certificate =
this.getConfig("certificate") || (await this.getCertArn());
if (certificate) {
distributionConfig.ViewerCertificate.AcmCertificateArn = certificate;
} else {
delete distributionConfig.ViewerCertificate.AcmCertificateArn;
delete distributionConfig.ViewerCertificate.SslSupportMethod;
distributionConfig.ViewerCertificate.CloudFrontDefaultCertificate = true;
}
}
prepareWaf(distributionConfig) {
const waf = this.getConfig("waf");
if (waf !== null) {
distributionConfig.WebACLId = waf;
} else {
delete distributionConfig.WebACLId;
}
}
prepareCompress(distributionConfig) {
distributionConfig.DefaultCacheBehavior.Compress =
this.getConfig("compress", false) === true;
}
prepareMinimumProtocolVersion(distributionConfig) {
const minimumProtocolVersion = this.getConfig(
"minimumProtocolVersion",
undefined
);
if (minimumProtocolVersion) {
distributionConfig.ViewerCertificate.MinimumProtocolVersion = minimumProtocolVersion;
}
}
getConfig(field, defaultValue = null) {
return _.get(
this.serverless,
`service.custom.appSyncCloudFront.${field}`,
defaultValue
);
}
}
module.exports = ServerlessAppSyncCloudFrontPlugin;