-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathcve.controller.js
534 lines (462 loc) · 17.6 KB
/
cve.controller.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
const Cve = require('../../model/cve')
const logger = require('../../middleware/logger')
const errors = require('./error')
const error = new errors.CveControllerError()
const CONSTANTS = require('../../constants')
const options = CONSTANTS.PAGINATOR_OPTIONS
// Helper function to create providerMetadata object
function createProviderMetadata (orgId, shortName, updateDate) {
return { orgId: orgId, shortName: shortName, dateUpdated: updateDate }
}
// Called by GET /cve/:id
async function getCve (req, res, next) {
try {
const id = req.ctx.params.id
const cveRepo = req.ctx.repositories.getCveRepository()
const result = await cveRepo.findOneByCveId(id)
if (!result) {
return res.status(404).json(error.cveRecordDne())
}
return res.status(200).json(result.cve)
} catch (err) {
next(err)
}
}
// Called by GET /cve
async function getFilteredCves (req, res, next) {
try {
options.page = req.ctx.query.page ? parseInt(req.ctx.query.page) : CONSTANTS.PAGINATOR_PAGE // if 'page' query parameter is not defined, set 'page' to the default page value
const cveRepo = req.ctx.repositories.getCveRepository()
let state = null
let assignerShortName = null
let assigner = null
const timeModified = {
timeStamp: [],
dateOperator: []
}
Object.keys(req.ctx.query).forEach(k => {
const key = k.toLowerCase()
if (key === 'time_modified.lt') {
timeModified.dateOperator.push('lt')
timeModified.timeStamp.push(req.ctx.query['time_modified.lt'])
} else if (key === 'time_modified.gt') {
timeModified.dateOperator.push('gt')
timeModified.timeStamp.push(req.ctx.query['time_modified.gt'])
} else if (key === 'state') {
state = req.ctx.query.state
} else if (key === 'assigner_short_name') { // the key is retrieved as lowercase
assignerShortName = req.ctx.query.assigner_short_name
} else if (key === 'assigner') {
assigner = req.ctx.query.assigner
}
})
const query = {}
if (timeModified.timeStamp.length > 0) {
query['time.modified'] = {}
for (let i = 0; i < timeModified.timeStamp.length; i++) {
if (timeModified.dateOperator[i] === 'lt') {
query['time.modified'].$lt = timeModified.timeStamp[i]
} else {
query['time.modified'].$gt = timeModified.timeStamp[i]
}
}
}
if (state) {
query['cve.cveMetadata.state'] = state
}
if (assignerShortName) {
query['cve.cveMetadata.assignerShortName'] = assignerShortName
}
if (assigner) {
query['cve.cveMetadata.assignerOrgId'] = assigner
}
const agt = [
{
$match: query
},
{
$project: {
_id: false,
time: false
}
}
]
// check whether user requested count_only
if (req.ctx.query.count_only === '1') {
const payload = {}
payload.totalCount = await cveRepo.countDocuments(query)
logger.info({ uuid: req.ctx.uuid, message: 'The cve records count was sent to the user.' })
return res.status(200).json(payload) // only return count number, not the records
}
const pg = await cveRepo.aggregatePaginate(agt, options)
const payload = { cveRecords: pg.itemsList.map(val => { return val.cve }) }
if (pg.itemCount >= CONSTANTS.PAGINATOR_OPTIONS.limit) {
payload.totalCount = pg.itemCount
payload.itemsPerPage = pg.itemsPerPage
payload.pageCount = pg.pageCount
payload.currentPage = pg.currentPage
payload.prevPage = pg.prevPage
payload.nextPage = pg.nextPage
}
logger.info({ uuid: req.ctx.uuid, message: 'The cve records were sent to the user.' })
return res.status(200).json(payload)
} catch (err) {
next(err)
}
}
// Called by POST /cve/:id
// Creates a new CVE only if it does not exists for the specified CVE ID in the request body. If it exists, it does not
// update the CVE.
async function submitCve (req, res, next) {
try {
const newCve = new Cve({ cve: req.ctx.body })
const id = req.ctx.params.id
const cveId = newCve.cve.cveMetadata.cveId
const state = newCve.cve.cveMetadata.state
const cveRepo = req.ctx.repositories.getCveRepository()
const cveIdRepo = req.ctx.repositories.getCveIdRepository()
const orgRepo = req.ctx.repositories.getOrgRepository()
// the cve id provided in the body must match the cve id provided in the URL params
if (id !== cveId) {
return res.status(400).json(error.cveIdMismatch())
}
// check that cve does not have status 'RESERVED'
if (state === CONSTANTS.CVE_STATES.RESERVED) {
return res.status(400).json(error.cveCreateUnsupportedState(CONSTANTS.CVE_STATES.RESERVED))
}
// check that cve id exists
let result = await cveIdRepo.findOneByCveId(id)
if (!result || result.state === CONSTANTS.CVE_STATES.AVAILABLE) {
return res.status(403).json(error.cveDne())
}
// check that cve record does not exist
result = await cveRepo.findOneByCveId(id)
if (result) {
return res.status(400).json(error.cveRecordExists())
}
await cveIdRepo.updateByCveId(cveId, { state: state })
await cveRepo.updateByCveId(cveId, newCve, { upsert: true })
const responseMessage = {
message: cveId + ' record was successfully created.',
created: newCve.cve
}
const payload = {
action: 'create_cve_record',
change: cveId + ' record was successfully created.',
req_UUID: req.ctx.uuid,
org_UUID: await orgRepo.getOrgUUID(req.ctx.org),
cve: cveId
}
const userRepo = req.ctx.repositories.getUserRepository()
payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
// Called by PUT /cve/:id
// Updates a CVE if one exists for the specified CVE ID
async function updateCve (req, res, next) {
try {
const newCve = new Cve({ cve: req.ctx.body })
const cveId = req.ctx.params.id
const cveRepo = req.ctx.repositories.getCveRepository()
const cveIdRepo = req.ctx.repositories.getCveIdRepository()
const orgRepo = req.ctx.repositories.getOrgRepository()
const newCveMetaData = newCve.cve.cveMetadata
const newCveId = newCveMetaData.cveId
const newCveState = newCveMetaData.state
if (cveId !== newCveId) {
return res.status(400).json(error.cveIdMismatch())
}
if (newCveState === CONSTANTS.CVE_STATES.RESERVED) {
return res.status(400).json(error.cveUpdateUnsupportedState(CONSTANTS.CVE_STATES.RESERVED))
}
let result = await cveIdRepo.findOneByCveId(cveId)
if (!result) {
logger.info(cveId + ' does not exist.')
return res.status(403).json(error.cveDne())
}
result = await cveRepo.findOneByCveId(cveId)
if (!result) {
logger.info(cveId + ' does not exist.')
return res.status(403).json(error.cveRecordDne())
}
await cveRepo.updateByCveId(cveId, newCve)
await cveIdRepo.updateByCveId(cveId, { state: newCveState })
const responseMessage = {
message: cveId + ' record was successfully updated.',
updated: newCve.cve
}
const payload = {
action: 'update_cve_record',
change: cveId + ' record was successfully updated.',
req_UUID: req.ctx.uuid,
org_UUID: await orgRepo.getOrgUUID(req.ctx.org),
cve: cveId
}
const userRepo = req.ctx.repositories.getUserRepository()
payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
// Called by POST /cve/:id/cna
async function submitCna (req, res, next) {
try {
const id = req.ctx.params.id
const cveRepo = req.ctx.repositories.getCveRepository()
const cveIdRepo = req.ctx.repositories.getCveIdRepository()
const orgRepo = req.ctx.repositories.getOrgRepository()
const userRepo = req.ctx.repositories.getUserRepository()
const orgUuid = await orgRepo.getOrgUUID(req.ctx.org)
const userUuid = await userRepo.getUserUUID(req.ctx.user, orgUuid)
// check that cve id exists
let result = await cveIdRepo.findOneByCveId(id)
if (!result || result.state === CONSTANTS.CVE_STATES.AVAILABLE) {
return res.status(400).json(error.cveDne())
}
// check that cveId org matches user org
const cveId = result
const isSecretariat = await orgRepo.isSecretariat(req.ctx.org)
if ((cveId.owning_cna !== orgUuid) && !isSecretariat) {
return res.status(403).json(error.owningOrgDoesNotMatch())
}
// check that cve record does not exist
result = await cveRepo.findOneByCveId(id)
if (result) {
return res.status(403).json(error.cveRecordExists())
}
// create full cve record here
const owningCna = await orgRepo.findOneByUUID(cveId.owning_cna)
const assignerShortName = owningCna.short_name
const cnaContainer = req.ctx.body.cnaContainer
const dateUpdated = (new Date()).toISOString()
const additionalCveMetadataFields = {
assignerShortName: assignerShortName,
requesterUserId: cveId.requested_by.user,
dateReserved: (cveId.reserved).toISOString(),
datePublished: dateUpdated
}
const providerMetadata = createProviderMetadata(orgUuid, req.ctx.org, dateUpdated)
const cveRecord = Cve.newPublishedCve(id, cveId.owning_cna, cnaContainer, additionalCveMetadataFields, providerMetadata)
const cveModel = new Cve({ cve: cveRecord })
result = Cve.validateCveRecord(cveModel.cve)
if (!result) {
return res.status(500).json(error.serverError())
}
// change cve id state to publish
await cveIdRepo.updateByCveId(id, { state: CONSTANTS.CVE_STATES.PUBLISHED })
await cveRepo.updateByCveId(id, cveModel, { upsert: true })
const responseMessage = {
message: id + ' record was successfully created.',
created: cveModel.cve
}
const payload = {
action: 'create_cve_record_from_cna',
change: id + ' record was successfully created.',
req_UUID: req.ctx.uuid,
org_UUID: orgUuid,
user_UUID: userUuid,
cve: id
}
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
// Called by PUT /cve/:id/cna
async function updateCna (req, res, next) {
try {
const id = req.ctx.params.id
const cveRepo = req.ctx.repositories.getCveRepository()
const cveIdRepo = req.ctx.repositories.getCveIdRepository()
const orgRepo = req.ctx.repositories.getOrgRepository()
const userRepo = req.ctx.repositories.getUserRepository()
const orgUuid = await orgRepo.getOrgUUID(req.ctx.org)
const userUuid = await userRepo.getUserUUID(req.ctx.user, orgUuid)
// check that cve id exists
let result = await cveIdRepo.findOneByCveId(id)
if (!result || result.state === CONSTANTS.CVE_STATES.AVAILABLE) {
return res.status(400).json(error.cveDne())
}
// check that cveId org matches user org
const cveId = result
const isSecretariat = await orgRepo.isSecretariat(req.ctx.org)
if ((cveId.owning_cna !== orgUuid) && !isSecretariat) {
return res.status(403).json(error.owningOrgDoesNotMatch())
}
// check that cve record does exist
result = await cveRepo.findOneByCveId(id)
if (!result) {
return res.status(403).json(error.cveRecordDne())
}
// update cve record here
const cveRecord = result.cve
const cnaContainer = req.ctx.body.cnaContainer
const dateUpdated = (new Date()).toISOString()
cveRecord.cveMetadata.dateUpdated = dateUpdated
if (cveRecord.cveMetadata.state === CONSTANTS.CVE_STATES.REJECTED) {
delete cveRecord.cveMetadata.dateRejected
}
if (cveRecord.cveMetadata.state !== CONSTANTS.CVE_STATES.PUBLISHED) {
cveRecord.cveMetadata.state = CONSTANTS.CVE_STATES.PUBLISHED
}
const providerMetadata = createProviderMetadata(orgUuid, req.ctx.org, dateUpdated)
cnaContainer.providerMetadata = providerMetadata
cveRecord.containers.cna = cnaContainer
const cveModel = new Cve({ cve: cveRecord })
result = Cve.validateCveRecord(cveModel.cve)
if (!result) {
return res.status(500).json(error.serverError())
}
// change cve id state to publish
if (cveId.state === CONSTANTS.CVE_STATES.REJECTED) {
result = await cveIdRepo.updateByCveId(id, { state: CONSTANTS.CVE_STATES.PUBLISHED })
if (!result) {
return res.status(500).json(error.serverError())
}
}
await cveRepo.updateByCveId(id, cveModel)
const responseMessage = {
message: id + ' record was successfully updated.',
updated: cveModel.cve
}
const payload = {
action: 'update_cve_record_from_cna',
change: id + ' record was successfully updated.',
req_UUID: req.ctx.uuid,
org_UUID: orgUuid,
user_UUID: userUuid,
cve: id
}
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
// Called by POST /cve/:id/reject
async function rejectCVE (req, res, next) {
try {
const id = req.ctx.params.id
const cveIdRepo = req.ctx.repositories.getCveIdRepository()
// check that cve id exists
const cveIdObj = await cveIdRepo.findOneByCveId(id)
if (!cveIdObj || cveIdObj.state === CONSTANTS.CVE_STATES.AVAILABLE) {
return res.status(400).json(error.cveDne())
}
// check that cve record does not exist
const cveRepo = req.ctx.repositories.getCveRepository()
let result = await cveRepo.findOneByCveId(id)
if (result) {
return res.status(400).json(error.cveRecordExists())
}
// Both orgs below should exist since they passed validation
const orgRepo = req.ctx.repositories.getOrgRepository()
const providerOrgObj = await orgRepo.findOneByShortName(req.ctx.org)
const owningCnaObj = await orgRepo.findOneByUUID(cveIdObj.owning_cna)
let owningCnaShortName = null
if (owningCnaObj) {
owningCnaShortName = owningCnaObj.short_name
}
const providerMetadata = createProviderMetadata(providerOrgObj.UUID, req.ctx.org, (new Date()).toISOString())
const rejectedCve = Cve.newRejectedCve(cveIdObj, req.ctx.body, owningCnaShortName, providerMetadata)
const newCveObj = new Cve({ cve: rejectedCve })
// Update state of CVE ID entry
result = await cveIdRepo.updateByCveId(id, { state: CONSTANTS.CVE_STATES.REJECTED })
if (!result) {
return res.status(500).json(error.serverError())
}
// Save rejected CVE record object
result = await cveRepo.updateByCveId(id, newCveObj, { upsert: true })
if (!result) {
return res.status(500).json(error.serverError())
}
const responseMessage = {
message: id + ' record was successfully submitted.',
created: newCveObj.cve
}
const payload = {
action: 'submit_rejected_cve_record',
change: id + ' record was successfully submitted.',
req_UUID: req.ctx.uuid,
org_UUID: await orgRepo.getOrgUUID(req.ctx.org),
cve: id
}
const userRepo = req.ctx.repositories.getUserRepository()
payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
// Called by PUT /cve/:id/reject
async function rejectExistingCve (req, res, next) {
try {
const id = req.ctx.params.id
const cveIdRepo = req.ctx.repositories.getCveIdRepository()
const cveRepo = req.ctx.repositories.getCveRepository()
const orgRepo = req.ctx.repositories.getOrgRepository()
const providerOrgObj = await orgRepo.findOneByShortName(req.ctx.org)
// check that cve id exists
const cveIdObj = await cveIdRepo.findOneByCveId(id)
if (!cveIdObj || cveIdObj.state === CONSTANTS.CVE_STATES.AVAILABLE) {
return res.status(400).json(error.cveDne())
}
// check that cve record exists
let result = await cveRepo.findOneByCveId(id)
if (!result) {
return res.status(400).json(error.cveRecordExists())
}
const providerMetadata = createProviderMetadata(providerOrgObj.UUID, req.ctx.org, (new Date()).toISOString())
// update CVE record to rejected
const updatedRecord = Cve.updateCveToRejected(id, providerMetadata, result.cve, req.ctx.body)
const updatedCve = new Cve({ cve: updatedRecord })
result = Cve.validateRejected(updatedCve)
if (!result) {
return res.status(500).json(error.serverError())
}
result = await cveRepo.updateByCveId(id, updatedCve)
if (!result) {
return res.status(500).json(error.unableToUpdateByCveID())
}
// update cveID to rejected
result = await cveIdRepo.updateByCveId(id, { state: CONSTANTS.CVE_STATES.REJECTED })
if (!result) {
return res.status(500).json(error.serverError())
}
const responseMessage = {
message: id + ' record was successfully submitted.',
updated: updatedCve.cve
}
const payload = {
action: 'update_rejected_cve_record',
change: id + ' record was successfully submitted.',
req_UUID: req.ctx.uuid,
org_UUID: providerOrgObj.UUID,
cve: id
}
const userRepo = req.ctx.repositories.getUserRepository()
payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
module.exports = {
CVE_GET_SINGLE: getCve,
CVE_GET_FILTERED: getFilteredCves,
CVE_SUBMIT: submitCve,
CVE_UPDATE_SINGLE: updateCve,
CVE_SUBMIT_CNA: submitCna,
CVE_UPDATE_CNA: updateCna,
CVE_REJECT_RECORD: rejectCVE,
CVE_REJECT_EXISTING_CVE: rejectExistingCve
}