forked from quantummaid/awswebsocketdemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cf-lambda.yml
313 lines (277 loc) · 14.5 KB
/
cf-lambda.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
---
AWSTemplateFormatVersion: '2010-09-09'
Description: "AWS Websocket Demo Lambda deployment."
Parameters:
StackIdentifier:
Type: String
Description: "Unique string to identify the stack"
ArtifactBucketName:
Type: String
Description: "S3 Bucket where jars are located"
ArtifactKey:
Type: String
Description: "S3 Key of the lamba jar to deploy"
LogRetentionInDays:
Type: Number
Description: "How many days the lambda and access logs are retained"
Default: 7
Resources:
##############
## DynamoDB ##
##############
WebsocketRegistryTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Ref StackIdentifier
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: "id"
AttributeType: "S"
KeySchema:
- AttributeName: "id"
KeyType: "HASH"
############
## Lambda ##
############
FunctionRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "${StackIdentifier}-FunctionRole"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: !Sub "${StackIdentifier}-FunctionRolePolicy"
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Resource: '*'
Effect: Allow
- PolicyName: !Sub "${StackIdentifier}-UseDBPolicy"
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- 'dynamodb:DeleteItem'
- 'dynamodb:GetItem'
- 'dynamodb:PutItem'
- 'dynamodb:Query'
- 'dynamodb:Scan'
- 'dynamodb:UpdateItem'
Resource: !Join ['', ["arn:aws:dynamodb:", !Sub "${AWS::Region}", ":", !Sub "${AWS::AccountId}", ":table/", !Ref WebsocketRegistryTable]]
Effect: Allow
- PolicyName: !Sub "${StackIdentifier}-Logging"
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- 'logs:*'
Resource: "*"
Effect: Allow
- PolicyName: !Sub "${StackIdentifier}-ExecuteApi"
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- 'execute-api:*'
Resource: "*"
Effect: Allow
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
FunctionResourcePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:invokeFunction
Principal: apigateway.amazonaws.com
FunctionName: !Ref Function
FunctionLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/${Function}"
RetentionInDays: !Ref LogRetentionInDays
Function:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${StackIdentifier}-Function"
Code:
S3Bucket: !Ref ArtifactBucketName
S3Key: !Ref ArtifactKey
Tags:
- Key: StackIdentifier
Value: !Ref StackIdentifier
MemorySize: 512
Handler: de.quantummaid.awswebsocketdemo.Lambda::handleRequest
Role: !GetAtt FunctionRole.Arn
Timeout: 20
Runtime: java11
Environment:
Variables:
WEBSOCKET_REGISTRY_TABLE: !Ref WebsocketRegistryTable
###########################
# Shared API Gateway setup
# required to solve error "CloudWatch Logs role ARN must be set in account settings to enable logging"
###########################
ApiGatewayPushToCloudWatchRole:
Type: "AWS::IAM::Role"
Properties:
Description: "Push logs to CloudWatch logs from API Gateway"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: apigateway.amazonaws.com
Action: "sts:AssumeRole"
ManagedPolicyArns:
- !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
ApiAccount:
Type: "AWS::ApiGateway::Account"
Properties:
CloudWatchRoleArn: !GetAtt ApiGatewayPushToCloudWatchRole.Arn
###########################
## HTTP LogGroup ##
###########################
HttpApiAccessLogs:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/apigateway/accesslogs/awswebsocketdemo/http-access-${StackIdentifier}"
RetentionInDays: !Ref LogRetentionInDays
#####################
## HTTP ApiGateway ##
#####################
HttpMaidHttpApiWithV1Payloads:
Type: "AWS::ApiGatewayV2::Api"
Properties:
Name: !Sub "${StackIdentifier} AWS Websocket Demo Http Lambda Proxy"
ProtocolType: HTTP
HttpMaidHttpApiWithV1PayloadsDefaultIntegration:
Type: AWS::ApiGatewayV2::Integration
DependsOn:
- HttpMaidHttpApiWithV1Payloads
Properties:
ApiId: !Ref HttpMaidHttpApiWithV1Payloads
IntegrationType: AWS_PROXY
PayloadFormatVersion: "2.0"
IntegrationUri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${StackIdentifier}-Function/invocations
HttpMaidHttpApiWithV1PayloadsDefaultRoute:
Type: AWS::ApiGatewayV2::Route
DependsOn:
- HttpMaidHttpApiWithV1Payloads
- HttpMaidHttpApiWithV1PayloadsDefaultIntegration
Properties:
ApiId: !Ref HttpMaidHttpApiWithV1Payloads
RouteKey: 'POST /{proxy+}'
Target: !Join ['/', [integrations, !Ref HttpMaidHttpApiWithV1PayloadsDefaultIntegration]]
AuthorizationType: NONE
HttpMaidHttpApiWithV1PayloadsDeployment:
Type: AWS::ApiGatewayV2::Deployment
DependsOn:
- HttpMaidHttpApiWithV1Payloads
- HttpMaidHttpApiWithV1PayloadsDefaultIntegration
- HttpMaidHttpApiWithV1PayloadsDefaultRoute
Properties:
ApiId: !Ref HttpMaidHttpApiWithV1Payloads
HttpMaidHttpApiWithV1PayloadsApiStage:
Type: AWS::ApiGatewayV2::Stage
DependsOn:
- HttpMaidHttpApiWithV1Payloads
- HttpMaidHttpApiWithV1PayloadsDeployment
Properties:
StageName: $default
ApiId: !Ref HttpMaidHttpApiWithV1Payloads
DeploymentId: !Ref HttpMaidHttpApiWithV1PayloadsDeployment
AccessLogSettings:
DestinationArn: !GetAtt HttpApiAccessLogs.Arn
Format: |
{"type":"http","accountId":"$context.accountId","apiId":"$context.apiId","authorizer.claims.property":"$context.authorizer.claims.property","authorizer.error":"$context.authorizer.error","authorizer.latency":"$context.authorizer.latency","authorizer.principalId":"$context.authorizer.principalId","authorizer.property":"$context.authorizer.property","authorizer.status":"$context.authorizer.status","awsEndpointRequestId":"$context.awsEndpointRequestId","awsEndpointRequestId2":"$context.awsEndpointRequestId2","dataProcessed":"$context.dataProcessed","domainName":"$context.domainName","domainPrefix":"$context.domainPrefix","error.message":"$context.error.message","error.messageString":"$context.error.messageString","error.responseType":"$context.error.responseType","extendedRequestId":"$context.extendedRequestId","httpMethod":"$context.httpMethod","identity.accountId":"$context.identity.accountId","identity.caller":"$context.identity.caller","identity.cognitoAuthenticationProvider":"$context.identity.cognitoAuthenticationProvider","identity.cognitoAuthenticationType":"$context.identity.cognitoAuthenticationType","identity.cognitoIdentityId":"$context.identity.cognitoIdentityId","identity.cognitoIdentityPoolId":"$context.identity.cognitoIdentityPoolId","identity.principalOrgId":"$context.identity.principalOrgId","identity.sourceIp":"$context.identity.sourceIp","identity.user":"$context.identity.user","identity.userAgent":"$context.identity.userAgent","identity.userArn":"$context.identity.userArn","integration.error":"$context.integration.error","integration.integrationStatus":"$context.integration.integrationStatus","integration.latency":"$context.integration.latency","integration.requestId":"$context.integration.requestId","integration.status":"$context.integration.status","integrationErrorMessage":"$context.integrationErrorMessage","integrationLatency":"$context.integrationLatency","integrationStatus":"$context.integrationStatus","path":"$context.path","protocol":"$context.protocol","requestId":"$context.requestId","requestTime":"$context.requestTime","requestTimeEpoch":"$context.requestTimeEpoch","responseLatency":"$context.responseLatency","responseLength":"$context.responseLength","routeKey":"$context.routeKey","stage":"$context.stage","status":"$context.status"}
###########################
## WebSockets LogGroup ##
###########################
WebsocketsApiAccessLogs:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/apigateway/accesslogs/awswebsocketdemo/websocket-access-${StackIdentifier}"
RetentionInDays: !Ref LogRetentionInDays
###########################
## WebSockets ApiGateway ##
###########################
HttpMaidWebsocketsApi:
DependsOn: ApiAccount
Type: AWS::ApiGatewayV2::Api
Properties:
Name: !Sub "${StackIdentifier} AWS Websocket Demo WebSockets Lambda Proxy"
ProtocolType: WEBSOCKET
RouteSelectionExpression: "$request.body.action"
Target: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${StackIdentifier}-Function/invocations
HttpMaidWebsocketsApiConnectRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref HttpMaidWebsocketsApi
RouteKey: $connect
AuthorizationType: NONE
RouteResponseSelectionExpression: $default
Target: !Join ['/', [integrations, !Ref HttpMaidWebsocketsApiConnectIntegration]] # See below
HttpMaidWebsocketsApiConnectIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref HttpMaidWebsocketsApi
Description: Integration for builtin $connect route
IntegrationType: AWS_PROXY
IntegrationUri:
!Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${StackIdentifier}-Function/invocations
HttpMaidWebsocketsApiDefaultRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref HttpMaidWebsocketsApi
RouteKey: $default
AuthorizationType: NONE
RouteResponseSelectionExpression: $default
Target: !Join ['/', [integrations, !Ref HttpMaidWebsocketsApiDefaultIntegration]]
HttpMaidWebsocketsApiDefaultIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref HttpMaidWebsocketsApi
IntegrationType: AWS_PROXY
IntegrationUri:
!Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${StackIdentifier}-Function/invocations
HttpMaidWebsocketsApiDefaultResponse:
Type: AWS::ApiGatewayV2::RouteResponse
Properties:
RouteId: !Ref HttpMaidWebsocketsApiDefaultRoute
ApiId: !Ref HttpMaidWebsocketsApi
RouteResponseKey: $default
HttpMaidWebsocketsApiDeployment:
Type: AWS::ApiGatewayV2::Deployment
DependsOn:
- HttpMaidWebsocketsApiDefaultRoute
- HttpMaidWebsocketsApiConnectRoute
- HttpMaidWebsocketsApiDefaultResponse
Properties:
ApiId: !Ref HttpMaidWebsocketsApi
HttpMaidWebsocketsApiStage:
Type: AWS::ApiGatewayV2::Stage
Properties:
StageName: !Ref StackIdentifier
DeploymentId: !Ref HttpMaidWebsocketsApiDeployment
ApiId: !Ref HttpMaidWebsocketsApi
AccessLogSettings:
DestinationArn: !GetAtt WebsocketsApiAccessLogs.Arn
Format: |
{"type":"websocket","apiId":"$context.apiId","authorize.error":"$context.authorize.error","authorize.latency":"$context.authorize.latency","authorize.status":"$context.authorize.status","authorizer.error":"$context.authorizer.error","authorizer.integrationLatency":"$context.authorizer.integrationLatency","authorizer.integrationStatus":"$context.authorizer.integrationStatus","authorizer.latency":"$context.authorizer.latency","authorizer.requestId":"$context.authorizer.requestId","authorizer.status":"$context.authorizer.status","authorizer.principalId":"$context.authorizer.principalId","authorizer.property":"$context.authorizer.property","authenticate.error":"$context.authenticate.error","authenticate.latency":"$context.authenticate.latency","authenticate.status":"$context.authenticate.status","connectedAt":"$context.connectedAt","connectionId":"$context.connectionId","domainName":"$context.domainName","error.message":"$context.error.message","error.messageString":"$context.error.messageString","error.responseType":"$context.error.responseType","error.validationErrorString":"$context.error.validationErrorString","eventType":"$context.eventType","extendedRequestId":"$context.extendedRequestId","identity.accountId":"$context.identity.accountId","identity.apiKey":"$context.identity.apiKey","identity.apiKeyId":"$context.identity.apiKeyId","identity.caller":"$context.identity.caller","identity.cognitoAuthenticationProvider":"$context.identity.cognitoAuthenticationProvider","identity.sourceIp":"$context.identity.sourceIp","identity.user":"$context.identity.user","identity.userAgent":"$context.identity.userAgent","identity.userArn":"$context.identity.userArn","integration.error":"$context.integration.error","integration.integrationStatus":"$context.integration.integrationStatus","integration.latency":"$context.integration.latency","integration.requestId":"$context.integration.requestId","integration.status":"$context.integration.status","integrationLatency":"$context.integrationLatency","messageId":"$context.messageId","requestId":"$context.requestId","requestTime":"$context.requestTime","requestTimeEpoch":"$context.requestTimeEpoch","routeKey":"$context.routeKey","stage":"$context.stage","status":"$context.status","waf.error":"$context.waf.error","waf.latency":"$context.waf.latency","waf.status":"$context.waf.status"}
Outputs:
HttpEndpoint:
Value: !Sub ${HttpMaidHttpApiWithV1Payloads.ApiEndpoint}
Export:
Name: !Sub ${StackIdentifier}-http-endpoint
WebSocketEndpoint:
Value: !Sub ${HttpMaidWebsocketsApi.ApiEndpoint}/${HttpMaidWebsocketsApiStage}
Export:
Name: !Sub ${StackIdentifier}-websocket-endpoint