forked from aws-samples/aws-serverless-workshops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend-api.yaml
424 lines (386 loc) · 13.8 KB
/
backend-api.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
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
---
AWSTemplateFormatVersion: "2010-09-09"
Description:
Creates the Lambda functions, DynamoDB table, and API Gateway endpoints for the web application workshop
Parameters:
UserPoolArn:
Type: String
Description: Wild Rydes Cognito User Pool ARN
WebsiteBucket:
Type: String
Description: The name for the bucket hosting your website, e.g. 'wildrydes-yourname.'
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
-
Label:
default: "Module 1 Details"
Parameters:
- WebsiteBucket
-
Label:
default: "Module 2 Details"
Parameters:
- UserPoolArn
ParameterLabels:
UserPoolArn:
default: "Cognito User Pool ARN"
WebsiteBucket:
default: "Website Bucket Name"
Resources:
RidesTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: Rides
AttributeDefinitions:
-
AttributeName: RideId
AttributeType: S
KeySchema:
-
AttributeName: RideId
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
RequestUnicornExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: WildRydesLambda
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- "sts:AssumeRole"
Path: "/wildrydes/"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
-
PolicyName: PutRidePolicy
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- dynamodb:PutItem
- dynamodb:Scan
Resource: !GetAtt RidesTable.Arn
RequestUnicornFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: RequestUnicorn
Runtime: nodejs6.10
Role: !GetAtt RequestUnicornExecutionRole.Arn
Timeout: 5
MemorySize: 128
Handler: index.handler
Code:
ZipFile: >
const randomBytes = require('crypto').randomBytes;
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();
const fleet = [
{
Name: 'Bucephalus',
Color: 'Golden',
Gender: 'Male',
},
{
Name: 'Shadowfax',
Color: 'White',
Gender: 'Male',
},
{
Name: 'Rocinante',
Color: 'Yellow',
Gender: 'Female',
},
];
exports.handler = (event, context, callback) => {
if (!event.requestContext.authorizer) {
errorResponse('Authorization not configured', context.awsRequestId, callback);
return;
}
const rideId = toUrlString(randomBytes(16));
console.log('Received event (', rideId, '): ', event);
// Because we're using a Cognito User Pools authorizer, all of the claims
// included in the authentication token are provided in the request context.
// This includes the username as well as other attributes.
const username = event.requestContext.authorizer.claims['cognito:username'];
// The body field of the event in a proxy integration is a raw string.
// In order to extract meaningful values, we need to first parse this string
// into an object. A more robust implementation might inspect the Content-Type
// header first and use a different parsing strategy based on that value.
const requestBody = JSON.parse(event.body);
const pickupLocation = requestBody.PickupLocation;
const unicorn = findUnicorn(pickupLocation);
recordRide(rideId, username, unicorn).then(() => {
// You can use the callback function to provide a return value from your Node.js
// Lambda functions. The first parameter is used for failed invocations. The
// second parameter specifies the result data of the invocation.
// Because this Lambda function is called by an API Gateway proxy integration
// the result object must use the following structure.
callback(null, {
statusCode: 201,
body: JSON.stringify({
RideId: rideId,
Unicorn: unicorn,
UnicornName: unicorn.Name,
Eta: '30 seconds',
Rider: username,
}),
headers: {
'Access-Control-Allow-Origin': '*',
},
});
}).catch((err) => {
console.error(err);
// If there is an error during processing, catch it and return
// from the Lambda function successfully. Specify a 500 HTTP status
// code and provide an error message in the body. This will provide a
// more meaningful error response to the end client.
errorResponse(err.message, context.awsRequestId, callback)
});
};
// This is where you would implement logic to find the optimal unicorn for
// this ride (possibly invoking another Lambda function as a microservice.)
// For simplicity, we'll just pick a unicorn at random.
function findUnicorn(pickupLocation) {
console.log('Finding unicorn for ', pickupLocation.Latitude, ', ', pickupLocation.Longitude);
return fleet[Math.floor(Math.random() * fleet.length)];
}
function recordRide(rideId, username, unicorn) {
return ddb.put({
TableName: 'Rides',
Item: {
RideId: rideId,
User: username,
Unicorn: unicorn,
RequestTime: new Date().toISOString(),
},
}).promise();
}
function toUrlString(buffer) {
return buffer.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
function errorResponse(errorMessage, awsRequestId, callback) {
callback(null, {
statusCode: 500,
body: JSON.stringify({
Error: errorMessage,
Reference: awsRequestId,
}),
headers: {
'Access-Control-Allow-Origin': '*',
},
});
}
WildRydesApi:
Type: AWS::ApiGateway::RestApi
Properties:
Name: WildRydes
Body:
swagger: 2.0
info:
version: 1.0.0
title: WildRydes
paths:
/ride:
post:
description: Requests a new ride
consumes:
- application/json
produces:
- application/json
security:
- CognitoAuthorizer: []
responses:
"200":
description: "200 response"
headers:
Access-Control-Allow-Origin:
type: "string"
x-amazon-apigateway-integration:
responses:
default:
statusCode: 200
responseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
uri:
Fn::Join:
- ""
- - "arn:aws:apigateway:"
- !Ref AWS::Region
- ":lambda:path/2015-03-31/functions/"
- !GetAtt RequestUnicornFunction.Arn
- "/invocations"
passthroughBehavior: "when_no_match"
httpMethod: "POST"
contentHandling: "CONVERT_TO_TEXT"
type: "aws_proxy"
options:
responses:
"200":
description: "200 response"
schema:
$ref: "#/definitions/Empty"
headers:
Access-Control-Allow-Origin:
type: "string"
Access-Control-Allow-Methods:
type: "string"
Access-Control-Allow-Headers:
type: "string"
x-amazon-apigateway-integration:
responses:
default:
statusCode: "200"
responseParameters:
method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS'"
method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
method.response.header.Access-Control-Allow-Origin: "'*'"
requestTemplates:
application/json: "{\"statusCode\": 200}"
passthroughBehavior: "when_no_match"
type: "mock"
securityDefinitions:
CognitoAuthorizer:
type: "apiKey"
name: Authorization
in: header
x-amazon-apigateway-authtype: cognito_user_pools
x-amazon-apigateway-authorizer:
providerARNs:
- !Ref UserPoolArn
type: "cognito_user_pools"
WildRydesApiDeployment:
Type: AWS::ApiGateway::Deployment
Properties:
Description: Prod deployment for wild Rydes API
RestApiId: !Ref WildRydesApi
StageName: prod
WildRydesFunctionPermissions:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref RequestUnicornFunction
Principal: apigateway.amazonaws.com
SourceArn:
Fn::Join:
- ""
- - "arn:aws:execute-api:"
- !Ref AWS::Region
- ":"
- !Ref AWS::AccountId
- ":"
- !Ref WildRydesApi
- "/*"
UpdateConfig:
Type: "Custom::ConfigFile"
Properties:
ServiceToken: !GetAtt UpdateConfigFunction.Arn
Bucket: !Ref WebsiteBucket
InvokeUrl:
Fn::Join:
- ""
- - "https://"
- !Ref WildRydesApi
- ".execute-api."
- !Ref AWS::Region
- ".amazonaws.com/prod"
UpdateConfigRole:
Type: AWS::IAM::Role
Properties:
Path: /wildrydes/
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
-
PolicyName: ApiConfig
PolicyDocument:
Version: 2012-10-17
Statement:
-
Sid: ConfigBucketWriteAccess
Effect: Allow
Action:
- "s3:PutObject"
- "s3:PutObjectAcl"
- "s3:PutObjectVersionAcl"
- "s3:GetObject"
Resource:
- !Sub "arn:aws:s3:::${WebsiteBucket}/*"
UpdateConfigFunction:
Type: AWS::Lambda::Function
Properties:
Description: Adds the API endpoint to the config.js file
Handler: index.handler
Runtime: python2.7
Role: !GetAtt UpdateConfigRole.Arn
Timeout: 120
Code:
ZipFile: |
import json
import boto3
import cfnresponse
s3 = boto3.resource('s3')
def create(properties, physical_id):
bucket = properties['Bucket']
config_object = s3.Object(bucket, 'js/config.js').get()
config_data = config_object["Body"].read()
config_data = config_data.replace("invokeUrl: ''", "invokeUrl: '%s'" % properties["InvokeUrl"])
config = s3.Object(bucket,'js/config.js')
config.put(Body=config_data)
return cfnresponse.SUCCESS, None
def update(properties, physical_id):
return create(properties, physical_id)
def delete(properties, physical_id):
return cfnresponse.SUCCESS, physical_id
def handler(event, context):
print "Received event: %s" % json.dumps(event)
status = cfnresponse.FAILED
new_physical_id = None
try:
properties = event.get('ResourceProperties')
physical_id = event.get('PhysicalResourceId')
status, new_physical_id = {
'Create': create,
'Update': update,
'Delete': delete
}.get(event['RequestType'], lambda x, y: (cfnresponse.FAILED, None))(properties, physical_id)
except Exception as e:
print "Exception: %s" % e
status = cfnresponse.FAILED
finally:
cfnresponse.send(event, context, status, {}, new_physical_id)
Outputs:
WildRydesApiInvokeUrl:
Description: URL for the deployed wild rydes API
Value:
Fn::Join:
- ""
- - "https://"
- !Ref WildRydesApi
- ".execute-api."
- !Ref AWS::Region
- ".amazonaws.com/prod"
Export:
Name: WildRydesApiUrl