-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathcve.controller.js
913 lines (784 loc) · 32.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
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
const Cve = require('../../model/cve')
const logger = require('../../middleware/logger')
const errors = require('./error')
const getConstants = require('../../constants').getConstants
const error = new errors.CveControllerError()
const booleanIsTrue = require('../../utils/utils').booleanIsTrue
const convertDatesToISO = require('../../utils/utils').convertDatesToISO
const isEnrichedContainer = require('../../utils/utils').isEnrichedContainer
const url = process.env.NODE_ENV === 'staging' ? 'https://test.cve.org/' : 'https://cve.org/'
// 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) {
const CONSTANTS = getConstants()
const options = CONSTANTS.PAGINATOR_OPTIONS
// temporary measure to allow tests to work after fixing #920
// tests required changing the global limit to force pagination
if (req.TEST_PAGINATOR_LIMIT) {
CONSTANTS.PAGINATOR_OPTIONS.limit = req.TEST_PAGINATOR_LIMIT
}
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
let cnaModified = false
let timeModifiedGtDateObject = null
let timeModifiedLtDateObject = null
let adpShortName = null
const timeModified = {
timeStamp: [],
dateOperator: []
}
// if count_only is the only parameter, return estimated count of full set of records
if ((Object.keys(req.ctx.query).length === 1) &&
(req.ctx.query.count_only) &&
(booleanIsTrue(req.ctx.query.count_only))) {
const payload = {}
payload.totalCount = await cveRepo.estimatedDocumentCount()
logger.info({ uuid: req.ctx.uuid, message: 'The cve records estimated count was sent to the user.' })
return res.status(200).json(payload) // only return estimated count, not the records
}
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'])
timeModifiedLtDateObject = 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'])
timeModifiedGtDateObject = 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
} else if (key === 'cna_modified') {
cnaModified = req.ctx.query.cna_modified
} else if (key === 'adp_short_name') {
adpShortName = req.ctx.query.adp_short_name
}
})
if (cnaModified && !(timeModifiedGtDateObject || timeModifiedLtDateObject)) {
return res.status(400).json(error.badUsageOfCnaModified())
}
const query = {}
if (timeModified.timeStamp.length > 0) {
if (!cnaModified) { query['time.modified'] = {} }
for (let i = 0; i < timeModified.timeStamp.length; i++) {
if (timeModified.dateOperator[i] === 'lt') {
if (cnaModified) {
query['cve.containers.cna.providerMetadata.dateUpdated'] = {}
// Due to this not being the mongo created date object, we need to actually check the "ISO String" version of this _NOT_ the date object that is being created in the middleware
query['cve.containers.cna.providerMetadata.dateUpdated'].$lt = timeModifiedLtDateObject.toISOString()
} else {
query['time.modified'].$lt = timeModified.timeStamp[i]
}
} else {
if (cnaModified) {
query['cve.containers.cna.providerMetadata.dateUpdated'] = {}
// Due to this not being the mongo created date object, we need to actually check the "ISO String" version of this _NOT_ the date object that is being created in the middleware
query['cve.containers.cna.providerMetadata.dateUpdated'].$gt = timeModifiedGtDateObject.toISOString()
} else {
query['time.modified'].$gt = timeModified.timeStamp[i]
}
}
}
}
if (adpShortName) {
query['cve.containers.adp.providerMetadata.shortName'] = adpShortName
}
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
},
// sort before project so DocDB uses the cveId index.
// aggregatePaginate accepts sort separately from the aggregate query
// so need to explicitly specify it here and remove it from the options
{
$sort: {
'cve.cveMetadata.cveId': 1
}
},
{
$project: {
_id: false,
time: false
}
}
]
delete options.sort
// check whether user requested count_only for filtered set of records
if ((req.ctx.query.count_only) &&
(booleanIsTrue(req.ctx.query.count_only))) {
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 GET /cve_cursor
// Cursor pagination implementation of getFilteredCves. Prevents data changes from affecting results between paginated calls
async function getFilteredCvesCursor (req, res, next) {
const CONSTANTS = getConstants()
const PAGINATED_FIELD = 'time.created'
// temporary measure to allow tests to work after fixing #920
// tests required changing the global limit to force pagination
if (req.TEST_PAGINATOR_LIMIT) {
CONSTANTS.PAGINATOR_OPTIONS.limit = req.TEST_PAGINATOR_LIMIT
}
try {
const cveRepo = req.ctx.repositories.getCveRepository()
let state = null
let assignerShortName = null
let assigner = null
let cnaModified = false
let timeModifiedGtDateObject = null
let timeModifiedLtDateObject = null
let adpShortName = null
let next = null
let previous = null
let limit = null || CONSTANTS.PAGINATOR_OPTIONS.limit
const timeModified = {
timeStamp: [],
dateOperator: []
}
// if count_only is the only parameter, return estimated count of full set of records
if ((Object.keys(req.ctx.query).length === 1) &&
(req.ctx.query.count_only) &&
(booleanIsTrue(req.ctx.query.count_only))) {
const payload = {}
payload.totalCount = await cveRepo.estimatedDocumentCount()
logger.info({ uuid: req.ctx.uuid, message: 'The cve records estimated count was sent to the user.' })
return res.status(200).json(payload) // only return estimated count, not the records
}
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'])
timeModifiedLtDateObject = 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'])
timeModifiedGtDateObject = 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
} else if (key === 'cna_modified') {
cnaModified = req.ctx.query.cna_modified
} else if (key === 'adp_short_name') {
adpShortName = req.ctx.query.adp_short_name
} else if (key === 'next_page') {
next = req.ctx.query.next_page
} else if (key === 'previous_page') {
previous = req.ctx.query.previous_page
} else if (key === 'limit') {
limit = req.ctx.query.limit
}
})
if (cnaModified && !(timeModifiedGtDateObject || timeModifiedLtDateObject)) {
return res.status(400).json(error.badUsageOfCnaModified())
}
const query = {}
if (timeModified.timeStamp.length > 0) {
if (!cnaModified) { query['time.modified'] = {} }
for (let i = 0; i < timeModified.timeStamp.length; i++) {
if (timeModified.dateOperator[i] === 'lt') {
if (cnaModified) {
query['cve.containers.cna.providerMetadata.dateUpdated'] = {}
// Due to this not being the mongo created date object, we need to actually check the "ISO String" version of this _NOT_ the date object that is being created in the middleware
query['cve.containers.cna.providerMetadata.dateUpdated'].$lt = timeModifiedLtDateObject.toISOString()
} else {
query['time.modified'].$lt = timeModified.timeStamp[i]
}
} else {
if (cnaModified) {
query['cve.containers.cna.providerMetadata.dateUpdated'] = {}
// Due to this not being the mongo created date object, we need to actually check the "ISO String" version of this _NOT_ the date object that is being created in the middleware
query['cve.containers.cna.providerMetadata.dateUpdated'].$gt = timeModifiedGtDateObject.toISOString()
} else {
query['time.modified'].$gt = timeModified.timeStamp[i]
}
}
}
}
if (adpShortName) {
query['cve.containers.adp.providerMetadata.shortName'] = adpShortName
}
if (state) {
query['cve.cveMetadata.state'] = state
}
if (assignerShortName) {
query['cve.cveMetadata.assignerShortName'] = assignerShortName
}
if (assigner) {
query['cve.cveMetadata.assignerOrgId'] = assigner
}
// check whether user requested count_only for filtered set of records
if ((req.ctx.query.count_only) &&
(booleanIsTrue(req.ctx.query.count_only))) {
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.cursorPaginate(query, limit, next, previous, PAGINATED_FIELD)
const payload = {
cveRecords: pg.results.map(val => { return { ...val.cve } })
}
payload.hasNext = pg.hasNext
payload.hasPrevious = pg.hasPrevious
payload.next = pg.next
payload.previous = pg.previous
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) {
const CONSTANTS = getConstants()
try {
const newCve = new Cve({ cve: convertDatesToISO(req.ctx.body, CONSTANTS.DATE_FIELDS) })
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 cveRepo.updateByCveId(cveId, newCve, { upsert: true })
await cveIdRepo.updateByCveId(cveId, { state: state })
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) {
const CONSTANTS = getConstants()
try {
// All CVE fields are stored in UTC format, we need to check and convert dates to ISO before storing in the database.
const newCve = new Cve({ cve: convertDatesToISO(req.ctx.body, CONSTANTS.DATE_FIELDS) })
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) {
const CONSTANTS = getConstants()
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)
// To avoid breaking legacy behavior in the "booleanIsTrue" function, we need to check to make sure that undefined is set to false
let erlCheck
if (typeof req.query.erlcheck === 'undefined') {
erlCheck = false
} else {
erlCheck = booleanIsTrue(req.query.erlcheck) || false
}
// 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())
}
const cnaContainer = convertDatesToISO(req.ctx.body.cnaContainer, CONSTANTS.DATE_FIELDS)
if (erlCheck && !isEnrichedContainer(cnaContainer)) {
// Process the ERL check here
return res.status(403).json(error.erlCheckFailed())
}
// create full cve record here
const owningCna = await orgRepo.findOneByUUID(cveId.owning_cna)
const assignerShortName = owningCna.short_name
const dateUpdated = (new Date()).toISOString()
const additionalCveMetadataFields = {
assignerShortName: assignerShortName,
dateReserved: (cveId.reserved).toISOString(),
datePublished: dateUpdated,
dateUpdated: 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.isValid) {
logger.error(JSON.stringify({ uuid: req.ctx.uuid, message: 'CVE JSON schema validation FAILED.' }))
return res.status(400).json(error.invalidCnaContainerJsonSchema(result.errors))
}
try {
await cveRepo.updateByCveId(id, cveModel, { upsert: true })
// change cve id state to publish after saving CVE Record in case above call fails
await cveIdRepo.updateByCveId(id, { state: CONSTANTS.CVE_STATES.PUBLISHED })
} catch (err) {
return res.status(400).json(error.unableToStoreCveRecord())
}
const responseMessage = {
message: id + ' record was successfully created. This submission should appear on ' + url + ' within 15 minutes.',
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) {
const CONSTANTS = getConstants()
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)
// To avoid breaking legacy behavior in the "booleanIsTrue" function, we need to check to make sure that undefined is set to false
let erlCheck
if (typeof req.query.erlcheck === 'undefined') {
erlCheck = false
} else {
erlCheck = booleanIsTrue(req.query.erlcheck) || false
}
// 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())
}
const cnaContainer = convertDatesToISO(req.ctx.body.cnaContainer, CONSTANTS.DATE_FIELDS)
if (erlCheck && !isEnrichedContainer(cnaContainer)) {
// Process the ERL check here
return res.status(403).json(error.erlCheckFailed())
}
// update cve record here
const cveRecord = result.cve
const dateUpdated = (new Date()).toISOString()
cveRecord.cveMetadata.dateUpdated = dateUpdated
// Update dataVersion to current schema version
if (cveRecord.dataVersion !== CONSTANTS.SCHEMA_VERSION) {
cveRecord.dataVersion = CONSTANTS.SCHEMA_VERSION
}
if (cveRecord.cveMetadata.state === CONSTANTS.CVE_STATES.REJECTED) {
delete cveRecord.cveMetadata.dateRejected
if (!cveRecord.cveMetadata.datePublished) {
cveRecord.cveMetadata.datePublished = dateUpdated
}
}
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.isValid) {
logger.error(JSON.stringify({ uuid: req.ctx.uuid, message: 'CVE JSON schema validation FAILED.' }))
return res.status(400).json(error.invalidCnaContainerJsonSchema(result.errors))
}
try {
await cveRepo.updateByCveId(id, cveModel)
// 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(400).json(error.unableToStoreCveRecord())
}
}
} catch (err) {
return res.status(400).json(error.unableToStoreCveRecord())
}
const responseMessage = {
message: id + ' record was successfully updated. This submission should appear on ' + url + ' within 15 minutes.',
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) {
const CONSTANTS = getConstants()
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)
const 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: convertDatesToISO(rejectedCve, CONSTANTS.DATE_FIELDS) })
result = Cve.validateCveRecord(newCveObj.cve)
if (!result.isValid) {
logger.error(JSON.stringify({ uuid: req.ctx.uuid, message: 'CVE JSON schema validation FAILED.' }))
return res.status(400).json(error.invalidCnaContainerJsonSchema(result.errors))
}
// Save rejected CVE record object
result = await cveRepo.updateByCveId(id, newCveObj, { upsert: true })
if (!result) {
return res.status(500).json(error.serverError())
}
// Update state of CVE ID
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.',
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) {
const CONSTANTS = getConstants()
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.cveRecordDne())
}
const providerMetadata = createProviderMetadata(providerOrgObj.UUID, req.ctx.org, (new Date()).toISOString())
// Update dataVersion to current schema version
if (result.cve.dataVersion !== CONSTANTS.SCHEMA_VERSION) {
result.cve.dataVersion = CONSTANTS.SCHEMA_VERSION
}
// update CVE record to rejected
const updatedRecord = Cve.updateCveToRejected(id, providerMetadata, result.cve, req.ctx.body)
const updatedCve = new Cve({ cve: convertDatesToISO(updatedRecord, CONSTANTS.DATE_FIELDS) })
result = Cve.validateCveRecord(updatedCve.cve)
if (!result.isValid) {
logger.error(JSON.stringify({ uuid: req.ctx.uuid, message: 'CVE JSON schema validation FAILED.' }))
return res.status(400).json(error.invalidCnaContainerJsonSchema(result.errors))
}
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)
}
}
// Called by PUT /cve/:id/adp
async function insertAdp (req, res, next) {
const CONSTANTS = getConstants()
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 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
// Update dataVersion to current schema version
if (cveRecord.dataVersion !== CONSTANTS.SCHEMA_VERSION) {
cveRecord.dataVersion = CONSTANTS.SCHEMA_VERSION
}
if (cveRecord.cveMetadata.state === CONSTANTS.CVE_STATES.REJECTED) {
return res.status(403).json(error.cveRecordRejected())
}
if (!Object.prototype.hasOwnProperty.call(req.ctx.body, 'adpContainer')) {
return res.status(400).json(error.badAdpFormat())
}
const adpContainer = req.ctx.body.adpContainer
const dateUpdated = (new Date()).toISOString()
cveRecord.cveMetadata.dateUpdated = dateUpdated
const providerMetadata = createProviderMetadata(orgUuid, req.ctx.org, dateUpdated)
adpContainer.providerMetadata = providerMetadata
let dupeFound = 0
let dupeIndex = -1
let dupeStatus = 'new'
if (Object.prototype.hasOwnProperty.call(cveRecord.containers, 'adp')) {
cveRecord.containers.adp.forEach(function (item, index) {
if (orgUuid === item.providerMetadata.orgId) {
dupeFound = 1
dupeIndex = index
dupeStatus = 'replacement'
}
})
logger.info('Number of ADP containers already: ' + cveRecord.containers.adp.length)
} else {
logger.info('There were previously zero ADP containers.')
cveRecord.containers.adp = []
}
if (dupeFound === 1) {
cveRecord.containers.adp[dupeIndex] = adpContainer
} else {
cveRecord.containers.adp.push(adpContainer)
}
const cveModel = new Cve({ cve: convertDatesToISO(cveRecord, CONSTANTS.DATE_FIELDS) })
result = Cve.validateCveRecord(cveModel.cve)
if (!result.isValid) {
logger.error(JSON.stringify({ uuid: req.ctx.uuid, message: 'CVE JSON schema validation FAILED.' }))
return res.status(400).json(error.badAdpJson(result.errors))
}
await cveRepo.updateByCveId(id, cveModel)
const outcome = id + ' record had ' + dupeStatus + ' ADP container for org ' + req.ctx.org + ' successfully inserted. This submission should appear on ' + url + ' within 15 minutes.'
const responseMessage = {
message: outcome,
updated: cveModel.cve
}
const payload = {
action: 'update_cve_record_from_adp',
change: outcome,
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)
}
}
module.exports = {
CVE_GET_SINGLE: getCve,
CVE_GET_FILTERED: getFilteredCves,
CVE_GET_FILTERED_CURSOR: getFilteredCvesCursor,
CVE_SUBMIT: submitCve,
CVE_UPDATE_SINGLE: updateCve,
CVE_SUBMIT_CNA: submitCna,
CVE_UPDATE_CNA: updateCna,
CVE_REJECT_RECORD: rejectCVE,
CVE_REJECT_EXISTING_CVE: rejectExistingCve,
CVE_INSERT_ADP: insertAdp
}