forked from arkime/arkime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiShortcuts.js
501 lines (441 loc) · 18.1 KB
/
apiShortcuts.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
/******************************************************************************/
/* apiShortcuts.js -- api calls for shortcuts
*
* Copyright Yahoo Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const Db = require('./db.js');
const util = require('util');
const ArkimeUtil = require('../common/arkimeUtil');
const User = require('../common/user');
const internals = require('./internals');
class Mutex {
constructor () {
this.queue = [];
this.locked = false;
}
lock () {
return new Promise((resolve, reject) => {
if (this.locked) {
this.queue.push(resolve);
} else {
this.locked = true;
resolve();
}
});
}
unlock () {
if (this.queue.length > 0) {
const resolve = this.queue.shift();
resolve();
} else {
this.locked = false;
}
}
}
class ShortcutAPIs {
// --------------------------------------------------------------------------
// HELPERS
// --------------------------------------------------------------------------
// https://stackoverflow.com/a/48569020
static #shortcutMutex = new Mutex();
// --------------------------------------------------------------------------
/**
* @private
*
* Normalizes the data in a shortcut by turning values and users string to arrays
* and removing the type parameter and replacing it with `type: values`
* Also validates that the users added to the shortcut are valid within the system
* NOTE: Mutates the shortcut directly
* @param {Shortcut} shortcut - The shortcut to normalize
* @returns {Object} {type, values, invalidusers} - The shortcut type (ip, string, number),
* array of values, and list of invalid users
*/
static async #normalizeShortcut (shortcut) {
// comma/newline separated value -> array of values
const values = ArkimeUtil.commaOrNewlineStringToArray(shortcut.value);
shortcut[shortcut.type] = values;
const type = shortcut.type;
delete shortcut.type;
delete shortcut.value;
// comma/newline separated value -> array of values
let users = ArkimeUtil.commaOrNewlineStringToArray(shortcut.users || '');
users = await User.validateUserIds(users);
shortcut.users = users.validUsers;
return { type, values, invalidUsers: users.invalidUsers };
}
// --------------------------------------------------------------------------
// APIs
// --------------------------------------------------------------------------
/**
* The shortcut object to store lists of values that can be used in search queries.
*
* @typedef Shortcut
* @type {object}
* @param {string} userId - The ID of the user that created the shortcut.
* @param {string} name - The name of the shortcut.
* @param {string} description - The description of the shortcut to display to users.
* @param {number[]} number - A list of number values to use as the shortcut value. A shortcut must contain a list of numbers, strings, or ips.
* @param {string[]} ip - A list of ip values to use as the shortcut value. A shortcut must contain a list of numbers, strings, or ips.
* @param {string[]} string - A list of string values to use as the shortcut value. A shortcut must contain a list of numbers, strings, or ips.
* @param {string} users - A list of userIds that have access to this shortcut.
* @param {string[]} roles - A list of Arkime roles that have access to this shortcut.
* @param {string[]} editRoles - A list of Arkime roles that have edit access to this shortcut.
* @param {boolean} locked=false - Whether the shortcut is locked and must be updated using the db.pl script (can't be updated in the web application user interface).
*/
// --------------------------------------------------------------------------
/**
* GET - /api/shortcuts
*
* Retrieves a list of shortcuts.
* @name /shortcuts
* @param {string} map=false - Whether to return a list or a map. Default is list.
* @param {string} sort=name - The field to sort the results by.
* @param {string} desc=true - Whether to sort the results descending or ascending. Default is descending.
* @param {string} searchTerm - The search text to filter the shortcut list by.
* @param {number} length=50 - The number of items to return. Defaults to 50.
* @param {number} start=0 - The entry to start at. Defaults to 0.
* @param {string} fieldType - Filter the results by type (number, ip, or string).
* @param {string} fieldFormat=false - Sends a help field with the shortcut with the description + the values of the shortcut.
* @returns {Shortcut[]} data - The list of shortcut results.
* @returns {number} recordsTotal - The total number of shortcut results stored.
* @returns {number} recordsFiltered - The number of shortcut items returned in this result.
*/
static async getShortcuts (req, res) {
// return nothing if we can't find the user
const user = req.settingUser;
if (!user) { return res.send({}); }
const allRoles = await user.getRoles();
const roles = [...allRoles.keys()]; // es requires an array for terms search
const map = req.query.map && req.query.map === 'true';
// only get shortcuts for setting user or shared
const query = {
query: {
bool: {
filter: [
{
bool: {
should: [
{ terms: { roles } }, // shared via user role
{ terms: { editRoles: roles } }, // shared via edit role
{ term: { users: req.settingUser.userId } }, // shared via userId
{ term: { userId: req.settingUser.userId } } // created by this user
]
}
}
]
}
},
sort: {},
size: req.query.length || 50,
from: req.query.start || 0
};
if (req.query.all && roles.includes('arkimeAdmin')) {
query.query.bool.filter = []; // remove sharing restrictions
}
query.sort[req.query.sort || 'name'] = {
order: req.query.desc === 'true' ? 'desc' : 'asc'
};
if (req.query.searchTerm) {
query.query.bool.filter.push({
wildcard: { name: '*' + req.query.searchTerm + '*' }
});
}
// if fieldType exists, filter it
if (req.query.fieldType) {
const fieldType = internals.shortcutTypeMap[req.query.fieldType];
if (fieldType) {
query.query.bool.filter.push({
exists: { field: fieldType }
});
}
}
const numQuery = { ...query };
delete numQuery.sort;
delete numQuery.size;
delete numQuery.from;
Promise.all([
Db.searchShortcuts(query),
Db.numberOfShortcuts(numQuery)
]).then(([{ body: { hits: shortcuts } }, { body: { count: total } }]) => {
const results = { list: [], map: {} };
for (const hit of shortcuts.hits) {
const shortcut = hit._source;
shortcut.id = hit._id;
if (shortcut.number) {
shortcut.type = 'number';
} else if (shortcut.ip) {
shortcut.type = 'ip';
} else {
shortcut.type = 'string';
}
const values = shortcut[shortcut.type];
if (req.query.fieldFormat && req.query.fieldFormat === 'true') {
const shortcutName = `$${shortcut.name}`;
shortcut.exp = shortcutName;
shortcut.dbField = shortcutName;
shortcut.help = shortcut.description
? `${shortcut.description}: ${values.join(', ')}`
: `${values.join(',')}`;
}
shortcut.value = values.join('\n');
delete shortcut[shortcut.type];
if ( // remove sensitive information for users this is shared with
// (except creator, arkimeAdmin, and editors)
user.userId !== shortcut.userId &&
!user.hasRole('arkimeAdmin') &&
!user.hasRole(shortcut.editRoles)) {
delete shortcut.users;
delete shortcut.roles;
delete shortcut.editRoles;
} else if (shortcut.users) {
// client expects a string
shortcut.users = shortcut.users.join(',');
}
if (map) {
results.map[shortcut.id] = shortcut;
} else {
results.list.push(shortcut);
}
}
const sendResults = map
? results.map
: {
data: results.list,
recordsTotal: total,
recordsFiltered: shortcuts.total
};
res.send(sendResults);
}).catch((err) => {
console.log(`ERROR - ${req.method} /api/shortcuts`, util.inspect(err, false, 50));
return res.serverError(500, 'Error retrieving shortcuts - ' + err);
});
};
// --------------------------------------------------------------------------
/**
* POST - /api/shortcut
*
* Creates a new shortcut.
* @name /shortcut
* @param {string} name - The name of the new shortcut.
* @param {string} type - The type of the shortcut (number, ip, or string).
* @param {string} value - The shortcut value.
* @param {string} description - The optional description of this shortcut.
* @param {string} users - A comma separated list of users that can view this shortcut.
* @param {Array} roles - The roles that can view this shortcut.
* @returns {Shortcut} shortcut - The new shortcut object.
* @returns {boolean} success - Whether the create shortcut operation was successful.
*/
static createShortcut (req, res) {
// make sure all the necessary data is included in the post body
if (!ArkimeUtil.isString(req.body.name)) {
return res.serverError(403, 'Missing shortcut name');
}
if (!ArkimeUtil.isString(req.body.type)) {
return res.serverError(403, 'Missing shortcut type');
}
if (!ArkimeUtil.isString(req.body.value)) {
return res.serverError(403, 'Missing shortcut value');
}
if (req.body.roles !== undefined && !ArkimeUtil.isStringArray(req.body.roles)) {
return res.serverError(403, 'Roles field must be an array of strings');
}
if (req.body.editRoles !== undefined && !ArkimeUtil.isStringArray(req.body.editRoles)) {
return res.serverError(403, 'Edit roles field must be an array of strings');
}
if (req.body.users !== undefined && !ArkimeUtil.isString(req.body.users, 0)) {
return res.serverError(403, 'Users field must be a string');
}
req.body.name = req.body.name.replace(/[^-a-zA-Z0-9_]/g, '');
// return nothing if we can't find the user
const user = req.settingUser;
if (!user) { return res.send({}); }
const query = {
query: {
bool: {
filter: [
{ term: { name: req.body.name } }
]
}
}
};
ShortcutAPIs.#shortcutMutex.lock().then(async () => {
try {
const { body: { hits: shortcuts } } = await Db.searchShortcuts(query);
// search for shortcut name collision
for (const hit of shortcuts.hits) {
const shortcut = hit._source;
if (shortcut.name === req.body.name) {
ShortcutAPIs.#shortcutMutex.unlock();
return res.serverError(403, `A shortcut with the name, ${req.body.name}, already exists`);
}
}
const newShortcut = req.body;
newShortcut.userId = user.userId;
const { type, values, invalidUsers } = await ShortcutAPIs.#normalizeShortcut(newShortcut);
try {
const { body: result } = await Db.createShortcut(newShortcut);
newShortcut.id = result._id;
newShortcut.type = type;
newShortcut.value = values.join('\n');
delete newShortcut.ip;
delete newShortcut.string;
delete newShortcut.number;
ShortcutAPIs.#shortcutMutex.unlock();
return res.send(JSON.stringify({
invalidUsers,
success: true,
shortcut: newShortcut,
text: 'Created new shortcut!'
}));
} catch (err) {
ShortcutAPIs.#shortcutMutex.unlock();
console.log(`ERROR - ${req.method} /api/shortcut (createShortcut)`, util.inspect(err, false, 50));
return res.serverError(500, 'Error creating shortcut');
}
} catch (err) {
ShortcutAPIs.#shortcutMutex.unlock();
console.log(`ERROR - ${req.method} /api/shortcut (searchShortcuts)`, util.inspect(err, false, 50));
return res.serverError(500, 'Error creating shortcut');
}
});
};
// --------------------------------------------------------------------------
/**
* PUT - /api/shortcut/:id
*
* Updates a shortcut.
* @name /shortcut/:id
* @param {string} name - The name of the shortcut.
* @param {string} type - The type of the shortcut (number, ip, or string).
* @param {string} value - The shortcut value.
* @param {string} description - The optional description of this shortcut.
* @param {string} users - A comma separated list of users that can view this shortcut.
* @param {Array} roles - The roles that can view this shortcut.
* @param {Array} editRoles - The roles that can edit this shortcut.
* @returns {Shortcut} shortcut - The updated shortcut object.
* @returns {boolean} success - Whether the update operation was successful.
* @returns {string} text - The success/error message to (optionally) display to the user.
*/
static async updateShortcut (req, res) {
// make sure all the necessary data is included in the post body
if (!ArkimeUtil.isString(req.body.name)) {
return res.serverError(403, 'Missing shortcut name');
}
if (!ArkimeUtil.isString(req.body.type)) {
return res.serverError(403, 'Missing shortcut type');
}
if (!ArkimeUtil.isString(req.body.value)) {
return res.serverError(403, 'Missing shortcut value');
}
if (req.body.roles !== undefined && !ArkimeUtil.isStringArray(req.body.roles)) {
return res.serverError(403, 'Roles field must be an array of strings');
}
if (req.body.editRoles !== undefined && !ArkimeUtil.isStringArray(req.body.editRoles)) {
return res.serverError(403, 'Edit roles field must be an array of strings');
}
if (req.body.users !== undefined && !ArkimeUtil.isString(req.body.users, 0)) {
return res.serverError(403, 'Users field must be a string');
}
const sentShortcut = req.body;
try {
const { body: fetchedShortcut } = await Db.getShortcut(req.params.id);
if (fetchedShortcut._source.locked) {
return res.serverError(403, 'Locked Shortcut. Use db.pl script to update this shortcut.');
}
const query = {
query: {
bool: {
filter: [
{ term: { name: req.body.name } } // same name
],
must_not: [
{ ids: { values: [req.params.id] } } // but different ID
]
}
}
};
ShortcutAPIs.#shortcutMutex.lock().then(async () => {
try {
const { body: { hits: shortcuts } } = await Db.searchShortcuts(query);
// search for shortcut name collision
for (const hit of shortcuts.hits) {
const shortcut = hit._source;
if (shortcut.name === req.body.name) {
ShortcutAPIs.#shortcutMutex.unlock();
return res.serverError(403, `A shortcut with the name, ${req.body.name}, already exists`);
}
}
const { values, invalidUsers } = await ShortcutAPIs.#normalizeShortcut(sentShortcut);
// sets the owner if it has changed
if (!await User.setOwner(req, res, sentShortcut, fetchedShortcut._source, 'userId')) {
ShortcutAPIs.#shortcutMutex.unlock();
return;
}
try {
await Db.setShortcut(req.params.id, sentShortcut);
ShortcutAPIs.#shortcutMutex.unlock();
sentShortcut.value = values.join('\n');
sentShortcut.users = sentShortcut.users.join(',');
return res.send(JSON.stringify({
invalidUsers,
success: true,
shortcut: sentShortcut,
text: 'Updated shortcut!'
}));
} catch (err) {
ShortcutAPIs.#shortcutMutex.unlock();
console.log(`ERROR - ${req.method} /api/shortcut/%s (setShortcut)`, ArkimeUtil.sanitizeStr(req.params.id), util.inspect(err, false, 50));
return res.serverError(500, 'Error updating shortcut');
}
} catch (err) {
ShortcutAPIs.#shortcutMutex.unlock();
console.log(`ERROR - ${req.method} /api/shortcut/%s (searchShortcuts)`, ArkimeUtil.sanitizeStr(req.params.id), util.inspect(err, false, 50));
return res.serverError(500, 'Error updating shortcut');
}
});
} catch (err) {
console.log(`ERROR - ${req.method} /api/shortcut/%s (getShortcut)`, ArkimeUtil.sanitizeStr(req.params.id), util.inspect(err, false, 50));
return res.serverError(500, 'Fetching shortcut to update failed');
}
};
// --------------------------------------------------------------------------
/**
* DELETE - /api/shortcut/:id
*
* Deletes a shortcut.
* @name /shortcut/:id
* @returns {boolean} success - Whether the delete shortcut operation was successful.
* @returns {string} text - The success/error message to (optionally) display to the user.
*/
static async deleteShortcut (req, res) {
try {
await Db.deleteShortcut(req.params.id);
res.send(JSON.stringify({
success: true,
text: 'Deleted shortcut successfully'
}));
} catch (err) {
console.log(`ERROR - ${req.method} /api/shortcut/%s (deleteShortcut)`, ArkimeUtil.sanitizeStr(req.params.id), util.inspect(err, false, 50));
return res.serverError(500, 'Error deleting shortcut');
}
};
// --------------------------------------------------------------------------
/**
* GET - /api/syncshortcuts
*
* @name /syncshortcuts
* Updates the shortcuts in the local db if they are out of sync with the
* remote db (remote db = user's es)
* This happens periodically (every minute) but can be triggered with this endpoint
* @ignore
* @returns {boolean} success - Always true.
*/
static syncShortcuts (req, res) {
Db.updateLocalShortcuts();
return res.send(JSON.stringify({ success: true }));
};
};
module.exports = ShortcutAPIs;