-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.yaml
More file actions
1179 lines (1107 loc) · 37.8 KB
/
template.yaml
File metadata and controls
1179 lines (1107 loc) · 37.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
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: Agent Hub (Forge) - authoritative personal agent hub with satellites (SAM)
Parameters:
StageName:
Type: String
Default: dev
DbName:
Type: String
Default: agenthub
AuroraMinACU:
Type: Number
Default: 0.5
AuroraMaxACU:
Type: Number
Default: 2
PlannerModel:
Type: String
Default: gpt-4.1-mini
MaxSpacesPerAgent:
Type: String
Default: "5"
LiveKitUrl:
Type: String
Description: LiveKit server URL (e.g. wss://your.livekit.host or https://...). Leave empty to disable LiveKit token minting.
Default: ""
ApiDeploymentVersion:
Type: String
Description: Version string to force API Gateway deployment updates
Default: "1"
CognitoDomainPrefix:
Type: String
Description: Prefix for Cognito Hosted UI domain (must be globally unique across all AWS accounts). Leave empty to auto-generate.
Default: ""
EnableGoogleAuth:
Type: String
Description: Enable Google as a Cognito Hosted UI identity provider (requires google-oauth secret to be populated).
AllowedValues:
- "true"
- "false"
Default: "false"
GuiCallbackUrls:
Type: CommaDelimitedList
Description: Allowed Cognito callback URLs for the (local) GUI OAuth flow
Default: "http://localhost:8084/auth/callback,https://localhost:8084/auth/callback"
GuiLogoutUrls:
Type: CommaDelimitedList
Description: Allowed Cognito logout URLs for the (local) GUI OAuth flow
Default: "http://localhost:8084/logged-out,https://localhost:8084/logged-out"
Conditions:
IsDeploymentV1: !Equals [!Ref ApiDeploymentVersion, "1"]
IsDeploymentV2: !Equals [!Ref ApiDeploymentVersion, "2"]
HasCognitoDomainPrefix: !Not [!Equals [!Ref CognitoDomainPrefix, ""]]
GoogleAuthEnabled: !Equals [!Ref EnableGoogleAuth, "true"]
GoogleAuthDisabled: !Equals [!Ref EnableGoogleAuth, "false"]
Globals:
Function:
Runtime: python3.11
Timeout: 30
MemorySize: 512
Tracing: Active
Environment:
Variables:
STAGE: !Ref StageName
Resources:
# -----------------------------
# Networking (minimal VPC for Aurora)
# -----------------------------
HubVpc:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.20.0.0/16
EnableDnsSupport: true
EnableDnsHostnames: true
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-vpc
PrivateSubnetA:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref HubVpc
AvailabilityZone: !Select [0, !GetAZs '']
CidrBlock: 10.20.0.0/24
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-priv-a
PrivateSubnetB:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref HubVpc
AvailabilityZone: !Select [1, !GetAZs '']
CidrBlock: 10.20.1.0/24
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-priv-b
PrivateRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref HubVpc
PrivateSubnetARouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PrivateSubnetA
RouteTableId: !Ref PrivateRouteTable
PrivateSubnetBRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PrivateSubnetB
RouteTableId: !Ref PrivateRouteTable
DbSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: !Sub ${AWS::StackName} Aurora SG
VpcId: !Ref HubVpc
DbSubnetGroup:
Type: AWS::RDS::DBSubnetGroup
Properties:
DBSubnetGroupDescription: Subnet group for AgentHub Aurora
SubnetIds:
- !Ref PrivateSubnetA
- !Ref PrivateSubnetB
# -----------------------------
# Secrets
# -----------------------------
DbCredentialsSecret:
Type: AWS::SecretsManager::Secret
Properties:
Name: !Sub ${AWS::StackName}/db-credentials
GenerateSecretString:
SecretStringTemplate: '{"username":"agenthub"}'
GenerateStringKey: password
ExcludePunctuation: true
PasswordLength: 32
AdminApiKeySecret:
Type: AWS::SecretsManager::Secret
Properties:
Name: !Sub ${AWS::StackName}/admin-api-key
GenerateSecretString:
SecretStringTemplate: '{"admin_api_key":""}'
GenerateStringKey: admin_api_key
PasswordLength: 40
ExcludePunctuation: true
OpenAISecret:
Type: AWS::SecretsManager::Secret
Properties:
Name: !Sub ${AWS::StackName}/openai
Description: Store your OpenAI API key as {"api_key":"..."}
SecretString: '{"api_key":"REPLACE_ME"}'
LiveKitSecret:
Type: AWS::SecretsManager::Secret
Properties:
Name: !Sub ${AWS::StackName}/livekit
Description: Store your LiveKit credentials as {"api_key":"...","api_secret":"..."}
SecretString: '{"api_key":"REPLACE_ME","api_secret":"REPLACE_ME"}'
GoogleOAuthSecret:
Type: AWS::SecretsManager::Secret
Properties:
Name: !Sub ${AWS::StackName}/google-oauth
Description: Store your Google OAuth credentials as {"client_id":"...","client_secret":"..."} for Cognito federation
SecretString: '{"client_id":"REPLACE_ME","client_secret":"REPLACE_ME"}'
# -----------------------------
# Aurora PostgreSQL Serverless v2 + Data API
# -----------------------------
AuroraCluster:
Type: AWS::RDS::DBCluster
Properties:
Engine: aurora-postgresql
DatabaseName: !Ref DbName
DBSubnetGroupName: !Ref DbSubnetGroup
VpcSecurityGroupIds:
- !Ref DbSecurityGroup
StorageEncrypted: true
MasterUsername: !Sub '{{resolve:secretsmanager:${DbCredentialsSecret}:SecretString:username}}'
MasterUserPassword: !Sub '{{resolve:secretsmanager:${DbCredentialsSecret}:SecretString:password}}'
EnableHttpEndpoint: true
ServerlessV2ScalingConfiguration:
MinCapacity: !Ref AuroraMinACU
MaxCapacity: !Ref AuroraMaxACU
AuroraInstance:
Type: AWS::RDS::DBInstance
Properties:
Engine: aurora-postgresql
DBClusterIdentifier: !Ref AuroraCluster
DBInstanceClass: db.serverless
# -----------------------------
# S3 buckets
# -----------------------------
ArtifactBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
VersioningConfiguration:
Status: Enabled
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
LifecycleConfiguration:
Rules:
- Id: ExpireRecognitionArtifacts
Status: Enabled
Prefix: recognition/
ExpirationInDays: 1
NoncurrentVersionExpirationInDays: 1
AbortIncompleteMultipartUpload:
DaysAfterInitiation: 1
AuditBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
ObjectLockEnabled: true
VersioningConfiguration:
Status: Enabled
ObjectLockConfiguration:
ObjectLockEnabled: Enabled
Rule:
DefaultRetention:
Mode: GOVERNANCE
Days: 3650
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
# -----------------------------
# Queues
# -----------------------------
TranscriptQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 60
ActionQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 60
RecognitionQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 60
# -----------------------------
# WebSocket connection registry
# -----------------------------
WsConnectionsTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: connection_id
AttributeType: S
- AttributeName: device_id
AttributeType: S
KeySchema:
- AttributeName: connection_id
KeyType: HASH
GlobalSecondaryIndexes:
- IndexName: device_id_index
KeySchema:
- AttributeName: device_id
KeyType: HASH
Projection:
ProjectionType: ALL
TimeToLiveSpecification:
AttributeName: ttl
Enabled: true
WsSubscriptionsTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: topic_key
AttributeType: S
- AttributeName: connection_id
AttributeType: S
KeySchema:
- AttributeName: topic_key
KeyType: HASH
- AttributeName: connection_id
KeyType: RANGE
GlobalSecondaryIndexes:
- IndexName: connection_id_index
KeySchema:
- AttributeName: connection_id
KeyType: HASH
- AttributeName: topic_key
KeyType: RANGE
Projection:
ProjectionType: KEYS_ONLY
TimeToLiveSpecification:
AttributeName: ttl
Enabled: true
# -----------------------------
# Lambda layer
# -----------------------------
SharedLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: !Sub ${AWS::StackName}-shared
ContentUri: layers/shared/
CompatibleRuntimes:
- python3.11
# -----------------------------
# REST API (Hub)
# -----------------------------
HubApi:
Type: AWS::ApiGateway::RestApi
Properties:
Name: !Sub ${AWS::StackName}-hub-api
EndpointConfiguration:
Types:
- REGIONAL
HubApiFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/hub_api/
Handler: lambda_handler.handler
Layers:
- !Ref SharedLayer
Environment:
Variables:
DB_RESOURCE_ARN: !GetAtt AuroraCluster.DBClusterArn
DB_SECRET_ARN: !Ref DbCredentialsSecret
DB_NAME: !Ref DbName
TRANSCRIPT_QUEUE_URL: !Ref TranscriptQueue
ACTION_QUEUE_URL: !Ref ActionQueue
RECOGNITION_QUEUE_URL: !Ref RecognitionQueue
AUDIT_BUCKET: !Ref AuditBucket
ARTIFACT_BUCKET: !Ref ArtifactBucket
ADMIN_SECRET_ARN: !Ref AdminApiKeySecret
OPENAI_SECRET_ARN: !Ref OpenAISecret
LIVEKIT_URL: !Ref LiveKitUrl
LIVEKIT_SECRET_ARN: !Ref LiveKitSecret
# Cognito settings
COGNITO_REGION: !Ref AWS::Region
COGNITO_USER_POOL_ID: !Ref CognitoUserPool
COGNITO_APP_CLIENT_ID: !If [GoogleAuthEnabled, !Ref CognitoUserPoolClientGoogle, !Ref CognitoUserPoolClientNative]
COGNITO_DOMAIN: !If
- HasCognitoDomainPrefix
- !Sub ${CognitoDomainPrefix}.auth.${AWS::Region}.amazoncognito.com
- !Sub marvain-${StageName}-${AWS::AccountId}.auth.${AWS::Region}.amazoncognito.com
COGNITO_REDIRECT_URI: !Sub https://${HubApi}.execute-api.${AWS::Region}.amazonaws.com/${StageName}/auth/callback
COGNITO_IDENTITY_PROVIDER: !If [GoogleAuthEnabled, "Google", ""]
SESSION_SECRET_ARN: !Ref SessionSecret
STACK_NAME: !Ref AWS::StackName
WS_TABLE: !Ref WsConnectionsTable
WS_SUBSCRIPTIONS_TABLE: !Ref WsSubscriptionsTable
WS_API_ENDPOINT: !Sub https://${WsApi}.execute-api.${AWS::Region}.amazonaws.com/${StageName}
AUTO_APPROVE_POLICY_MODE: "enforce"
MARVAIN_METRICS_NAMESPACE: "Marvain"
MAX_SPACES_PER_AGENT: !Ref MaxSpacesPerAgent
Policies:
- AWSLambdaBasicExecutionRole
- DynamoDBCrudPolicy:
TableName: !Ref WsConnectionsTable
- DynamoDBCrudPolicy:
TableName: !Ref WsSubscriptionsTable
- Statement:
- Effect: Allow
Action:
- rds-data:ExecuteStatement
- rds-data:BatchExecuteStatement
- rds-data:BeginTransaction
- rds-data:CommitTransaction
- rds-data:RollbackTransaction
Resource: "*"
- Effect: Allow
Action:
- secretsmanager:GetSecretValue
Resource:
- !Ref DbCredentialsSecret
- !Ref AdminApiKeySecret
- !Ref OpenAISecret
- !Ref LiveKitSecret
- !Ref SessionSecret
- Effect: Allow
Action:
- sqs:SendMessage
- sqs:GetQueueAttributes
Resource:
- !GetAtt TranscriptQueue.Arn
- !GetAtt ActionQueue.Arn
- !GetAtt RecognitionQueue.Arn
- Effect: Allow
Action:
- logs:FilterLogEvents
- logs:DescribeLogStreams
Resource:
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${AWS::StackName}-ToolRunnerFunction*
- Effect: Allow
Action:
- s3:PutObject
- s3:GetObject
Resource:
- !Sub ${AuditBucket.Arn}/*
- !Sub ${ArtifactBucket.Arn}/*
- Effect: Allow
Action:
- execute-api:ManageConnections
Resource: "*"
# Explicit API Gateway integration (replaces Events section to avoid circular dependency)
HubApiPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref HubApiFunction
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HubApi}/*/*
HubApiResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref HubApi
ParentId: !GetAtt HubApi.RootResourceId
PathPart: "{proxy+}"
HubApiMethod:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref HubApi
ResourceId: !Ref HubApiResource
HttpMethod: ANY
AuthorizationType: NONE
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HubApiFunction.Arn}/invocations
# Add CORS support at the resource level
HubApiCorsMethod:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref HubApi
ResourceId: !Ref HubApiResource
HttpMethod: OPTIONS
AuthorizationType: NONE
Integration:
Type: MOCK
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Admin-Key'"
method.response.header.Access-Control-Allow-Methods: "'GET,POST,PUT,PATCH,DELETE,OPTIONS'"
method.response.header.Access-Control-Allow-Origin: "'*'"
RequestTemplates:
application/json: '{"statusCode": 200}'
MethodResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: true
method.response.header.Access-Control-Allow-Methods: true
method.response.header.Access-Control-Allow-Origin: true
# Root resource method for /
HubApiRootMethod:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref HubApi
ResourceId: !GetAtt HubApi.RootResourceId
HttpMethod: ANY
AuthorizationType: NONE
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HubApiFunction.Arn}/invocations
# Root resource CORS method
HubApiRootCorsMethod:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref HubApi
ResourceId: !GetAtt HubApi.RootResourceId
HttpMethod: OPTIONS
AuthorizationType: NONE
Integration:
Type: MOCK
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Admin-Key'"
method.response.header.Access-Control-Allow-Methods: "'GET,POST,PUT,PATCH,DELETE,OPTIONS'"
method.response.header.Access-Control-Allow-Origin: "'*'"
RequestTemplates:
application/json: '{"statusCode": 200}'
MethodResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: true
method.response.header.Access-Control-Allow-Methods: true
method.response.header.Access-Control-Allow-Origin: true
HubApiDeploymentV1:
Type: AWS::ApiGateway::Deployment
Condition: IsDeploymentV1
DependsOn:
- HubApiMethod
- HubApiCorsMethod
- HubApiRootMethod
- HubApiRootCorsMethod
Properties:
RestApiId: !Ref HubApi
Description: "Deployment v1"
HubApiDeploymentV2:
Type: AWS::ApiGateway::Deployment
Condition: IsDeploymentV2
DependsOn:
- HubApiMethod
- HubApiCorsMethod
- HubApiRootMethod
- HubApiRootCorsMethod
Properties:
RestApiId: !Ref HubApi
Description: "Deployment v2"
HubApiStage:
Type: AWS::ApiGateway::Stage
Properties:
RestApiId: !Ref HubApi
DeploymentId: !If [IsDeploymentV2, !Ref HubApiDeploymentV2, !Ref HubApiDeploymentV1]
StageName: !Ref StageName
MethodSettings:
- HttpMethod: "*"
ResourcePath: "/*"
ThrottlingBurstLimit: 50
ThrottlingRateLimit: 100
# -----------------------------
# Planner (deliberative loop)
# -----------------------------
PlannerFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/planner/
Handler: handler.handler
Timeout: 60
MemorySize: 1024
Layers:
- !Ref SharedLayer
Environment:
Variables:
DB_RESOURCE_ARN: !GetAtt AuroraCluster.DBClusterArn
DB_SECRET_ARN: !Ref DbCredentialsSecret
DB_NAME: !Ref DbName
ACTION_QUEUE_URL: !Ref ActionQueue
AUDIT_BUCKET: !Ref AuditBucket
OPENAI_SECRET_ARN: !Ref OpenAISecret
PLANNER_MODEL: !Ref PlannerModel
WS_TABLE: !Ref WsConnectionsTable
WS_SUBSCRIPTIONS_TABLE: !Ref WsSubscriptionsTable
WS_API_ENDPOINT: !Sub https://${WsApi}.execute-api.${AWS::Region}.amazonaws.com/${StageName}
AUTO_APPROVE_POLICY_MODE: "enforce"
MARVAIN_METRICS_NAMESPACE: "Marvain"
Policies:
- AWSLambdaBasicExecutionRole
- DynamoDBCrudPolicy:
TableName: !Ref WsConnectionsTable
- DynamoDBCrudPolicy:
TableName: !Ref WsSubscriptionsTable
- Statement:
- Effect: Allow
Action:
- rds-data:ExecuteStatement
- rds-data:BatchExecuteStatement
- rds-data:BeginTransaction
- rds-data:CommitTransaction
- rds-data:RollbackTransaction
Resource: "*"
- Effect: Allow
Action:
- secretsmanager:GetSecretValue
Resource:
- !Ref DbCredentialsSecret
- !Ref OpenAISecret
- Effect: Allow
Action:
- sqs:SendMessage
Resource:
- !GetAtt ActionQueue.Arn
- Effect: Allow
Action:
- s3:PutObject
Resource:
- !Sub ${AuditBucket.Arn}/*
- Effect: Allow
Action:
- execute-api:ManageConnections
Resource: "*"
Events:
TranscriptQueueEvent:
Type: SQS
Properties:
Queue: !GetAtt TranscriptQueue.Arn
BatchSize: 5
# -----------------------------
# Tool Runner (execution plane)
# -----------------------------
ToolRunnerFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/tool_runner/
Handler: handler.handler
Timeout: 60
MemorySize: 512
Layers:
- !Ref SharedLayer
Environment:
Variables:
DB_RESOURCE_ARN: !GetAtt AuroraCluster.DBClusterArn
DB_SECRET_ARN: !Ref DbCredentialsSecret
DB_NAME: !Ref DbName
AUDIT_BUCKET: !Ref AuditBucket
WS_TABLE: !Ref WsConnectionsTable
WS_SUBSCRIPTIONS_TABLE: !Ref WsSubscriptionsTable
WS_API_ENDPOINT: !Sub https://${WsApi}.execute-api.${AWS::Region}.amazonaws.com/${StageName}
DEVICE_RESULT_TIMEOUT_SECONDS: "90"
MARVAIN_METRICS_NAMESPACE: "Marvain"
Policies:
- AWSLambdaBasicExecutionRole
- DynamoDBCrudPolicy:
TableName: !Ref WsConnectionsTable
- DynamoDBCrudPolicy:
TableName: !Ref WsSubscriptionsTable
- Statement:
- Effect: Allow
Action:
- rds-data:ExecuteStatement
- rds-data:BatchExecuteStatement
- rds-data:BeginTransaction
- rds-data:CommitTransaction
- rds-data:RollbackTransaction
Resource: "*"
- Effect: Allow
Action:
- secretsmanager:GetSecretValue
Resource:
- !Ref DbCredentialsSecret
- Effect: Allow
Action:
- s3:PutObject
Resource:
- !Sub ${AuditBucket.Arn}/*
- Effect: Allow
Action:
- execute-api:ManageConnections
Resource: "*"
Events:
ActionQueueEvent:
Type: SQS
Properties:
Queue: !GetAtt ActionQueue.Arn
BatchSize: 5
ActionTimeoutSweeperFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/action_timeout_sweeper/
Handler: handler.handler
Timeout: 30
MemorySize: 256
Layers:
- !Ref SharedLayer
Environment:
Variables:
DB_RESOURCE_ARN: !GetAtt AuroraCluster.DBClusterArn
DB_SECRET_ARN: !Ref DbCredentialsSecret
DB_NAME: !Ref DbName
WS_TABLE: !Ref WsConnectionsTable
WS_SUBSCRIPTIONS_TABLE: !Ref WsSubscriptionsTable
WS_API_ENDPOINT: !Sub https://${WsApi}.execute-api.${AWS::Region}.amazonaws.com/${StageName}
ACTION_TIMEOUT_SWEEPER_BATCH_SIZE: "200"
MARVAIN_METRICS_NAMESPACE: "Marvain"
Policies:
- AWSLambdaBasicExecutionRole
- DynamoDBCrudPolicy:
TableName: !Ref WsConnectionsTable
- DynamoDBCrudPolicy:
TableName: !Ref WsSubscriptionsTable
- Statement:
- Effect: Allow
Action:
- rds-data:ExecuteStatement
- rds-data:BatchExecuteStatement
Resource: "*"
- Effect: Allow
Action:
- secretsmanager:GetSecretValue
Resource:
- !Ref DbCredentialsSecret
- Effect: Allow
Action:
- execute-api:ManageConnections
Resource: "*"
Events:
SweepSchedule:
Type: Schedule
Properties:
Schedule: rate(1 minute)
# -----------------------------
# WebSocket API (sideband control channel)
# -----------------------------
WsApi:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: !Sub ${AWS::StackName}-ws
ProtocolType: WEBSOCKET
RouteSelectionExpression: "$request.body.action"
WsConnectFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/ws_connect/
Handler: handler.handler
Layers:
- !Ref SharedLayer
Environment:
Variables:
WS_TABLE: !Ref WsConnectionsTable
WS_SUBSCRIPTIONS_TABLE: !Ref WsSubscriptionsTable
Policies:
- AWSLambdaBasicExecutionRole
- DynamoDBCrudPolicy:
TableName: !Ref WsConnectionsTable
- DynamoDBCrudPolicy:
TableName: !Ref WsSubscriptionsTable
WsDisconnectFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/ws_disconnect/
Handler: handler.handler
Layers:
- !Ref SharedLayer
Environment:
Variables:
WS_TABLE: !Ref WsConnectionsTable
WS_SUBSCRIPTIONS_TABLE: !Ref WsSubscriptionsTable
Policies:
- AWSLambdaBasicExecutionRole
- DynamoDBCrudPolicy:
TableName: !Ref WsConnectionsTable
- DynamoDBCrudPolicy:
TableName: !Ref WsSubscriptionsTable
WsMessageFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/ws_message/
Handler: handler.handler
Layers:
- !Ref SharedLayer
Environment:
Variables:
WS_TABLE: !Ref WsConnectionsTable
WS_SUBSCRIPTIONS_TABLE: !Ref WsSubscriptionsTable
WS_AUTH_TTL_SECONDS: "3600"
DB_RESOURCE_ARN: !GetAtt AuroraCluster.DBClusterArn
DB_SECRET_ARN: !Ref DbCredentialsSecret
DB_NAME: !Ref DbName
MARVAIN_METRICS_NAMESPACE: "Marvain"
Policies:
- AWSLambdaBasicExecutionRole
- DynamoDBCrudPolicy:
TableName: !Ref WsConnectionsTable
- DynamoDBCrudPolicy:
TableName: !Ref WsSubscriptionsTable
- Statement:
- Effect: Allow
Action:
- rds-data:ExecuteStatement
Resource: "*"
- Effect: Allow
Action:
- secretsmanager:GetSecretValue
Resource:
- !Ref DbCredentialsSecret
- Effect: Allow
Action:
- execute-api:ManageConnections
Resource: "*"
- Effect: Allow
Action:
- cognito-idp:GetUser
Resource: !GetAtt CognitoUserPool.Arn
WsConnectIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref WsApi
IntegrationType: AWS_PROXY
IntegrationUri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${WsConnectFunction.Arn}/invocations
WsDisconnectIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref WsApi
IntegrationType: AWS_PROXY
IntegrationUri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${WsDisconnectFunction.Arn}/invocations
WsMessageIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref WsApi
IntegrationType: AWS_PROXY
IntegrationUri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${WsMessageFunction.Arn}/invocations
WsConnectRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref WsApi
RouteKey: $connect
AuthorizationType: NONE
Target: !Join [ '/', [ 'integrations', !Ref WsConnectIntegration ] ]
WsDisconnectRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref WsApi
RouteKey: $disconnect
AuthorizationType: NONE
Target: !Join [ '/', [ 'integrations', !Ref WsDisconnectIntegration ] ]
WsDefaultRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref WsApi
RouteKey: $default
AuthorizationType: NONE
Target: !Join [ '/', [ 'integrations', !Ref WsMessageIntegration ] ]
WsDeployment:
Type: AWS::ApiGatewayV2::Deployment
DependsOn:
- WsConnectRoute
- WsDisconnectRoute
- WsDefaultRoute
Properties:
ApiId: !Ref WsApi
WsStage:
Type: AWS::ApiGatewayV2::Stage
Properties:
ApiId: !Ref WsApi
StageName: !Ref StageName
DeploymentId: !Ref WsDeployment
WsConnectPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref WsConnectFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WsApi}/*/$connect
WsDisconnectPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref WsDisconnectFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WsApi}/*/$disconnect
WsDefaultPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref WsMessageFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WsApi}/*/$default
# -----------------------------
# Cognito User Pool for Authentication
# -----------------------------
CognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: !Sub ${AWS::StackName}-users
AutoVerifiedAttributes:
- email
# IMPORTANT: UsernameAttributes is immutable. Must match existing pool exactly.
UsernameAttributes:
- email
UsernameConfiguration:
CaseSensitive: false
AdminCreateUserConfig:
AllowAdminCreateUserOnly: true
AccountRecoverySetting:
RecoveryMechanisms:
- Name: verified_email
Priority: 1
Policies:
PasswordPolicy:
MinimumLength: 8
RequireLowercase: true
RequireNumbers: true
RequireSymbols: false
RequireUppercase: true
# NOTE: Do not specify Schema - it's immutable and the existing pool has the default schema
CognitoGoogleIdentityProvider:
Type: AWS::Cognito::UserPoolIdentityProvider
Condition: GoogleAuthEnabled
Properties:
ProviderName: Google
ProviderType: Google
UserPoolId: !Ref CognitoUserPool
ProviderDetails:
client_id: !Sub '{{resolve:secretsmanager:${GoogleOAuthSecret}:SecretString:client_id}}'
client_secret: !Sub '{{resolve:secretsmanager:${GoogleOAuthSecret}:SecretString:client_secret}}'
authorize_scopes: "openid email profile"
AttributeMapping:
email: email
name: name
username: sub
given_name: given_name
family_name: family_name
picture: picture
CognitoUserPoolClientNative:
Type: AWS::Cognito::UserPoolClient
Condition: GoogleAuthDisabled
Properties:
ClientName: !Sub ${AWS::StackName}-app
UserPoolId: !Ref CognitoUserPool
GenerateSecret: false
AllowedOAuthFlows:
- code
AllowedOAuthFlowsUserPoolClient: true
AllowedOAuthScopes:
- openid
- email
- profile
- aws.cognito.signin.user.admin
CallbackURLs: !Ref GuiCallbackUrls
LogoutURLs: !Ref GuiLogoutUrls
SupportedIdentityProviders:
- COGNITO
ExplicitAuthFlows:
- ALLOW_USER_PASSWORD_AUTH
- ALLOW_USER_SRP_AUTH
- ALLOW_REFRESH_TOKEN_AUTH
CognitoUserPoolClientGoogle:
Type: AWS::Cognito::UserPoolClient
Condition: GoogleAuthEnabled
DependsOn:
- CognitoGoogleIdentityProvider
Properties:
ClientName: !Sub ${AWS::StackName}-app
UserPoolId: !Ref CognitoUserPool
GenerateSecret: false
AllowedOAuthFlows:
- code
AllowedOAuthFlowsUserPoolClient: true
AllowedOAuthScopes:
- openid
- email
- profile
- aws.cognito.signin.user.admin