-
Notifications
You must be signed in to change notification settings - Fork 28
/
CollectionService.js
2424 lines (2255 loc) · 83.8 KB
/
CollectionService.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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const dbUtils = require('./utils')
const config = require('../utils/config.js')
const MyController = require('../controllers/Collection')
const _this = this
/**
Generalized queries for collection(s).
**/
exports.queryCollections = async function (inProjection = [], inPredicates = {}, elevate = false, userObject) {
const context = elevate ? dbUtils.CONTEXT_ALL : dbUtils.CONTEXT_USER
const queries = []
const groupBy = []
const orderBy = []
const columns = [
'CAST(c.collectionId as char) as collectionId',
'c.name',
'c.description',
`JSON_MERGE_PATCH('${JSON.stringify(MyController.defaultSettings)}', c.settings) as settings`,
'c.metadata'
]
const joins = [
'collection c',
'left join collection_grant cg on c.collectionId = cg.collectionId',
'left join asset a on c.collectionId = a.collectionId and a.state = "enabled"',
'left join stig_asset_map sa on a.assetId = sa.assetId'
]
// PROJECTIONS
if (inProjection.includes('assets')) {
columns.push(`cast(
concat('[',
coalesce (
group_concat(distinct
case when a.assetId is not null then
json_object(
'assetId', CAST(a.assetId as char),
'name', a.name
)
else null end
order by a.name),
''),
']')
as json) as "assets"`)
}
if (inProjection.includes('stigs')) {
joins.push('left join default_rev dr on (sa.benchmarkId=dr.benchmarkId and c.collectionId = dr.collectionId)')
joins.push('left join revision on dr.revId = revision.revId')
columns.push(`cast(
concat('[',
coalesce (
group_concat(distinct
case when sa.benchmarkId is not null then
json_object(
'benchmarkId', sa.benchmarkId,
'revisionStr', revision.revisionStr,
'benchmarkDate', date_format(revision.benchmarkDateSql,'%Y-%m-%d'),
'revisionPinned', CASE WHEN dr.revisionPinned = 1 THEN CAST(true as json) ELSE CAST(false as json) END,
'ruleCount', revision.ruleCount)
else null end
order by sa.benchmarkId),
''),
']')
as json) as "stigs"`)
}
if (inProjection.includes('grants')) {
columns.push(`(select
coalesce(
(select json_arrayagg(
json_object(
'user', json_object(
'userId', CAST(user_data.userId as char),
'username', user_data.username,
'displayName', COALESCE(
JSON_UNQUOTE(JSON_EXTRACT(user_data.lastClaims, "$.${config.oauth.claims.name}")),
user_data.username)
),
'accessLevel', accessLevel
)
)
from collection_grant left join user_data using (userId) where collectionId = c.collectionId)
, json_array()
)
) as "grants"`)
}
if (inProjection.includes('owners')) {
columns.push(`(select
coalesce(
(select json_arrayagg(
json_object(
'userId', CAST(user_data.userId as char),
'username', user_data.username,
'email', JSON_UNQUOTE(JSON_EXTRACT(user_data.lastClaims, "$.${config.oauth.claims.email}")),
'displayName', JSON_UNQUOTE(JSON_EXTRACT(user_data.lastClaims, "$.${config.oauth.claims.name}"))
)
)
from collection_grant
left join user_data using (userId)
where collectionId = c.collectionId and accessLevel = 4)
, json_array()
)
) as "owners"`)
}
if (inProjection.includes('labels')) {
queries.push(_this.getCollectionLabels('all', userObject))
}
if (inProjection.includes('statistics')) {
if (context == dbUtils.CONTEXT_USER) {
joins.push('left join collection_grant cgstat on c.collectionId = cgstat.collectionId')
columns.push(`(select
json_object(
'created', DATE_FORMAT(c.created, '%Y-%m-%dT%TZ'),
'grantCount', CASE WHEN cg.accessLevel = 1 THEN 1 ELSE COUNT( distinct cgstat.cgId ) END,
'assetCount', COUNT( distinct a.assetId ),
'checklistCount', COUNT( distinct sa.saId )
)
) as "statistics"`)
}
else {
columns.push(`(select
json_object(
'created', DATE_FORMAT(c.created, '%Y-%m-%dT%TZ'),
'grantCount', COUNT( distinct cg.cgId ),
'assetCount', COUNT( distinct a.assetId ),
'checklistCount', COUNT( distinct sa.saId )
)
) as "statistics"`)
}
}
// PREDICATES
let predicates = {
statements: [`c.state = "enabled"`],
binds: []
}
if ( inPredicates.collectionId ) {
predicates.statements.push('c.collectionId = ?')
predicates.binds.push( inPredicates.collectionId )
}
if ( inPredicates.name ) {
let matchStr = '= ?'
if ( inPredicates.nameMatch && inPredicates.nameMatch !== 'exact') {
matchStr = 'LIKE ?'
switch (inPredicates.nameMatch) {
case 'startsWith':
inPredicates.name = `${inPredicates.name}%`
break
case 'endsWith':
inPredicates.name = `%${inPredicates.name}`
break
case 'contains':
inPredicates.name = `%${inPredicates.name}%`
break
}
}
predicates.statements.push(`c.name ${matchStr}`)
predicates.binds.push( inPredicates.name )
}
if ( inPredicates.metadata ) {
for (const pair of inPredicates.metadata) {
const [key, value] = pair.split(/:(.*)/s)
predicates.statements.push('JSON_CONTAINS(c.metadata, ?, ?)')
predicates.binds.push( `"${value}"`, `$.${key}`)
}
}
if (context == dbUtils.CONTEXT_USER) {
joins.push('left join user_stig_asset_map usa on sa.saId = usa.saId')
predicates.statements.push('(cg.userId = ? AND CASE WHEN cg.accessLevel = 1 THEN usa.userId = cg.userId ELSE TRUE END)')
predicates.binds.push( userObject.userId, userObject.userId )
}
groupBy.push('c.collectionId, c.name, c.description, c.settings, c.metadata')
orderBy.push('c.name')
const sql = dbUtils.makeQueryString({columns, joins, predicates,groupBy, orderBy})
// perform concurrent labels query
if (queries.length) {
queries.push(dbUtils.pool.query(sql, predicates.binds))
const results = await Promise.all(queries)
const labelResults = results[0]
const collectionResults = results[1][0]
// transform labels into Map
const labelMap = new Map()
for (const labelResult of labelResults) {
const {collectionId, ...label} = labelResult
const existing = labelMap.get(collectionId)
if (existing) {
existing.push(label)
}
else {
labelMap.set(collectionId, [label])
}
}
for (const collectionResult of collectionResults) {
collectionResult.labels = labelMap.get(collectionResult.collectionId) ?? []
}
return collectionResults
}
else {
let [rows] = await dbUtils.pool.query(sql, predicates.binds)
return (rows)
}
}
exports.queryFindings = async function (aggregator, inProjection = [], inPredicates = {}, userObject) {
let columns, groupBy, orderBy
switch (aggregator) {
case 'ruleId':
columns = [
'rgr.ruleId',
'rgr.title',
'rgr.severity',
'count(distinct a.assetId) as assetCount'
]
groupBy = [
'rgr.rgrId'
]
orderBy = ['rgr.ruleId']
break
case 'groupId':
columns = [
'rgr.groupId',
'rgr.groupTitle as title',
'rgr.severity',
'count(distinct a.assetId) as assetCount'
]
groupBy = [
'rgr.rgrId'
]
orderBy = ['substring(rgr.groupId from 3) + 0']
break
case 'cci':
columns = [
'cci.cci',
'cci.definition',
'cci.apAcronym',
'count(distinct a.assetId) as assetCount'
]
groupBy = [
'cci.cci'
]
orderBy = ['cci.cci']
break
}
let joins = [
'collection c',
'left join collection_grant cg on c.collectionId = cg.collectionId',
'inner join asset a on (c.collectionId = a.collectionId and a.state = "enabled")',
'inner join stig_asset_map sa on a.assetId = sa.assetId',
'left join user_stig_asset_map usa on sa.saId = usa.saId',
'left join default_rev dr on (sa.benchmarkId = dr.benchmarkId and c.collectionId = dr.collectionId)',
'left join rev_group_rule_map rgr on dr.revId = rgr.revId',
'left join rev_group_rule_cci_map rgrcc using (rgrId)',
'left join rule_version_check_digest rvcd on rgr.ruleId = rvcd.ruleId',
'inner join review rv on (rvcd.version = rv.version and rvcd.checkDigest = rv.checkDigest and a.assetId = rv.assetId and rv.resultId = 4)',
'left join cci on rgrcc.cci = cci.cci'
]
// PROJECTIONS
// Not exposed in API, used internally
if (inProjection.includes('rulesWithDiscussion')) {
columns.push(`cast(concat('[', group_concat(distinct json_object (
'ruleId', rgr.ruleId,
'title', rgr.title,
'severity', rgr.severity,
'vulnDiscussion', rgr.vulnDiscussion) order by rgr.ruleId), ']') as json) as "rules"`)
}
// Not exposed in API, used internally
// if (inProjection.includes('stigsInfo')) {
// columns.push(`cast( concat( '[', group_concat(distinct json_object (
// 'benchmarkId', dr.benchmarkId,
// 'version', dr.version,
// 'release', dr.release,
// 'benchmarkDate', dr.benchmarkDate) order by dr.benchmarkId), ']') as json) as "stigsInfo"`)
// }
if (inProjection.includes('rules')) {
columns.push(`cast(concat('[', group_concat(distinct json_object (
'ruleId', rgr.ruleId,
'title', rgr.title,
'version', rgr.version,
'severity', rgr.severity) order by rgr.ruleId), ']') as json) as "rules"`)
}
if (inProjection.includes('groups')) {
columns.push(`cast(concat('[', group_concat(distinct json_object (
'groupId', rgr.groupId,
'title', rgr.groupTitle,
'severity', rgr.groupSeverity) order by rgr.groupId), ']') as json) as "groups"`)
}
if (inProjection.includes('assets')) {
columns.push(`cast(concat('[', group_concat(distinct json_object (
'assetId', CAST(a.assetId as char),
'name', a.name) order by a.name), ']') as json) as "assets"`)
}
if (inProjection.includes('stigs')) {
joins.push('left join revision on dr.revId = revision.revId')
columns.push(`cast(
concat('[',
coalesce (
group_concat(distinct
case when revision.benchmarkId is not null then
json_object(
'benchmarkId', revision.benchmarkId,
'revisionStr', revision.revisionStr,
'benchmarkDate', date_format(revision.benchmarkDateSql,'%Y-%m-%d'),
'revisionPinned', CASE WHEN dr.revisionPinned = 1 THEN CAST(true as json) ELSE CAST(false as json) END,
'ruleCount', revision.ruleCount)
else null end
order by revision.benchmarkId),
''),
']')
as json) as "stigs"`)
// columns.push(`cast( concat( '[', group_concat(distinct concat('"',dr.benchmarkId,'"')), ']' ) as json ) as "stigs"`)
}
if (inProjection.includes('ccis')) {
columns.push(`cast(concat('[',
coalesce(
group_concat(distinct
case when cci.cci is not null
then json_object(
'cci', cci.cci,
'definition', cci.definition,
'apAcronym', cci.apAcronym)
else null end order by cci.cci),
''),
']') as json) as "ccis"`)
}
// PREDICATES
let predicates = {
statements: ['c.state = "enabled"'],
binds: []
}
// collectionId predicate is mandatory per API spec
if ( inPredicates.collectionId ) {
predicates.statements.push('c.collectionId = ?')
predicates.binds.push( inPredicates.collectionId )
}
if ( inPredicates.assetId ) {
predicates.statements.push('a.assetId = ?')
predicates.binds.push( inPredicates.assetId )
}
if ( inPredicates.acceptedOnly ) {
predicates.statements.push('rv.statusId = ?')
predicates.binds.push( 3 )
}
if ( inPredicates.benchmarkId ) {
predicates.statements.push('dr.benchmarkId = ?')
predicates.binds.push( inPredicates.benchmarkId )
}
predicates.statements.push('(cg.userId = ? AND CASE WHEN cg.accessLevel = 1 THEN usa.userId = cg.userId ELSE TRUE END)')
predicates.binds.push( userObject.userId, userObject.userId )
const sql = dbUtils.makeQueryString({columns, joins, predicates, groupBy, orderBy})
let [rows] = await dbUtils.pool.query(sql, predicates.binds)
return (rows)
}
exports.queryStatus = async function (inPredicates = {}, userObject) {
let orderBy = ['a.name', 'sa.benchmarkId']
let columns = [
`distinct cast(a.assetId as char) as assetId`,
'a.name as assetName',
`coalesce(
(select
json_arrayagg(BIN_TO_UUID(cl.uuid,1))
from
collection_label_asset_map cla
left join collection_label cl on cla.clId = cl.clId
where
cla.assetId = a.assetId),
json_array()
) as assetLabelIds`,
'sa.benchmarkId',
`json_object(
'total', cr.ruleCount
) as rules`,
'sa.minTs',
'sa.maxTs',
`json_object(
'low', sa.lowCount,
'medium', sa.mediumCount,
'high', sa.highCount
) as findings`,
`json_object(
'saved', json_object(
'total', sa.saved,
'resultEngine', sa.savedResultEngine),
'submitted', json_object(
'total', sa.submitted,
'resultEngine', sa.submittedResultEngine),
'rejected', json_object(
'total', sa.rejected,
'resultEngine', sa.rejectedResultEngine),
'accepted', json_object(
'total', sa.accepted,
'resultEngine', sa.acceptedResultEngine)
) as status`,
`json_object(
'notchecked', json_object(
'total', sa.notchecked ,
'resultEngine', sa.notcheckedResultEngine),
'notapplicable', json_object(
'total', sa.notapplicable ,
'resultEngine', sa.notapplicableResultEngine),
'pass', json_object(
'total', sa.pass,
'resultEngine', sa.passResultEngine),
'fail', json_object(
'total', sa.fail,
'resultEngine', sa.failResultEngine),
'unknown', json_object(
'total', sa.unknown,
'resultEngine', sa.unknownResultEngine),
'error', json_object(
'total', sa.error ,
'resultEngine', sa.errorResultEngine),
'notselected', json_object(
'total', sa.notselected,
'resultEngine', sa.notselectedResultEngine),
'informational', json_object(
'total', sa.informational,
'resultEngine', sa.informationalResultEngine),
'fixed', json_object(
'total', sa.fixed ,
'resultEngine', sa.fixedResultEngine)
) as result`
]
let joins = [
'collection c',
'left join collection_grant cg on c.collectionId = cg.collectionId',
'inner join asset a on c.collectionId = a.collectionId and a.state = "enabled" ',
'inner join stig_asset_map sa on a.assetId = sa.assetId',
'left join user_stig_asset_map usa on sa.saId = usa.saId',
'left join current_rev cr on sa.benchmarkId = cr.benchmarkId',
]
// PROJECTIONS
// PREDICATES
let predicates = {
statements: ['c.state = "enabled"'],
binds: []
}
// collectionId predicate is mandatory per API spec
if ( inPredicates.collectionId ) {
predicates.statements.push('c.collectionId = ?')
predicates.binds.push( inPredicates.collectionId )
}
if ( inPredicates.benchmarkIds ) {
predicates.statements.push('sa.benchmarkId IN ?')
predicates.binds.push( [inPredicates.benchmarkIds] )
}
if ( inPredicates.assetIds ) {
predicates.statements.push('sa.assetId IN ?')
predicates.binds.push( [inPredicates.assetIds] )
}
predicates.statements.push('(cg.userId = ? AND CASE WHEN cg.accessLevel = 1 THEN usa.userId = cg.userId ELSE TRUE END)')
predicates.binds.push( userObject.userId, userObject.userId )
const sql = dbUtils.makeQueryString({columns, joins, predicates, orderBy})
let [rows] = await dbUtils.pool.query(sql, predicates.binds)
return (rows)
}
exports.queryStigAssets = async function (inProjection = [], inPredicates = {}, userObject) {
let columns = [
'sa.benchmarkId',
`json_object(
'assetId', CAST(a.assetId as char),
'name', a.name
) as asset`
]
let joins = [
'collection c',
'left join asset a on c.collectionId = a.collectionId',
'left join stig_asset_map sa on a.assetId = sa.assetId',
]
// PREDICATES
let predicates = {
statements: [
'c.state = "enabled"',
'a.state = "enabled"'
],
binds: []
}
let orderBy = ['sa.benchmarkId', 'a.name']
if ( inPredicates.collectionId ) {
predicates.statements.push('c.collectionId = ?')
predicates.binds.push( inPredicates.collectionId )
} else {
throw ( {status: 400, message: 'Missing required predicate: collectionId'} )
}
if ( inPredicates.userId ) {
joins.push('left join user_stig_asset_map usa on sa.saId = usa.saId')
predicates.statements.push('usa.userId = ?')
predicates.binds.push( inPredicates.userId )
}
const sql = dbUtils.makeQueryString({columns, joins, predicates, orderBy})
let [rows] = await dbUtils.pool.query(sql, predicates.binds)
return (rows)
}
exports.setStigAssetsByCollectionUser = async function(collectionId, userId, stigAssets, svcStatus = {}) {
let connection // available to try, catch, and finally blocks
try {
connection = await dbUtils.pool.getConnection()
connection.config.namedPlaceholders = true
async function transaction () {
await connection.query('START TRANSACTION');
const sqlDelete = `DELETE FROM
user_stig_asset_map
WHERE
userId = ?
and saId IN (
SELECT saId from stig_asset_map left join asset using (assetId) where asset.collectionId = ?
)`
await connection.execute(sqlDelete, [userId, collectionId])
if (stigAssets.length > 0) {
// Get saIds
const bindsInsertSaIds = [userId, collectionId]
const predicatesInsertSaIds = []
for (const stigAsset of stigAssets) {
bindsInsertSaIds.push(stigAsset.benchmarkId, stigAsset.assetId)
predicatesInsertSaIds.push('(sa.benchmarkId = ? AND sa.assetId = ?)')
}
let sqlInsertSaIds = `INSERT IGNORE INTO user_stig_asset_map (userId, saId)
SELECT
?,
sa.saId
FROM
stig_asset_map sa
inner join asset a on (sa.assetId = a.assetId and a.collectionId = ? and a.isEnabled = 1)
WHERE `
sqlInsertSaIds += predicatesInsertSaIds.join('\nOR\n')
await connection.execute(sqlInsertSaIds, bindsInsertSaIds)
}
await connection.commit()
}
await dbUtils.retryOnDeadlock(transaction, svcStatus)
}
catch (err) {
if (typeof connection !== 'undefined') {
await connection.rollback()
}
throw (err)
}
finally {
if (typeof connection !== 'undefined') {
await connection.release()
}
}
}
exports.addOrUpdateCollection = async function(writeAction, collectionId, body, projection, userObject, svcStatus = {}) {
// CREATE: collectionId will be null
// REPLACE/UPDATE: collectionId is not null
let connection // available to try, catch, and finally blocks
try {
const {grants, labels, ...collectionFields} = body
// Stringify JSON values
if ('metadata' in collectionFields) {
collectionFields.metadata = JSON.stringify(collectionFields.metadata)
}
// Merge default settings with any provided settings
collectionFields.settings = JSON.stringify({...MyController.defaultSettings, ...collectionFields.settings})
// Connect to MySQL
connection = await dbUtils.pool.getConnection()
connection.config.namedPlaceholders = true
async function transaction () {
await connection.query('START TRANSACTION');
// Process scalar properties
let binds = { ...collectionFields}
if (writeAction === dbUtils.WRITE_ACTION.CREATE) {
// INSERT into collections
let sqlInsert =
`INSERT INTO
collection
(name, description, settings, metadata)
VALUES
(:name, :description, :settings, :metadata)`
let [rows] = await connection.execute(sqlInsert, binds)
collectionId = rows.insertId
}
else if (writeAction === dbUtils.WRITE_ACTION.UPDATE || writeAction === dbUtils.WRITE_ACTION.REPLACE) {
if (Object.keys(binds).length > 0) {
// UPDATE into collections
let sqlUpdate =
`UPDATE
collection
SET
?
WHERE
collectionId = ?`
await connection.query(sqlUpdate, [collectionFields, collectionId])
}
}
else {
throw ( {status: 500, message: 'Invalid writeAction'} )
}
// Process grants
if (grants && writeAction !== dbUtils.WRITE_ACTION.CREATE) {
// DELETE from collection_grant
let sqlDeleteGrants = 'DELETE FROM collection_grant where collectionId = ?'
await connection.execute(sqlDeleteGrants, [collectionId])
}
if (grants && grants.length > 0) {
// INSERT into collection_grant
let sqlInsertGrants = `
INSERT INTO
collection_grant (collectionId, userId, accessLevel)
VALUES
?`
let binds = grants.map(i => [collectionId, i.userId, i.accessLevel])
await connection.query(sqlInsertGrants, [binds])
}
// Process labels
if (labels && writeAction !== dbUtils.WRITE_ACTION.CREATE) {
// DELETE from collection_grant
let sqlDeleteLabels = 'DELETE FROM collection_label where collectionId = ?'
await connection.execute(sqlDeleteLabels, [collectionId])
}
if (labels && labels.length > 0) {
// INSERT into collection_label
let sqlInsertLabels = `
INSERT INTO
collection_label (collectionId, name, description, color, uuid)
VALUES
?`
const binds = labels.map(i => [collectionId, i.name, i.description, i.color, {
toSqlString: function () {
return `UUID_TO_BIN(UUID(),1)`
}
}])
await connection.query(sqlInsertLabels, [binds])
}
// Commit the changes
await connection.commit()
}
await dbUtils.retryOnDeadlock(transaction, svcStatus)
}
catch (err) {
await connection.rollback()
throw err
}
finally {
if (typeof connection !== 'undefined') {
await connection.release()
}
}
let row = await _this.getCollection(collectionId, projection, true, userObject)
return row
}
/**
* Create a Collection
*
* body CollectionAssign (optional)
* returns List
**/
exports.createCollection = async function(body, projection, userObject, svcStatus = {}) {
let row = await _this.addOrUpdateCollection(dbUtils.WRITE_ACTION.CREATE, null, body, projection, userObject, svcStatus)
return (row)
}
/**
* Delete a Collection
*
* collectionId Integer A path parameter that identifies a Collection
* returns CollectionInfo
**/
exports.deleteCollection = async function(collectionId, projection, elevate, userObject) {
const row = await _this.queryCollections(projection, { collectionId: collectionId }, elevate, userObject)
const sqlDelete = `UPDATE collection SET state = "disabled", stateDate = NOW(), stateUserId = ? where collectionId = ?`
await dbUtils.pool.query(sqlDelete, [userObject.userId, collectionId])
return (row[0])
}
/**
* Return the Checklist for the supplied Collection and STIG
*
* collectionId Integer A path parameter that identifies a Collection
* benchmarkId String A path parameter that identifies a STIG
* revisionStr String A path parameter that identifies a STIG revision [ V{version_num}R{release_num} | 'latest' ]
* returns CollectionChecklist
**/
exports.getChecklistByCollectionStig = async function (collectionId, benchmarkId, revisionStr, userObject ) {
let connection
try {
const groupBy = ['rgr.rgrId']
const orderBy = ['rgr.ruleId']
const columns = [
`rgr.ruleId
,rgr.title as ruleTitle
,rgr.severity
,rgr.\`version\`
,rgr.groupId
,rgr.groupTitle
,json_object(
'results', json_object(
'pass', sum(CASE WHEN r.resultId = 3 THEN 1 ELSE 0 END),
'fail', sum(CASE WHEN r.resultId = 4 THEN 1 ELSE 0 END),
'notapplicable', sum(CASE WHEN r.resultId = 2 THEN 1 ELSE 0 END),
'other', sum(CASE WHEN r.resultId is null OR (r.resultId != 2 AND r.resultId != 3 AND r.resultId != 4) THEN 1 ELSE 0 END)
),
'statuses', json_object(
'saved', sum(CASE WHEN r.statusId = 0 THEN 1 ELSE 0 END),
'submitted', sum(CASE WHEN r.statusId = 1 THEN 1 ELSE 0 END),
'rejected', sum(CASE WHEN r.statusId = 2 THEN 1 ELSE 0 END),
'accepted', sum(CASE WHEN r.statusId = 3 THEN 1 ELSE 0 END)
)
) as counts
,json_object(
'ts', json_object(
'min', DATE_FORMAT(MIN(r.ts),'%Y-%m-%dT%H:%i:%sZ'),
'max', DATE_FORMAT(MAX(r.ts),'%Y-%m-%dT%H:%i:%sZ')
),
'statusTs', json_object(
'min', DATE_FORMAT(MIN(r.statusTs),'%Y-%m-%dT%H:%i:%sZ'),
'max', DATE_FORMAT(MAX(r.statusTs),'%Y-%m-%dT%H:%i:%sZ')
),
'touchTs', json_object(
'min', DATE_FORMAT(MIN(r.touchTs),'%Y-%m-%dT%H:%i:%sZ'),
'max', DATE_FORMAT(MAX(r.touchTs),'%Y-%m-%dT%H:%i:%sZ')
)
) as timestamps`
]
const joins = [
'asset a',
'left join stig_asset_map sa using (assetId)',
'left join current_rev rev using (benchmarkId)',
'left join rev_group_rule_map rgr using (revId)',
'left join rule_version_check_digest rvcd using (ruleId)',
'left join review r on (rvcd.version=r.version and rvcd.checkDigest=r.checkDigest and sa.assetId=r.assetId)'
]
const predicates = {
statements: [
'a.collectionId = :collectionId',
'rev.benchmarkId = :benchmarkId',
'a.state = "enabled"'
],
binds: {
collectionId: collectionId,
benchmarkId: benchmarkId
}
}
// Non-current revision
if (revisionStr !== 'latest') {
joins.splice(2, 1, 'left join revision rev on sa.benchmarkId=rev.benchmarkId')
const {version, release} = dbUtils.parseRevisionStr(revisionStr)
predicates.statements.push('rev.version = :version')
predicates.statements.push('rev.release = :release')
predicates.binds.version = version
predicates.binds.release = release
}
// Access control
const collectionGrant = userObject.collectionGrants.find( g => g.collection.collectionId === collectionId )
if (collectionGrant?.accessLevel === 1) {
predicates.statements.push(`a.assetId in (
select
sa.assetId
from
user_stig_asset_map usa
left join stig_asset_map sa on (usa.saId=sa.saId and sa.benchmarkId = :benchmarkId)
where
usa.userId=:userId)`)
predicates.binds.userId = userObject.userId
}
const sql = dbUtils.makeQueryString({columns, joins, predicates, groupBy, orderBy})
// Send query
connection = await dbUtils.pool.getConnection()
connection.config.namedPlaceholders = true
const [rows] = await connection.query(sql, predicates.binds)
return (rows)
}
finally {
if (typeof connection !== 'undefined') {
await connection.release()
}
}
}
/**
* Return a Collection
*
* collectionId Integer A path parameter that identifies a Collection
* returns CollectionInfo
**/
exports.getCollection = async function(collectionId, projection, elevate, userObject) {
let rows = await _this.queryCollections(projection, {
collectionId: collectionId
}, elevate, userObject)
return (rows[0])
}
/**
* Return a list of Collections accessible to the user
*
* returns List
**/
exports.getCollections = async function(predicates, projection, elevate, userObject) {
let rows = await _this.queryCollections(projection, predicates, elevate, userObject)
return (rows)
}
exports.getFindingsByCollection = async function( collectionId, aggregator, benchmarkId, assetId, acceptedOnly, projection, userObject ) {
let rows = await _this.queryFindings(aggregator, projection, {
collectionId: collectionId,
benchmarkId: benchmarkId,
assetId: assetId,
acceptedOnly: acceptedOnly
}, userObject)
return (rows)
}
exports.getStigAssetsByCollectionUser = async function (collectionId, userId, elevate, userObject) {
let rows = await _this.queryStigAssets([], {
collectionId: collectionId,
userId: userId
}, userObject)
return (rows)
}
exports.getStigsByCollection = async function( {collectionId, labelIds, labelNames, labelMatch, userObject, benchmarkId, projections} ) {
const columns = [
'sa.benchmarkId',
'stig.title',
'revision.revisionStr',
`date_format(revision.benchmarkDateSql,'%Y-%m-%d') as benchmarkDate`,
'CASE WHEN dr.revisionPinned = 1 THEN CAST(true as json) ELSE CAST(false as json) END as revisionPinned',
'revision.ruleCount',
'count(sa.assetId) as assetCount'
]
const groupBy = ['sa.benchmarkId', 'revision.revId', 'dr.revisionPinned', 'stig.benchmarkId']
const orderBy = ['sa.benchmarkId']
const joins = [
'collection c',
'left join collection_grant cg on c.collectionId = cg.collectionId',
'left join asset a on c.collectionId = a.collectionId',
'inner join stig_asset_map sa on a.assetId = sa.assetId',
'left join default_rev dr on (sa.benchmarkId = dr.benchmarkId and c.collectionId = dr.collectionId)',
'left join revision on dr.revId = revision.revId',
'left join stig on revision.benchmarkId = stig.benchmarkId'
]
// PREDICATES
const predicates = {
statements: [
'a.state = "enabled"'
],
binds: []
}
predicates.statements.push('c.collectionId = ?')
predicates.binds.push( collectionId )
if (labelIds || labelNames || labelMatch) {
joins.push(
'left join collection_label_asset_map cla2 on a.assetId = cla2.assetId',
'left join collection_label cl2 on cla2.clId = cl2.clId'
)
const labelPredicates = []
if (labelIds) {
labelPredicates.push('cl2.uuid IN ?')
const uuidBinds = labelIds.map( uuid => dbUtils.uuidToSqlString(uuid))
predicates.binds.push([uuidBinds])
}
if (labelNames) {
labelPredicates.push('cl2.name IN ?')
predicates.binds.push([labelNames])
}
if (labelMatch === 'null') {
labelPredicates.push('cl2.uuid IS NULL')
}
const labelPredicatesClause = `(${labelPredicates.join(' OR ')})`
predicates.statements.push(labelPredicatesClause)
}
if (benchmarkId) {
predicates.statements.push('sa.benchmarkId = ?')
predicates.binds.push( benchmarkId )
}
if (projections?.includes('assets')) {
columns.push(`cast(concat('[', group_concat(distinct json_object (
'assetId', CAST(a.assetId as char),
'name', a.name) order by a.name), ']') as json) as "assets"`)
}
joins.push('left join user_stig_asset_map usa on sa.saId = usa.saId')
predicates.statements.push('(cg.userId = ? AND CASE WHEN cg.accessLevel = 1 THEN usa.userId = cg.userId ELSE TRUE END)')
predicates.binds.push( userObject.userId )
const sql = dbUtils.makeQueryString({columns, joins, predicates, groupBy, orderBy})
let [rows] = await dbUtils.pool.query(sql, predicates.binds)
return (rows)
}
/**
* Replace all properties of a Collection
*
* body CollectionAssign (optional)
* collectionId Integer A path parameter that identifies a Collection
* returns CollectionInfo
**/
exports.replaceCollection = async function( collectionId, body, projection, userObject, svcStatus = {}) {
let row = await _this.addOrUpdateCollection(dbUtils.WRITE_ACTION.REPLACE, collectionId, body, projection, userObject, svcStatus)
return (row)
}
/**
* Merge updates to a Collection
*
* body CollectionAssign (optional)
* collectionId Integer A path parameter that identifies a Collection
* returns CollectionInfo
**/
exports.updateCollection = async function( collectionId, body, projection, userObject, svcStatus = {}) {
let row = await _this.addOrUpdateCollection(dbUtils.WRITE_ACTION.UPDATE, collectionId, body, projection, userObject, svcStatus)
return (row)
}
exports.getCollectionMetadataKeys = async function ( collectionId ) {
const binds = []
let sql = `
select
JSON_KEYS(metadata) as keyArray
from
collection
where
collectionId = ?`
binds.push(collectionId)
let [rows] = await dbUtils.pool.query(sql, binds)
return rows.length > 0 ? rows[0].keyArray : []
}
exports.getCollectionMetadata = async function ( collectionId ) {
const binds = []
let sql = `
select
metadata
from
collection
where
collectionId = ?`
binds.push(collectionId)
let [rows] = await dbUtils.pool.query(sql, binds)
return rows.length > 0 ? rows[0].metadata : {}
}
exports.patchCollectionMetadata = async function ( collectionId, metadata ) {
const binds = []
let sql = `
update
collection
set
metadata = JSON_MERGE_PATCH(metadata, ?)
where
collectionId = ?`