-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathserverless.yaml
341 lines (319 loc) · 11.1 KB
/
serverless.yaml
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
service: myapp${{env:SERVERLESS_SERVICE_SUFFIX, ''}}
provider:
name: aws
stackName: ${{self:service}}-${{self:provider.stage}}
runtime: nodejs12.x
memorySize: 1024
timeout: 6
stage: ${{opt:stage, env:NODE_ENV, 'development'}}
profile: ${{self:custom.stageConfig.profile}}
region: us-east-1
variableSyntax: "\\${{([ ~:a-zA-Z0-9._@\\'\",\\-\\/\\(\\)]+?)}}"
logs:
restApi:
format: '{ "requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "caller":"$context.identity.caller", "user":"$context.identity.user", "requestTime":"$context.requestTime", "httpMethod":"$context.httpMethod", "resourcePath":"$context.resourcePath", "status":"$context.status", "protocol":"$context.protocol", "responseLength":"$context.responseLength" }'
level: INFO # TODO: add custom field for setting this; default to ERROR for prod
environment:
USER_TABLE: !Ref UserTable
# Enable connection reuse for AWS SDK for instant performance boost
# https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/node-reusing-connections.html
AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1
package:
individually: true
plugins:
- serverless-dotenv-plugin
- serverless-domain-manager
- serverless-prune-plugin
- serverless-plugin-tracing
- serverless-iam-roles-per-function
- serverless-webpack
# - serverless-apigateway-service-proxy
# - serverless-plugin-split-stacks
- serverless-stack-output
- serverless-cloudside-plugin
- serverless-plugin-aws-alerts
# - '../serverless-amplify-plugin'
- '@wizeline/serverless-amplify-plugin'
- serverless-offline
- serverless-stack-termination-protection
custom:
stages:
development:
profile: myapp_dev
amplify:
api:
domainEnabled: false
alarms:
notificationEmail: ${{env:ALARMS_NOTIFICATION_EMAIL}}
staging:
profile: myapp_staging
api:
domainEnabled: false
domainName: staging.api.example.com
validationDomain: example.com
amplify:
# domainName: staging.example.com
# branch: staging
alarms:
notificationEmail: [email protected]
production:
profile: myapp_prod
api:
domainEnabled: false
domainName: api.example.com
validationDomain: example.com
amplify:
# domainName: example.com
alarms:
notificationEmail: [email protected]
stageConfig: ${{self:custom.stages.${{self:provider.stage}}}}
prune:
automatic: true
number: 10
customDomain:
domainName: ${{self:custom.stageConfig.api.domainName, ''}}
certificateName: ${{self:custom.stageConfig.api.domainName, ''}}
enabled: ${{self:custom.stageConfig.api.domainEnabled, false}}
# createRoute53Record: ${{self:custom.stageConfig.api.isDomainRoute53, false}}
serverless-offline:
httpPort: 4911
noPrependStageInUrl: true
useChildProcesses: true # hack to get watching working
useSeparateProcesses: true
amplify:
isManual: true
domainName: ${{self:custom.stageConfig.amplify.domainName, ''}}
buildSpecValues:
artifactBaseDirectory: packages/ui/build
preBuildWorkingDirectory: packages/ui
buildCommandEnvVars:
prefix: 'REACT_APP_'
allow:
- ApiEndpoint
- CognitoIdentityPoolId,
- CognitoUserPoolId,
- CognitoUserPoolClientId,
webpack:
webpackConfig: ./functions.webpack.config.js
output:
file: ./stack-outputs.json
# TODO: Add custom splitting with ./split-stack-splitter.js
# splitStacks:
# perFunction: true
# custom: ./split-stack-splitter.js
alerts:
dashboards: true
nameTemplate: $[functionName]-$[metricName]-Alarm
topics:
alarm:
topic: ${{self:service}}-${{self:provider.stage}}-alarm
notifications:
- protocol: email
endpoint: ${{self:custom.stageConfig.alarms.notificationEmail}}
# TODO: Add short and long alarms for each
alarms:
- functionThrottles
- functionErrors
- functionInvocations
- functionDuration
serverlessTerminationProtection:
stages:
- staging
- production
functions:
express:
handler: packages/api/functions/express/lambda.handler
events:
- http:
method: ANY
path: /
cors: true
authorizer:
type: COGNITO_USER_POOLS
authorizerId: !Ref ApiGatewayAuthorizer
# name: CognitoAuthorizer
# type: COGNITO_USER_POOLS
# arn: !GetAtt CognitoUserPool.Arn
- http:
method: ANY
path: '{proxy+}'
cors: true
authorizer:
type: COGNITO_USER_POOLS
authorizerId: !Ref ApiGatewayAuthorizer
# NOTE: Instead of creating an Authorizer ourselves, we could use the below when this is fixed
# https://github.com/serverless/serverless/issues/3212#issuecomment-450574093
# name: CognitoAuthorizer
# type: COGNITO_USER_POOLS
# arn: !GetAtt CognitoUserPool.Arn
iamRoleStatements:
- Effect: "Allow"
Action:
- "xray:PutTraceSegments"
- "xray:PutTelemetryRecords"
Resource:
- "*"
- Effect: "Allow"
Action:
- dynamodb:BatchGetItem
- dynamodb:BatchWriteItem
- dynamodb:DeleteItem
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:Query
- dynamodb:Scan
- dynamodb:UpdateItem
Resource:
- !GetAtt UserTable.Arn
autoConfirmUser:
handler: packages/api/functions/cognito/auto-confirm-user.handler
postAuthN:
handler: packages/api/functions/cognito/post-authentication.handler
iamRoleStatements:
- Effect: "Allow"
Action:
- dynamodb:GetItem
- dynamodb:PutItem
Resource:
- !GetAtt UserTable.Arn
resources:
Conditions:
IsApiCustomDomainEnabled:
!Equals
- ${{self:custom.customDomain.enabled}}
- true
Resources:
AcmCertificate:
Type: AWS::CertificateManager::Certificate
Condition: IsApiCustomDomainEnabled
Properties:
DomainName: ${{self:custom.customDomain.domainName}}
DomainValidationOptions:
- DomainName: ${{self:custom.customDomain.domainName}}
ValidationDomain: ${{self:custom.stageConfig.api.validationDomain, ''}}
UserTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
PointInTimeRecoverySpecification:
PointInTimeRecoveryEnabled: false
KeySchema:
- KeyType: HASH
AttributeName: id
AttributeDefinitions:
- AttributeName: id
AttributeType: S
CognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
Policies:
PasswordPolicy:
MinimumLength: 6
Schema:
- AttributeDataType: String
Name: email
Required: true
AutoVerifiedAttributes:
- email
# EmailConfiguration:
# EmailSendingAccount: DEVELOPER
# ReplyToEmailAddress: [email protected]
# SourceArn: arn:aws:ses:us-east-1:xxxx:identity/[email protected]
LambdaConfig:
PreSignUp: !GetAtt AutoConfirmUserLambdaFunction.Arn
PostAuthentication: !GetAtt PostAuthNLambdaFunction.Arn
CognitoUserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
UserPoolId: !Ref CognitoUserPool
ClientName: CognitoIdentityPool
GenerateSecret: false
RefreshTokenValidity: 30
CognitoIdentityPool:
Type: AWS::Cognito::IdentityPool
Properties:
AllowUnauthenticatedIdentities: false
# SupportedLoginProviders:
# graph.facebook.com: 'xxxxx'
# accounts.google.com: 'xxxxx-v02jjpd5r9ig0pdacbhpill2asuqtvnf.apps.googleusercontent.com'
# api.twitter.com:
CognitoIdentityProviders:
- ClientId: !Ref CognitoUserPoolClient
ProviderName: !GetAtt CognitoUserPool.ProviderName
# Allow Cognito to invoke the cognitoAutoConfirm and cognitoPostAuthN functions
AutoConfirmUserLambdaCognitoPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt AutoConfirmUserLambdaFunction.Arn
Principal: cognito-idp.amazonaws.com
SourceArn: !GetAtt CognitoUserPool.Arn
PostAuthNLambdaCognitoPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt PostAuthNLambdaFunction.Arn
Principal: cognito-idp.amazonaws.com
SourceArn: !GetAtt CognitoUserPool.Arn
CognitoUserRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
# Allow authenticated users to assume this role
- Effect: Allow
Principal:
Federated: cognito-identity.amazonaws.com
Action: sts:AssumeRoleWithWebIdentity
Condition:
StringEquals:
'cognito-identity.amazonaws.com:aud': !Ref CognitoIdentityPool
'ForAnyValue:StringLike':
'cognito-identity.amazonaws.com:amr': authenticated
# Authenticated users are allowed to invoke the API
Policies:
- PolicyName: InvokeApi
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- execute-api:Invoke
Resource: !Sub 'arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ApiGatewayRestApi}/${{self:provider.stage}}/*/*'
Path: '/'
CognitoIdentityPoolRoles:
Type: AWS::Cognito::IdentityPoolRoleAttachment
Properties:
IdentityPoolId: !Ref CognitoIdentityPool
Roles:
authenticated: !GetAtt CognitoUserRole.Arn
# Due to a Serverless Framework bug, we need to create our own Authorizer, instead of
# simply specifying `authorizer.arn: !GetAtt CognitoUserPool.Arn` in the function.
# https://github.com/serverless/serverless/issues/3212#issuecomment-450574093
ApiGatewayAuthorizer:
DependsOn:
- ApiGatewayRestApi
Type: AWS::ApiGateway::Authorizer
Properties:
Name: CognitoAuthorizer
IdentitySource: method.request.header.Authorization
RestApiId:
Ref: ApiGatewayRestApi
Type: COGNITO_USER_POOLS
ProviderARNs:
- !GetAtt CognitoUserPool.Arn
Outputs:
CognitoUserPoolId:
Description: ID of the Cognito User Pool
Value: !Ref CognitoUserPool
CognitoUserPoolClientId:
Description: 'Client ID of the Cognito User Pool App: Identity Pool'
Value: !Ref CognitoUserPoolClient
CognitoIdentityPoolId:
Description: ID of the Cognito Identity Pool
Value: !Ref CognitoIdentityPool
UserTableName:
Value: !Ref UserTable
ApiEndpoint:
Value: !Sub https://${ApiGatewayRestApi}.execute-api.${AWS::Region}.amazonaws.com/${{self:provider.stage}}