forked from KnisterPeter/aws-api-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
573 lines (470 loc) · 14.5 KB
/
utils.js
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
const pRetry = require('p-retry')
const { utils } = require('@serverless/core')
const retry = (fn, opts = {}) => {
return pRetry(
async () => {
try {
return await fn()
} catch (error) {
if (error.code !== 'TooManyRequestsException') {
// Stop retrying and throw the error
throw new pRetry.AbortError(error)
}
throw error
}
},
{
retries: 5,
minTimeout: 1000,
factor: 2,
...opts
}
)
}
const apiExists = async ({ apig, apiId }) => {
try {
await apig.getRestApi({ restApiId: apiId }).promise()
return true
} catch (e) {
if (e.code === 'NotFoundException') {
return false
}
throw Error(e)
}
}
const createApi = async ({ apig, name, description, endpointTypes }) => {
const api = await apig
.createRestApi({
name,
description,
endpointConfiguration: {
types: endpointTypes
}
})
.promise()
return api.id
}
const getPathId = async ({ apig, apiId, endpoint }) => {
// todo this called many times to stay up to date. Is it worth the latency?
const existingEndpoints = (await apig
.getResources({
restApiId: apiId
})
.promise()).items
if (!endpoint) {
const rootResourceId = existingEndpoints.find(
(existingEndpoint) => existingEndpoint.path === '/'
).id
return rootResourceId
}
const endpointFound = existingEndpoints.find(
(existingEndpoint) => existingEndpoint.path === endpoint.path
)
return endpointFound ? endpointFound.id : null
}
const endpointExists = async ({ apig, apiId, endpoint }) => {
const resourceId = await retry(() => getPathId({ apig, apiId, endpoint }))
if (!resourceId) {
return false
}
const params = {
httpMethod: endpoint.method,
resourceId,
restApiId: apiId
}
try {
await retry(() => apig.getMethod(params).promise())
return true
} catch (e) {
if (e.code === 'NotFoundException') {
return false
}
}
}
const myEndpoint = (state, endpoint) => {
if (
state.endpoints &&
state.endpoints.find((e) => e.method === endpoint.method && e.path === endpoint.path)
) {
return true
}
return false
}
const validateEndpointObject = ({ endpoint, apiId, stage, region }) => {
const validMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'ANY']
if (typeof endpoint !== 'object') {
throw Error('endpoint must be an object')
}
if (!endpoint.method) {
throw Error(`missing method property for endpoint "${JSON.stringify(endpoint)}"`)
}
if (endpoint.path === '') {
throw Error(
`endpoint path cannot be an empty string for endpoint "${JSON.stringify(endpoint)}"`
)
}
if (!endpoint.path) {
throw Error(`missing path property for endpoint "${JSON.stringify(endpoint)}"`)
}
if (typeof endpoint.method !== 'string' || typeof endpoint.path !== 'string') {
throw Error(`invalid endpoint "${JSON.stringify(endpoint)}"`)
}
if (!validMethods.includes(endpoint.method.toUpperCase())) {
throw Error(`invalid method for endpoint "${JSON.stringify(endpoint)}"`)
}
if (endpoint.path !== '/') {
if (!endpoint.path.startsWith('/')) {
endpoint.path = `/${endpoint.path}`
}
if (endpoint.path.endsWith('/')) {
endpoint.path = endpoint.path.substring(0, endpoint.path.length - 1)
}
}
const validatedEndpoint = {
url: `https://${apiId}.execute-api.${region}.amazonaws.com/${stage}${endpoint.path}`,
path: endpoint.path,
method: endpoint.method.toUpperCase()
}
return { ...endpoint, ...validatedEndpoint }
}
const validateEndpoint = async ({ apig, apiId, endpoint, state, stage, region }) => {
const validatedEndpoint = validateEndpointObject({ endpoint, apiId, stage, region })
if (await endpointExists({ apig, apiId, endpoint: validatedEndpoint })) {
if (!myEndpoint(state, validatedEndpoint)) {
throw Error(
`endpoint ${validatedEndpoint.method} ${validatedEndpoint.path} already exists in provider`
)
}
}
return validatedEndpoint
}
const validateEndpoints = async ({ apig, apiId, endpoints, state, stage, region }) => {
const promises = []
for (const endpoint of endpoints) {
promises.push(validateEndpoint({ apig, apiId, endpoint, state, stage, region }))
}
return Promise.all(promises)
}
const createPath = async ({ apig, apiId, endpoint }) => {
const pathId = await getPathId({ apig, apiId, endpoint })
if (pathId) {
return pathId
}
const pathParts = endpoint.path.split('/')
const pathPart = pathParts.pop()
const parentEndpoint = { path: pathParts.join('/') }
let parentId
if (parentEndpoint.path === '') {
parentId = await getPathId({ apig, apiId })
} else {
parentId = await createPath({ apig, apiId, endpoint: parentEndpoint })
}
const params = {
pathPart,
parentId,
restApiId: apiId
}
const createdPath = await apig.createResource(params).promise()
return createdPath.id
}
const createPaths = async ({ apig, apiId, endpoints }) => {
const createdEndpoints = []
for (const endpoint of endpoints) {
endpoint.id = await createPath({ apig, apiId, endpoint })
createdEndpoints.push(endpoint)
}
return createdEndpoints
}
const createMethod = async ({ apig, apiId, endpoint }) => {
const params = {
authorizationType: 'NONE',
httpMethod: endpoint.method,
resourceId: endpoint.id,
restApiId: apiId,
apiKeyRequired: (typeof endpoint.apiKeyRequired !== "undefined") && endpoint.apiKeyRequired
}
if (endpoint.authorizerId) {
params.authorizationType = 'CUSTOM'
params.authorizerId = endpoint.authorizerId
}
try {
await apig.putMethod(params).promise()
} catch (e) {
if (e.code === 'ConflictException' && endpoint.authorizerId) {
// make sure authorizer config are always up to date
const updateMethodParams = {
httpMethod: endpoint.method,
resourceId: endpoint.id,
restApiId: apiId,
patchOperations: [
{
op: 'replace',
path: '/authorizationType',
value: 'CUSTOM'
},
{
op: 'replace',
path: '/authorizerId',
value: endpoint.authorizerId
}
]
}
await apig.updateMethod(updateMethodParams).promise()
} else if (e.code !== 'ConflictException') {
throw Error(e)
}
}
}
const createMethods = async ({ apig, apiId, endpoints }) => {
const promises = []
for (const endpoint of endpoints) {
promises.push(createMethod({ apig, apiId, endpoint }))
}
await Promise.all(promises)
return endpoints
}
const createIntegration = async ({ apig, lambda, apiId, endpoint }) => {
const isLambda = !!endpoint.function
let functionName, accountId, region
if (isLambda) {
functionName = endpoint.function.split(':')[6]
accountId = endpoint.function.split(':')[4]
region = endpoint.function.split(':')[3] // todo what if the lambda in another region?
}
const integrationParams = {
httpMethod: endpoint.method,
resourceId: endpoint.id,
restApiId: apiId,
type: isLambda ? 'AWS_PROXY' : 'HTTP_PROXY',
integrationHttpMethod: 'POST',
uri: isLambda
? `arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/${endpoint.function}/invocations`
: endpoint.proxyURI
}
try {
await apig.putIntegration(integrationParams).promise()
} catch (e) {
if (e.code === 'ConflictException') {
// this usually happens when there are too many endpoints for
// the same function. Retrying after couple of seconds ensures
// any pending integration requests are resolved.
await utils.sleep(2000)
return createIntegration({ apig, lambda, apiId, endpoint })
}
throw Error(e)
}
// Create lambda trigger for AWS_PROXY endpoints
if (isLambda) {
const permissionsParams = {
Action: 'lambda:InvokeFunction',
FunctionName: functionName,
Principal: 'apigateway.amazonaws.com',
SourceArn: `arn:aws:execute-api:${region}:${accountId}:${apiId}/*/*`,
StatementId: `${functionName}-${apiId}`
}
try {
await lambda.addPermission(permissionsParams).promise()
} catch (e) {
if (e.code !== 'ResourceConflictException') {
throw Error(e)
}
}
}
return endpoint
}
const createIntegrations = async ({ apig, lambda, apiId, endpoints }) => {
const promises = []
for (const endpoint of endpoints) {
promises.push(createIntegration({ apig, lambda, apiId, endpoint }))
}
return Promise.all(promises)
}
const createDeployment = async ({ apig, apiId, stage }) => {
const deployment = await apig.createDeployment({ restApiId: apiId, stageName: stage }).promise()
// todo add update stage functionality
return deployment.id
}
const removeMethod = async ({ apig, apiId, endpoint }) => {
const params = {
restApiId: apiId,
resourceId: endpoint.id,
httpMethod: endpoint.method
}
try {
await apig.deleteMethod(params).promise()
} catch (e) {
if (e.code !== 'NotFoundException') {
throw Error(e)
}
}
return {}
}
const removeMethods = async ({ apig, apiId, endpoints }) => {
const promises = []
for (const endpoint of endpoints) {
promises.push(removeMethod({ apig, apiId, endpoint }))
}
return Promise.all(promises)
}
const removeResource = async ({ apig, apiId, endpoint }) => {
try {
await apig.deleteResource({ restApiId: apiId, resourceId: endpoint.id }).promise()
} catch (e) {
if (e.code !== 'NotFoundException') {
throw Error(e)
}
}
return {}
}
const removeResources = async ({ apig, apiId, endpoints }) => {
const params = {
restApiId: apiId
}
const resources = await apig.getResources(params).promise()
const promises = []
for (const endpoint of endpoints) {
const resource = resources.items.find((resourceItem) => resourceItem.id === endpoint.id)
const childResources = resources.items.filter(
(resourceItem) => resourceItem.parentId === endpoint.id
)
const resourceMethods = resource ? Object.keys(resource.resourceMethods || {}) : []
// only remove resources if they don't have methods nor child resources
// to make sure we don't disrupt other services using the same api
if (resource && resourceMethods.length === 0 && childResources.length === 0) {
promises.push(removeResource({ apig, apiId, endpoint }))
}
}
if (promises.length === 0) {
return []
}
await Promise.all(promises)
return removeResources({ apig, apiId, endpoints })
}
const removeApi = async ({ apig, apiId }) => {
try {
await apig.deleteRestApi({ restApiId: apiId }).promise()
} catch (e) {}
}
const createAuthorizer = async ({ apig, lambda, apiId, endpoint }) => {
if (endpoint.authorizer) {
const authorizerName = endpoint.authorizer.split(':')[6]
const region = endpoint.authorizer.split(':')[3]
const accountId = endpoint.authorizer.split(':')[4]
const authorizers = await apig.getAuthorizers({ restApiId: apiId }).promise()
let authorizer = authorizers.items.find(
(authorizerItem) => authorizerItem.name === authorizerName
)
if (!authorizer) {
const createAuthorizerParams = {
name: authorizerName,
restApiId: apiId,
type: 'TOKEN',
authorizerUri: `arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/${endpoint.authorizer}/invocations`,
identitySource: 'method.request.header.Auth'
}
authorizer = await apig.createAuthorizer(createAuthorizerParams).promise()
const permissionsParams = {
Action: 'lambda:InvokeFunction',
FunctionName: authorizerName,
Principal: 'apigateway.amazonaws.com',
SourceArn: `arn:aws:execute-api:${region}:${accountId}:${apiId}/*/*`,
StatementId: `${authorizerName}-${apiId}`
}
try {
await lambda.addPermission(permissionsParams).promise()
} catch (e) {
if (e.code !== 'ResourceConflictException') {
throw Error(e)
}
}
}
endpoint.authorizerId = authorizer.id
}
return endpoint
}
const createAuthorizers = async ({ apig, lambda, apiId, endpoints }) => {
const updatedEndpoints = []
for (const endpoint of endpoints) {
endpoint.authorizerId = (await createAuthorizer({ apig, lambda, apiId, endpoint })).authorizerId
updatedEndpoints.push(endpoint)
}
return updatedEndpoints
}
const removeAuthorizer = async ({ apig, apiId, endpoint }) => {
// todo only remove authorizers that are not used by other services
if (endpoint.authorizerId) {
const updateMethodParams = {
httpMethod: endpoint.method,
resourceId: endpoint.id,
restApiId: apiId,
patchOperations: [
{
op: 'replace',
path: '/authorizationType',
value: 'NONE'
}
]
}
await apig.updateMethod(updateMethodParams).promise()
const deleteAuthorizerParams = { restApiId: apiId, authorizerId: endpoint.authorizerId }
await apig.deleteAuthorizer(deleteAuthorizerParams).promise()
}
return endpoint
}
const removeAuthorizers = async ({ apig, apiId, endpoints }) => {
const promises = []
for (const endpoint of endpoints) {
promises.push(removeAuthorizer({ apig, apiId, endpoint }))
}
await Promise.all(promises)
return endpoints
}
const removeOutdatedEndpoints = async ({ apig, apiId, endpoints, stateEndpoints }) => {
const outdatedEndpoints = []
const outdatedAuthorizers = []
for (const stateEndpoint of stateEndpoints) {
const endpointInUse = endpoints.find(
(endpoint) => endpoint.method === stateEndpoint.method && endpoint.path === stateEndpoint.path
)
const authorizerInUse = endpoints.find(
(endpoint) => endpoint.authorizerId === stateEndpoint.authorizerId
)
if (!endpointInUse) {
outdatedEndpoints.push(stateEndpoint)
} else if (!authorizerInUse) {
outdatedAuthorizers.push(stateEndpoint)
}
}
await removeResources({ apig, apiId, endpoints: outdatedEndpoints })
await removeMethods({ apig, apiId, endpoints: outdatedEndpoints })
await removeAuthorizers({ apig, apiId, endpoints: outdatedAuthorizers })
return outdatedEndpoints
}
module.exports = {
validateEndpointObject,
validateEndpoint,
validateEndpoints,
endpointExists,
myEndpoint,
apiExists,
createApi,
getPathId,
createAuthorizer,
createAuthorizers,
createPath,
createPaths,
createMethod,
createMethods,
createIntegration,
createIntegrations,
createDeployment,
removeMethod,
removeMethods,
removeResource,
removeResources,
removeAuthorizer,
removeAuthorizers,
removeApi,
removeOutdatedEndpoints,
retry
}