/
cloudformation.yml
673 lines (626 loc) · 20.5 KB
/
cloudformation.yml
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
AWSTemplateFormatVersion: 2010-09-09
Parameters:
SiteAssetDomain:
Type: String
Description: Fully qualified hostname for site assets
VideoAssetDomain:
Type: String
Description: Fully qualified hostname for video assets
SignerDomain:
Type: String
Description: Fully qualified hostname for signer route
SignerPath:
Type: String
Description: Signer route path including leading /
HostedZoneId:
Type: String
Description: Route53 Hosted Zone Id
VideoPublicKey:
Type: String
Description: Public key used for signing cookies for access to video assets
VideoPrivateKeyUriEncoded:
Type: String
Description: Private key used for signing cookies for access to video assets, URI encoded
SignedCookieDomain:
Type: String
Description: Domain used for the signed cookie that gives access to video assets
FacebookAppId:
Type: String
Description: Facebook client_id for authorizing Facebook app
FacebookAppSecret:
Type: String
Description: Facebook client_secret for authorizing Facebook app
GoogleClientId:
Type: String
Description: Google client_id for authorizing Google sign in
GoogleClientSecret:
Type: String
Description: Google client_secret for authorizing Google sign in
VideoAssetBucket:
Type: String
Description: Bucket containing stored video assets
VideoAssetPath:
Type: String
Description: Optional path for video assets in VideoAssetBucket; start but do not end with /
AccessAdminEmail:
Type: String
Description: The email address to which access request notifications will be sent
AccessSourceEmail:
Type: String
Description: The email address from which access request notifications will be sent
Rules:
domainParamsRequired:
Assertions:
- Assert: !Not
- !Equals
- !Ref SiteAssetDomain
- ""
- Assert: !Not
- !Equals
- !Ref VideoAssetDomain
- ""
- Assert: !Not
- !Equals
- !Ref SignerPath
- ""
- Assert: !Not
- !Equals
- !Ref SignerDomain
- ""
- Assert: !Not
- !Equals
- !Ref HostedZoneId
- ""
facebookParamsRequired:
Assertions:
- Assert: !Not
- !Equals
- !Ref FacebookAppId
- ""
AssertDescription: FacebookAppId is required
- Assert: !Not
- !Equals
- !Ref FacebookAppSecret
- ""
AssertDescription: FacebookAppSecret is required
googleParamsRequired:
Assertions:
- Assert: !Not
- !Equals
- !Ref GoogleClientId
- ""
AssertDescription: GoogleClientId is required
- Assert: !Not
- !Equals
- !Ref GoogleClientSecret
- ""
AssertDescription: GoogleClientSecret is required
videoParamsRequired:
Assertions:
- Assert: !Not
- !Equals
- !Ref VideoAssetBucket
- ""
- Assert: !Not
- !Equals
- !Ref VideoPrivateKeyUriEncoded
- ""
- Assert: !Not
- !Equals
- !Ref VideoPublicKey
- ""
- Assert: !Not
- !Equals
- !Ref SignedCookieDomain
- ""
Resources:
SiteBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Ref AWS::StackName
WebsiteConfiguration:
IndexDocument: index.html
VideoDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Origins:
- DomainName: !Sub ["${VideoAssetBucket}.s3.${Region}.amazonaws.com", { VideoAssetBucket: !Ref VideoAssetBucket, Region: !Ref AWS::Region }]
OriginPath: !Ref VideoAssetPath
Id: video-assets
S3OriginConfig:
OriginAccessIdentity: !Sub ["origin-access-identity/cloudfront/${VideoAssetOriginAccessIdentity}", { VideoAssetOriginAccessIdentity: !Ref VideoAssetOriginAccessIdentity }]
Enabled: true
HttpVersion: http2
Aliases:
- !Ref VideoAssetDomain
DefaultCacheBehavior:
AllowedMethods:
- GET
- HEAD
- OPTIONS
Compress: true
TargetOriginId: video-assets
ViewerProtocolPolicy: redirect-to-https
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 # Managed-CachingOptimized
OriginRequestPolicyId: 88a5eaf4-2fd4-4709-b370-b4c650ea3fcf # Managed-CORS-S3Origin
TrustedKeyGroups:
- !Ref VideoKeyGroup
PriceClass: PriceClass_100
ViewerCertificate:
SslSupportMethod: "sni-only"
MinimumProtocolVersion: "TLSv1"
AcmCertificateArn: !Ref VideoCertificate
IPV6Enabled: true
VideoKeyGroup:
Type: AWS::CloudFront::KeyGroup
Properties:
KeyGroupConfig:
Name: !Ref AWS::StackName
Items:
- !Ref CFVideoPublicKey
CFVideoPublicKey:
Type: AWS::CloudFront::PublicKey
Properties:
PublicKeyConfig:
CallerReference: !Ref AWS::StackName
Name: !Ref AWS::StackName
EncodedKey: !Ref VideoPublicKey
VideoAssetOriginAccessIdentity:
Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: !Sub ["${StackName}-videos-cloudfront", { StackName: !Ref AWS::StackName }]
VideoCertificate:
Type: AWS::CertificateManager::Certificate
Properties:
CertificateTransparencyLoggingPreference: ENABLED
DomainName: !Ref VideoAssetDomain
DomainValidationOptions:
- DomainName: !Ref VideoAssetDomain
HostedZoneId: !Ref HostedZoneId
ValidationMethod: DNS
Certificate:
Type: AWS::CertificateManager::Certificate
Properties:
CertificateTransparencyLoggingPreference: ENABLED
DomainName: !Ref SiteAssetDomain
DomainValidationOptions:
- DomainName: !Ref SiteAssetDomain
HostedZoneId: !Ref HostedZoneId
ValidationMethod: DNS
Distribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Origins:
- DomainName: !Sub ["${BucketName}.s3-website-${Region}.amazonaws.com", { BucketName: !Ref SiteBucket, Region: !Ref AWS::Region }]
Id: site-assets
CustomOriginConfig:
OriginProtocolPolicy: http-only
Enabled: true
HttpVersion: http2
Aliases:
- !Ref SiteAssetDomain
DefaultCacheBehavior:
AllowedMethods:
- GET
- HEAD
Compress: true
TargetOriginId: site-assets
ViewerProtocolPolicy: redirect-to-https
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 # Managed-CachingOptimized
OriginRequestPolicyId: acba4595-bd28-49b8-b9fe-13317c0390fa # Managed-UserAgentRefererHeaders
PriceClass: PriceClass_100
ViewerCertificate:
SslSupportMethod: "sni-only"
MinimumProtocolVersion: "TLSv1"
AcmCertificateArn: !Ref Certificate
IPV6Enabled: true
DNSRecord:
Type: AWS::Route53::RecordSet
Properties:
HostedZoneId: !Ref HostedZoneId
Name: !Ref SiteAssetDomain
Type: A
AliasTarget:
DNSName: !GetAtt Distribution.DomainName
HostedZoneId: Z2FDTNDATAQYW2
VideoDNSRecord:
Type: AWS::Route53::RecordSet
Properties:
HostedZoneId: !Ref HostedZoneId
Name: !Ref VideoAssetDomain
Type: A
AliasTarget:
DNSName: !GetAtt VideoDistribution.DomainName
HostedZoneId: Z2FDTNDATAQYW2
SignerAPI:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: !Sub ["${StackName}-signer", { StackName: !Ref AWS::StackName }]
Description: Proxies the cookie signing Lambda function
ProtocolType: HTTP
CorsConfiguration:
AllowCredentials: True
AllowOrigins:
- !Sub [ "https://${SiteAssetDomain}", { SiteAssetDomain: !Ref SiteAssetDomain }]
AllowMethods:
- GET
AllowHeaders:
- authorization
SignerRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref SignerAPI
AuthorizationType: JWT
AuthorizerId: !Ref SignerAuthorizer
RouteKey: !Sub ["GET ${SignerPath}", { SignerPath: !Ref SignerPath }]
Target: !Sub ["integrations/${Integration}", { Integration: !Ref SignerIntegration }]
SignerStage:
Type: AWS::ApiGatewayV2::Stage
Properties:
ApiId: !Ref SignerAPI
AutoDeploy: True
StageName: $default
SignerIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref SignerAPI
IntegrationMethod: GET
IntegrationType: AWS_PROXY
IntegrationUri: !GetAtt SignerFunction.Arn
PayloadFormatVersion: 2.0
SignerAuthorizer:
Type: AWS::ApiGatewayV2::Authorizer
Properties:
ApiId: !Ref SignerAPI
AuthorizerType: JWT
IdentitySource:
- "$request.header.Authorization"
JwtConfiguration:
Audience:
- !Ref UserPoolClient
Issuer: !GetAtt UserPool.ProviderURL
Name: !Ref AWS::StackName
AuthorizerDomainName:
Type: AWS::ApiGatewayV2::DomainName
Properties:
DomainName: !Ref SignerDomain
DomainNameConfigurations:
- CertificateArn: !Ref SignerCertificate
CertificateName: !Sub ["${StackName}-signer", { StackName: !Ref AWS::StackName }]
SignerApiMapping:
Type: AWS::ApiGatewayV2::ApiMapping
Properties:
ApiId: !Ref SignerAPI
DomainName: !Ref AuthorizerDomainName
Stage: "$default"
SignerCertificate:
Type: AWS::CertificateManager::Certificate
Properties:
CertificateTransparencyLoggingPreference: ENABLED
DomainName: !Ref SignerDomain
DomainValidationOptions:
- DomainName: !Ref SignerDomain
HostedZoneId: !Ref HostedZoneId
ValidationMethod: DNS
SignerDNSRecord:
Type: AWS::Route53::RecordSet
Properties:
HostedZoneId: !Ref HostedZoneId
Name: !Ref SignerDomain
Type: A
AliasTarget:
DNSName: !GetAtt AuthorizerDomainName.RegionalDomainName
HostedZoneId: !GetAtt AuthorizerDomainName.RegionalHostedZoneId
SignerFunctionPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt SignerFunction.Arn
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub ["arn:aws:execute-api:${Region}:${Account}:${API}/*/*/authorize", { Region: !Ref AWS::Region, Account: !Ref AWS::AccountId, API: !Ref SignerAPI }]
SignerFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub ["${StackName}_Signer", { StackName: !Ref AWS::StackName }]
Description: Signs cookies for access to videos
Handler: index.handler
Role: !GetAtt SignerFunctionRole.Arn
Environment:
Variables:
CLOUDFRONT_KEY_PAIR_ID: !Ref CFVideoPublicKey
URI_ENCODED_PRIVATE_KEY: !Ref VideoPrivateKeyUriEncoded
COOKIE_DOMAIN: !Ref SignedCookieDomain
VIDEOS_URL: !Ref VideoAssetDomain
Code:
ZipFile: |
const AWS = require('aws-sdk')
exports.handler = async (event) => {
const privateKey = decodeURI(process.env.URI_ENCODED_PRIVATE_KEY)
const signer = new AWS.CloudFront.Signer(process.env.CLOUDFRONT_KEY_PAIR_ID, privateKey)
const now = new Date()
const cookie = signer.getSignedCookie({
policy: JSON.stringify({
Statement: [{
Resource: `https://${process.env.VIDEOS_URL}/*`,
Condition: {
DateLessThan: {
"AWS:EpochTime": Math.floor(now.setDate(now.getDate() + 30) / 1000)
}
}
}]
})
})
return {
statusCode: 200,
headers: {
"Content-Type": "application/json"
},
cookies: [
`CloudFront-Policy=${cookie['CloudFront-Policy']}; Domain=${process.env.COOKIE_DOMAIN}`,
`CloudFront-Key-Pair-Id=${cookie['CloudFront-Key-Pair-Id']}; Domain=${process.env.COOKIE_DOMAIN}`,
`CloudFront-Signature=${cookie['CloudFront-Signature']}; Domain=${process.env.COOKIE_DOMAIN}`,
],
}
}
Runtime: nodejs16.x
SignerFunctionRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: !Sub ["${StackName}_Signer", { StackName: !Ref AWS::StackName }]
Description: Allows Signer lambda function to...
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs
UserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: !Ref AWS::StackName
LambdaConfig:
PreAuthentication: !GetAtt UserAuthorizerFunction.Arn
PreSignUp: !GetAtt UserAuthorizerFunction.Arn
UsernameAttributes:
- email
UsernameConfiguration:
CaseSensitive: false
FacebookIdentityProvider:
Type: AWS::Cognito::UserPoolIdentityProvider
Properties:
UserPoolId: !Ref UserPool
ProviderType: Facebook
ProviderName: Facebook
ProviderDetails:
client_id: !Ref FacebookAppId
client_secret: !Ref FacebookAppSecret
authorize_scopes: public_profile, email
api_version: v17.0
AttributeMapping:
username: id
email: email
name: name
picture: picture
GoogleIdentityProvider:
Type: AWS::Cognito::UserPoolIdentityProvider
Properties:
UserPoolId: !Ref UserPool
ProviderType: Google
ProviderName: Google
ProviderDetails:
client_id: !Ref GoogleClientId
client_secret: !Ref GoogleClientSecret
authorize_scopes: profile email
AttributeMapping:
username: sub
email: email
name: name
picture: picture
UserPoolDomain:
Type: AWS::Cognito::UserPoolDomain
Properties:
UserPoolId: !Ref UserPool
Domain: !Ref AWS::StackName
UserPoolClient:
Type: AWS::Cognito::UserPoolClient
DependsOn:
- FacebookIdentityProvider
- GoogleIdentityProvider
- UserPoolDomain
Properties:
UserPoolId: !Ref UserPool
GenerateSecret: true
AllowedOAuthFlowsUserPoolClient: true
AllowedOAuthFlows:
- implicit
AllowedOAuthScopes:
- email
- openid
- aws.cognito.signin.user.admin
CallbackURLs:
- http://localhost:8000/
- !Sub
- https://${Site}/
- { Site: !GetAtt Distribution.DomainName }
- !Sub
- https://${Site}/
- { Site: !Ref SiteAssetDomain }
LogoutURLs:
- http://localhost:8000/
- !Sub
- https://${Site}/
- { Site: !GetAtt Distribution.DomainName }
- !Sub
- https://${Site}/
- { Site: !Ref SiteAssetDomain }
ClientName: site-users
ExplicitAuthFlows:
- ALLOW_USER_PASSWORD_AUTH
- ALLOW_REFRESH_TOKEN_AUTH
PreventUserExistenceErrors: ENABLED
SupportedIdentityProviders:
- Facebook
- Google
UsersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Ref AWS::StackName
AttributeDefinitions:
- AttributeName: email
AttributeType: S
KeySchema:
- AttributeName: email
KeyType: HASH
BillingMode: PAY_PER_REQUEST
AuthorizeInsideStoryUserPolicy:
Type: 'AWS::IAM::ManagedPolicy'
Properties:
Description: Provides access to DynamoDB users table
ManagedPolicyName: !Sub ["${StackName}-AccessUsersTable", { StackName: !Ref AWS::StackName }]
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- dynamodb:GetItem
- dynamodb:PutItem
Resource:
- !GetAtt UsersTable.Arn
- Effect: Allow
Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
Resource:
- '*'
- Effect: Allow
Action:
- 'ses:SendEmail'
- 'ses:SendRawEmail'
Resource:
- '*'
AuthorizerFunctionRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: !Sub ["${StackName}_Authorize_Users_Access", { StackName: !Ref AWS::StackName }]
Description: Allows AuthorizeInsideStoryUser lambda function to connect to DynamoDB
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
ManagedPolicyArns:
- !Ref AuthorizeInsideStoryUserPolicy
AuthorizerFunctionPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt UserAuthorizerFunction.Arn
Action: lambda:InvokeFunction
Principal: cognito-idp.amazonaws.com
SourceArn: !GetAtt UserPool.Arn
UserAuthorizerFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub ["${StackName}_Authorize_Users", { StackName: !Ref AWS::StackName }]
Description: Authorizes Inside Story users
Handler: index.handler
Role: !GetAtt AuthorizerFunctionRole.Arn
Environment:
Variables:
USER_TABLE: !Ref UsersTable
ACCESS_ADMIN_EMAIL: !Ref AccessAdminEmail
ACCESS_SOURCE_EMAIL: !Ref AccessSourceEmail
Code:
ZipFile: |
const AWS = require('aws-sdk')
const dynamodb = new AWS.DynamoDB()
const ses = new AWS.SES()
exports.handler = async (event, context, callback) => {
const getItemParams = {
Key: {
email: {
S: event.request.userAttributes.email
}
},
TableName: process.env.USER_TABLE
}
try {
const data = await dynamodb.getItem(getItemParams).promise()
const { email, name } = event.request.userAttributes
if (!Object.keys(data).length) {
const notification = {
Destination: {
ToAddresses: [process.env.ACCESS_ADMIN_EMAIL]
},
Message: {
Body: {
Text: { Data: `${name} <${email}> has requested access` }
},
Subject: { Data: `Access request: ${name} <${email}>` }
},
Source: process.env.ACCESS_SOURCE_EMAIL
}
await dynamodb.putItem({
TableName: process.env.USER_TABLE,
Item: {
email: {
S: email
},
name: {
S: name
},
is_approved: {
BOOL: false
},
created_at: {
S: (new Date()).toISOString()
}
}
}).promise()
await ses.sendEmail(notification).promise()
callback(new Error(`Unknown user; email=${email}; name=${name}`), event)
return
}
if (!(data.Item.is_approved && data.Item.is_approved.BOOL)) {
callback(new Error(`Unapproved user; email=${email}; name=${name}`), event)
return
}
callback(null, event)
} catch (e) {
callback(e)
}
}
Runtime: nodejs16.x
Outputs:
BucketName:
Description: Site bucket name
Value: !Ref SiteBucket
UserPoolClientId:
Description: Cognito User Pool Client id
Value: !Ref UserPoolClient
SiteDomain:
Description: The CloudFront domain for site assets
Value: !Ref SiteAssetDomain
VideoDomain:
Description: The CloudFront domain for video assets
Value: !Ref VideoAssetDomain
SignerDomain:
Description: The CloudFront domain for signer route
Value: !Ref SignerDomain
VideoAssetOriginAccessIdentity:
Description: The ID for the origin access identity that will be used by the video CloudFront distribution
Value: !Ref VideoAssetOriginAccessIdentity