-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-api-postbox.cform
702 lines (702 loc) · 29.1 KB
/
create-api-postbox.cform
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
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Creates an API Gateway allowing authorised callers to POST data, which is stored in SQS/S3",
"Parameters" : {
"APIName" : {
"Default" : "PostBox",
"Description" : "The name of the API",
"Type" : "String"
},
"APIDescription" : {
"Default" : "Allows data to be POSTed to AWS for processing",
"Description" : "Description of the API",
"Type" : "String"
},
"StageName" : {
"Default" : "beta",
"Description" : "The name for the API stage",
"Type" : "String"
},
"AuthorisationTokenHeaderName" : {
"Default" : "AuthDetails",
"Description" : "The name of the header containing the authorisation token",
"Type" : "String"
},
"AuthorisationTimeout" : {
"Default" : "10",
"Description" : "The TTL in seconds for authorisation token. Set to 0 for no authorisation caching",
"Type" : "Number",
"MinValue" : 0,
"MaxValue" : 3600
},
"LoggingTTL" : {
"Default" : 7,
"Description" : "The TTL in days for the logs generated by the Lambda function",
"Type" : "Number",
"AllowedValues" : [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]
},
"MaxProcessingAttempts" : {
"Default" : 5,
"Description" : "The number of times a message posted by Lambda can be retried prior to moving to Redrive",
"Type" : "Number",
"MinValue" : 1,
"MaxValue" : 100
},
"S3EndpointPrefixList" : {
"Description" : "The prefix list 'pl-xxxxxxx' value for S3 in the deployment region. Use 'aws ec2 describe-prefix-lists'",
"Type" : "String"
}
},
"Resources" : {
"RestApi": {
"Type": "AWS::ApiGateway::RestApi",
"Properties": {
"Name": { "Ref" : "APIName" },
"Description" : { "Ref" : "APIDescription" }
}
},
"SaveDataResourceName": {
"Type": "AWS::ApiGateway::Resource",
"Properties": {
"RestApiId": { "Ref" : "RestApi" },
"ParentId": { "Fn::GetAtt" : [ "RestApi", "RootResourceId" ] },
"PathPart": "publish"
}
},
"ResourceMethod": {
"Type": "AWS::ApiGateway::Method",
"DependsOn": [ "SaveDataLambda" ],
"Properties": {
"AuthorizationType" : "CUSTOM",
"AuthorizerId" : { "Ref" : "Authoriser" },
"HttpMethod" : "POST",
"Integration": {
"Type": "AWS_PROXY",
"IntegrationHttpMethod": "POST",
"Uri": {
"Fn::Join" : [ "",
[
"arn:aws:apigateway:",
{ "Ref" : "AWS::Region" },
":lambda:path/2015-03-31/functions/",
{ "Fn::GetAtt" : [ "SaveDataLambda", "Arn" ] },
"/invocations"
]
]
}
},
"ResourceId" : { "Ref" : "SaveDataResourceName" },
"RestApiId" : { "Ref" : "RestApi" }
}
},
"RestApiStage": {
"Type": "AWS::ApiGateway::Stage",
"DependsOn": [ "ResourceMethod" ],
"Properties": {
"DeploymentId": { "Ref" : "RestApiDeployment" },
"RestApiId": { "Ref" : "RestApi" },
"StageName": { "Ref" : "StageName" },
"TracingEnabled": true
}
},
"RestApiDeployment": {
"Type": "AWS::ApiGateway::Deployment",
"DependsOn": [ "ResourceMethod" ],
"Properties": {
"RestApiId": { "Ref" : "RestApi" }
}
},
"Authoriser" : {
"Type" : "AWS::ApiGateway::Authorizer",
"Properties" : {
"AuthorizerCredentials" : { "Fn::GetAtt" : [ "AuthoriserRole", "Arn" ] },
"AuthorizerResultTtlInSeconds" : { "Ref" : "AuthorisationTimeout" },
"AuthorizerUri" : {
"Fn::Join" : [ "",
[
"arn:aws:apigateway:",
{ "Ref" : "AWS::Region" },
":lambda:path/2015-03-31/functions/",
{ "Fn::GetAtt" : [ "LambdaAuthoriser", "Arn" ] },
"/invocations"
]
]
},
"IdentitySource" : { "Fn::Sub": [ "method.request.header.${HeaderName}", { "HeaderName": { "Ref" : "AuthorisationTokenHeaderName" } } ] },
"Name" : { "Ref" : "RestApi" },
"RestApiId" : { "Ref" : "RestApi" },
"Type" : "TOKEN"
}
},
"AuthoriserRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
},
"Path": "/",
"Policies": [
{
"PolicyName": "root",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action" : [ "lambda:InvokeFunction" ],
"Effect" : "Allow",
"Resource" : { "Fn::GetAtt" : [ "LambdaAuthoriser", "Arn" ] }
}
]
}
}
]
}
},
"LambdaAuthoriser": {
"Properties": {
"Code": {
"ZipFile": {
"Fn::Join": [
"\n",
[
"from uuid import uuid4",
"",
"def generate_policy(principal_id, effect, resource):",
" response = {}",
" ",
" response[\"principalId\"] = principal_id",
" if effect and resource:",
" policy = { ",
" \"Version\" : \"2012-10-17\",",
" \"Statement\" : [",
" {",
" \"Action\" : \"execute-api:Invoke\",",
" \"Effect\" : effect,",
" \"Resource\" : resource",
" }",
" ]",
" }",
" response[\"policyDocument\"] = policy",
"",
" # Can optionally return a context object of your choosing.",
" response[\"context\"] = {",
" \"aKey\" : \"Hello\",",
" \"bKey\" : 123",
" }",
" return response",
"",
"def validate_token(token):",
" # Comprehensive validation should be performed here",
" # based on a user_id embedded/derived from the token",
"",
" # Here we simply create unique ids for each call",
" user_id = str(uuid4())",
"",
" val = token.lower()",
" if val in [ \"allow\", \"deny\" ]:",
" m = { \"allow\" : \"Allow\", \"deny\": \"Deny\" }",
" return (user_id, m[val])",
" return (user_id, \"Deny\")",
"",
"def process(event):",
" token = event.get(\"authorizationToken\", \"\")",
" (user_id, status) = validate_token(token)",
" return generate_policy(user_id, status, event[\"methodArn\"])",
"",
"def lambda_handler(event, context):",
" return process(event)",
""
]
]
}
},
"Description": "Custom authorising Lambda for this API",
"Handler": "index.lambda_handler",
"MemorySize": 128,
"Role": { "Fn::GetAtt": [ "SaveDataLambdaRole", "Arn" ] },
"Runtime": "python2.7",
"Timeout": 5,
"TracingConfig" : {
"Mode" : "Active"
}
},
"Type": "AWS::Lambda::Function"
},
"Bucket": {
"Type" : "AWS::S3::Bucket",
"Description" : "Bucket that Lambda will store data within, by Region, with default SSE-S",
"Properties" : {
"AccessControl" : "Private",
"BucketEncryption" : {
"ServerSideEncryptionConfiguration" : [
{
"ServerSideEncryptionByDefault" : {
"SSEAlgorithm" : "AES256"
}
}
]
},
"LifecycleConfiguration" : {
"Rules" : [
{
"ExpirationInDays" : 14,
"Prefix" : "Data/",
"Status" : "Enabled"
}
]
}
}
},
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"DelaySeconds" : 3,
"MaximumMessageSize" : 1024,
"MessageRetentionPeriod" : 1209600,
"ReceiveMessageWaitTimeSeconds" : 20,
"RedrivePolicy" : {
"deadLetterTargetArn" : { "Fn::GetAtt" : [ "RedriveQueue", "Arn" ] },
"maxReceiveCount" : { "Ref" : "MaxProcessingAttempts" }
}
}
},
"RedriveQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"MessageRetentionPeriod" : 1209600
}
},
"SaveDataLambda" : {
"Type": "AWS::Lambda::Function",
"Properties" : {
"Code" : {
"ZipFile" : {
"Fn::Join": [
"\n",
[
"from json import dumps, loads",
"from datetime import datetime",
"import boto3",
"import botocore.config",
"import os",
"from uuid import uuid4",
"",
"BUCKET_NAME = os.environ['BucketName']",
"QUEUE_URL = os.environ['QueueURL']",
"REGION_NAME = os.environ['RegionName']",
"",
"# Using S3 VPC Endpoint requires 'path' style addressing, to avoid global url resolution",
"# Create client per: http://boto3.readthedocs.io/en/latest/guide/s3.html",
"S3_CLIENT = boto3.client('s3', REGION_NAME, config=botocore.config.Config(s3={'addressing_style':'path'}))",
"",
"# Initialise SQS client",
"SQSCLIENT = boto3.client('sqs')",
"",
"def save_data(data):",
" # Save the message to S3 and return the key",
" key = \"Data/{}\".format(str(uuid4()))",
" S3_CLIENT.put_object(",
" Bucket=BUCKET_NAME,",
" Key=key,",
" Body=data)",
" return key",
"",
"def post_message(key):",
" # Post the message to the SQS queue for onwards processing",
" SQSCLIENT.send_message(",
" QueueUrl=QUEUE_URL,",
" MessageBody=dumps(",
" {",
" \"Bucket\" : BUCKET_NAME,",
" \"Key\" : key,",
" \"SubmitDateTime\" : datetime.utcnow().isoformat('T')",
" }))",
"",
"def process(event):",
" # Processing goes here, returning status code of processing as well as result",
" # Here just return the value of supplied body attribute 'dt', if provided.",
" print(event)",
"",
" b = event.get('body', None)",
" if b != None and isinstance(b, (str, unicode)):",
" key = save_data(b)",
" post_message(key)",
" return (200, '')",
" return (500, 'Not found')",
"",
"def lambda_handler(event, context):",
" # Wrapper code to catch unexpected errors",
" try:",
" response = process(event)",
" return { \"statusCode\" : response[0], \"headers\" : {}, \"body\": dumps(response[1]) }",
" except Exception as e:",
" return { \"statusCode\" : 500, \"headers\" : {}, \"body\": \"Internal error: {}\".format(e) }",
""
]
]
}
},
"Description" : "Lambda saves data to S3 and queues reference on SQS",
"Environment" : {
"Variables" : {
"BucketName" : { "Ref": "Bucket" },
"QueueURL" : { "Ref" : "Queue" },
"RegionName" : { "Ref": "AWS::Region" }
}
},
"Handler" : "index.lambda_handler",
"MemorySize" : 128,
"Role" : { "Fn::GetAtt": [ "SaveDataLambdaRole", "Arn" ] },
"Runtime" : "python2.7",
"Timeout" : 5,
"TracingConfig" : {
"Mode" : "Active"
},
"VpcConfig" : {
"SecurityGroupIds" : [ { "Ref" : "SaveDataLambdaSecurityGroup" }],
"SubnetIds" : {
"Fn::Split" : [ ",",
{
"Fn::Sub" : [
"${Subnet1},${Subnet2}",
{
"Subnet1" : { "Ref" : "PrivateSubnet1" },
"Subnet2" : { "Ref" : "PrivateSubnet2" }
}
]
}
]
}
}
}
},
"SaveDataLambdaRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
},
"Path": "/",
"Policies": [
{
"PolicyName": "LoggingLambdaActivity",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*",
"Effect": "Allow"
}
]
}
},
{
"PolicyName": "X-RayTracing",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"xray:PutTraceSegments",
"xray:PutTelemetryRecords"
],
"Resource": "*",
"Effect": "Allow"
}
]
}
},
{
"PolicyName": "S3Publication",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect" : "Allow",
"Action" : "s3:PutObject",
"Resource": { "Fn::Sub" : [ "${Arn}/*", { "Arn" : { "Fn::GetAtt" : [ "Bucket", "Arn" ] } } ] }
}
]
}
},
{
"PolicyName": "VPCAccess",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect":"Allow",
"Action":[
"ec2:CreateNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DeleteNetworkInterface"
],
"Resource": [
"*"
]
}
]
}
},
{
"PolicyName": "SQSPublication",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect" : "Allow",
"Action" : "sqs:SendMessage",
"Resource": { "Fn::GetAtt" : [ "Queue", "Arn" ] }
}
]
}
}
]
}
},
"SaveDataLambdaLogGroup" : {
"Type" : "AWS::Logs::LogGroup",
"Properties" : {
"LogGroupName" : {
"Fn::Sub" : [ "/aws/lambda/${LambdaName}", { "LambdaName" : { "Ref" : "SaveDataLambda" } } ]
},
"RetentionInDays" : { "Ref" : "LoggingTTL" }
}
},
"LambdaAuthoriserLogGroup" : {
"Type" : "AWS::Logs::LogGroup",
"Properties" : {
"LogGroupName" : {
"Fn::Sub" : [ "/aws/lambda/${LambdaName}", { "LambdaName" : { "Ref" : "LambdaAuthoriser" } } ]
},
"RetentionInDays" : { "Ref" : "LoggingTTL" }
}
},
"APIResourceLambdaPermission": {
"Type": "AWS::Lambda::Permission",
"Properties": {
"Action": "lambda:InvokeFunction",
"FunctionName": { "Ref" : "SaveDataLambda" },
"Principal": "apigateway.amazonaws.com",
"SourceArn": {
"Fn::Join": [ "",
[
"arn:aws:execute-api:",
{ "Ref" : "AWS::Region" },
":",
{ "Ref" : "AWS::AccountId" },
":",
{ "Ref" : "RestApi" },
"/*/*"
]
]
}
}
},
"VPC": {
"Type": "AWS::EC2::VPC",
"Properties": {
"CidrBlock": "10.0.0.0/16",
"EnableDnsHostnames": true,
"EnableDnsSupport": true,
"InstanceTenancy": "default"
}
},
"InternetGateway" : {
"Type": "AWS::EC2::InternetGateway"
},
"AttachInternetGatewayToVPC" : {
"Type": "AWS::EC2::VPCGatewayAttachment",
"Properties": {
"VpcId" : { "Ref" : "VPC" },
"InternetGatewayId" : { "Ref" : "InternetGateway" }
}
},
"PublicSubnet1": {
"Type": "AWS::EC2::Subnet",
"Properties": {
"AvailabilityZone": { "Fn::Select" : [ "0", { "Fn::GetAZs" : "" } ] },
"CidrBlock": "10.0.64.0/24",
"VpcId": {
"Ref": "VPC"
}
}
},
"PublicSubnetRouteTable": {
"Type": "AWS::EC2::RouteTable",
"Properties": {
"VpcId": {
"Ref": "VPC"
}
}
},
"PublicSubnet1RouteTableAssociation": {
"Type": "AWS::EC2::SubnetRouteTableAssociation",
"Properties": {
"RouteTableId": { "Ref": "PublicSubnetRouteTable" },
"SubnetId": { "Ref": "PublicSubnet1" }
}
},
"PublicSubnetRouteToInternet" : {
"Type": "AWS::EC2::Route",
"Properties" : {
"RouteTableId" : { "Ref" : "PublicSubnetRouteTable" },
"DestinationCidrBlock" : "0.0.0.0/0",
"GatewayId" : { "Ref" : "InternetGateway" }
}
},
"NATEIP" : {
"Type" : "AWS::EC2::EIP",
"Properties" : {
"Domain" : "vpc"
}
},
"NAT" : {
"Type" : "AWS::EC2::NatGateway",
"Properties" : {
"AllocationId" : { "Fn::GetAtt" : [ "NATEIP", "AllocationId" ] },
"SubnetId" : { "Ref": "PublicSubnet1" }
}
},
"PrivateSubnetRouteTable": {
"Type": "AWS::EC2::RouteTable",
"Properties": {
"VpcId": {
"Ref": "VPC"
}
}
},
"PrivateSubnetRouteToInternet" : {
"Type": "AWS::EC2::Route",
"Properties" : {
"RouteTableId" : { "Ref" : "PrivateSubnetRouteTable" },
"DestinationCidrBlock" : "0.0.0.0/0",
"NatGatewayId" : { "Ref" : "NAT" }
}
},
"PrivateSubnet1": {
"Type": "AWS::EC2::Subnet",
"Properties": {
"AvailabilityZone": { "Fn::Select" : [ "0", { "Fn::GetAZs" : "" } ] },
"CidrBlock": "10.0.0.0/20",
"VpcId": {
"Ref": "VPC"
}
}
},
"PrivateSubnet1RouteTableAssociation": {
"Type": "AWS::EC2::SubnetRouteTableAssociation",
"Properties": {
"RouteTableId": { "Ref": "PrivateSubnetRouteTable" },
"SubnetId": { "Ref": "PrivateSubnet1" }
}
},
"PrivateSubnet2": {
"Type": "AWS::EC2::Subnet",
"Properties": {
"AvailabilityZone": { "Fn::Select" : [ "0", { "Fn::GetAZs" : "" } ] },
"CidrBlock": "10.0.33.0/20",
"VpcId": {
"Ref": "VPC"
}
}
},
"PrivateSubnet2RouteTableAssociation": {
"Type": "AWS::EC2::SubnetRouteTableAssociation",
"Properties": {
"RouteTableId": { "Ref": "PrivateSubnetRouteTable" },
"SubnetId": { "Ref": "PrivateSubnet2" }
}
},
"S3Endpoint" : {
"Type" : "AWS::EC2::VPCEndpoint",
"Properties" : {
"PolicyDocument" : {
"Version":"2012-10-17",
"Statement": [
{
"Effect" : "Allow",
"Principal" : "*",
"Action" : [ "s3:PutObject" ],
"Resource": [ { "Fn::Sub": [ "${Arn}/*", { "Arn": { "Fn::GetAtt" : [ "Bucket", "Arn" ] } } ] } ]
}
]
},
"RouteTableIds" : [ { "Ref" : "PrivateSubnetRouteTable" } ],
"ServiceName" : { "Fn::Sub" : [ "com.amazonaws.${Region}.s3", { "Region" : { "Ref" : "AWS::Region" } } ] },
"VpcId" : { "Ref" : "VPC" }
}
},
"SaveDataLambdaSecurityGroup" : {
"Type" : "AWS::EC2::SecurityGroup",
"Properties" : {
"GroupDescription" : "Security Group for SaveDataLambda Egress",
"VpcId" : { "Ref" : "VPC" },
"SecurityGroupEgress" : [
{
"DestinationPrefixListId" : { "Ref" : "S3EndpointPrefixList" },
"IpProtocol" : "-1"
},
{
"IpProtocol" : "tcp",
"FromPort" : 443,
"ToPort" : 443,
"CidrIp" : "0.0.0.0/0"
}
]
}
}
},
"Outputs" : {
"URL" : {
"Description" : "The URL to the deployed stage",
"Value" : {
"Fn::Join" : [ "",
[
"https://",
{ "Ref" : "RestApi" },
".execute-api.",
{ "Ref" : "AWS::Region" },
".amazonaws.com/",
{ "Ref" : "StageName" }
]
]
}
},
"Queue" : {
"Description" : "The URL to the message queue to retrieve for onwards processing",
"Value" : { "Ref" : "Queue" }
},
"ErrorQueue" : {
"Description" : "The URL to the message error queue",
"Value" : { "Ref" : "RedriveQueue" }
},
"BucketName" : {
"Description" : "The bucket in which the data is stored",
"Value" : { "Ref" : "Bucket" }
}
}
}