-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhosting.ts
More file actions
696 lines (627 loc) · 21.4 KB
/
hosting.ts
File metadata and controls
696 lines (627 loc) · 21.4 KB
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
import { Aws, Duration, RemovalPolicy, CfnOutput } from "aws-cdk-lib";
import { Construct } from "constructs";
import {
Bucket,
type IBucket,
BlockPublicAccess,
ObjectOwnership,
BucketEncryption,
} from "aws-cdk-lib/aws-s3";
import {
Role,
PolicyStatement,
Effect,
ServicePrincipal,
AnyPrincipal,
ManagedPolicy,
} from "aws-cdk-lib/aws-iam";
import {
Distribution,
CachePolicy,
SecurityPolicyProtocol,
HttpVersion,
ResponseHeadersPolicy,
HeadersFrameOption,
HeadersReferrerPolicy,
type BehaviorOptions,
AllowedMethods,
ViewerProtocolPolicy,
CacheCookieBehavior,
CacheHeaderBehavior,
CacheQueryStringBehavior,
CfnOriginAccessControl,
CachedMethods,
LambdaEdgeEventType,
AccessLevel,
IOrigin,
experimental,
} from "aws-cdk-lib/aws-cloudfront";
import { S3BucketOrigin } from "aws-cdk-lib/aws-cloudfront-origins";
import {
AaaaRecord,
ARecord,
HostedZone,
type IHostedZone,
RecordTarget,
} from "aws-cdk-lib/aws-route53";
import { CloudFrontTarget } from "aws-cdk-lib/aws-route53-targets";
import { Certificate } from "aws-cdk-lib/aws-certificatemanager";
import { Runtime, Code } from "aws-cdk-lib/aws-lambda";
import { StaticProps } from "../../types";
import { getResourceIdPrefix } from "../utils";
export class HostingConstruct extends Construct {
private resourceIdPrefix: string;
public hostingBucket: IBucket;
private accessLogsBucket: IBucket | undefined;
public distribution: Distribution;
private s3Origin: IOrigin;
public originAccessControl: CfnOriginAccessControl | undefined;
private lambdaEdgeRole: Role;
private cloudFrontRedirectsRewrites: experimental.EdgeFunction;
private cloudFrontHeaders: experimental.EdgeFunction;
constructor(scope: Construct, id: string, props: StaticProps) {
super(scope, id);
// Set the resource prefix
this.resourceIdPrefix = getResourceIdPrefix(
props.application,
props.service,
props.environment,
);
// create the S3 bucket for hosting
this.hostingBucket = this.createHostingBucket(props);
/**
* Lambda@edge
*/
// Create the Lambda@edge role
this.lambdaEdgeRole = this.createLambdaEdgeRole();
// Create the redirects and rewrites function
this.cloudFrontRedirectsRewrites =
this.createCloudFrontRedirectsRewrites(props);
// Create the custom response headers function
if (props.headers) {
this.cloudFrontHeaders = this.createCloudFrontHeaders(props);
}
/**
* Create the CDN
*/
// Create the CloudFront distribution
this.distribution = this.createCloudFrontDistribution(props);
// Grant CloudFront permission to get the objects from the s3 bucket origin
this.hostingBucket.addToResourcePolicy(
new PolicyStatement({
effect: Effect.ALLOW,
actions: ["s3:GetObject"], // 's3:ListBucket' slows down deployment
principals: [new ServicePrincipal("cloudfront.amazonaws.com")],
resources: [`${this.hostingBucket.bucketArn}/*`],
conditions: {
StringEquals: {
"AWS:SourceArn": `arn:aws:cloudfront::${Aws.ACCOUNT_ID}:distribution/${this.distribution.distributionId}`,
},
},
}),
);
// Set the domains with Route53
if (props.domain && props.globalCertificateArn && props.hostedZoneId) {
this.createDnsRecords(props);
}
/**
* Outputs
*/
// Create an output for the distribution's physical ID
new CfnOutput(this, "DistributionId", {
value: this.distribution.distributionId,
description: "The ID of the CloudFront distribution",
exportName: `${this.resourceIdPrefix}-CloudFrontDistributionId`,
});
// Create an output for the distribution's URL
new CfnOutput(this, "DistributionUrl", {
value: `https://${this.distribution.distributionDomainName}`,
description: "The URL of the CloudFront distribution",
exportName: `${this.resourceIdPrefix}-CloudFrontDistributionUrl`,
});
if (props.domain) {
new CfnOutput(this, "Route53Domain", {
value: `https://${props.domain}`,
description: "The custom domain URL",
exportName: `${this.resourceIdPrefix}-Route53Domain`,
});
}
}
/**
* Creates the bucket to store the static deployment asset files of your site.
*
* @private
*/
private createHostingBucket(props: StaticProps): Bucket {
// Hosting bucket access log bucket
const originLogsBucket = props.debug
? new Bucket(this, "OriginLogsBucket", {
bucketName: `${this.resourceIdPrefix}-origin-logs`,
encryption: BucketEncryption.S3_MANAGED,
blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
objectOwnership: ObjectOwnership.OBJECT_WRITER,
enforceSSL: true,
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
})
: undefined;
// primary hosting bucket
const bucket = new Bucket(this, "Bucket", {
bucketName: `${this.resourceIdPrefix}-hosting`,
versioned: true,
serverAccessLogsBucket: originLogsBucket,
enforceSSL: true,
encryption: BucketEncryption.S3_MANAGED,
blockPublicAccess: new BlockPublicAccess({
blockPublicPolicy: true,
blockPublicAcls: true,
ignorePublicAcls: true,
restrictPublicBuckets: true,
}),
removalPolicy: RemovalPolicy.RETAIN,
});
// Create the Origin Access Control
this.originAccessControl = new CfnOriginAccessControl(
this,
"CloudFrontOac",
{
originAccessControlConfig: {
name: `${this.resourceIdPrefix}-OAC`,
description: `Origin Access Control for ${this.resourceIdPrefix}`,
originAccessControlOriginType: "s3",
signingBehavior: "always",
signingProtocol: "sigv4",
},
},
);
this.s3Origin = S3BucketOrigin.withOriginAccessControl(bucket, {
originId: `${this.resourceIdPrefix}-s3origin`,
originAccessLevels: [AccessLevel.READ],
originAccessControlId: this.originAccessControl?.attrId,
});
// Update the bucket policy to allow access from CloudFront via OAC
bucket.addToResourcePolicy(
new PolicyStatement({
effect: Effect.ALLOW,
actions: ["s3:GetObject"],
principals: [new AnyPrincipal()],
resources: [`${bucket.bucketArn}/*`],
conditions: {
StringEquals: {
"AWS:SourceArn": `arn:aws:cloudfront::${Aws.ACCOUNT_ID}:origin-access-control/${this.originAccessControl?.attrId}`,
"aws:SourceAccount": Aws.ACCOUNT_ID,
},
},
}),
);
return bucket;
}
/**
* Create Lambda@edge Role
* @private
*/
private createLambdaEdgeRole(): Role {
// Create the execution role for Lambda@Edge
const lambdaEdgeRole = new Role(this, "LambdaEdgeExecutionRole", {
assumedBy: new ServicePrincipal("lambda.amazonaws.com"),
});
lambdaEdgeRole.assumeRolePolicy?.addStatements(
new PolicyStatement({
effect: Effect.ALLOW,
principals: [new ServicePrincipal("edgelambda.amazonaws.com")],
actions: ["sts:AssumeRole"],
}),
);
lambdaEdgeRole.addManagedPolicy(
ManagedPolicy.fromAwsManagedPolicyName(
"service-role/AWSLambdaBasicExecutionRole",
),
);
// Give the edge lambdas permission to access hosting bucket
lambdaEdgeRole.addToPolicy(
new PolicyStatement({
effect: Effect.ALLOW,
actions: ["s3:GetObject"],
resources: [`${this.hostingBucket.bucketArn}/*`],
}),
);
return lambdaEdgeRole;
}
/**
* Create a Lambda@Edge Function for Redirects and Rewrites
* @param props StaticProps
*
*/
// Helper function to escape special regex characters
private escapeRegex = (string: string) => {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
};
private createCloudFrontRedirectsRewrites(
props: StaticProps,
): experimental.EdgeFunction {
const redirects = props.redirects || [];
const rewrites = props.rewrites || [];
// Generate redirects code
const redirectsCode = redirects
.map((rule) => {
const params: string[] = [];
const source = this.escapeRegex(rule.source)
.replace(/:[^/]+/g, (match) => {
params.push(match.substring(1));
return "([^/]+)";
})
.replace(/\\\*/g, "(.*)");
const destination = rule.destination
.replace(/:[^/]+/g, (match) => {
const paramName = match.substring(1);
const position = params.indexOf(paramName) + 1;
return `$${position}`;
})
.replace(/\*/g, "$1");
return `
if (uri.match(new RegExp('^${source}$'))) {
const response = {
status: '301',
statusDescription: 'Moved Permanently',
headers: {
'location': [{
key: 'Location',
value: 'https://' + host + uri.replace(new RegExp('^${source}$'), '${destination}')
}]
},
};
callback(null, response);
return;
}
`;
})
.join("\n");
// Generate rewrites code
const rewritesCode = rewrites
.map((rule) => {
const params: string[] = [];
const source = this.escapeRegex(rule.source)
.replace(/:[^/]+/g, (match) => {
params.push(match.substring(1));
return "([^/]+)";
})
.replace(/\\\*/g, "(.*)");
const destination = rule.destination
.replace(/:[^/]+/g, (match) => {
const paramName = match.substring(1);
const position = params.indexOf(paramName) + 1;
return `$${position}`;
})
.replace(/\*/g, "$1");
return `
if (uri.match(new RegExp('^${source}$'))) {
request.uri = uri.replace(new RegExp('^${source}$'), '${destination}');
}
`;
})
.join("\n");
const functionCode = `
'use strict';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
var uri = request.uri;
var host = request.headers.host[0].value;
// Handle redirects
${redirectsCode}
// Handle rewrites
${rewritesCode}
// Check whether the URI is missing a file name.
if (request.uri.endsWith('/')) {
request.uri += 'index.html';
}
// Check whether the URI is missing a file extension.
else if (!request.uri.includes('.')) {
request.uri += '/index.html';
}
callback(null, request);
};
`;
const cloudFrontRedirectsRewrites = new experimental.EdgeFunction(
this,
"RedirectRewriteFunction",
{
code: Code.fromInline(functionCode),
runtime: Runtime.NODEJS_18_X,
handler: "index.handler",
role: this.lambdaEdgeRole,
},
);
return cloudFrontRedirectsRewrites;
}
/**
* Create a Lambda@Edge Function for Custom Headers
* @param props StaticProps
*
*/
private createCloudFrontHeaders(
props: StaticProps,
): experimental.EdgeFunction {
const headers = props.headers || [];
// Generate the Lambda function code with the headers embedded
const functionCode = `
exports.handler = async (event) => {
const { request, response } = event.Records[0].cf;
const uri = request.uri;
const headersConfig = ${JSON.stringify(headers)};
const convertPathToRegex = (pattern) => {
// First handle the file extension pattern with braces
let regex = pattern.replace(/{([^}]+)}/g, (match, group) => {
return '(' + group.split(',').join('|') + ')';
});
// Replace * with non-greedy match that doesn't include slashes
regex = regex.replace(/\\*/g, '[^/]*');
// Escape special characters in the pattern, preserving forward slashes
regex = regex.split('/').map(part =>
part.replace(/[.+^$()|[\\\]]/g, '\\$&')
).join('/');
return regex;
};
headersConfig.forEach((header) => {
const regex = new RegExp(convertPathToRegex(header.path));
if (regex.test(uri)) {
const headerName = header.name.toLowerCase();
const headerValue = header.value;
response.headers[headerName] = [{ key: header.name, value: headerValue }];
}
});
return response;
};
`;
// Create and return the Edge Function
const cloudFrontHeadersFunction = new experimental.EdgeFunction(
this,
"HeadersFunction",
{
code: Code.fromInline(functionCode),
runtime: Runtime.NODEJS_18_X,
handler: "index.handler",
role: this.lambdaEdgeRole,
},
);
// Create a version for Lambda@Edge
return cloudFrontHeadersFunction;
}
/**
* Create the primary cloudfront distribution
* @param props
* @private
*/
private createCloudFrontDistribution(props: StaticProps): Distribution {
// access logs bucket
this.accessLogsBucket = props.debug
? new Bucket(this, "AccessLogsBucket", {
bucketName: `${this.resourceIdPrefix}-access-logs`,
encryption: BucketEncryption.S3_MANAGED,
blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
objectOwnership: ObjectOwnership.OBJECT_WRITER,
enforceSSL: true,
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
})
: undefined;
/**
* Response Headers Policy
* This policy is used to set default security headers for the CloudFront distribution.
*/
const responseHeadersPolicy = new ResponseHeadersPolicy(
this,
"ResponseHeadersPolicy",
{
responseHeadersPolicyName: `${this.resourceIdPrefix}-ResponseHeadersPolicy`,
comment: "ResponseHeadersPolicy" + Aws.STACK_NAME + "-" + Aws.REGION,
securityHeadersBehavior: {
contentSecurityPolicy: {
contentSecurityPolicy:
"default-src 'self'; style-src https: 'unsafe-inline'; script-src https: 'unsafe-inline' 'wasm-unsafe-eval'; font-src https: 'unsafe-inline'; connect-src https: wss: 'unsafe-inline'; img-src https: data:; base-uri 'self'; form-action 'self';",
override: true,
},
strictTransportSecurity: {
accessControlMaxAge: Duration.days(365),
includeSubdomains: true,
preload: true,
override: true,
},
contentTypeOptions: {
override: true,
},
referrerPolicy: {
referrerPolicy:
HeadersReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN,
override: true,
},
frameOptions: {
frameOption: HeadersFrameOption.DENY,
override: true,
},
xssProtection: {
protection: true,
modeBlock: true,
override: true,
},
},
corsBehavior: {
accessControlAllowCredentials: false,
accessControlAllowHeaders: ["*"],
accessControlAllowMethods: ["GET", "HEAD", "OPTIONS"],
accessControlAllowOrigins: ["*"],
accessControlExposeHeaders: [],
accessControlMaxAge: Duration.seconds(600),
originOverride: true,
},
customHeadersBehavior: {
customHeaders: [],
},
removeHeaders: ["server", "age", "date"],
},
);
/**
* The default cache policy for HTML documents with short TTL.
* This policy is used for the default behavior of the CloudFront distribution.
*/
const defaultCachePolicy = new CachePolicy(this, "DefaultCachePolicy", {
cachePolicyName: `${this.resourceIdPrefix}-DefaultCachePolicy`,
comment: "Cache policy for HTML documents with short TTL",
defaultTtl: Duration.minutes(1),
minTtl: Duration.seconds(0),
maxTtl: Duration.minutes(1),
headerBehavior: props.allowHeaders?.length
? CacheHeaderBehavior.allowList(...props.allowHeaders)
: CacheHeaderBehavior.none(),
cookieBehavior: props.allowCookies?.length
? CacheCookieBehavior.allowList(...props.allowCookies)
: CacheCookieBehavior.none(),
queryStringBehavior: props.allowQueryParams?.length
? CacheQueryStringBehavior.allowList(...props.allowQueryParams)
: props.denyQueryParams?.length
? CacheQueryStringBehavior.denyList(...props.denyQueryParams)
: CacheQueryStringBehavior.none(),
enableAcceptEncodingGzip: true,
enableAcceptEncodingBrotli: true,
});
/**
* The default behavior for the CloudFront distribution.
* This behavior is used for the default behavior of the CloudFront distribution.
*/
const defaultBehavior: BehaviorOptions = {
origin: this.s3Origin,
compress: true,
responseHeadersPolicy: responseHeadersPolicy,
cachePolicy: defaultCachePolicy,
allowedMethods: AllowedMethods.ALLOW_GET_HEAD,
cachedMethods: CachedMethods.CACHE_GET_HEAD,
viewerProtocolPolicy: ViewerProtocolPolicy.HTTPS_ONLY,
edgeLambdas: [
...(this.cloudFrontRedirectsRewrites
? [
{
eventType: LambdaEdgeEventType.VIEWER_REQUEST,
functionVersion:
this.cloudFrontRedirectsRewrites.currentVersion,
},
]
: []),
...(this.cloudFrontHeaders
? [
{
eventType: LambdaEdgeEventType.VIEWER_RESPONSE,
functionVersion: this.cloudFrontHeaders.currentVersion,
},
]
: []),
],
};
// Additional behaviors
const additionalBehaviors: { [pathPattern: string]: BehaviorOptions } = {};
/**
* The behavior for static assets.
* It is configured to cache static assets for a longer period of time.
* Using a managed cache policy CACHING_OPTIMIZED.
* Using a managed response headers policy: CORS_ALLOW_ALL_ORIGINS_WITH_PREFLIGHT
*/
const staticAssetsBehaviour: BehaviorOptions = {
origin: this.s3Origin,
compress: true,
responseHeadersPolicy:
ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS_WITH_PREFLIGHT,
cachePolicy: CachePolicy.CACHING_OPTIMIZED,
allowedMethods: AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
cachedMethods: CachedMethods.CACHE_GET_HEAD_OPTIONS,
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
};
// Add static asset behaviors
const staticAssetPatterns = [
"*.png",
"*.jpg",
"*.jpeg",
"*.gif",
"*.ico",
"*.css",
"*.js",
];
for (const pattern of staticAssetPatterns) {
additionalBehaviors[pattern] = staticAssetsBehaviour;
}
/**
* Create CloudFront Distribution
*
*/
const distributionProps = {
comment: "Stack name: " + Aws.STACK_NAME,
enableLogging: props.debug ? true : false,
logBucket: props.debug ? this.accessLogsBucket : undefined,
defaultBehavior: defaultBehavior,
additionalBehaviors: additionalBehaviors,
responseHeadersPolicy: responseHeadersPolicy,
httpVersion: HttpVersion.HTTP3,
minimumProtocolVersion: SecurityPolicyProtocol.TLS_V1_2_2021,
defaultRootObject: "index.html",
errorResponses: [
{
httpStatus: 404,
responseHttpStatus: 404,
ttl: Duration.seconds(0),
responsePagePath: props.errorPagePath || "/index.html",
},
],
...(props.domain && props.globalCertificateArn
? {
domainNames: [props.domain],
certificate: Certificate.fromCertificateArn(
this,
`${this.resourceIdPrefix}-global-certificate`,
props.globalCertificateArn,
),
}
: {}),
};
// Creating CloudFront distribution
return new Distribution(this, "CDN", distributionProps);
}
/**
* Resolves the hosted zone at which the DNS records shall be created to access the app on the internet.
*
* @param props
* @private
*/
private findHostedZone(props: StaticProps): IHostedZone | void {
const domainParts = props.domain?.split(".");
if (!domainParts) return;
return HostedZone.fromHostedZoneAttributes(
this,
`${this.resourceIdPrefix}-hosted-zone`,
{
hostedZoneId: props.hostedZoneId as string,
zoneName: domainParts[domainParts.length - 1], // Support subdomains
},
);
}
/**
* Creates the DNS records to access the app on the internet via the custom domain.
*
* @param props
* @private
*/
private createDnsRecords(props: StaticProps): void {
const hostedZone = this.findHostedZone(props);
const dnsTarget = RecordTarget.fromAlias(
new CloudFrontTarget(this.distribution),
);
// Create a record for IPv4
new ARecord(this, `${this.resourceIdPrefix}-ipv4-record`, {
recordName: props.domain,
zone: hostedZone as IHostedZone,
target: dnsTarget,
});
// Create a record for IPv6
new AaaaRecord(this, `${this.resourceIdPrefix}-ipv6-record`, {
recordName: props.domain,
zone: hostedZone as IHostedZone,
target: dnsTarget,
});
}
}