-
Notifications
You must be signed in to change notification settings - Fork 4k
/
web-distribution.ts
1172 lines (1032 loc) · 38.3 KB
/
web-distribution.ts
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
import * as certificatemanager from '@aws-cdk/aws-certificatemanager';
import * as iam from '@aws-cdk/aws-iam';
import * as lambda from '@aws-cdk/aws-lambda';
import * as s3 from '@aws-cdk/aws-s3';
import * as cdk from '@aws-cdk/core';
import { Construct } from 'constructs';
import { CfnDistribution } from './cloudfront.generated';
import { HttpVersion, IDistribution, LambdaEdgeEventType, OriginProtocolPolicy, PriceClass, ViewerProtocolPolicy, SSLMethod, SecurityPolicyProtocol } from './distribution';
import { FunctionAssociation } from './function';
import { GeoRestriction } from './geo-restriction';
import { IKeyGroup } from './key-group';
import { IOriginAccessIdentity } from './origin-access-identity';
/**
* HTTP status code to failover to second origin
*/
export enum FailoverStatusCode {
/**
* Forbidden (403)
*/
FORBIDDEN = 403,
/**
* Not found (404)
*/
NOT_FOUND = 404,
/**
* Internal Server Error (500)
*/
INTERNAL_SERVER_ERROR = 500,
/**
* Bad Gateway (502)
*/
BAD_GATEWAY = 502,
/**
* Service Unavailable (503)
*/
SERVICE_UNAVAILABLE = 503,
/**
* Gateway Timeout (504)
*/
GATEWAY_TIMEOUT = 504,
}
/**
* Configuration for custom domain names
*
* CloudFront can use a custom domain that you provide instead of a
* "cloudfront.net" domain. To use this feature you must provide the list of
* additional domains, and the ACM Certificate that CloudFront should use for
* these additional domains.
* @deprecated see {@link CloudFrontWebDistributionProps#viewerCertificate} with {@link ViewerCertificate#acmCertificate}
*/
export interface AliasConfiguration {
/**
* ARN of an AWS Certificate Manager (ACM) certificate.
*/
readonly acmCertRef: string;
/**
* Domain names on the certificate
*
* Both main domain name and Subject Alternative Names.
*/
readonly names: string[];
/**
* How CloudFront should serve HTTPS requests.
*
* See the notes on SSLMethod if you wish to use other SSL termination types.
*
* @default SSLMethod.SNI
* @see https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ViewerCertificate.html
*/
readonly sslMethod?: SSLMethod;
/**
* The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections.
*
* CloudFront serves your objects only to browsers or devices that support at
* least the SSL version that you specify.
*
* @default - SSLv3 if sslMethod VIP, TLSv1 if sslMethod SNI
*/
readonly securityPolicy?: SecurityPolicyProtocol;
}
/**
* Logging configuration for incoming requests
*/
export interface LoggingConfiguration {
/**
* Bucket to log requests to
*
* @default - A logging bucket is automatically created.
*/
readonly bucket?: s3.IBucket,
/**
* Whether to include the cookies in the logs
*
* @default false
*/
readonly includeCookies?: boolean,
/**
* Where in the bucket to store logs
*
* @default - No prefix.
*/
readonly prefix?: string
}
// Subset of SourceConfiguration for rendering properties internally
interface SourceConfigurationRender {
readonly connectionAttempts?: number;
readonly connectionTimeout?: cdk.Duration;
readonly s3OriginSource?: S3OriginConfig;
readonly customOriginSource?: CustomOriginConfig;
readonly originPath?: string;
readonly originHeaders?: { [key: string]: string };
readonly originShieldRegion?: string
}
/**
* A source configuration is a wrapper for CloudFront origins and behaviors.
* An origin is what CloudFront will "be in front of" - that is, CloudFront will pull it's assets from an origin.
*
* If you're using s3 as a source - pass the `s3Origin` property, otherwise, pass the `customOriginSource` property.
*
* One or the other must be passed, and it is invalid to pass both in the same SourceConfiguration.
*/
export interface SourceConfiguration {
/**
* The number of times that CloudFront attempts to connect to the origin.
* You can specify 1, 2, or 3 as the number of attempts.
*
* @default 3
*/
readonly connectionAttempts?: number;
/**
* The number of seconds that CloudFront waits when trying to establish a connection to the origin.
* You can specify a number of seconds between 1 and 10 (inclusive).
*
* @default cdk.Duration.seconds(10)
*/
readonly connectionTimeout?: cdk.Duration;
/**
* An s3 origin source - if you're using s3 for your assets
*/
readonly s3OriginSource?: S3OriginConfig;
/**
* A custom origin source - for all non-s3 sources.
*/
readonly customOriginSource?: CustomOriginConfig;
/**
* An s3 origin source for failover in case the s3OriginSource returns invalid status code
*
* @default - no failover configuration
*/
readonly failoverS3OriginSource?: S3OriginConfig;
/**
* A custom origin source for failover in case the s3OriginSource returns invalid status code
*
* @default - no failover configuration
*/
readonly failoverCustomOriginSource?: CustomOriginConfig;
/**
* HTTP status code to failover to second origin
*
* @default [500, 502, 503, 504]
*/
readonly failoverCriteriaStatusCodes?: FailoverStatusCode[];
/**
* The behaviors associated with this source.
* At least one (default) behavior must be included.
*/
readonly behaviors: Behavior[];
/**
* The relative path to the origin root to use for sources.
*
* @default /
* @deprecated Use originPath on s3OriginSource or customOriginSource
*/
readonly originPath?: string;
/**
* Any additional headers to pass to the origin
*
* @default - No additional headers are passed.
* @deprecated Use originHeaders on s3OriginSource or customOriginSource
*/
readonly originHeaders?: { [key: string]: string };
/**
* When you enable Origin Shield in the AWS Region that has the lowest latency to your origin, you can get better network performance
*
* @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/origin-shield.html
*
* @default - origin shield not enabled
*/
readonly originShieldRegion?: string;
}
/**
* A custom origin configuration
*/
export interface CustomOriginConfig {
/**
* The domain name of the custom origin. Should not include the path - that should be in the parent SourceConfiguration
*/
readonly domainName: string,
/**
* The origin HTTP port
*
* @default 80
*/
readonly httpPort?: number,
/**
* The origin HTTPS port
*
* @default 443
*/
readonly httpsPort?: number,
/**
* The keep alive timeout when making calls in seconds.
*
* @default Duration.seconds(5)
*/
readonly originKeepaliveTimeout?: cdk.Duration,
/**
* The protocol (http or https) policy to use when interacting with the origin.
*
* @default OriginProtocolPolicy.HttpsOnly
*/
readonly originProtocolPolicy?: OriginProtocolPolicy,
/**
* The read timeout when calling the origin in seconds
*
* @default Duration.seconds(30)
*/
readonly originReadTimeout?: cdk.Duration
/**
* The SSL versions to use when interacting with the origin.
*
* @default OriginSslPolicy.TLS_V1_2
*/
readonly allowedOriginSSLVersions?: OriginSslPolicy[];
/**
* The relative path to the origin root to use for sources.
*
* @default /
*/
readonly originPath?: string;
/**
* Any additional headers to pass to the origin
*
* @default - No additional headers are passed.
*/
readonly originHeaders?: { [key: string]: string };
/**
* When you enable Origin Shield in the AWS Region that has the lowest latency to your origin, you can get better network performance
*
* @default - origin shield not enabled
*/
readonly originShieldRegion?: string;
}
export enum OriginSslPolicy {
SSL_V3 = 'SSLv3',
TLS_V1 = 'TLSv1',
TLS_V1_1 = 'TLSv1.1',
TLS_V1_2 = 'TLSv1.2',
}
/**
* S3 origin configuration for CloudFront
*/
export interface S3OriginConfig {
/**
* The source bucket to serve content from
*/
readonly s3BucketSource: s3.IBucket;
/**
* The optional Origin Access Identity of the origin identity cloudfront will use when calling your s3 bucket.
*
* @default No Origin Access Identity which requires the S3 bucket to be public accessible
*/
readonly originAccessIdentity?: IOriginAccessIdentity;
/**
* The relative path to the origin root to use for sources.
*
* @default /
*/
readonly originPath?: string;
/**
* Any additional headers to pass to the origin
*
* @default - No additional headers are passed.
*/
readonly originHeaders?: { [key: string]: string };
/**
* When you enable Origin Shield in the AWS Region that has the lowest latency to your origin, you can get better network performance
*
* @default - origin shield not enabled
*/
readonly originShieldRegion?: string;
}
/**
* An enum for the supported methods to a CloudFront distribution.
*/
export enum CloudFrontAllowedMethods {
GET_HEAD = 'GH',
GET_HEAD_OPTIONS = 'GHO',
ALL = 'ALL'
}
/**
* Enums for the methods CloudFront can cache.
*/
export enum CloudFrontAllowedCachedMethods {
GET_HEAD = 'GH',
GET_HEAD_OPTIONS = 'GHO',
}
/**
* A CloudFront behavior wrapper.
*/
export interface Behavior {
/**
* If CloudFront should automatically compress some content types.
*
* @default true
*/
readonly compress?: boolean;
/**
* If this behavior is the default behavior for the distribution.
*
* You must specify exactly one default distribution per CloudFront distribution.
* The default behavior is allowed to omit the "path" property.
*/
readonly isDefaultBehavior?: boolean;
/**
* Trusted signers is how CloudFront allows you to serve private content.
* The signers are the account IDs that are allowed to sign cookies/presigned URLs for this distribution.
*
* If you pass a non empty value, all requests for this behavior must be signed (no public access will be allowed)
* @deprecated - We recommend using trustedKeyGroups instead of trustedSigners.
*/
readonly trustedSigners?: string[];
/**
* A list of Key Groups that CloudFront can use to validate signed URLs or signed cookies.
*
* @default - no KeyGroups are associated with cache behavior
* @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html
*/
readonly trustedKeyGroups?: IKeyGroup[];
/**
*
* The default amount of time CloudFront will cache an object.
*
* This value applies only when your custom origin does not add HTTP headers,
* such as Cache-Control max-age, Cache-Control s-maxage, and Expires to objects.
* @default 86400 (1 day)
*
*/
readonly defaultTtl?: cdk.Duration;
/**
* The method this CloudFront distribution responds do.
*
* @default GET_HEAD
*/
readonly allowedMethods?: CloudFrontAllowedMethods;
/**
* The path this behavior responds to.
* Required for all non-default behaviors. (The default behavior implicitly has "*" as the path pattern. )
*
*/
readonly pathPattern?: string;
/**
* Which methods are cached by CloudFront by default.
*
* @default GET_HEAD
*/
readonly cachedMethods?: CloudFrontAllowedCachedMethods;
/**
* The values CloudFront will forward to the origin when making a request.
*
* @default none (no cookies - no headers)
*
*/
readonly forwardedValues?: CfnDistribution.ForwardedValuesProperty;
/**
* The minimum amount of time that you want objects to stay in the cache
* before CloudFront queries your origin.
*/
readonly minTtl?: cdk.Duration;
/**
* The max amount of time you want objects to stay in the cache
* before CloudFront queries your origin.
*
* @default Duration.seconds(31536000) (one year)
*/
readonly maxTtl?: cdk.Duration;
/**
* Declares associated lambda@edge functions for this distribution behaviour.
*
* @default No lambda function associated
*/
readonly lambdaFunctionAssociations?: LambdaFunctionAssociation[];
/**
* The CloudFront functions to invoke before serving the contents.
*
* @default - no functions will be invoked
*/
readonly functionAssociations?: FunctionAssociation[];
/**
* The viewer policy for this behavior.
*
* @default - the distribution wide viewer protocol policy will be used
*/
readonly viewerProtocolPolicy?: ViewerProtocolPolicy;
}
export interface LambdaFunctionAssociation {
/**
* The lambda event type defines at which event the lambda
* is called during the request lifecycle
*/
readonly eventType: LambdaEdgeEventType;
/**
* A version of the lambda to associate
*/
readonly lambdaFunction: lambda.IVersion;
/**
* Allows a Lambda function to have read access to the body content.
* Only valid for "request" event types (`ORIGIN_REQUEST` or `VIEWER_REQUEST`).
* See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-include-body-access.html
*
* @default false
*/
readonly includeBody?: boolean;
}
export interface ViewerCertificateOptions {
/**
* How CloudFront should serve HTTPS requests.
*
* See the notes on SSLMethod if you wish to use other SSL termination types.
*
* @default SSLMethod.SNI
* @see https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ViewerCertificate.html
*/
readonly sslMethod?: SSLMethod;
/**
* The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections.
*
* CloudFront serves your objects only to browsers or devices that support at
* least the SSL version that you specify.
*
* @default - SSLv3 if sslMethod VIP, TLSv1 if sslMethod SNI
*/
readonly securityPolicy?: SecurityPolicyProtocol;
/**
* Domain names on the certificate (both main domain name and Subject Alternative names)
*/
readonly aliases?: string[];
}
/**
* Viewer certificate configuration class
*/
export class ViewerCertificate {
/**
* Generate an AWS Certificate Manager (ACM) viewer certificate configuration
*
* @param certificate AWS Certificate Manager (ACM) certificate.
* Your certificate must be located in the us-east-1 (US East (N. Virginia)) region to be accessed by CloudFront
* @param options certificate configuration options
*/
public static fromAcmCertificate(certificate: certificatemanager.ICertificate, options: ViewerCertificateOptions = {}) {
const {
sslMethod: sslSupportMethod = SSLMethod.SNI,
securityPolicy: minimumProtocolVersion,
aliases,
} = options;
return new ViewerCertificate({
acmCertificateArn: certificate.certificateArn, sslSupportMethod, minimumProtocolVersion,
}, aliases);
}
/**
* Generate an IAM viewer certificate configuration
*
* @param iamCertificateId Identifier of the IAM certificate
* @param options certificate configuration options
*/
public static fromIamCertificate(iamCertificateId: string, options: ViewerCertificateOptions = {}) {
const {
sslMethod: sslSupportMethod = SSLMethod.SNI,
securityPolicy: minimumProtocolVersion,
aliases,
} = options;
return new ViewerCertificate({
iamCertificateId, sslSupportMethod, minimumProtocolVersion,
}, aliases);
}
/**
* Generate a viewer certifcate configuration using
* the CloudFront default certificate (e.g. d111111abcdef8.cloudfront.net)
* and a {@link SecurityPolicyProtocol.TLS_V1} security policy.
*
* @param aliases Alternative CNAME aliases
* You also must create a CNAME record with your DNS service to route queries
*/
public static fromCloudFrontDefaultCertificate(...aliases: string[]) {
return new ViewerCertificate({ cloudFrontDefaultCertificate: true }, aliases);
}
private constructor(
public readonly props: CfnDistribution.ViewerCertificateProperty,
public readonly aliases: string[] = []) { }
}
export interface CloudFrontWebDistributionProps {
/**
* AliasConfiguration is used to configured CloudFront to respond to requests on custom domain names.
*
* @default - None.
* @deprecated see {@link CloudFrontWebDistributionProps#viewerCertificate} with {@link ViewerCertificate#acmCertificate}
*/
readonly aliasConfiguration?: AliasConfiguration;
/**
* A comment for this distribution in the CloudFront console.
*
* @default - No comment is added to distribution.
*/
readonly comment?: string;
/**
* Enable or disable the distribution.
*
* @default true
*/
readonly enabled?: boolean;
/**
* The default object to serve.
*
* @default - "index.html" is served.
*/
readonly defaultRootObject?: string;
/**
* If your distribution should have IPv6 enabled.
*
* @default true
*/
readonly enableIpV6?: boolean;
/**
* The max supported HTTP Versions.
*
* @default HttpVersion.HTTP2
*/
readonly httpVersion?: HttpVersion;
/**
* The price class for the distribution (this impacts how many locations CloudFront uses for your distribution, and billing)
*
* @default PriceClass.PRICE_CLASS_100 the cheapest option for CloudFront is picked by default.
*/
readonly priceClass?: PriceClass;
/**
* The default viewer policy for incoming clients.
*
* @default RedirectToHTTPs
*/
readonly viewerProtocolPolicy?: ViewerProtocolPolicy;
/**
* The origin configurations for this distribution. Behaviors are a part of the origin.
*/
readonly originConfigs: SourceConfiguration[];
/**
* Optional - if we should enable logging.
* You can pass an empty object ({}) to have us auto create a bucket for logging.
* Omission of this property indicates no logging is to be enabled.
*
* @default - no logging is enabled by default.
*/
readonly loggingConfig?: LoggingConfiguration;
/**
* How CloudFront should handle requests that are not successful (eg PageNotFound)
*
* By default, CloudFront does not replace HTTP status codes in the 4xx and 5xx range
* with custom error messages. CloudFront does not cache HTTP status codes.
*
* @default - No custom error configuration.
*/
readonly errorConfigurations?: CfnDistribution.CustomErrorResponseProperty[];
/**
* Unique identifier that specifies the AWS WAF web ACL to associate with this CloudFront distribution.
*
* To specify a web ACL created using the latest version of AWS WAF, use the ACL ARN, for example
* `arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a`.
*
* To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example `473e64fd-f30b-4765-81a0-62ad96dd167a`.
*
* @see https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html
* @see https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html#API_CreateDistribution_RequestParameters.
*
* @default - No AWS Web Application Firewall web access control list (web ACL).
*/
readonly webACLId?: string;
/**
* Specifies whether you want viewers to use HTTP or HTTPS to request your objects,
* whether you're using an alternate domain name with HTTPS, and if so,
* if you're using AWS Certificate Manager (ACM) or a third-party certificate authority.
*
* @default ViewerCertificate.fromCloudFrontDefaultCertificate()
*
* @see https://aws.amazon.com/premiumsupport/knowledge-center/custom-ssl-certificate-cloudfront/
*/
readonly viewerCertificate?: ViewerCertificate;
/**
* Controls the countries in which your content is distributed.
*
* @default No geo restriction
*/
readonly geoRestriction?: GeoRestriction;
}
/**
* Internal only - just adds the originId string to the Behavior
*/
interface BehaviorWithOrigin extends Behavior {
readonly targetOriginId: string;
}
/**
* Attributes used to import a Distribution.
*/
export interface CloudFrontWebDistributionAttributes {
/**
* The generated domain name of the Distribution, such as d111111abcdef8.cloudfront.net.
*
* @attribute
*/
readonly domainName: string;
/**
* The distribution ID for this distribution.
*
* @attribute
*/
readonly distributionId: string;
}
/**
* Amazon CloudFront is a global content delivery network (CDN) service that securely delivers data, videos,
* applications, and APIs to your viewers with low latency and high transfer speeds.
* CloudFront fronts user provided content and caches it at edge locations across the world.
*
* Here's how you can use this construct:
*
* ```ts
* const sourceBucket = new s3.Bucket(this, 'Bucket');
*
* const distribution = new cloudfront.CloudFrontWebDistribution(this, 'MyDistribution', {
* originConfigs: [
* {
* s3OriginSource: {
* s3BucketSource: sourceBucket,
* },
* behaviors : [ {isDefaultBehavior: true}],
* },
* ],
* });
* ```
*
* This will create a CloudFront distribution that uses your S3Bucket as it's origin.
*
* You can customize the distribution using additional properties from the CloudFrontWebDistributionProps interface.
*
* @resource AWS::CloudFront::Distribution
*/
export class CloudFrontWebDistribution extends cdk.Resource implements IDistribution {
/**
* Creates a construct that represents an external (imported) distribution.
*/
public static fromDistributionAttributes(scope: Construct, id: string, attrs: CloudFrontWebDistributionAttributes): IDistribution {
return new class extends cdk.Resource implements IDistribution {
public readonly domainName: string;
public readonly distributionDomainName: string;
public readonly distributionId: string;
constructor() {
super(scope, id);
this.domainName = attrs.domainName;
this.distributionDomainName = attrs.domainName;
this.distributionId = attrs.distributionId;
}
}();
}
/**
* The logging bucket for this CloudFront distribution.
* If logging is not enabled for this distribution - this property will be undefined.
*/
public readonly loggingBucket?: s3.IBucket;
/**
* The domain name created by CloudFront for this distribution.
* If you are using aliases for your distribution, this is the domainName your DNS records should point to.
* (In Route53, you could create an ALIAS record to this value, for example.)
*
* @deprecated - Use `distributionDomainName` instead.
*/
public readonly domainName: string;
/**
* The domain name created by CloudFront for this distribution.
* If you are using aliases for your distribution, this is the domainName your DNS records should point to.
* (In Route53, you could create an ALIAS record to this value, for example.)
*/
public readonly distributionDomainName: string;
/**
* The distribution ID for this distribution.
*/
public readonly distributionId: string;
/**
* Maps our methods to the string arrays they are
*/
private readonly METHOD_LOOKUP_MAP = {
GH: ['GET', 'HEAD'],
GHO: ['GET', 'HEAD', 'OPTIONS'],
ALL: ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT'],
};
/**
* Maps for which SecurityPolicyProtocol are available to which SSLMethods
*/
private readonly VALID_SSL_PROTOCOLS: { [method in SSLMethod]: string[] } = {
[SSLMethod.SNI]: [
SecurityPolicyProtocol.TLS_V1, SecurityPolicyProtocol.TLS_V1_1_2016,
SecurityPolicyProtocol.TLS_V1_2016, SecurityPolicyProtocol.TLS_V1_2_2018,
SecurityPolicyProtocol.TLS_V1_2_2019, SecurityPolicyProtocol.TLS_V1_2_2021,
],
[SSLMethod.VIP]: [SecurityPolicyProtocol.SSL_V3, SecurityPolicyProtocol.TLS_V1],
};
constructor(scope: Construct, id: string, props: CloudFrontWebDistributionProps) {
super(scope, id);
// Comments have an undocumented limit of 128 characters
const trimmedComment =
props.comment && props.comment.length > 128
? `${props.comment.slice(0, 128 - 3)}...`
: props.comment;
const behaviors: BehaviorWithOrigin[] = [];
const origins: CfnDistribution.OriginProperty[] = [];
const originGroups: CfnDistribution.OriginGroupProperty[] = [];
let originIndex = 1;
for (const originConfig of props.originConfigs) {
let originId = `origin${originIndex}`;
const originProperty = this.toOriginProperty(originConfig, originId);
if (originConfig.failoverCustomOriginSource || originConfig.failoverS3OriginSource) {
const originSecondaryId = `originSecondary${originIndex}`;
const originSecondaryProperty = this.toOriginProperty(
{
s3OriginSource: originConfig.failoverS3OriginSource,
customOriginSource: originConfig.failoverCustomOriginSource,
originPath: originConfig.originPath,
originHeaders: originConfig.originHeaders,
originShieldRegion: originConfig.originShieldRegion,
},
originSecondaryId,
);
const originGroupsId = `OriginGroup${originIndex}`;
const failoverCodes = originConfig.failoverCriteriaStatusCodes ?? [500, 502, 503, 504];
originGroups.push({
id: originGroupsId,
members: {
items: [{ originId }, { originId: originSecondaryId }],
quantity: 2,
},
failoverCriteria: {
statusCodes: {
items: failoverCodes,
quantity: failoverCodes.length,
},
},
});
originId = originGroupsId;
origins.push(originSecondaryProperty);
}
for (const behavior of originConfig.behaviors) {
behaviors.push({ ...behavior, targetOriginId: originId });
}
origins.push(originProperty);
originIndex++;
}
origins.forEach(origin => {
if (!origin.s3OriginConfig && !origin.customOriginConfig) {
throw new Error(`Origin ${origin.domainName} is missing either S3OriginConfig or CustomOriginConfig. At least 1 must be specified.`);
}
});
const originGroupsDistConfig =
originGroups.length > 0
? {
items: originGroups,
quantity: originGroups.length,
}
: undefined;
const defaultBehaviors = behaviors.filter(behavior => behavior.isDefaultBehavior);
if (defaultBehaviors.length !== 1) {
throw new Error('There can only be one default behavior across all sources. [ One default behavior per distribution ].');
}
const otherBehaviors: CfnDistribution.CacheBehaviorProperty[] = [];
for (const behavior of behaviors.filter(b => !b.isDefaultBehavior)) {
if (!behavior.pathPattern) {
throw new Error('pathPattern is required for all non-default behaviors');
}
otherBehaviors.push(this.toBehavior(behavior, props.viewerProtocolPolicy) as CfnDistribution.CacheBehaviorProperty);
}
let distributionConfig: CfnDistribution.DistributionConfigProperty = {
comment: trimmedComment,
enabled: props.enabled ?? true,
defaultRootObject: props.defaultRootObject ?? 'index.html',
httpVersion: props.httpVersion || HttpVersion.HTTP2,
priceClass: props.priceClass || PriceClass.PRICE_CLASS_100,
ipv6Enabled: props.enableIpV6 ?? true,
// eslint-disable-next-line max-len
customErrorResponses: props.errorConfigurations, // TODO: validation : https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-customerrorresponse.html#cfn-cloudfront-distribution-customerrorresponse-errorcachingminttl
webAclId: props.webACLId,
origins,
originGroups: originGroupsDistConfig,
defaultCacheBehavior: this.toBehavior(defaultBehaviors[0], props.viewerProtocolPolicy),
cacheBehaviors: otherBehaviors.length > 0 ? otherBehaviors : undefined,
};
if (props.aliasConfiguration && props.viewerCertificate) {
throw new Error([
'You cannot set both aliasConfiguration and viewerCertificate properties.',
'Please only use viewerCertificate, as aliasConfiguration is deprecated.',
].join(' '));
}
let _viewerCertificate = props.viewerCertificate;
if (props.aliasConfiguration) {
const { acmCertRef, securityPolicy, sslMethod, names: aliases } = props.aliasConfiguration;
_viewerCertificate = ViewerCertificate.fromAcmCertificate(
certificatemanager.Certificate.fromCertificateArn(this, 'AliasConfigurationCert', acmCertRef),
{ securityPolicy, sslMethod, aliases },
);
}
if (_viewerCertificate) {
const { props: viewerCertificate, aliases } = _viewerCertificate;
Object.assign(distributionConfig, { aliases, viewerCertificate });
const { minimumProtocolVersion, sslSupportMethod } = viewerCertificate;
if (minimumProtocolVersion != null && sslSupportMethod != null) {
const validProtocols = this.VALID_SSL_PROTOCOLS[sslSupportMethod as SSLMethod];
if (validProtocols.indexOf(minimumProtocolVersion.toString()) === -1) {
// eslint-disable-next-line max-len
throw new Error(`${minimumProtocolVersion} is not compabtible with sslMethod ${sslSupportMethod}.\n\tValid Protocols are: ${validProtocols.join(', ')}`);
}
}
} else {
distributionConfig = {
...distributionConfig,
viewerCertificate: { cloudFrontDefaultCertificate: true },
};
}
if (props.loggingConfig) {
this.loggingBucket = props.loggingConfig.bucket || new s3.Bucket(this, 'LoggingBucket', {
encryption: s3.BucketEncryption.S3_MANAGED,
});
distributionConfig = {
...distributionConfig,
logging: {
bucket: this.loggingBucket.bucketRegionalDomainName,
includeCookies: props.loggingConfig.includeCookies || false,
prefix: props.loggingConfig.prefix,
},
};
}
if (props.geoRestriction) {
distributionConfig = {
...distributionConfig,
restrictions: {
geoRestriction: {
restrictionType: props.geoRestriction.restrictionType,
locations: props.geoRestriction.locations,
},
},
};
}
const distribution = new CfnDistribution(this, 'CFDistribution', { distributionConfig });
this.node.defaultChild = distribution;
this.domainName = distribution.attrDomainName;
this.distributionDomainName = distribution.attrDomainName;
this.distributionId = distribution.ref;
}
private toBehavior(input: BehaviorWithOrigin, protoPolicy?: ViewerProtocolPolicy) {
let toReturn = {
allowedMethods: this.METHOD_LOOKUP_MAP[input.allowedMethods || CloudFrontAllowedMethods.GET_HEAD],
cachedMethods: this.METHOD_LOOKUP_MAP[input.cachedMethods || CloudFrontAllowedCachedMethods.GET_HEAD],
compress: input.compress !== false,
defaultTtl: input.defaultTtl && input.defaultTtl.toSeconds(),
forwardedValues: input.forwardedValues || { queryString: false, cookies: { forward: 'none' } },
maxTtl: input.maxTtl && input.maxTtl.toSeconds(),
minTtl: input.minTtl && input.minTtl.toSeconds(),
trustedKeyGroups: input.trustedKeyGroups?.map(key => key.keyGroupId),
trustedSigners: input.trustedSigners,
targetOriginId: input.targetOriginId,
viewerProtocolPolicy: input.viewerProtocolPolicy || protoPolicy || ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
};