-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild-stack.yml
More file actions
607 lines (570 loc) · 20.9 KB
/
Copy pathbuild-stack.yml
File metadata and controls
607 lines (570 loc) · 20.9 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
AWSTemplateFormatVersion: 2010-09-09
# Edit DomainName and CertificateArn here to move
# the project from subdomains on talusanalytics.com
# to a project-specific domain name.
# the project name is automatically pulled from the
# stack name given when invoking this template.
# command to run build-stack:
# aws --region us-east-1 cloudformation deploy --stack-name [projectname] --template-file build-stack.yml --capabilities CAPABILITY_NAMED_IAM
Parameters:
DomainName:
Type: String
Default: 'ghssidea.org'
# Default: "talusanalytics.com"
CertificateArn:
Type: String
Default: 'arn:aws:acm:us-east-1:560812044035:certificate/32647416-bbb8-4860-9114-9ca1f773b0b8'
# Default: "arn:aws:acm:us-east-1:560812044035:certificate/6e6a8e16-520e-4a15-bf4e-18cbd416be15"
# Default: "arn:aws:acm:us-east-1:560812044035:certificate/de08d472-9d84-437b-b05b-6f3894be7dc5"
# Default: 'arn:aws:acm:us-east-1:560812044035:certificate/d98e831c-999b-4d94-8d09-5b8922f2fcb8'
Conditions:
# This conditional checks if the domain name is project-specific, or
# if it is using talusanalytics.com; if talusanalytics.com is being
# used, all the urls are built as subdomains with the branch name
# hyphenated to the project name (pulled from the stack name):
# dev-project.talusanalytics.com
# review-project.talusanalytics.com
# staging-project.talusanalytics.com
# prod-project.talusanalytics.com
# Once the project has a custom domain, this stack should be updated
# with the correct domain and cert arn above, which will move all
# associated resources to the standard project pattern:
# dev.projectdomain.com
# review.projectdomain.com
# staging.projectdomain.com
# projectdomain.com
# Example update command (after editing domainName and cert above):
# aws cloudformation update-stack \
# --stack-name build-stack-test \
# --template-body file://build-stack.yaml
CustomDomainProvided: !Not [!Equals [!Ref DomainName, 'talusanalytics.com']]
Resources:
# Using lambda to generate random string to use in headers between CF and S3
# this locks down the s3 buckets so that their websites are only accessible
# to cloudfront, so that they S3 website urls don't go around the lambda-at-edge
# password checking on cloudfront requests
# execution role for the lambda custom cloudfront resource
RandomStringExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: allowLambdaLogging
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Action:
- 'logs:*'
Resource: '*'
# lambda function to generate pseudo-random strings
RandomStringLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: >
const response = require("cfn-response");
const randomString = (length) => {
const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
exports.handler = (event, context) => {
const str = randomString(event['ResourceProperties']['Length']);
const responseData = {RandomString: str};
response.send(event, context, response.SUCCESS, responseData);
};
Handler: index.handler
Runtime: nodejs14.x
Role: !GetAtt RandomStringExecutionRole.Arn
MemorySize: 128
Timeout: 20
# the custom resource itself, this is what calls
# the lambda once per create / update and makes
# sure all of the resources below get the same
# pseudo-random string.
ProjectInternalHeaderString:
Type: AWS::CloudFormation::CustomResource
Properties:
Length: 16
ServiceToken: !GetAtt RandomStringLambdaFunction.Arn
# Execution role for the basic auth lambda
AuthLambdaExecutionRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Principal:
Service:
- 'lambda.amazonaws.com'
- 'edgelambda.amazonaws.com'
Action:
- 'sts:AssumeRole'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/CloudWatchLogsFullAccess'
Policies:
- PolicyName: allowLambdaLogging
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Action:
- 'logs:*'
Resource: '*'
BasicAuthLambda:
Type: 'AWS::Lambda::Function'
Properties:
FunctionName: !Join ['-', [!Ref AWS::StackName, 'basic-auth']]
Role: !GetAtt AuthLambdaExecutionRole.Arn
Runtime: nodejs14.x
Handler: 'index.handler'
MemorySize: 128
Timeout: 5
Code:
ZipFile: >
'use strict';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
const host = headers.host[0].value;
const containsTerm = (term) => host.includes(term);
let subdomain;
if (host.includes('dev')) subdomain = 'dev';
if (host.includes('review')) subdomain = 'review';
if (host.includes('staging')) subdomain = 'staging';
if (host.includes('prod')) subdomain = 'prod';
const authObj = {
dev: ['dev', ''],
review: ['review', ''],
staging: ['staging', ''],
prod: ['prod', ''],
};
const checkAuthorized = headers => {
if (typeof headers.authorization == 'undefined')
return false;
const authString = headers.authorization[0].value;
const user = authObj[subdomain];
const checkString = 'Basic ' +
new Buffer(user[0] + ':' +
user[1]).toString('base64');
return authString === checkString;
};
if (!checkAuthorized(headers)) {
const response = {
status: '401',
body: 'Unauthorized',
statusDescription: 'Unauthorized',
headers: {
'www-authenticate': [{
key: 'WWW-Authenticate',
value:'Basic',
}]
},
};
callback(null, response);
};
callback(null, request);
};
BasicAuthLambdaVersion:
Type: 'AWS::Lambda::Version'
Properties:
Description: '1'
FunctionName: !Ref BasicAuthLambda
# ############ Dev site setup ############
# S3DevBucket:
# Type: AWS::S3::Bucket
# Properties:
# BucketName: !Join ["-", ["dev", !Ref AWS::StackName]]
# WebsiteConfiguration:
# ErrorDocument: index.html
# IndexDocument: index.html
# # the bucket hosts the website. This is
# # not the standard way to connect S3 to
# # cloudfront, but allows us to do redirects
# # and pretty urls from S3, instead of needing
# # a separate webserver. The StringEquals
# # condition checks for the Referer header
# # set by cloudfront so that this website
# # can't be accessed except by cloudfront.
# S3DevBucketPolicy:
# Type: AWS::S3::BucketPolicy
# Properties:
# Bucket: !Join ["-", ["dev", !Ref AWS::StackName]]
# PolicyDocument:
# Id: MyPolicy
# Version: 2012-10-17
# Statement:
# - Sid: PublicReadForGetBucketObjects
# Effect: Allow
# Principal: "*"
# Action: s3:GetObject
# Condition:
# StringEquals:
# "aws:Referer": !GetAtt ProjectInternalHeaderString.RandomString
# Resource:
# !Join ["", ["arn:aws:s3:::", "dev-", !Ref AWS::StackName, "/*"]]
# # Fairly standard CF distribution, with the difference
# # that the S3 bucket is added as a CustomOrigin pointed
# # at the S3 website instead of as an S3 origin. The
# # OriginCustomHeaders Referer header tells S3 that this
# # is the correct cloudfront distribution to respond to.
# DevDistribution:
# Type: "AWS::CloudFront::Distribution"
# Properties:
# DistributionConfig:
# Aliases:
# - !If [
# CustomDomainProvided,
# !Join [".", ["dev", !Ref DomainName]],
# !Join ["", ["dev-", !Ref AWS::StackName, ".", !Ref DomainName]],
# ]
# Origins:
# - DomainName:
# !Select [1, !Split ["//", !GetAtt S3DevBucket.WebsiteURL]]
# Id: myCustomOrigin
# CustomOriginConfig:
# HTTPPort: "80"
# HTTPSPort: "443"
# OriginProtocolPolicy: http-only
# OriginCustomHeaders:
# - HeaderName: "Referer"
# HeaderValue: !GetAtt ProjectInternalHeaderString.RandomString
# HttpVersion: http2
# Enabled: "true"
# DefaultRootObject: index.html
# DefaultCacheBehavior:
# AllowedMethods:
# - GET
# - HEAD
# CachedMethods:
# - GET
# - HEAD
# TargetOriginId: myCustomOrigin
# SmoothStreaming: "false"
# ForwardedValues:
# QueryString: "true"
# ViewerProtocolPolicy: redirect-to-https
# LambdaFunctionAssociations:
# - EventType: "viewer-request"
# LambdaFunctionARN: !Ref BasicAuthLambdaVersion
# PriceClass: PriceClass_100
# ViewerCertificate:
# AcmCertificateArn: !Ref CertificateArn
# MinimumProtocolVersion: TLSv1.2_2018
# SslSupportMethod: sni-only
# # The Route53 A record pointing the subdomain to
# # the cloudfront distribution
# Route53DevRecord:
# Type: AWS::Route53::RecordSetGroup
# Properties:
# # HostedZoneName must include a trailing dot, this is so anoying
# # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-hostedzonename
# HostedZoneName: !Join ["", [!Ref DomainName, "."]]
# RecordSets:
# - AliasTarget:
# DNSName: !GetAtt DevDistribution.DomainName
# HostedZoneId: Z2FDTNDATAQYW2
# Name:
# !If [
# CustomDomainProvided,
# !Join [".", ["dev", !Ref DomainName]],
# !Join ["", ["dev-", !Ref AWS::StackName, ".", !Ref DomainName]],
# ]
# Type: A
# ########### Review site setup ############
# # The following blocks follow the same pattern
# # documented in the dev site setup.
# S3ReviewBucket:
# Type: AWS::S3::Bucket
# Properties:
# BucketName: !Join ["-", ["review", !Ref AWS::StackName]]
# WebsiteConfiguration:
# ErrorDocument: index.html
# IndexDocument: index.html
# S3ReviewBucketPolicy:
# Type: AWS::S3::BucketPolicy
# Properties:
# Bucket: !Join ["-", ["review", !Ref AWS::StackName]]
# PolicyDocument:
# Id: MyPolicy
# Version: 2012-10-17
# Statement:
# - Sid: PublicReadForGetBucketObjects
# Effect: Allow
# Principal: "*"
# Action: s3:GetObject
# Condition:
# StringEquals:
# "aws:Referer": !GetAtt ProjectInternalHeaderString.RandomString
# Resource:
# !Join [
# "",
# ["arn:aws:s3:::", "review-", !Ref AWS::StackName, "/*"],
# ]
# ReviewDistribution:
# Type: "AWS::CloudFront::Distribution"
# Properties:
# DistributionConfig:
# Aliases:
# - !If [
# CustomDomainProvided,
# !Join [".", ["review", !Ref DomainName]],
# !Join [
# "",
# ["review-", !Ref AWS::StackName, ".", !Ref DomainName],
# ],
# ]
# Origins:
# - DomainName:
# !Select [1, !Split ["//", !GetAtt S3ReviewBucket.WebsiteURL]]
# Id: myCustomOrigin
# CustomOriginConfig:
# HTTPPort: "80"
# HTTPSPort: "443"
# OriginProtocolPolicy: http-only
# OriginCustomHeaders:
# - HeaderName: "Referer"
# HeaderValue: !GetAtt ProjectInternalHeaderString.RandomString
# HttpVersion: http2
# Enabled: "true"
# DefaultRootObject: index.html
# DefaultCacheBehavior:
# AllowedMethods:
# - GET
# - HEAD
# CachedMethods:
# - GET
# - HEAD
# TargetOriginId: myCustomOrigin
# SmoothStreaming: "false"
# ForwardedValues:
# QueryString: "true"
# ViewerProtocolPolicy: redirect-to-https
# LambdaFunctionAssociations:
# - EventType: "viewer-request"
# LambdaFunctionARN: !Ref BasicAuthLambdaVersion
# PriceClass: PriceClass_100
# ViewerCertificate:
# AcmCertificateArn: !Ref CertificateArn
# MinimumProtocolVersion: TLSv1.2_2018
# SslSupportMethod: sni-only
# Route53ReviewRecord:
# Type: AWS::Route53::RecordSetGroup
# Properties:
# # HostedZoneName must include a trailing dot
# # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-hostedzonename
# HostedZoneName: !Join ["", [!Ref DomainName, "."]]
# RecordSets:
# - AliasTarget:
# DNSName: !GetAtt ReviewDistribution.DomainName
# HostedZoneId: Z2FDTNDATAQYW2
# Name:
# !If [
# CustomDomainProvided,
# !Join [".", ["review", !Ref DomainName]],
# !Join [
# "",
# ["review-", !Ref AWS::StackName, ".", !Ref DomainName],
# ],
# ]
# Type: A
############ Staging site setup ############
S3StagingBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Join ['-', ['staging', !Ref AWS::StackName]]
WebsiteConfiguration:
ErrorDocument: index.html
IndexDocument: index.html
S3StagingBucketPolicy:
Type: AWS::S3::BucketPolicy
DependsOn: S3StagingBucket
Properties:
Bucket: !Join ['-', ['staging', !Ref AWS::StackName]]
PolicyDocument:
Id: MyPolicy
Version: 2012-10-17
Statement:
- Sid: PublicReadForGetBucketObjects
Effect: Allow
Principal: '*'
Action: s3:GetObject
Condition:
StringEquals:
'aws:Referer': !GetAtt ProjectInternalHeaderString.RandomString
Resource:
!Join [
'',
['arn:aws:s3:::', 'staging-', !Ref AWS::StackName, '/*'],
]
StagingDistribution:
Type: 'AWS::CloudFront::Distribution'
Properties:
DistributionConfig:
Aliases:
- !If [
CustomDomainProvided,
!Join ['.', ['staging', !Ref DomainName]],
!Join [
'',
['staging-', !Ref AWS::StackName, '.', !Ref DomainName],
],
]
Origins:
- DomainName:
!Select [1, !Split ['//', !GetAtt S3StagingBucket.WebsiteURL]]
Id: myCustomOrigin
CustomOriginConfig:
HTTPPort: '80'
HTTPSPort: '443'
OriginProtocolPolicy: http-only
OriginCustomHeaders:
- HeaderName: 'Referer'
HeaderValue: !GetAtt ProjectInternalHeaderString.RandomString
HttpVersion: http2
Enabled: 'true'
DefaultRootObject: index.html
DefaultCacheBehavior:
AllowedMethods:
- GET
- HEAD
CachedMethods:
- GET
- HEAD
TargetOriginId: myCustomOrigin
SmoothStreaming: 'false'
ForwardedValues:
QueryString: 'true'
ViewerProtocolPolicy: redirect-to-https
LambdaFunctionAssociations:
- EventType: 'viewer-request'
LambdaFunctionARN: !Ref BasicAuthLambdaVersion
PriceClass: PriceClass_100
ViewerCertificate:
AcmCertificateArn: !Ref CertificateArn
MinimumProtocolVersion: TLSv1.2_2018
SslSupportMethod: sni-only
Route53StagingRecord:
Type: AWS::Route53::RecordSetGroup
Properties:
# HostedZoneName must include a trailing dot
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-hostedzonename
HostedZoneName: !Join ['', [!Ref DomainName, '.']]
RecordSets:
- AliasTarget:
DNSName: !GetAtt StagingDistribution.DomainName
HostedZoneId: Z2FDTNDATAQYW2
Name:
!If [
CustomDomainProvided,
!Join ['.', ['staging', !Ref DomainName]],
!Join [
'',
['staging-', !Ref AWS::StackName, '.', !Ref DomainName],
],
]
Type: A
# ############ Prod site setup ############
# S3ProdBucket:
# Type: AWS::S3::Bucket
# Properties:
# BucketName: !Join ["-", ["prod", !Ref AWS::StackName]]
# WebsiteConfiguration:
# ErrorDocument: index.html
# IndexDocument: index.html
# S3ProdBucketPolicy:
# Type: AWS::S3::BucketPolicy
# Properties:
# Bucket: !Join ["-", ["prod", !Ref AWS::StackName]]
# PolicyDocument:
# Id: MyPolicy
# Version: 2012-10-17
# Statement:
# - Sid: PublicReadForGetBucketObjects
# Effect: Allow
# Principal: "*"
# Action: s3:GetObject
# Condition:
# StringEquals:
# "aws:Referer": !GetAtt ProjectInternalHeaderString.RandomString
# Resource:
# !Join ["", ["arn:aws:s3:::", "prod-", !Ref AWS::StackName, "/*"]]
# ProdDistribution:
# Type: "AWS::CloudFront::Distribution"
# Properties:
# DistributionConfig:
# Aliases:
# - !If [
# CustomDomainProvided,
# !Ref DomainName,
# !Join ["", ["prod-", !Ref AWS::StackName, ".", !Ref DomainName]],
# ]
# Origins:
# - DomainName:
# !Select [1, !Split ["//", !GetAtt S3ProdBucket.WebsiteURL]]
# Id: myCustomOrigin
# CustomOriginConfig:
# HTTPPort: "80"
# HTTPSPort: "443"
# OriginProtocolPolicy: http-only
# OriginCustomHeaders:
# - HeaderName: "Referer"
# HeaderValue: !GetAtt ProjectInternalHeaderString.RandomString
# HttpVersion: http2
# Enabled: "true"
# DefaultRootObject: index.html
# DefaultCacheBehavior:
# AllowedMethods:
# - GET
# - HEAD
# CachedMethods:
# - GET
# - HEAD
# TargetOriginId: myCustomOrigin
# SmoothStreaming: "false"
# ForwardedValues:
# QueryString: "true"
# ViewerProtocolPolicy: redirect-to-https
# LambdaFunctionAssociations:
# - EventType: "viewer-request"
# LambdaFunctionARN: !Ref BasicAuthLambdaVersion
# PriceClass: PriceClass_All
# ViewerCertificate:
# AcmCertificateArn: !Ref CertificateArn
# MinimumProtocolVersion: TLSv1.2_2018
# SslSupportMethod: sni-only
# Route53ProdRecord:
# Type: AWS::Route53::RecordSetGroup
# Properties:
# # HostedZoneName must include a trailing dot
# # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-hostedzonename
# HostedZoneName: !Join ["", [!Ref DomainName, "."]]
# RecordSets:
# - AliasTarget:
# DNSName: !GetAtt ProdDistribution.DomainName
# HostedZoneId: Z2FDTNDATAQYW2
# Name:
# !If [
# CustomDomainProvided,
# !Ref DomainName,
# !Join ["", ["prod-", !Ref AWS::StackName, ".", !Ref DomainName]],
# ]
# Type: A
# Outputs:
# CloudFrontID:
# Value: !Ref DevDistribution
# Description: Dev CloudFront ID
# CloudFrontURL:
# Value: !GetAtt DevDistribution.DomainName
# Description: CloudFront URL for updating DNS record