-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbeta-template.yml.erb
1129 lines (1071 loc) · 41.8 KB
/
beta-template.yml.erb
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
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: Provision an instance of the Javabuilder service. Empty the ContentBucket before deleting this Stack.
Parameters:
BaseDomainName:
Type: String
Description: Base domain name (e.g. 'code.org' in 'javabuilder.code.org').
BaseDomainNameHostedZonedID:
Type: String
Description: AWS Route53 Hosted Zone ID for base domain name.
SubdomainName:
Type: String
Description: Subdomain name for javabuilder service (e.g. 'javabuilder' in 'javabuilder.code.org').
# LogBucket:
# Type: String
# Default: cdo-logs.s3.amazonaws.com
ProvisionedConcurrentExecutions:
Type: Number
Description: The amount of provisioned concurrency to allocate for the BuildAndRunJavaProject Lambda.
MinValue: 1
Default: 1
ReservedConcurrentExecutions:
Type: Number
Description: The amount of concurrency to allow for the BuildAndRunJavaProject Lambda.
MinValue: 1
Default: 3
LimitPerHour:
Type: Number
Description: The number of Javabuilder invocations allowed per user per hour.
MinValue: 1
Default: 50
LimitPerDay:
Type: Number
Description: The number of Javabuilder invocations allowed per user per day.
MinValue: 1
Default: 150
TeacherLimitPerHour:
Type: Number
Description: The number of Javabuilder invocations allowed for all students in a classroom per hour.
MinValue: 1
Default: 1000
StageName:
Type: String
Description: The default stage name in the API Gateway APIs
Default: Prod
SilenceAlerts:
Type: String
AllowedValues: [true, false]
Description: If alerts should be silenced on this instance
Default: false
<%
JAVALAB_APP_TYPES = %w(
Theater
Neighborhood
Console
)
-%>
Globals:
Function:
Runtime: ruby2.7
Timeout: 30
MemorySize: 256
Tracing: Active
Conditions:
IsDevCondition: !Equals [!Ref BaseDomainName, "dev-code.org"]
SilenceAlertsCondition: !Or [Condition: IsDevCondition, !Equals [!Ref SilenceAlerts, "true"]]
Resources:
# Note: We can't update the name of a DomainName resource once it has been created because the
# domain name itself has already been provisioned. When we change from javabuilderbeta to
# javabuilder, we should update the WebSocket resources here to use the prefix "WebSocket"
<%{
Http: {Prefix: "Http", Suffix: "-http"},
WebSocket: {Prefix: "", Suffix: ""},
}.each do |apiName, config| -%>
<%=config[:Prefix]%>Domain:
Type: AWS::Route53::RecordSet
Properties:
HostedZoneName: !Sub "${BaseDomainName}."
Name: !Sub "${SubdomainName}<%=config[:Suffix]%>.${BaseDomainName}"
Type: A
AliasTarget:
DNSName: !GetAtt <%=config[:Prefix]%>DomainName.RegionalDomainName
HostedZoneId: !GetAtt <%=config[:Prefix]%>DomainName.RegionalHostedZoneId
<%=config[:Prefix]%>DomainName:
Type: AWS::ApiGatewayV2::DomainName
Properties:
DomainName: !Sub "${SubdomainName}<%=config[:Suffix]%>.${BaseDomainName}"
DomainNameConfigurations:
- EndpointType: REGIONAL
CertificateArn: !Ref <%=config[:Prefix]%>Certificate
CertificateName: !Sub "${SubdomainName}<%=config[:Suffix]%>.${BaseDomainName}"
<%=config[:Prefix]%>Certificate:
Type: AWS::CertificateManager::Certificate
Properties:
DomainName: !Sub "${SubdomainName}<%=config[:Suffix]%>.${BaseDomainName}"
ValidationMethod: DNS
DomainValidationOptions:
- DomainName: !Sub "${SubdomainName}<%=config[:Suffix]%>.${BaseDomainName}"
HostedZoneId: !Ref BaseDomainNameHostedZonedID
<%=config[:Prefix]%>DomainNameAPIMapping:
Type: AWS::ApiGatewayV2::ApiMapping
DependsOn:
- <%=config[:Prefix]%>Domain
Properties:
ApiId: !Ref <%=apiName%>API
DomainName: !Sub "${SubdomainName}<%=config[:Suffix]%>.${BaseDomainName}"
Stage: !Ref <%=apiName%>Stage
<%end -%>
HttpAPI:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: !Sub "${SubdomainName}-http.${BaseDomainName}"
ProtocolType: HTTP
PutRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref HttpAPI
RouteKey: PUT /seedsources/sources.json
AuthorizationType: CUSTOM
AuthorizerId: !Ref HttpAuthorizer
OperationName: PutRoute
Target: !Join
- '/'
- - 'integrations'
- !Ref PutIntegration
PutSourcesFunction:
Type: AWS::Serverless::Function
Properties:
Description: Puts user sources into the S3 bucket
CodeUri: api-gateway-routes/
Handler: api_gateway_put_function.lambda_handler
Role: !ImportValue JavabuilderPutSourcesLambdaRole
Environment:
Variables:
CONTENT_BUCKET_NAME: !Ref ContentBucket
PutSourcesPermission:
Type: AWS::Lambda::Permission
DependsOn:
- HttpAPI
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref PutSourcesFunction
Principal: apigateway.amazonaws.com
PutIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref HttpAPI
Description: PUT Integration
# Integration method must be POST for AWS_PROXY integrations even though we're PUTting into an S3 bucket
IntegrationMethod: POST
IntegrationType: AWS_PROXY
IntegrationUri:
Fn::Sub:
arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PutSourcesFunction.Arn}/invocations
PayloadFormatVersion: 2.0
HttpStageLogs:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/apigateway/accesslog/${SubdomainName}-http.${BaseDomainName}"
HttpStage:
Type: AWS::ApiGatewayV2::Stage
Properties:
# Using AutoDeploy rather than a Deployment resource (as we do with the WebSocket API) because
# the Deployment resource doesn't seem to work with HTTP APIs.
AutoDeploy: true
StageName: !Sub "${StageName}"
Description: The stage to deploy
ApiId: !Ref HttpAPI
DefaultRouteSettings:
DetailedMetricsEnabled: true
AccessLogSettings:
DestinationArn: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/apigateway/accesslog/${SubdomainName}-http.${BaseDomainName}"
# TODO: Also log authorizer status code, authorizer error message, Javabuilder session id, and Origin.
Format: '{
"host": "$context.domainName",
"requestId": "$context.requestId",
"ip": "$context.identity.sourceIp",
"requestTime": "$context.requestTime",
"httpMethod": "$context.httpMethod",
"caller": "$context.identity.caller",
"routeKey": "$context.routeKey",
"status": "$context.status",
"protocol": "$context.protocol",
"userAgent": "$context.identity.userAgent",
"responseLength":"$context.responseLength",
"contextErrorMessage": "$context.error.message",
"contextErrorMessageString": "$context.error.messageString",
"integrationError": "$context.integration.error",
"authorizerError": "$context.authorizer.error"
}'
HttpAuthorizer:
Type: AWS::ApiGatewayV2::Authorizer
Properties:
ApiId: !Ref HttpAPI
AuthorizerCredentialsArn:
Fn::ImportValue: JavabuilderAPIGatewayRole
AuthorizerPayloadFormatVersion: 2.0
AuthorizerResultTtlInSeconds: 0
AuthorizerType: REQUEST
AuthorizerUri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HttpAuthorizerLambda.Arn}/invocations"
IdentitySource:
- "$request.querystring.Authorization"
Name: HttpAuthorizer
WebSocketAPI:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: !Sub "${SubdomainName}.${BaseDomainName}"
ProtocolType: WEBSOCKET
RouteSelectionExpression: "$request.body.action"
ConnectRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref WebSocketAPI
RouteKey: $connect
AuthorizationType: CUSTOM
AuthorizerId: !Ref WebSocketAuthorizer
OperationName: ConnectRoute
Target: !Join
- '/'
- - 'integrations'
- !Ref ConnectInteg
WebSocketAuthorizer:
Type: AWS::ApiGatewayV2::Authorizer
Properties:
ApiId: !Ref WebSocketAPI
AuthorizerType: REQUEST
AuthorizerUri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${WebsocketAuthorizerLambda.Arn}/invocations"
IdentitySource:
- route.request.querystring.Authorization
Name: WebSocketAuthorizer
ConnectInteg:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref WebSocketAPI
Description: Connect Integration
IntegrationType: AWS_PROXY
IntegrationUri:
Fn::Sub:
arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${StartSessionAndRelayMessagesFunction.Arn}/invocations
DefaultRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref WebSocketAPI
RouteKey: $default
AuthorizationType: NONE
OperationName: DefaultRoute
Target:
Fn::Join:
- /
- - integrations
- Ref: DefaultIntegration
DefaultIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref WebSocketAPI
Description: Lambda Proxy Integration
IntegrationType: AWS_PROXY
IntegrationUri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${StartSessionAndRelayMessagesFunction.Arn}/invocations"
DisconnectRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref WebSocketAPI
RouteKey: $disconnect
AuthorizationType: NONE
OperationName: DisconnectRoute
Target: !Join
- '/'
- - 'integrations'
- !Ref DisconnectInteg
DisconnectInteg:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref WebSocketAPI
Description: Disconnect Integration
IntegrationType: AWS_PROXY
IntegrationUri:
Fn::Sub:
arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${StartSessionAndRelayMessagesFunction.Arn}/invocations
WebSocketDeployment:
Type: AWS::ApiGatewayV2::Deployment
DependsOn:
- ConnectRoute
- DefaultRoute
- DisconnectRoute
Properties:
ApiId: !Ref WebSocketAPI
WebSocketStage:
Type: AWS::ApiGatewayV2::Stage
Properties:
StageName: !Sub "${StageName}"
Description: The stage to deploy
DeploymentId: !Ref WebSocketDeployment
ApiId: !Ref WebSocketAPI
DefaultRouteSettings:
DetailedMetricsEnabled: true
LoggingLevel: INFO
DataTraceEnabled: true
AccessLogSettings:
DestinationArn: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/apigateway/accesslog/${SubdomainName}.${BaseDomainName}"
# TODO: Also log authorizer status code, authorizer error message, Javabuilder session id, and Origin.
Format: '{
"host": "$context.domainName",
"requestId": "$context.requestId",
"ip": "$context.identity.sourceIp",
"requestTime": "$context.requestTime",
"method": "$context.httpMethod",
"caller": "$context.identity.caller",
"eventType": "$context.eventType",
"routeKey": "$context.routeKey",
"status": "$context.status",
"connectionId": "$context.connectionId",
"protocol": "$context.protocol",
"userAgent": "$context.identity.userAgent",
"contextErrorMessage": "$context.error.message",
"contextErrorMessageString": "$context.error.messageString",
"integrationError": "$context.integration.error",
"authorizerError": "$context.authorizer.error"
}'
StartSessionAndRelayMessagesFunction:
Type: AWS::Serverless::Function
Properties:
Description: Starts the long-running Lambda that compiles and runs a JavaLab project and relays messages to it from the JavaLab client.
CodeUri: api-gateway-routes/
Handler: api_gateway_proxy_function.lambda_handler
Role: !ImportValue JavabuilderSessionManagerMessageRelayLambdaRole
Environment:
Variables:
# The Logical ID of the BuildAndRun Lambda Alias, which is generated by SAM because AutoPublishAlias is enabled
# has a predictable format: <function‑LogicalId>Alias<alias‑name>
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-generated-resources-function.html#sam-specification-generated-resources-function-autopublishalias
<%JAVALAB_APP_TYPES.each do | name | -%>
BUILD_AND_RUN_<%=name.upcase%>_PROJECT_LAMBDA_ARN: !Ref BuildAndRunJava<%=name%>ProjectFunctionAliaslive
<%end -%>
StartSessionAndRelayMessagesPermission:
Type: AWS::Lambda::Permission
DependsOn:
- WebSocketAPI
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref StartSessionAndRelayMessagesFunction
Principal: apigateway.amazonaws.com
# AWS does not seem to be case sensitive, but is case aware. Therefore, we can't update from
# Websocket here to WebSocket as is used elsewhere when updating an existing stack. Updating this is
# a step we should take when we create our non-beta environment from scratch. At that point, we
# should also update uses of HttpAPI and WebSocketAPI to be HttpApi and WebSocketApi, respectively,
# to match the AWS standard elsewhere in this template. Example: "AWS::ApiGatewayV2::ApiMapping"
#
# Note: hourly and daily limit values provided to both authorizers here as environment variables,
# but are only needed in the HTTP authorizer.
# Both authorizers need to access the token_status DynamoDB table, but only the HTTP authorizer
# needs to access to the other tables.
<%{
Http: {
LambdaName: "Http",
Handler: "http_authorizer_function",
Description: "'Authorize PUT by decoding JWT in Authorization querystring parameter.'"
},
WebSocket: {
LambdaName: "Websocket",
Handler: "websocket_authorizer_function",
Description: "'Authorize WebSocket connect by decoding JWT in Authorization querystring parameter.'"
},
}.each do |name, config| -%>
<%=config[:LambdaName]%>AuthorizerLambda:
Type: AWS::Serverless::Function
Properties:
Handler: <%=config[:Handler]%>.lambda_handler
CodeUri: javabuilder-authorizer/
Description: <%=config[:Description]%>
Timeout: 3
Role: !ImportValue JavabuilderAuthorizerLambdaRole
Environment:
Variables:
limit_per_hour: !Ref LimitPerHour
limit_per_day: !Ref LimitPerDay
teacher_limit_per_hour: !Ref TeacherLimitPerHour
blocked_users_table: !Ref BlockedUsersTable
token_status_table: !Ref TokenStatusTable
user_requests_table: !Ref UserRequestsTable
teacher_associated_requests_table: !Ref TeacherAssociatedRequestsTable
<%=name%>AuthorizerPermission:
Type: AWS::Lambda::Permission
DependsOn:
- <%=name%>Authorizer
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref <%=config[:LambdaName]%>AuthorizerLambda
Principal: apigateway.amazonaws.com
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${<%=name%>API}/authorizers/${<%=name%>Authorizer}"
<%end -%>
ChangeJavaRuntimeDirectoryLayer:
Type: AWS::Serverless::LayerVersion
Properties:
CompatibleRuntimes:
- java11
ContentUri: org-code-javabuilder/change_runtime_directory
Description: Change Java runtime to launch from the writeable /tmp directory to enable student projects to write files more easily.
LayerName: change-java-runtime-directory
FontConfigurationLayer:
Type: AWS::Serverless::LayerVersion
Properties:
CompatibleRuntimes:
- java11
ContentUri: org-code-javabuilder/font_config.zip
Description: Add a font configuration file to enable use of fonts.
LayerName: font-configuration
<%{
Theater: {MemorySize: 1769, Timeout: 90},
Neighborhood: {MemorySize: 512, Timeout: 90},
Console: {MemorySize: 512, Timeout: 90}
}.each do |name, config| -%>
BuildAndRunJava<%=name%>ProjectFunction:
Type: AWS::Serverless::Function
Properties:
Layers:
- !Ref FontConfigurationLayer
- !Ref ChangeJavaRuntimeDirectoryLayer
Handler: org.code.javabuilder.LambdaRequestHandler::handleRequest
Runtime: java11
CodeUri: org-code-javabuilder/lib/build/distributions/lib.zip
AutoPublishAlias: live
ReservedConcurrentExecutions: !Ref ReservedConcurrentExecutions
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: !Ref ProvisionedConcurrentExecutions
Description: Compile and execute a JavaLab <%=name%> project.
MemorySize: <%=config[:MemorySize]%>
Timeout: <%=config[:Timeout]%>
EventInvokeConfig:
MaximumRetryAttempts: 0
Role:
Fn::ImportValue: JavabuilderBuildAndRunLambdaRole
Environment:
Variables:
AWS_LAMBDA_EXEC_WRAPPER: /opt/change_runtime_directory
CONTENT_BUCKET_NAME: !Ref ContentBucket
CONTENT_BUCKET_URL: !Sub "https://${ContentDomain}"
API_ENDPOINT: !Sub
- "https://${ApiId}.execute-api.${AWS::Region}.amazonaws.com/${StageName}"
- ApiId: !Ref WebSocketAPI
<%end -%>
ContentBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !If [IsDevCondition, !Sub "cdo-dev-${SubdomainName}-content", !Sub "cdo-${SubdomainName}-content"]
CorsConfiguration:
CorsRules:
- AllowedMethods: [GET, PUT]
AllowedOrigins: ['*']
AllowedHeaders: ['*']
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: 'AES256'
LifecycleConfiguration:
Rules:
- Id: ExpirationRule
Status: Enabled
ExpirationInDays: 1
ContentBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref ContentBucket
PolicyDocument:
Statement:
- Action: ['s3:GetObject']
Effect: Allow
Resource: !Sub "arn:aws:s3:::${ContentBucket}/*"
Principal: '*'
ContentAPICertificate:
Type: AWS::CertificateManager::Certificate
Properties:
DomainName: !Sub "${SubdomainName}-content.${BaseDomainName}"
ValidationMethod: DNS
DomainValidationOptions:
- DomainName: !Sub "${SubdomainName}-content.${BaseDomainName}"
HostedZoneId: !Ref BaseDomainNameHostedZonedID
ContentDomain:
Type: AWS::Route53::RecordSet
Properties:
HostedZoneName: !Sub "${BaseDomainName}."
Name: !Sub "${SubdomainName}-content.${BaseDomainName}"
Type: A
AliasTarget:
DNSName: !GetAtt ContentCDN.DomainName
HostedZoneId: Z2FDTNDATAQYW2 # static ID for cloudfront aliases
ContentCDN:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Enabled: true
Aliases: [!Sub "${SubdomainName}-content.${BaseDomainName}"]
ViewerCertificate:
AcmCertificateArn: !Ref ContentAPICertificate
MinimumProtocolVersion: TLSv1
SslSupportMethod: sni-only
CustomErrorResponses:
- ErrorCode: 403
ErrorCachingMinTTL: 0
# TODO: enable logging when LogBucket is set up
# Logging:
# Bucket: !Ref LogBucket
# IncludeCookies: false
# Prefix: !Sub "${SubdomainName}-content.${BaseDomainName}"
Origins:
- Id: ContentBucket
DomainName: !GetAtt ContentBucket.DomainName
S3OriginConfig: {}
DefaultCacheBehavior:
TargetOriginId: ContentBucket
AllowedMethods: [DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT]
Compress: true
DefaultTTL: 0
ForwardedValues: {QueryString: true}
ViewerProtocolPolicy: redirect-to-https
HighConcurrentExecutionsAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_high_concurrent_executions"
AlarmDescription: !Sub |
This will page the DOTD if javabuilder usage exceeds 50 concurrent
executions for 10 minutes. Occasional spikes are expected, but
long-running high usage is an indication of an attack. Go to the
following URLs and set reserved concurrency to 10 immediately
<%JAVALAB_APP_TYPES.each do | name | -%>
https://console.aws.amazon.com/lambda/home?region=${AWS::Region}#/functions/${BuildAndRunJava<%=name%>ProjectFunction}/edit/concurrency?tab=configure
<%end -%>
Then post in #ap-csa-dev.
ActionsEnabled: true
AlarmActions:
- !If [SilenceAlertsCondition, !Ref AWS::NoValue, !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:CDO-Urgent"]
EvaluationPeriods: 10
DatapointsToAlarm: 10
Threshold: 50
ComparisonOperator: GreaterThanThreshold
TreatMissingData: notBreaching
Metrics:
- Id: e1
Label: Concurrent Executions Across All Lambdas
ReturnData: true
Expression: SUM(METRICS())
<%{Theater: "m2", Neighborhood: "m3", Console: "m4"}.each do |name, id| -%>
- Id: <%=id%>
ReturnData: false
MetricStat:
Metric:
Namespace: AWS/Lambda
MetricName: ConcurrentExecutions
Dimensions:
- Name: FunctionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
Period: 60
Stat: Maximum
<%end -%>
HighWebsocketConnectionsAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_high_websocket_connections"
AlarmDescription: Significantly higher websocket connections than normal detected. Investigate if there is a DDOS.
ActionsEnabled: false
EvaluationPeriods: 20
DatapointsToAlarm: 20
ComparisonOperator: GreaterThanUpperThreshold
TreatMissingData: notBreaching
Metrics:
- Id: m1
ReturnData: true
MetricStat:
Metric:
Namespace: AWS/ApiGateway
MetricName: ConnectCount
Dimensions:
- Name: Stage
Value: !Sub "${StageName}"
- Name: ApiId
Value: !Ref WebSocketAPI
Period: 60
Stat: Sum
- Id: ad1
Label: ConnectCount (expected)
ReturnData: true
Expression: ANOMALY_DETECTION_BAND(m1, 8)
ThresholdMetricId: ad1
HighHttpRequestsAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_high_http_requests"
AlarmDescription: Significantly higher HTTP requests than normal detected.
Investigate if there is a DDOS.
ActionsEnabled: true
OKActions: []
AlarmActions: []
InsufficientDataActions: []
EvaluationPeriods: 20
DatapointsToAlarm: 20
ComparisonOperator: GreaterThanUpperThreshold
TreatMissingData: notBreaching
Metrics:
- Id: m1
ReturnData: true
MetricStat:
Metric:
Namespace: AWS/ApiGateway
MetricName: Count
Dimensions:
- Name: ApiId
Value: !Ref HttpAPI
Period: 60
Stat: Sum
- Id: ad1
Label: Count (expected)
ReturnData: true
Expression: ANOMALY_DETECTION_BAND(m1, 8)
ThresholdMetricId: ad1
HighUsageCompositeAlarm:
Type: AWS::CloudWatch::CompositeAlarm
DependsOn:
- HighHttpRequestsAlarm
- HighWebsocketConnectionsAlarm
- NeighborhoodHighInvocationsAlarm
- TheaterHighInvocationsAlarm
Properties:
ActionsEnabled: true
AlarmActions:
# TODO: after we have run at high usage for a while, consider re-enabling this alarm. Right now it is too noisy
# - !If [SilenceAlertsCondition, !Ref AWS::NoValue, !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:javabuilder-high-usage"]
- !Ref AWS::NoValue
AlarmDescription: Send message if abnormally high Javabuilder usage detected.
Monitors usage across the HTTP API, WebSocket API, and all Build and Run
Lambdas.
AlarmName: !Sub "${SubdomainName}_high_usage_composite"
AlarmRule: !Sub "ALARM(${SubdomainName}_console_high_invocations) OR
ALARM(${SubdomainName}_high_http_requests) OR
ALARM(${SubdomainName}_high_websocket_connections) OR
ALARM(${SubdomainName}_neighborhood_high_invocations) OR
ALARM(${SubdomainName}_theater_high_invocations)"
InsufficientDataActions: []
OKActions: []
<%JAVALAB_APP_TYPES.each do | name | -%>
<%=name%>HighSevereErrorRateAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_<%=name.downcase%>_high_severe_error_rate"
AlarmDescription: Send page if Javabuilder severe error rate exceeds 10% for 20
minutes. Occasional spikes are expected, but a sustained high error rate
is an indication of an outage.
ActionsEnabled: true
AlarmActions:
- !If [SilenceAlertsCondition, !Ref AWS::NoValue, !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:Javabuilder-high-error-rate"]
EvaluationPeriods: 4
DatapointsToAlarm: 4
Threshold: 10
ComparisonOperator: GreaterThanThreshold
TreatMissingData: notBreaching
Metrics:
- Id: e1
Label: Error Rate (%)
ReturnData: true
Expression: (m1 / m2) * 100
- Id: m1
ReturnData: false
MetricStat:
Metric:
Namespace: Javabuilder
MetricName: SevereError
Dimensions:
- Name: functionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
Period: 300
Stat: Sum
- Id: m2
ReturnData: false
MetricStat:
Metric:
Namespace: AWS/Lambda
MetricName: Invocations
Dimensions:
- Name: FunctionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
Period: 300
Stat: Sum
<%=name%>HighErrorRateAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_build_and_run_<%=name.downcase%>_lambda_error_rate"
AlarmDescription: Error rate in Javabuilder's <%=name%> build and run lambda (the core of
Javabuilder, which executes student <%=name%> code) exceeded 10% for four
consecutive 5 minute periods.
ActionsEnabled: true
AlarmActions:
- !If [SilenceAlertsCondition, !Ref AWS::NoValue, !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:javabuilder-build-and-run-lambda-error-rate"]
EvaluationPeriods: 4
DatapointsToAlarm: 4
Threshold: 25
ComparisonOperator: GreaterThanThreshold
TreatMissingData: notBreaching
Metrics:
- Id: e1
Label: Errors / Invocations
ReturnData: true
Expression: ((m1 - m3) / m2) * 100
- Id: m1
ReturnData: false
MetricStat:
Metric:
Namespace: AWS/Lambda
MetricName: Errors
Dimensions:
- Name: FunctionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
Period: 300
Stat: Sum
- Id: m2
ReturnData: false
MetricStat:
Metric:
Namespace: AWS/Lambda
MetricName: Invocations
Dimensions:
- Name: FunctionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
Period: 300
Stat: Sum
- Id: m3
ReturnData: false
MetricStat:
Metric:
Namespace: AWS/Lambda
MetricName: Duration
Dimensions:
- Name: FunctionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
Period: 300
Stat: TC(89000:)
<%=name%>SlowCleanupTimeAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_<%=name.downcase%>_slow_cleanup_time"
AlarmDescription: Average cleanup time in Javabuilder's <%=name%> build and run lambda was high for at
least 15 out of the last 20 minutes. Investigate if there has been a performance regression.
ActionsEnabled: true
OKActions: []
AlarmActions:
- !If [SilenceAlertsCondition, !Ref AWS::NoValue, !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:javabuilder-slow-performance"]
InsufficientDataActions: []
MetricName: CleanupTime
Namespace: Javabuilder
Statistic: Average
Dimensions:
- Name: functionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
EvaluationPeriods: 20
DatapointsToAlarm: 15
ComparisonOperator: GreaterThanThreshold
TreatMissingData: notBreaching
Threshold: 200
Period: 60
<%=name%>SlowColdBootTimeAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_<%=name.downcase%>_slow_cold_boot_time"
AlarmDescription: Average cold boot time in Javabuilder's <%=name%> build and run lambda was high for at
least 15 out of the last 20 minutes. Investigate if there has been a performance regression.
ActionsEnabled: true
OKActions: []
AlarmActions:
- !If [SilenceAlertsCondition, !Ref AWS::NoValue, !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:javabuilder-slow-performance"]
InsufficientDataActions: []
MetricName: ColdBootTime
Namespace: Javabuilder
Statistic: Average
Dimensions:
- Name: functionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
EvaluationPeriods: 20
DatapointsToAlarm: 15
ComparisonOperator: GreaterThanThreshold
TreatMissingData: notBreaching
Threshold: 10500
Period: 60
<%=name%>SlowInitializationTimeAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_<%=name.downcase%>_slow_initialization_time"
AlarmDescription: Average initialization time in Javabuilder's <%=name%> build and run lambda was high for at
least 15 out of the last 20 minutes. Investigate if there has been a performance regression.
ActionsEnabled: true
OKActions: []
AlarmActions:
- !If [SilenceAlertsCondition, !Ref AWS::NoValue, !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:javabuilder-slow-performance"]
InsufficientDataActions: []
MetricName: InitializationTime
Namespace: Javabuilder
Statistic: Average
Dimensions:
- Name: functionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
EvaluationPeriods: 20
DatapointsToAlarm: 15
ComparisonOperator: GreaterThanThreshold
TreatMissingData: notBreaching
Threshold: 5000
Period: 60
<%=name%>SlowTransitionTimeAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_<%=name.downcase%>_slow_transition_time"
AlarmDescription: Average transition time in Javabuilder's <%=name%> build and run lambda was high for at
least 15 out of the last 20 minutes. Investigate if there has been a performance regression.
ActionsEnabled: true
OKActions: []
AlarmActions:
- !If [SilenceAlertsCondition, !Ref AWS::NoValue, !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:javabuilder-slow-performance"]
InsufficientDataActions: []
MetricName: TransitionTime
Namespace: Javabuilder
Statistic: Average
Dimensions:
- Name: functionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
EvaluationPeriods: 20
DatapointsToAlarm: 15
ComparisonOperator: GreaterThanThreshold
TreatMissingData: notBreaching
Threshold: 2500
Period: 60
<%=name%>HighInvocationsAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_<%=name.downcase%>_high_invocations"
AlarmDescription: Significantly higher <%=name%> build and run invocations than
normal detected. Investigate if there is a DDOS.
ActionsEnabled: false
EvaluationPeriods: 20
DatapointsToAlarm: 20
ComparisonOperator: GreaterThanUpperThreshold
TreatMissingData: notBreaching
Metrics:
- Id: m1
ReturnData: true
MetricStat:
Metric:
Namespace: AWS/Lambda
MetricName: Invocations
Dimensions:
- Name: FunctionName
Value: !Ref BuildAndRunJava<%=name%>ProjectFunction
Period: 60
Stat: Sum
- Id: ad1
Label: Invocations (expected)
ReturnData: true
Expression: ANOMALY_DETECTION_BAND(m1, 8)
ThresholdMetricId: ad1
<%end -%>
# We use shortened versions of names for partition keys (eg, user_id),
# but values will be a concatenation of the domain name and appropriate ID.
# Values will look something like:
# studio.code.org#123456 (user_requests table)
# studio.code.org#UserId#123456 (blocked_users table)
<%
DOMAIN_AND_USER_ID_COMPOSITE_ATTRIBUTE_NAME = 'user_id'
DOMAIN_AND_SECTION_OWNER_ID_COMPOSITE_ATTRIBUTE_NAME = 'section_owner_id'
TOKEN_ID_ATTRIBUTE_NAME = 'token_id'
ISSUED_AT_TIMESTAMP_ATTRIBUTE_NAME = 'issued_at'
TIME_TO_LIVE_ATTRIBUTE_NAME = 'ttl'
-%>
BlockedUsersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${SubdomainName}_blocked_users"
KeySchema:
- AttributeName: <%=DOMAIN_AND_USER_ID_COMPOSITE_ATTRIBUTE_NAME%>
KeyType: HASH
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: <%=DOMAIN_AND_USER_ID_COMPOSITE_ATTRIBUTE_NAME%>
AttributeType: S
PointInTimeRecoverySpecification:
PointInTimeRecoveryEnabled: true
TokenStatusTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${SubdomainName}_tokens"
KeySchema:
- AttributeName: <%=TOKEN_ID_ATTRIBUTE_NAME%>
KeyType: HASH
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: <%=TOKEN_ID_ATTRIBUTE_NAME%>
AttributeType: S
TimeToLiveSpecification:
AttributeName: <%=TIME_TO_LIVE_ATTRIBUTE_NAME%>
Enabled: true
UserRequestsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${SubdomainName}_user_requests"
KeySchema:
- AttributeName: <%=DOMAIN_AND_USER_ID_COMPOSITE_ATTRIBUTE_NAME%>
KeyType: HASH
- AttributeName: <%=ISSUED_AT_TIMESTAMP_ATTRIBUTE_NAME%>
KeyType: RANGE
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: <%=DOMAIN_AND_USER_ID_COMPOSITE_ATTRIBUTE_NAME%>
AttributeType: S
- AttributeName: <%=ISSUED_AT_TIMESTAMP_ATTRIBUTE_NAME%>
AttributeType: N
TimeToLiveSpecification:
AttributeName: <%=TIME_TO_LIVE_ATTRIBUTE_NAME%>
Enabled: true
TeacherAssociatedRequestsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${SubdomainName}_teacher_associated_requests"
KeySchema:
- AttributeName: <%=DOMAIN_AND_SECTION_OWNER_ID_COMPOSITE_ATTRIBUTE_NAME%>
KeyType: HASH
- AttributeName: <%=ISSUED_AT_TIMESTAMP_ATTRIBUTE_NAME%>
KeyType: RANGE
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: <%=DOMAIN_AND_SECTION_OWNER_ID_COMPOSITE_ATTRIBUTE_NAME%>
AttributeType: S
- AttributeName: <%=ISSUED_AT_TIMESTAMP_ATTRIBUTE_NAME%>
AttributeType: N
TimeToLiveSpecification:
AttributeName: <%=TIME_TO_LIVE_ATTRIBUTE_NAME%>
Enabled: true
HighUsersBlockedAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${SubdomainName}_high_users_blocked"
AlarmDescription: Unusually high number of users being blocked by our throttling
thresholds.
ActionsEnabled: true
OKActions: []
AlarmActions:
- !If [SilenceAlertsCondition, !Ref AWS::NoValue, !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:javabuilder-high-throttling"]
InsufficientDataActions: []
MetricName: UserBlocked
Namespace: Javabuilder
Statistic: Sum
Dimensions:
- Name: functionName
Value: !Ref HttpAuthorizerLambda
Period: 60
EvaluationPeriods: 1