This repository has been archived by the owner on Jan 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpayid-stack.yaml
484 lines (428 loc) · 15.8 KB
/
payid-stack.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
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
AWSTemplateFormatVersion: "2010-09-09"
Description: "[v1.0] PayID Lambda Server and API Gateway front end"
Parameters:
domainName:
Type: "String"
AllowedPattern: "^[a-z0-9.]+$"
Description: "A domain that you can manage which you want your Pay IDs to be hosted at."
Resources:
listCertificatesFn:
Type: "AWS::Lambda::Function"
Properties:
Code:
ZipFile: |
const AWS = require('aws-sdk');
const response = require('cfn-response');
const acm = new AWS.ACM({region: 'us-east-1'});
exports.handler = function(event, context) {
acm.listCertificates({}, (err, data) => {
if (err) {
console.log(err);
response.send(event, context, response.FAILURE, {});
return;
}
const cert = data.CertificateSummaryList.find(c => c.DomainName === process.env.PAYID_DOMAIN);
console.log('found cert arn', cert.CertificateArn);
response.send(event, context, response.SUCCESS, { payIdCertArn: cert.CertificateArn });
});
};
Description: "Certificate lister for CloudFormation"
Environment:
Variables:
PAYID_DOMAIN: !Ref "domainName"
Handler: "index.handler"
MemorySize: 128
Role: !GetAtt "listCertificatesLambdaIAMRole.Arn"
Runtime: "nodejs12.x"
Timeout: 10
listCertificatesLambdaIAMRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "sts:AssumeRole"
Effect: "Allow"
Principal:
Service:
- "lambda.amazonaws.com"
Policies:
- PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Effect: "Allow"
Resource: "*"
PolicyName: "list-certificates-logs"
- PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "acm:ListCertificates"
Effect: "Allow"
Resource:
- "*"
PolicyName: "list-certificates-acm-role"
listCertificates:
Type: "Custom::listCertificatesFn"
Properties:
ServiceToken: !GetAtt "listCertificatesFn.Arn"
apiGateway:
Type: "AWS::ApiGateway::RestApi"
Properties:
Name: "payid-server-api"
Description: "API Gateway endpoints to invoke PayID Lambda"
apiGatewayPayIdResource:
Type: "AWS::ApiGateway::Resource"
Properties:
RestApiId: !Ref apiGateway
ParentId: !GetAtt
- apiGateway
- RootResourceId
PathPart: "{payId}"
apiGatewayRootMethod:
Type: "AWS::ApiGateway::Method"
Properties:
AuthorizationType: "NONE"
HttpMethod: "GET"
Integration:
IntegrationHttpMethod: "POST"
Type: "AWS_PROXY"
Uri: !Sub
- "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
- lambdaArn: !GetAtt "payIdServerLambdaFunction.Arn"
ResourceId: !GetAtt "apiGateway.RootResourceId"
RestApiId: !Ref "apiGateway"
apiGatewayPayIdMethod:
Type: "AWS::ApiGateway::Method"
Properties:
AuthorizationType: "NONE"
HttpMethod: "GET"
Integration:
IntegrationHttpMethod: "POST"
Type: "AWS_PROXY"
Uri: !Sub
- "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
- lambdaArn: !GetAtt "payIdServerLambdaFunction.Arn"
ResourceId: !Ref "apiGatewayPayIdResource"
RestApiId: !Ref "apiGateway"
apiGatewayDeployment:
Type: "AWS::ApiGateway::Deployment"
DependsOn:
- "apiGatewayRootMethod"
Properties:
RestApiId: !Ref "apiGateway"
StageName: "release"
apiGatewayCustomDomain:
Type: "AWS::ApiGateway::DomainName"
Properties:
CertificateArn: !GetAtt "listCertificates.payIdCertArn"
DomainName: !Ref "domainName"
SecurityPolicy: "TLS_1_2"
apiGatewayDomainResourceMapping:
Type: "AWS::ApiGateway::BasePathMapping"
DependsOn:
- "apiGatewayDeployment"
- "apiGatewayCustomDomain"
Properties:
DomainName: !Ref "domainName"
RestApiId: !Ref "apiGateway"
Stage: "release"
s3Bucket:
Type: "AWS::S3::Bucket"
Properties:
AccessControl: Private
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
writeTestAccountToS3Fn:
Type: "AWS::Lambda::Function"
Properties:
Code:
ZipFile: |
const AWS = require('aws-sdk');
const response = require('cfn-response');
const s3 = new AWS.S3();
exports.handler = function(event, context) {
const testAccount = {
addresses: [
{
paymentNetwork: "XRPL",
environment: "TESTNET",
addressDetailsType: "CryptoAddressDetails",
addressDetails: {
address: "T772A73My52QaUonaai6VE4X98zLu7VBQSXJKLYimjXDAJi"
}
}
],
payId: `testaccount$${process.env.PAYID_DOMAIN}`
};
const params = {
Bucket: process.env.PAYID_BUCKET,
Key: 'testaccount.json',
Body: JSON.stringify(testAccount),
ContentType: "application/json"
};
console.log('creating test account');
s3.putObject(params).promise().then(() => {
console.log('test account created');
response.send(event, context, response.SUCCESS, {});
}).catch((error) => {
console.log('Cannot create the test account but proceeding', error);
response.send(event, context, response.SUCCESS, {});
});
};
Description: "PayID Test Account Generator"
Environment:
Variables:
PAYID_BUCKET: !Ref "s3Bucket"
PAYID_DOMAIN: !Ref "domainName"
Handler: "index.handler"
MemorySize: 128
Role: !GetAtt "testAccountLambdaIAMRole.Arn"
Runtime: "nodejs12.x"
Timeout: 10
testAccountLambdaIAMRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "sts:AssumeRole"
Effect: "Allow"
Principal:
Service:
- "lambda.amazonaws.com"
Policies:
- PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Effect: "Allow"
Resource: "*"
PolicyName: "create-test-account-logs"
- PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "s3:*"
Effect: "Allow"
Resource:
- "*"
PolicyName: "create-test-account-s3"
writeTestAccountToS3:
Type: "Custom::writeTestAccountToS3Fn"
Properties:
ServiceToken: !GetAtt "writeTestAccountToS3Fn.Arn"
payIdServerLambdaFunction:
Type: "AWS::Lambda::Function"
Properties:
Code:
ZipFile: |
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const allAddressesHeader = 'application/payid+json'
const responseHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'PayID-Version',
'Access-Control-Expose-Headers': 'PayID-Version, PayID-Server-Version',
'Cache-Control': 'no-store',
};
const successResponse = {
statusCode: 200,
headers: responseHeaders,
};
const notFoundResponse = {
statusCode: 404,
}
// From payid/src/services/headers.ts
// This will throw if the regex doesn't match.
function parseAcceptHeader(acceptHeader) {
const ACCEPT_HEADER_REGEX = /^(?:application\/)(?<paymentNetwork>\w+)-?(?<environment>\w+)?(?:\+json)$/u
// TODO (tedkalaw): Support content negotiation?
// From payid/services/headers.ts
const lowerCaseMediaType = acceptHeader.toLowerCase();
const regexResult = ACCEPT_HEADER_REGEX.exec(lowerCaseMediaType);
return {
mediaType: lowerCaseMediaType,
// Optionally returns the environment (only if it exists)
...(regexResult && regexResult.groups && regexResult.groups.environment && {
environment: regexResult.groups.environment.toUpperCase(),
}),
paymentNetwork: regexResult && regexResult.groups && regexResult.groups.paymentNetwork.toUpperCase(),
}
}
exports.handler = async function(event, context) {
if (event.path === '/') {
return { ...successResponse, body: 'Welcome to PayID!' };
}
const payIdVersionHeader = event.headers['PayID-Version'];
if (payIdVersionHeader && payIdVersionHeader !== '1.0') {
return {
statusCode: 422,
body: 'Unknown PayID version set.',
};
}
const payId = event.pathParameters.payId;
const fullPayId = `${payId}$${process.env.PAYID_DOMAIN}`
try {
const params = {
Bucket: `${process.env.PAYID_BUCKET}`,
Key: `${payId}.json`,
};
const payIdResource = await s3.getObject(params).promise();
const payIdJson = JSON.parse(payIdResource.Body.toString());
const acceptHeader = event.headers.Accept;
if (!acceptHeader || acceptHeader === allAddressesHeader) {
return {
...successResponse,
body: JSON.stringify({
addresses: payIdJson.addresses,
payId: fullPayId
})
}
}
const {paymentNetwork, environment} = parseAcceptHeader(acceptHeader);
if (!paymentNetwork && !environment) {
return {
...successResponse,
body: JSON.stringify({
addresses: payIdJson.addresses,
payId: fullPayId
})
}
}
const selectedAddress = payIdJson.addresses
.find(a => a.paymentNetwork === paymentNetwork
&& (!environment || a.environment === environment)
);
if (!selectedAddress) {
return {
...notFoundResponse,
body: JSON.stringify({
...notFoundResponse,
error: 'Not found',
message: `Payment information for ${payId}$${process.env.PAYID_DOMAIN} could not be found.`,
})
};
}
const addressFoundResponse = {...successResponse }
addressFoundResponse.headers['Content-Type'] = acceptHeader;
return {
...addressFoundResponse,
body: JSON.stringify({
addresses: [selectedAddress],
payId: fullPayId
})
};
} catch (error) {
console.error('Uncaught exception handling PayID request', error);
return {
...notFoundResponse,
body: JSON.stringify({
...notFoundResponse,
message: 'PayID resource not found',
})
};
}
};
Description: "PayID Server"
Environment:
Variables:
PAYID_BUCKET: !Ref "s3Bucket"
PAYID_DOMAIN: !Ref "domainName"
Handler: "index.handler"
MemorySize: 128
Role: !GetAtt "lambdaIAMRole.Arn"
Runtime: "nodejs12.x"
Timeout: 10
lambdaApiGatewayInvoke:
Type: "AWS::Lambda::Permission"
Properties:
Action: "lambda:InvokeFunction"
FunctionName: !GetAtt "payIdServerLambdaFunction.Arn"
Principal: "apigateway.amazonaws.com"
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/GET/"
lambdaApiGatewayPayIdResourceInvoke:
Type: "AWS::Lambda::Permission"
Properties:
Action: "lambda:InvokeFunction"
FunctionName: !GetAtt "payIdServerLambdaFunction.Arn"
Principal: "apigateway.amazonaws.com"
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/GET/*"
lambdaIAMRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "sts:AssumeRole"
Effect: "Allow"
Principal:
Service:
- "lambda.amazonaws.com"
Policies:
- PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Effect: "Allow"
Resource: "*"
PolicyName: "payid-server-logs"
- PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "s3:*"
Effect: "Allow"
Resource:
- "*"
PolicyName: "payid-server-s3"
hostedZone:
Type: "AWS::Route53::HostedZone"
Properties:
Name: !Ref "domainName"
dnsForHostedZone:
Type: "AWS::Route53::RecordSetGroup"
Properties:
HostedZoneId: !Ref "hostedZone"
RecordSets:
- Name: !Sub "${domainName}."
Type: "A"
AliasTarget:
DNSName: !GetAtt "apiGatewayCustomDomain.DistributionDomainName"
HostedZoneId: !GetAtt "apiGatewayCustomDomain.DistributionHostedZoneId"
Outputs:
apiGatewayBaseURL:
Value: !Sub "https://${apiGateway}.execute-api.${AWS::Region}.amazonaws.com/"
apiGatewayInvokeURL:
Value: !Sub "https://${apiGateway}.execute-api.${AWS::Region}.amazonaws.com/release"
lambdaArn:
Value: !GetAtt "payIdServerLambdaFunction.Arn"
nameserver1:
Value: !Select [0, !GetAtt "hostedZone.NameServers"]
nameserver2:
Value: !Select [1, !GetAtt "hostedZone.NameServers"]
nameserver3:
Value: !Select [2, !GetAtt "hostedZone.NameServers"]
nameserver4:
Value: !Select [3, !GetAtt "hostedZone.NameServers"]
PayIdLambdaStackVersion:
Value: "v1.0"