-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathchannels.js
668 lines (599 loc) · 16.9 KB
/
channels.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
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
'use strict'
import logger from 'winston'
import axios from 'axios'
import * as Channels from '../model/channels'
import * as authorisation from './authorisation'
import * as polling from '../polling'
import * as routerMiddleware from '../middleware/router'
import * as server from '../server'
import * as tcpAdapter from '../tcpAdapter'
import * as utils from '../utils'
import {TransactionModelAPI} from '../model/transactions'
import {config} from '../config'
const {ChannelModel} = Channels
const MAX_BODY_AGE_MESSAGE = `Channel property maxBodyAgeDays has to be a number that's valid and requestBody or responseBody must be true.`
const TIMEOUT_SECONDS_MESSAGE = `Channel property timeoutSeconds has to be a number greater than 1 and less than an 3600`
config.polling = config.get('polling')
function isPathValid(channel) {
if (channel.routes != null) {
for (const route of Array.from(channel.routes)) {
// There cannot be both path and pathTransform. pathTransform must be valid
if (
(route.path && route.pathTransform) ||
(route.pathTransform && !/s\/.*\/.*/.test(route.pathTransform))
) {
return false
}
}
}
return true
}
/*
* Retrieves the list of active channels
*/
export async function getChannels(ctx) {
try {
ctx.body = await authorisation.getUserViewableChannels(ctx.authenticated)
} catch (err) {
utils.logAndSetResponse(
ctx,
500,
`Could not fetch all channels via the API: ${err}`,
'error'
)
}
}
function processPostAddTriggers(channel) {
if (channel.type && Channels.isChannelEnabled(channel)) {
if (
(channel.type === 'tcp' || channel.type === 'tls') &&
server.isTcpHttpReceiverRunning()
) {
return tcpAdapter.notifyMasterToStartTCPServer(channel._id, err => {
if (err) {
return logger.error(err)
}
})
} else if (channel.type === 'polling') {
return polling.registerPollingChannel(channel, err => {
if (err) {
return logger.error(err)
}
})
}
}
}
export function validateMethod(channel) {
const {methods = []} = channel || {}
if (methods.length === 0) {
return
}
if (!/http/i.test(channel.type || 'http')) {
return `Channel method can't be defined if channel type is not http`
}
const mapCount = methods.reduce((dictionary, method) => {
if (dictionary[method] == null) {
dictionary[method] = 0
}
dictionary[method] += 1
return dictionary
}, {})
const repeats = Object.keys(mapCount)
.filter(k => mapCount[k] > 1)
.sort()
if (repeats.length > 0) {
return `Channel methods can't be repeated. Repeated methods are ${repeats.join(
', '
)}`
}
}
export function isTimeoutValid(channel) {
if (channel.timeout == null) {
return true
}
return (
typeof channel.timeout === 'number' &&
channel.timeout > 0 &&
channel.timeout <= 3600000
)
}
export function isMaxBodyDaysValid(channel) {
if (channel.maxBodyAgeDays == null) {
return true
}
if (!channel.requestBody && !channel.responseBody) {
return false
}
return (
typeof channel.maxBodyAgeDays === 'number' &&
channel.maxBodyAgeDays > 0 &&
channel.maxBodyAgeDays < 36500
)
}
/*
* Creates a new channel
*/
export async function addChannel(ctx) {
// Test if the user is authorised
if (authorisation.inGroup('admin', ctx.authenticated) === false) {
utils.logAndSetResponse(
ctx,
403,
`User ${ctx.authenticated.email} is not an admin, API access to addChannel denied.`,
'info'
)
return
}
// Get the values to use
const channelData = ctx.request.body
// Set the user creating the channel for auditing purposes
channelData.updatedBy = utils.selectAuditFields(ctx.authenticated)
try {
const channel = new ChannelModel(channelData)
if (!isPathValid(channel)) {
ctx.body =
'Channel cannot have both path and pathTransform. pathTransform must be of the form s/from/to[/g]'
ctx.status = 400
return
}
if (channel.priority != null && channel.priority < 1) {
ctx.body = 'Channel priority cannot be below 1 (= Highest priority)'
ctx.status = 400
return
}
let methodValidation = validateMethod(channel)
if (methodValidation != null) {
ctx.body = methodValidation
ctx.status = 400
return
}
if (!isTimeoutValid(channel)) {
ctx.body = TIMEOUT_SECONDS_MESSAGE
ctx.status = 400
return
}
const numPrimaries = routerMiddleware.numberOfPrimaryRoutes(channel.routes)
if (numPrimaries === 0) {
ctx.body = 'Channel must have a primary route'
ctx.status = 400
return
}
if (numPrimaries > 1) {
ctx.body = 'Channel cannot have a multiple primary routes'
ctx.status = 400
return
}
if (!isMaxBodyDaysValid(channelData)) {
ctx.body = MAX_BODY_AGE_MESSAGE
ctx.status = 400
return
}
await channel.save()
// All ok! So set the result
ctx.body = 'Channel successfully created'
ctx.status = 201
logger.info(
`User ${ctx.authenticated.email} created channel with id ${channel.id}`
)
channelData._id = channel._id
processPostAddTriggers(channelData)
} catch (err) {
// Error! So inform the user
utils.logAndSetResponse(
ctx,
400,
`Could not add channel via the API: ${err}`,
'error'
)
}
}
/*
* Retrieves the details for a specific channel
*/
export async function getChannel(ctx, channelId) {
// Get the values to use
const id = unescape(channelId)
try {
// Try to get the channel
let result = null
let accessDenied = false
// if admin allow acces to all channels otherwise restrict result set
if (authorisation.inGroup('admin', ctx.authenticated) === false) {
result = await ChannelModel.findOne({
_id: id,
txViewAcl: {$in: ctx.authenticated.groups}
}).exec()
const adminResult = await ChannelModel.findById(id).exec()
if (adminResult != null) {
accessDenied = true
}
} else {
result = await ChannelModel.findById(id).exec()
}
// Test if the result if valid
if (result === null) {
if (accessDenied) {
// Channel exists but this user doesn't have access
ctx.body = `Access denied to channel with Id: '${id}'.`
ctx.status = 403
} else {
// Channel not found! So inform the user
ctx.body = `We could not find a channel with Id:'${id}'.`
ctx.status = 404
}
} else {
// All ok! So set the result
ctx.body = result
}
} catch (err) {
// Error! So inform the user
utils.logAndSetResponse(
ctx,
500,
`Could not fetch channel by Id '${id}' via the API: ${err}`,
'error'
)
}
}
export async function getChannelByName(ctx, channelName) {
// Get the values to use
const name = channelName
try {
// Try to get the channel
let result = null
let accessDenied = false
// if admin allow acces to all channels otherwise restrict result set
if (authorisation.inGroup('admin', ctx.authenticated) === false) {
result = await ChannelModel.findOne({
name: name,
txViewAcl: {$in: ctx.authenticated.groups}
}).exec()
const adminResult = await ChannelModel.findOne({
name: name
}).exec()
if (adminResult != null) {
accessDenied = true
}
} else {
result = await ChannelModel.findOne({
name: name
}).exec()
}
// Test if the result if valid
if (result === null) {
if (accessDenied) {
// Channel exists but this user doesn't have access
ctx.body = `Access denied to channel with name: '${name}'.`
ctx.status = 403
} else {
// Channel not found! So inform the user
ctx.body = `We could not find a channel with name:'${name}'.`
ctx.status = 404
}
} else {
// All ok! So set the result
ctx.body = result
}
} catch (err) {
// Error! So inform the user
utils.logAndSetResponse(
ctx,
500,
`Could not fetch channel by name '${name}' via the API: ${err}`,
'error'
)
}
}
export async function getChannelAudits(ctx, channelId) {
if (!authorisation.inGroup('admin', ctx.authenticated)) {
utils.logAndSetResponse(
ctx,
403,
`User ${ctx.authenticated.email} is not an admin, API access to addChannel denied.`,
'info'
)
return
}
try {
const channel = await ChannelModel.findById(channelId).exec()
if (channel) {
ctx.body = await channel.patches
.find({
$and: [
{ref: channel.id},
{ops: {$elemMatch: {path: {$ne: '/lastBodyCleared'}}}}
]
})
.sort({_id: -1})
.exec()
} else {
ctx.body = []
}
} catch (err) {
utils.logAndSetResponse(
ctx,
500,
`Could not fetch all channels via the API: ${err}`,
'error'
)
}
}
function processPostUpdateTriggers(channel) {
if (channel.type) {
if (
(channel.type === 'tcp' || channel.type === 'tls') &&
server.isTcpHttpReceiverRunning()
) {
if (Channels.isChannelEnabled(channel)) {
return tcpAdapter.notifyMasterToStartTCPServer(channel._id, err => {
if (err) {
return logger.error(err)
}
})
} else {
return tcpAdapter.notifyMasterToStopTCPServer(channel._id, err => {
if (err) {
return logger.error(err)
}
})
}
} else if (channel.type === 'polling') {
if (Channels.isChannelEnabled(channel)) {
return polling.registerPollingChannel(channel, err => {
if (err) {
return logger.error(err)
}
})
} else {
return polling.removePollingChannel(channel, err => {
if (err) {
return logger.error(err)
}
})
}
}
}
}
async function findChannelByIdAndUpdate(id, channelData) {
const channel = await ChannelModel.findById(id)
if (
channelData.maxBodyAgeDays != null &&
channel.maxBodyAgeDays != null &&
channelData.maxBodyAgeDays !== channel.maxBodyAgeDays
) {
channelData.lastBodyCleared = undefined
}
channel.set(channelData)
return channel.save()
}
/*
* Updates the details for a specific channel
*/
export async function updateChannel(ctx, channelId) {
// Test if the user is authorised
if (authorisation.inGroup('admin', ctx.authenticated) === false) {
utils.logAndSetResponse(
ctx,
403,
`User ${ctx.authenticated.email} is not an admin, API access to updateChannel denied.`,
'info'
)
return
}
// Get the values to use
const id = unescape(channelId)
const channelData = ctx.request.body
// Set the user updating the channel for auditing purposes
channelData.updatedBy = utils.selectAuditFields(ctx.authenticated)
const updatedChannel = await ChannelModel.findById(id)
// This is so you can see how the channel will look as a whole before saving
updatedChannel.set(channelData)
if (
!utils.isNullOrWhitespace(channelData.type) &&
utils.isNullOrEmpty(channelData.methods)
) {
// Empty the methods if the type has changed from http
if (channelData.type !== 'http') {
channelData.methods = []
}
} else {
const {type} = updatedChannel
let {methods} = updatedChannel
let methodValidation = validateMethod({type, methods})
if (methodValidation != null) {
ctx.body = methodValidation
ctx.status = 400
return
}
}
if (!isTimeoutValid(channelData)) {
ctx.body = TIMEOUT_SECONDS_MESSAGE
ctx.status = 400
return
}
// Ignore _id if it exists, user cannot change the internal id
if (typeof channelData._id !== 'undefined') {
delete channelData._id
}
if (!isPathValid(channelData)) {
utils.logAndSetResponse(
ctx,
400,
'Channel cannot have both path and pathTransform. pathTransform must be of the form s/from/to[/g]',
'info'
)
return
}
if (channelData.priority != null && channelData.priority < 1) {
ctx.body = 'Channel priority cannot be below 1 (= Highest priority)'
ctx.status = 400
return
}
if (channelData.routes != null) {
const numPrimaries = routerMiddleware.numberOfPrimaryRoutes(
channelData.routes
)
if (numPrimaries === 0) {
ctx.body = 'Channel must have a primary route'
ctx.status = 400
return
}
if (numPrimaries > 1) {
ctx.body = 'Channel cannot have a multiple primary routes'
ctx.status = 400
return
}
}
if (!isTimeoutValid(updatedChannel)) {
ctx.body = TIMEOUT_SECONDS_MESSAGE
ctx.status = 400
return
}
if (!isMaxBodyDaysValid(updatedChannel)) {
ctx.body = MAX_BODY_AGE_MESSAGE
ctx.status = 400
return
}
try {
const channel = await findChannelByIdAndUpdate(id, channelData)
// All ok! So set the result
ctx.body = 'The channel was successfully updated'
logger.info(`User ${ctx.authenticated.email} updated channel with id ${id}`)
return processPostUpdateTriggers(channel)
} catch (err) {
// Error! So inform the user
utils.logAndSetResponse(
ctx,
500,
`Could not update channel by id: ${id} via the API: ${err}`,
'error'
)
}
}
function processPostDeleteTriggers(channel) {
if (channel.type) {
if (
(channel.type === 'tcp' || channel.type === 'tls') &&
server.isTcpHttpReceiverRunning()
) {
return tcpAdapter.notifyMasterToStopTCPServer(channel._id, err => {
if (err) {
return logger.error(err)
}
})
} else if (channel.type === 'polling') {
return polling.removePollingChannel(channel, err => {
if (err) {
return logger.error(err)
}
})
}
}
}
/*
* Deletes a specific channels details
*/
export async function removeChannel(ctx, channelId) {
// Test if the user is authorised
if (authorisation.inGroup('admin', ctx.authenticated) === false) {
utils.logAndSetResponse(
ctx,
403,
`User ${ctx.authenticated.email} is not an admin, API access to removeChannel denied.`,
'info'
)
return
}
// Get the values to use
const id = unescape(channelId)
try {
let channel
const numExistingTransactions = await TransactionModelAPI.countDocuments({
channelID: id
}).exec()
// Try to get the channel (Call the function that emits a promise and Koa will wait for the function to complete)
if (numExistingTransactions === 0) {
// safe to remove
channel = await ChannelModel.findByIdAndRemove(id).exec()
} else {
// not safe to remove. just flag as deleted
channel = await findChannelByIdAndUpdate(id, {
status: 'deleted',
updatedBy: utils.selectAuditFields(ctx.authenticated)
})
}
// All ok! So set the result
ctx.body = 'The channel was successfully deleted'
logger.info(`User ${ctx.authenticated.email} removed channel with id ${id}`)
return processPostDeleteTriggers(channel)
} catch (err) {
// Error! So inform the user
utils.logAndSetResponse(
ctx,
500,
`Could not remove channel by id: ${id} via the API: ${err}`,
'error'
)
}
}
/*
* Manually Triggers Polling Channel
*/
export async function triggerChannel(ctx, channelId) {
// Test if the user is authorised
if (authorisation.inGroup('admin', ctx.authenticated) === false) {
utils.logAndSetResponse(
ctx,
403,
`User ${ctx.authenticated.email} is not an admin, API access to removeChannel denied.`,
'info'
)
return
}
// Get the values to use
const id = unescape(channelId)
// need to initialize return status otherwise will always return 404
ctx.status = 200
try {
const channel = await ChannelModel.findById(id).exec()
// Test if the result if valid
if (channel === null) {
// Channel not found! So inform the user
ctx.body = `We could not find a channel with Id:'${id}'.`
ctx.status = 404
return
} else {
logger.info(`Manually Polling channel ${channel._id}`)
const options = {
url: `http://${config.polling.host}:${config.polling.pollingPort}/trigger`,
headers: {
'channel-id': channel._id,
'X-OpenHIM-LastRunAt': new Date()
},
method: 'GET'
}
await new Promise(resolve => {
axios(options)
.then(() => {
logger.info(`Channel Successfully polled ${channel._id}`)
// Return success status
ctx.status = 200
resolve()
})
.catch(err => {
logger.error(err.message)
ctx.status = 500
resolve()
})
})
}
} catch (err) {
// Error! So inform the user
utils.logAndSetResponse(
ctx,
500,
`Could not fetch channel by Id '${id}' via the API: ${err}`,
'error'
)
}
}