sbom-tools 0.2.0

Semantic SBOM diff and analysis tool
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
//! Generic-path compliance checks shared across the non-dedicated
//! profiles (Minimum, Standard, NTIA, CRA phases, FDA, Comprehensive):
//! document metadata, components, dependencies, vulnerability metadata,
//! and format-specific (CycloneDX / SPDX) requirements.

use super::*;

impl ComplianceChecker {
    pub(crate) fn check_document_metadata(
        &self,
        sbom: &NormalizedSbom,
        violations: &mut Vec<Violation>,
    ) {
        use crate::model::{CreatorType, ExternalRefType};

        // All levels require creator information
        if sbom.document.creators.is_empty() {
            let (requirement, rule_id) = match self.level {
                ComplianceLevel::NtiaMinimum => (
                    "NTIA Minimum Elements: Author".to_string(),
                    "SBOM-NTIA-AUTHOR",
                ),
                ComplianceLevel::FdaMedicalDevice => (
                    "FDA: SBOM creator/manufacturer identification".to_string(),
                    "SBOM-FDA-CREATOR",
                ),
                _ => (
                    "Document creator identification".to_string(),
                    generic_rule_id_for_level(self.level),
                ),
            };
            violations.push(Violation {
                severity: match self.level {
                    ComplianceLevel::Minimum => ViolationSeverity::Warning,
                    _ => ViolationSeverity::Error,
                },
                category: ViolationCategory::DocumentMetadata,
                message: "SBOM must have creator/tool information".to_string(),
                element: None,
                requirement,
                rule_id,
                component_id: None,
                counts: None,
                standard_refs: Vec::new(),
            });
        }

        // CRA: Manufacturer identification and product name
        if self.level.is_cra() {
            let has_org = sbom
                .document
                .creators
                .iter()
                .any(|c| c.creator_type == CreatorType::Organization);
            let sidecar_has_manufacturer = self
                .sidecar
                .as_ref()
                .is_some_and(|s| s.manufacturer_name.is_some());
            if !has_org {
                if sidecar_has_manufacturer {
                    violations.push(Violation {
                        severity: ViolationSeverity::Info,
                        category: ViolationCategory::DocumentMetadata,
                        message:
                            "[CRA Art. 13(16)] Manufacturer identified via CRA sidecar (consider adding to the SBOM directly for portability)"
                                .to_string(),
                        element: None,
                        requirement: "CRA Art. 13(16): Manufacturer identification".to_string(),
                        rule_id: "SBOM-CRA-ART-13-16",
                        component_id: None,
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                } else {
                    violations.push(Violation {
                        severity: ViolationSeverity::Warning,
                        category: ViolationCategory::DocumentMetadata,
                        message:
                            "[CRA Art. 13(16)] SBOM should identify the manufacturer (organization)"
                                .to_string(),
                        element: None,
                        requirement: "CRA Art. 13(16): Manufacturer identification".to_string(),
                        rule_id: "SBOM-CRA-ART-13-16",
                        component_id: None,
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                }
            }

            // Validate manufacturer email format if present
            for creator in &sbom.document.creators {
                if creator.creator_type == CreatorType::Organization
                    && let Some(email) = &creator.email
                    && !is_valid_email_format(email)
                {
                    violations.push(Violation {
                        severity: ViolationSeverity::Warning,
                        category: ViolationCategory::DocumentMetadata,
                        message: format!(
                            "[CRA Art. 13(16)] Manufacturer email '{email}' appears invalid"
                        ),
                        element: None,
                        requirement: "CRA Art. 13(16): Valid contact information".to_string(),
                        rule_id: "SBOM-CRA-ART-13-16-EMAIL",
                        component_id: None,
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                }
            }

            if sbom.document.name.is_none() {
                let sidecar_has_product_name = self
                    .sidecar
                    .as_ref()
                    .is_some_and(|s| s.product_name.is_some());
                if sidecar_has_product_name {
                    violations.push(Violation {
                        severity: ViolationSeverity::Info,
                        category: ViolationCategory::DocumentMetadata,
                        message: "[CRA Art. 13(15)] Product name provided via CRA sidecar (consider adding metadata.component.name to the SBOM)".to_string(),
                        element: None,
                        requirement: "CRA Art. 13(15): Product identification".to_string(),
                        rule_id: "SBOM-CRA-ART-13-15-PRODUCT",
                        component_id: None,
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                } else {
                    violations.push(Violation {
                        severity: ViolationSeverity::Warning,
                        category: ViolationCategory::DocumentMetadata,
                        message: "[CRA Art. 13(15)] SBOM should include the product name"
                            .to_string(),
                        element: None,
                        requirement: "CRA Art. 13(15): Product identification".to_string(),
                        rule_id: "SBOM-CRA-ART-13-15-PRODUCT",
                        component_id: None,
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                }
            }

            // CRA: Security contact / vulnerability disclosure point
            // First check document-level security contact (preferred)
            let has_doc_security_contact = sbom.document.security_contact.is_some()
                || sbom.document.vulnerability_disclosure_url.is_some();

            // Fallback: check component-level external refs — but only on the
            // primary/root components. A third-party dependency's upstream
            // advisories or support URL is not the manufacturer's contact.
            let has_component_security_contact =
                manufacturer_scope_components(sbom).iter().any(|comp| {
                    comp.external_refs.iter().any(|r| {
                        matches!(
                            r.ref_type,
                            ExternalRefType::SecurityContact
                                | ExternalRefType::Support
                                | ExternalRefType::Advisories
                        )
                    })
                });

            if !has_doc_security_contact && !has_component_security_contact {
                let sidecar_has_security = self.sidecar.as_ref().is_some_and(|s| {
                    s.security_contact.is_some() || s.vulnerability_disclosure_url.is_some()
                });
                if sidecar_has_security {
                    violations.push(Violation {
                        severity: ViolationSeverity::Info,
                        category: ViolationCategory::SecurityInfo,
                        message: "[CRA Art. 13(17)] Security contact provided via CRA sidecar (consider adding a security-contact externalReference to the SBOM)".to_string(),
                        element: None,
                        requirement: "CRA Art. 13(17): Vulnerability disclosure contact"
                            .to_string(),
                        rule_id: "SBOM-CRA-ART-13-17-CONTACT",
                        component_id: None,
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                } else {
                    violations.push(Violation {
                        severity: ViolationSeverity::Warning,
                        category: ViolationCategory::SecurityInfo,
                        message: "[CRA Art. 13(17)] SBOM should include a security contact or vulnerability disclosure reference".to_string(),
                        element: None,
                        requirement: "CRA Art. 13(17): Vulnerability disclosure contact"
                            .to_string(),
                        rule_id: "SBOM-CRA-ART-13-17-CONTACT",
                        component_id: None,
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                }
            }

            // CRA: Check for primary/root product component identification
            if sbom.primary_component_id.is_none() && sbom.components.len() > 1 {
                violations.push(Violation {
                    severity: ViolationSeverity::Warning,
                    category: ViolationCategory::DocumentMetadata,
                    message: "[CRA Annex I] SBOM should identify the primary product component (CycloneDX metadata.component or SPDX documentDescribes)".to_string(),
                    element: None,
                    requirement: "CRA Annex I: Primary product identification".to_string(),
                    rule_id: "SBOM-CRA-ANNEX-I-PRIMARY",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // CRA: Check for support end date (informational). The support
            // period is determined under Art. 13(8); its end date must be
            // disclosed at purchase (Art. 13(19)) and accompany the product
            // (Annex II (7)).
            if sbom.document.support_end_date.is_none() {
                violations.push(Violation {
                    severity: ViolationSeverity::Info,
                    category: ViolationCategory::SecurityInfo,
                    message: "[CRA Art. 13(8) / 13(19)] Consider specifying a support end date for security updates".to_string(),
                    element: None,
                    requirement: "CRA Art. 13(8) / 13(19): Support period disclosure".to_string(),
                    rule_id: "SBOM-CRA-ART-13-8",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // CRA Annex I Part II (1): Machine-readable SBOM format validation
            // The CRA requires SBOMs in a "commonly used and machine-readable"
            // format (Annex I Part II (1)). CycloneDX 1.4+ and SPDX 2.3+ are
            // widely accepted as machine-readable.
            let format_ok = match sbom.document.format {
                SbomFormat::CycloneDx => {
                    let v = &sbom.document.spec_version;
                    !(v.starts_with("1.0")
                        || v.starts_with("1.1")
                        || v.starts_with("1.2")
                        || v.starts_with("1.3"))
                }
                SbomFormat::Spdx => {
                    // An empty spec_version means the document declared no
                    // version (parsers never fabricate one): skip rather
                    // than false-fail, matching the CycloneDX arm where an
                    // empty version also passes.
                    let v = &sbom.document.spec_version;
                    v.is_empty() || v.starts_with("2.3") || v.starts_with("3.")
                }
            };
            if !format_ok {
                violations.push(Violation {
                    severity: ViolationSeverity::Warning,
                    category: ViolationCategory::FormatSpecific,
                    message: format!(
                        "[CRA Annex I Part II (1)] SBOM format version {} {} may not meet the CRA machine-readable requirement; use CycloneDX 1.4+, SPDX 2.3+, or SPDX 3.0+",
                        sbom.document.format, sbom.document.spec_version
                    ),
                    element: None,
                    requirement: "CRA Annex I Part II (1): Machine-readable SBOM format"
                        .to_string(),
                    rule_id: "SBOM-CRA-MACHINE-READABLE",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // CRA Annex I Part II (1): Unique product identifier traceability
            // The primary/root component should have a stable unique identifier (PURL or CPE)
            // that can be traced across software updates.
            if let Some(ref primary_id) = sbom.primary_component_id
                && let Some(primary) = sbom.components.get(primary_id)
                && primary.identifiers.purl.is_none()
                && primary.identifiers.cpe.is_empty()
            {
                violations.push(Violation {
                            severity: ViolationSeverity::Warning,
                            category: ViolationCategory::ComponentIdentification,
                            message: format!(
                                "[CRA Annex I Part II (1)] Primary component '{}' missing unique identifier (PURL/CPE) for cross-update traceability",
                                primary.name
                            ),
                            element: Some(primary.name.clone()),
                            requirement: "CRA Annex I Part II (1): Product identifier traceability across updates".to_string(),
                            rule_id: "SBOM-CRA-ANNEX-I-TRACEABILITY",
                            component_id: Some(primary.canonical_id.value().to_string()),
                            counts: None,
                            standard_refs: Vec::new(),
                        });
            }
        }

        // CRA Phase 2-only checks (full application of the regulation: 11 Dec 2027)
        if matches!(self.level, ComplianceLevel::CraPhase2) {
            // CRA Annex I Part II (5): Coordinated vulnerability disclosure policy reference
            // Check for a vulnerability disclosure policy URL or advisories reference
            // Component-level Advisories refs count only on the primary/root
            // components — a dependency's upstream advisories URL is not the
            // manufacturer's CVD policy.
            let has_vuln_disclosure_policy = sbom.document.vulnerability_disclosure_url.is_some()
                || manufacturer_scope_components(sbom).iter().any(|comp| {
                    comp.external_refs
                        .iter()
                        .any(|r| matches!(r.ref_type, ExternalRefType::Advisories))
                });
            if !has_vuln_disclosure_policy {
                let sidecar_has_cvd = self
                    .sidecar
                    .as_ref()
                    .is_some_and(|s| s.vulnerability_disclosure_url.is_some());
                if sidecar_has_cvd {
                    violations.push(Violation {
                        severity: ViolationSeverity::Info,
                        category: ViolationCategory::SecurityInfo,
                        message: "[CRA Annex I Part II (5)] CVD policy URL provided via CRA sidecar (consider adding an advisories externalReference to the SBOM)".to_string(),
                        element: None,
                        requirement: "CRA Annex I Part II (5): Coordinated vulnerability disclosure policy".to_string(),
                        rule_id: "SBOM-CRA-CVD-POLICY",
                        component_id: None,
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                } else {
                    violations.push(Violation {
                        severity: ViolationSeverity::Warning,
                        category: ViolationCategory::SecurityInfo,
                        message: "[CRA Annex I Part II (5)] SBOM should reference a coordinated vulnerability disclosure policy (advisories URL or disclosure URL)".to_string(),
                        element: None,
                        requirement: "CRA Annex I Part II (5): Coordinated vulnerability disclosure policy".to_string(),
                        rule_id: "SBOM-CRA-CVD-POLICY",
                        component_id: None,
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                }
            }

            // CRA Art. 13(8) / Annex II (7): Component lifecycle status
            // Check whether the primary component (or any top-level component) has end-of-life
            // or lifecycle information. Currently we check support_end_date at doc level.
            // Also check for lifecycle properties on components.
            if !self.has_support_lifecycle_evidence(sbom) {
                violations.push(Violation {
                    severity: ViolationSeverity::Info,
                    category: ViolationCategory::SecurityInfo,
                    message: "[CRA Art. 13(8) / Annex II (7)] Consider including component lifecycle/end-of-support information".to_string(),
                    element: None,
                    requirement: "CRA Annex II (7): Component lifecycle status".to_string(),
                    rule_id: "SBOM-CRA-LIFECYCLE",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // CRA Annex V: EU Declaration of Conformity reference
            // Check for an attestation, certification, or declaration-of-conformity reference
            let has_conformity_ref = sbom.components.values().any(|comp| {
                comp.external_refs.iter().any(|r| {
                    matches!(
                        r.ref_type,
                        ExternalRefType::Attestation | ExternalRefType::Certification
                    ) || (matches!(r.ref_type, ExternalRefType::Other(ref s) if s.to_lowercase().contains("declaration-of-conformity"))
                    )
                })
            });
            let sidecar_has_doc_ref = self
                .sidecar
                .as_ref()
                .is_some_and(|s| s.ce_marking_reference.is_some());
            if !has_conformity_ref && !sidecar_has_doc_ref {
                let severity = self
                    .class_severity(ClassCheck::DocReference)
                    .unwrap_or(ViolationSeverity::Info);
                violations.push(Violation {
                    severity,
                    category: ViolationCategory::DocumentMetadata,
                    message: format!(
                        "[CRA Annex V] Missing reference to the EU Declaration of Conformity (attestation or certification external reference) for product class {}",
                        self.effective_product_class().label()
                    ),
                    element: None,
                    requirement: "CRA Annex V: EU Declaration of Conformity reference".to_string(),
                    rule_id: "SBOM-CRA-ANNEX-V",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }
        }

        // FDA requires manufacturer (organization) as creator
        if matches!(self.level, ComplianceLevel::FdaMedicalDevice) {
            let has_org = sbom
                .document
                .creators
                .iter()
                .any(|c| c.creator_type == CreatorType::Organization);
            if !has_org {
                violations.push(Violation {
                    severity: ViolationSeverity::Warning,
                    category: ViolationCategory::DocumentMetadata,
                    message: "FDA: SBOM should have manufacturer (organization) as creator"
                        .to_string(),
                    element: None,
                    requirement: "FDA: Manufacturer identification".to_string(),
                    rule_id: "SBOM-FDA-SUPPLIER",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // FDA recommends contact information
            let has_contact = sbom.document.creators.iter().any(|c| c.email.is_some());
            if !has_contact {
                violations.push(Violation {
                    severity: ViolationSeverity::Warning,
                    category: ViolationCategory::DocumentMetadata,
                    message: "FDA: SBOM creators should include contact email".to_string(),
                    element: None,
                    requirement: "FDA: Contact information".to_string(),
                    rule_id: "SBOM-FDA-SUPPORT",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // FDA: Document name required
            if sbom.document.name.is_none() {
                violations.push(Violation {
                    severity: ViolationSeverity::Warning,
                    category: ViolationCategory::DocumentMetadata,
                    message: "FDA: SBOM should have a document name/title".to_string(),
                    element: None,
                    requirement: "FDA: Document identification".to_string(),
                    rule_id: "SBOM-FDA-NAME",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // FDA 2023 premarket guidance / FD&C §524B: beyond the NTIA
            // baseline, the SBOM package must convey each component's level
            // of support and end-of-support date. The guidance allows this
            // to accompany the SBOM, so absence is a Warning (not a gating
            // Error): we accept a document-level support end date, component
            // lifecycle/EOL properties, or the sidecar's support end date as
            // evidence.
            if !self.has_support_lifecycle_evidence(sbom) {
                violations.push(Violation {
                    severity: ViolationSeverity::Warning,
                    category: ViolationCategory::SecurityInfo,
                    message: "FDA: no level-of-support or end-of-support information found \
                        (required by the premarket cybersecurity guidance / FD&C §524B; \
                        add component lifecycle/end-of-support data or provide it alongside the SBOM)"
                        .to_string(),
                    element: None,
                    requirement: "FDA: Level of support and end-of-support date".to_string(),
                    rule_id: "SBOM-FDA-SUPPORT",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }
        }

        // NTIA "Timestamp" is one of the seven required minimum data fields,
        // and the FDA premarket guidance incorporates the NTIA baseline.
        // `DocumentMetadata::created` is never None, but a missing/invalid
        // source timestamp is stored as the UNIX_EPOCH sentinel (see
        // `has_known_timestamp`), so gate on that rather than assuming it is
        // always meaningful.
        if matches!(
            self.level,
            ComplianceLevel::NtiaMinimum
                | ComplianceLevel::FdaMedicalDevice
                | ComplianceLevel::Comprehensive
        ) && !sbom.document.has_known_timestamp()
        {
            let requirement = if self.level == ComplianceLevel::FdaMedicalDevice {
                "FDA (NTIA baseline): Timestamp".to_string()
            } else {
                "NTIA Minimum Elements: Timestamp".to_string()
            };
            violations.push(Violation {
                severity: ViolationSeverity::Error,
                category: ViolationCategory::DocumentMetadata,
                message: "SBOM is missing a creation timestamp (NTIA required data field)"
                    .to_string(),
                element: None,
                requirement,
                rule_id: "SBOM-NTIA-TIMESTAMP",
                component_id: None,
                counts: None,
                standard_refs: Vec::new(),
            });
        }

        // Standard+ requires serial number/document ID
        if matches!(
            self.level,
            ComplianceLevel::Standard
                | ComplianceLevel::FdaMedicalDevice
                | ComplianceLevel::CraPhase1
                | ComplianceLevel::CraPhase2
                | ComplianceLevel::Comprehensive
        ) && sbom.document.serial_number.is_none()
        {
            let rule_id = if self.level == ComplianceLevel::FdaMedicalDevice {
                "SBOM-FDA-NAMESPACE"
            } else {
                generic_rule_id_for_level(self.level)
            };
            violations.push(Violation {
                severity: ViolationSeverity::Warning,
                category: ViolationCategory::DocumentMetadata,
                message: "SBOM should have a serial number/unique identifier".to_string(),
                element: None,
                requirement: "Document unique identification".to_string(),
                rule_id,
                component_id: None,
                counts: None,
                standard_refs: Vec::new(),
            });
        }
    }

    /// Whether the SBOM (or its sidecar) carries any support-lifecycle
    /// evidence: a document-level support end date, component
    /// lifecycle/end-of-life/end-of-support properties, or a sidecar
    /// support end date. Shared by the CRA lifecycle (Art. 13(8) /
    /// Annex II (7)) and FDA level-of-support checks.
    fn has_support_lifecycle_evidence(&self, sbom: &NormalizedSbom) -> bool {
        sbom.document.support_end_date.is_some()
            || self
                .sidecar
                .as_ref()
                .is_some_and(|s| s.support_end_date.is_some())
            || sbom.components.values().any(|comp| {
                comp.extensions.properties.iter().any(|p| {
                    // Token-match the property name — a bare substring test
                    // let "geolocation" satisfy the lifecycle element via
                    // its embedded "eol" — and require a real value.
                    let name_lower = p.name.to_lowercase();
                    let is_lifecycle_name = name_lower
                        .split(|c: char| !c.is_ascii_alphanumeric())
                        .any(|t| t == "eol" || t == "lifecycle")
                        || name_lower.contains("end-of-life")
                        || name_lower.contains("end-of-support")
                        || name_lower.contains("endoflife")
                        || name_lower.contains("endofsupport");
                    is_lifecycle_name && known_value(Some(p.value.as_str())).is_some()
                })
            })
    }

    pub(crate) fn check_components(&self, sbom: &NormalizedSbom, violations: &mut Vec<Violation>) {
        use crate::model::HashAlgorithm;

        for comp in sbom.components.values() {
            // All levels: component must have a name. Whitespace-only names
            // and placeholder sentinels count as missing, but genuine
            // packages named "none"/"unknown" (corroborated by their PURL)
            // do not (see `known_component_name`).
            if !known_component_name(comp) {
                let (requirement, rule_id) = match self.level {
                    ComplianceLevel::NtiaMinimum => (
                        "NTIA Minimum Elements: Component Name".to_string(),
                        "SBOM-NTIA-NAME",
                    ),
                    ComplianceLevel::FdaMedicalDevice => (
                        "FDA: Component name (required)".to_string(),
                        "SBOM-FDA-GENERAL",
                    ),
                    _ => (
                        "Component name (required)".to_string(),
                        generic_rule_id_for_level(self.level),
                    ),
                };
                violations.push(Violation {
                    severity: ViolationSeverity::Error,
                    category: ViolationCategory::ComponentIdentification,
                    message: "Component must have a name".to_string(),
                    element: Some(comp.identifiers.format_id.clone()),
                    requirement,
                    rule_id,
                    component_id: Some(comp.canonical_id.value().to_string()),
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // File/snippet inventory entries are name+hash records, not
            // packages: the version / unique-identifier / supplier / license
            // requirements below do not apply to them (NTIA scopes those to
            // components). Without this carve-out, a file-cataloguing SBOM
            // emits thousands of spurious Errors and auto-fails compliance.
            if matches!(comp.component_type, crate::model::ComponentType::File) {
                continue;
            }

            // NTIA minimum & FDA: version required (the CRA levels include
            // the Art. 24 steward profile — steward SBOMs still need
            // versioned components)
            if matches!(
                self.level,
                ComplianceLevel::NtiaMinimum
                    | ComplianceLevel::FdaMedicalDevice
                    | ComplianceLevel::Standard
                    | ComplianceLevel::CraPhase1
                    | ComplianceLevel::CraPhase2
                    | ComplianceLevel::CraOssSteward
                    | ComplianceLevel::Comprehensive
            ) && !has_known_value(&comp.version)
            {
                let (req, msg, rule_id) = match self.level {
                    ComplianceLevel::FdaMedicalDevice => (
                        "FDA: Component version".to_string(),
                        format!("Component '{}' missing version", comp.name),
                        "SBOM-FDA-VERSION",
                    ),
                    ComplianceLevel::CraPhase1
                    | ComplianceLevel::CraPhase2
                    | ComplianceLevel::CraOssSteward => (
                        "CRA Annex I Part II (1): Component version".to_string(),
                        format!(
                            "[CRA Annex I Part II (1)] Component '{}' missing version",
                            comp.name
                        ),
                        "SBOM-CRA-COMPONENT-VERSION",
                    ),
                    _ => (
                        "NTIA: Component version".to_string(),
                        format!("Component '{}' missing version", comp.name),
                        "SBOM-NTIA-VERSION",
                    ),
                };
                violations.push(Violation {
                    severity: ViolationSeverity::Error,
                    category: ViolationCategory::ComponentIdentification,
                    message: msg,
                    element: Some(comp.name.clone()),
                    requirement: req,
                    rule_id,
                    component_id: Some(comp.canonical_id.value().to_string()),
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // NTIA, Standard+ & FDA: should have PURL/CPE/SWHID/SWID
            // "Other Unique Identifiers" is one of the seven NTIA minimum
            // data fields; CRA prEN 40000-1-3 [PRE-7-RQ-07] explicitly names
            // PURL, CPE, SWHID
            if matches!(
                self.level,
                ComplianceLevel::NtiaMinimum
                    | ComplianceLevel::Standard
                    | ComplianceLevel::FdaMedicalDevice
                    | ComplianceLevel::CraPhase1
                    | ComplianceLevel::CraPhase2
                    | ComplianceLevel::CraOssSteward
                    | ComplianceLevel::Comprehensive
            ) && !comp.identifiers.has_cra_identifier()
            {
                let severity = if matches!(
                    self.level,
                    ComplianceLevel::NtiaMinimum
                        | ComplianceLevel::FdaMedicalDevice
                        | ComplianceLevel::CraPhase1
                        | ComplianceLevel::CraPhase2
                        | ComplianceLevel::CraOssSteward
                ) {
                    ViolationSeverity::Error
                } else {
                    ViolationSeverity::Warning
                };
                let (message, requirement, rule_id) = match self.level {
                    ComplianceLevel::NtiaMinimum => (
                        format!(
                            "Component '{}' missing unique identifier (PURL/CPE/SWHID/SWID)",
                            comp.name
                        ),
                        "NTIA Minimum Elements: Other Unique Identifiers".to_string(),
                        "SBOM-NTIA-IDENTIFIER",
                    ),
                    ComplianceLevel::FdaMedicalDevice => (
                        format!(
                            "Component '{}' missing unique identifier (PURL/CPE/SWHID/SWID)",
                            comp.name
                        ),
                        "FDA: Unique component identifier".to_string(),
                        "SBOM-FDA-IDENTIFIER",
                    ),
                    ComplianceLevel::CraPhase1
                    | ComplianceLevel::CraPhase2
                    | ComplianceLevel::CraOssSteward => (
                        format!(
                            "[CRA Annex I, [PRE-7-RQ-07]] Component '{}' missing unique identifier (PURL/CPE/SWHID/SWID)",
                            comp.name
                        ),
                        "CRA Annex I / prEN 40000-1-3 [PRE-7-RQ-07]: Unique component identifier (PURL/CPE/SWHID/SWID)".to_string(),
                        "SBOM-CRA-ANNEX-I-IDENTIFIER",
                    ),
                    _ => (
                        format!(
                            "Component '{}' missing unique identifier (PURL/CPE/SWHID/SWID)",
                            comp.name
                        ),
                        "Standard identifier (PURL/CPE/SWHID)".to_string(),
                        generic_rule_id_for_level(self.level),
                    ),
                };
                violations.push(Violation {
                    severity,
                    category: ViolationCategory::ComponentIdentification,
                    message,
                    element: Some(comp.name.clone()),
                    requirement,
                    rule_id,
                    component_id: Some(comp.canonical_id.value().to_string()),
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // NTIA minimum & FDA: supplier required
            if matches!(
                self.level,
                ComplianceLevel::NtiaMinimum
                    | ComplianceLevel::FdaMedicalDevice
                    | ComplianceLevel::CraPhase1
                    | ComplianceLevel::CraPhase2
                    | ComplianceLevel::CraOssSteward
                    | ComplianceLevel::Comprehensive
            ) && !has_known_supplier(&comp.supplier, &comp.author)
            {
                let severity = match self.level {
                    ComplianceLevel::CraPhase1
                    | ComplianceLevel::CraPhase2
                    | ComplianceLevel::CraOssSteward => ViolationSeverity::Warning,
                    _ => ViolationSeverity::Error,
                };
                let (message, requirement, rule_id) = match self.level {
                    ComplianceLevel::FdaMedicalDevice => (
                        format!("Component '{}' missing supplier/manufacturer", comp.name),
                        "FDA: Supplier/manufacturer information".to_string(),
                        "SBOM-FDA-SUPPLIER",
                    ),
                    // Component suppliers are part of the Annex I Part II (1)
                    // SBOM inventory — distinct from the document-level
                    // Art. 13(16) manufacturer-identification obligation.
                    ComplianceLevel::CraPhase1 | ComplianceLevel::CraPhase2 => (
                        format!(
                            "[CRA Annex I Part II (1)] Component '{}' missing supplier/manufacturer",
                            comp.name
                        ),
                        "CRA Annex I Part II (1): Component supplier information".to_string(),
                        "SBOM-CRA-COMPONENT-SUPPLIER",
                    ),
                    // Steward profile: component supplier info is part of the
                    // Art. 24 SBOM floor, but stewards are exempt from the
                    // Art. 13(16) manufacturer-identification obligation, so
                    // the citation must not reference it.
                    ComplianceLevel::CraOssSteward => (
                        format!(
                            "[CRA Art. 24] Component '{}' missing supplier/manufacturer",
                            comp.name
                        ),
                        "CRA Art. 24 (steward): Component supplier information".to_string(),
                        "SBOM-CRA-ART-24-SUPPLIER",
                    ),
                    _ => (
                        format!("Component '{}' missing supplier/manufacturer", comp.name),
                        "NTIA: Supplier information".to_string(),
                        "SBOM-NTIA-SUPPLIER",
                    ),
                };
                violations.push(Violation {
                    severity,
                    category: ViolationCategory::SupplierInfo,
                    message,
                    element: Some(comp.name.clone()),
                    requirement,
                    rule_id,
                    component_id: Some(comp.canonical_id.value().to_string()),
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // Standard+: should have license information
            if matches!(
                self.level,
                ComplianceLevel::Standard | ComplianceLevel::Comprehensive
            ) && comp.licenses.declared.is_empty()
                && comp.licenses.concluded.is_none()
            {
                violations.push(Violation {
                    severity: ViolationSeverity::Warning,
                    category: ViolationCategory::LicenseInfo,
                    message: format!("Component '{}' should have license information", comp.name),
                    element: Some(comp.name.clone()),
                    requirement: "License declaration".to_string(),
                    rule_id: generic_rule_id_for_level(self.level),
                    component_id: Some(comp.canonical_id.value().to_string()),
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            // FDA & Comprehensive: must have cryptographic hashes
            if matches!(
                self.level,
                ComplianceLevel::FdaMedicalDevice | ComplianceLevel::Comprehensive
            ) {
                if comp.hashes.is_empty() {
                    violations.push(Violation {
                        severity: if self.level == ComplianceLevel::FdaMedicalDevice {
                            ViolationSeverity::Error
                        } else {
                            ViolationSeverity::Warning
                        },
                        category: ViolationCategory::IntegrityInfo,
                        message: format!("Component '{}' missing cryptographic hash", comp.name),
                        element: Some(comp.name.clone()),
                        requirement: if self.level == ComplianceLevel::FdaMedicalDevice {
                            "FDA: Cryptographic hash for integrity".to_string()
                        } else {
                            "Integrity verification (hashes)".to_string()
                        },
                        rule_id: if self.level == ComplianceLevel::FdaMedicalDevice {
                            "SBOM-FDA-HASH"
                        } else {
                            generic_rule_id_for_level(self.level)
                        },
                        component_id: Some(comp.canonical_id.value().to_string()),
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                } else if self.level == ComplianceLevel::FdaMedicalDevice {
                    // FDA: Check for strong hash algorithm (SHA-256 or better)
                    let has_strong_hash = comp.hashes.iter().any(|h| {
                        matches!(
                            h.algorithm,
                            HashAlgorithm::Sha256
                                | HashAlgorithm::Sha384
                                | HashAlgorithm::Sha512
                                | HashAlgorithm::Sha3_256
                                | HashAlgorithm::Sha3_384
                                | HashAlgorithm::Sha3_512
                                | HashAlgorithm::Blake2b256
                                | HashAlgorithm::Blake2b384
                                | HashAlgorithm::Blake2b512
                                | HashAlgorithm::Blake3
                                | HashAlgorithm::Streebog256
                                | HashAlgorithm::Streebog512
                        )
                    });
                    if !has_strong_hash {
                        violations.push(Violation {
                            severity: ViolationSeverity::Warning,
                            category: ViolationCategory::IntegrityInfo,
                            message: format!(
                                "Component '{}' has only weak hash algorithm (use SHA-256+)",
                                comp.name
                            ),
                            element: Some(comp.name.clone()),
                            requirement: "FDA: Strong cryptographic hash (SHA-256 or better)"
                                .to_string(),
                            rule_id: "SBOM-FDA-HASH",
                            component_id: Some(comp.canonical_id.value().to_string()),
                            counts: None,
                            standard_refs: Vec::new(),
                        });
                    }
                }
            }

            // CRA: hashes are recommended for integrity verification
            if self.level.is_cra() && comp.hashes.is_empty() {
                violations.push(Violation {
                    severity: ViolationSeverity::Info,
                    category: ViolationCategory::IntegrityInfo,
                    message: format!(
                        "[CRA Annex I Part I (2)(f)] Component '{}' missing cryptographic hash (recommended for integrity)",
                        comp.name
                    ),
                    element: Some(comp.name.clone()),
                    requirement: "CRA Annex I Part I (2)(f): Component integrity information (hash)"
                        .to_string(),
                    rule_id: "SBOM-CRA-ANNEX-I-INTEGRITY",
                    component_id: Some(comp.canonical_id.value().to_string()),
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }
        }
    }

    pub(crate) fn check_dependencies(
        &self,
        sbom: &NormalizedSbom,
        violations: &mut Vec<Violation>,
    ) {
        // NTIA & FDA require dependency relationships (the CRA levels
        // include the Art. 24 steward profile)
        if matches!(
            self.level,
            ComplianceLevel::NtiaMinimum
                | ComplianceLevel::FdaMedicalDevice
                | ComplianceLevel::CraPhase1
                | ComplianceLevel::CraPhase2
                | ComplianceLevel::CraOssSteward
                | ComplianceLevel::Comprehensive
        ) {
            let has_deps = !sbom.edges.is_empty();
            let has_multiple_components = sbom.components.len() > 1;

            let (requirement, rule_id) = match self.level {
                ComplianceLevel::CraPhase1
                | ComplianceLevel::CraPhase2
                | ComplianceLevel::CraOssSteward => (
                    "CRA Annex I: Dependency relationships",
                    "SBOM-CRA-ANNEX-I-DEPENDENCY",
                ),
                ComplianceLevel::FdaMedicalDevice => {
                    ("FDA: Dependency relationships", "SBOM-FDA-DEPENDENCY")
                }
                _ => ("NTIA: Dependency relationships", "SBOM-NTIA-DEPENDENCY"),
            };

            if has_multiple_components && !has_deps {
                let message = match self.level {
                    ComplianceLevel::CraPhase1
                    | ComplianceLevel::CraPhase2
                    | ComplianceLevel::CraOssSteward =>
                        "[CRA Annex I] SBOM with multiple components must include dependency relationships".to_string(),
                    _ =>
                        "SBOM with multiple components must include dependency relationships".to_string(),
                };
                violations.push(Violation {
                    severity: ViolationSeverity::Error,
                    category: ViolationCategory::DependencyInfo,
                    message,
                    element: None,
                    requirement: requirement.to_string(),
                    rule_id,
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            } else if has_multiple_components {
                // Edges exist — check the graph is more than a token gesture.
                // A single edge among N components used to satisfy the
                // "dependency relationships" element for the whole SBOM.
                use std::collections::HashSet;
                let mut connected: HashSet<&crate::model::CanonicalId> = HashSet::new();
                for edge in &sbom.edges {
                    connected.insert(&edge.from);
                    connected.insert(&edge.to);
                }

                // A component that appears in the CycloneDX dependencies
                // array with an explicitly empty dependsOn has positively
                // declared "no dependencies" — that is documentation, not a
                // gap (the parser marks it with a synthetic property).
                let declares_no_deps = |c: &crate::model::Component| {
                    c.extensions
                        .properties
                        .iter()
                        .any(|p| p.name == crate::parsers::DECLARED_NO_DEPENDENCIES_PROPERTY)
                };

                // The primary product component must participate in the
                // dependency graph — an SBOM whose root has no declared
                // relationships does not describe the product's dependencies.
                if let Some(primary_id) = &sbom.primary_component_id
                    && let Some(primary) = sbom.components.get(primary_id)
                    && !connected.contains(primary_id)
                    && !declares_no_deps(primary)
                {
                    violations.push(Violation {
                        severity: ViolationSeverity::Warning,
                        category: ViolationCategory::DependencyInfo,
                        message: format!(
                            "Primary component '{}' participates in no dependency relationship",
                            primary.name
                        ),
                        element: Some(primary.name.clone()),
                        requirement: requirement.to_string(),
                        rule_id,
                        component_id: Some(primary.canonical_id.value().to_string()),
                        counts: None,
                        standard_refs: Vec::new(),
                    });
                }

                // Most components disconnected from the graph → the
                // dependency information is likely incomplete. Suppressed
                // when the SBOM explicitly declares an incomplete inventory.
                use crate::model::CompletenessDeclaration as CD;
                let declared_incomplete = matches!(
                    sbom.document.completeness_declaration,
                    CD::Incomplete | CD::IncompleteFirstPartyOnly | CD::IncompleteThirdPartyOnly
                );
                let total = sbom.components.len();
                let orphans = sbom
                    .components
                    .iter()
                    .filter(|(id, c)| !connected.contains(id) && !declares_no_deps(c))
                    .count();
                // FDA keeps the retired fast-path's any-orphan sensitivity
                // ("each component's dependencies"); other standards warn
                // only when orphans form a majority.
                let fda = self.level == ComplianceLevel::FdaMedicalDevice;
                if !declared_incomplete
                    && ((fda && orphans >= 1) || (orphans >= 2 && orphans * 2 > total))
                {
                    let pct = (orphans * 100) / total.max(1);
                    violations.push(Violation {
                        severity: ViolationSeverity::Warning,
                        category: ViolationCategory::DependencyInfo,
                        message: format!(
                            "{orphans}/{total} components ({pct}%) participate in no dependency relationship; dependency information appears incomplete"
                        ),
                        element: None,
                        requirement: requirement.to_string(),
                        rule_id,
                        component_id: None,
                        counts: Some(ViolationCounts {
                            affected: orphans,
                            total,
                        }),
                        standard_refs: Vec::new(),
                    });
                }
            }
        }

        // CRA product-class calibration: dependency cycles undermine the
        // reliability of the SBOM's dependency graph (Annex I Part II (1)
        // requires the SBOM to cover the product's dependencies). Severity
        // scales with the CRA product class (`ClassCheck::Cycles`).
        if self.level.is_cra() && !sbom.edges.is_empty() {
            let dm = crate::quality::DependencyMetrics::from_sbom(sbom);
            if !dm.graph_analysis_skipped
                && dm.cycle_count > 0
                && let Some(severity) = self.class_severity(ClassCheck::Cycles)
            {
                violations.push(Violation {
                    severity,
                    category: ViolationCategory::DependencyInfo,
                    message: format!(
                        "[CRA Annex I Part II (1)] Dependency graph contains {} cycle(s); cyclic dependency declarations make the component inventory ambiguous",
                        dm.cycle_count
                    ),
                    element: None,
                    requirement: "CRA Annex I Part II (1): Dependency graph consistency"
                        .to_string(),
                    rule_id: "SBOM-CRA-CYCLES",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }
        }

        // CRA: warn if multiple root components (no incoming edges) and no primary component set
        if self.level.is_cra() && sbom.components.len() > 1 && sbom.primary_component_id.is_none() {
            use std::collections::HashSet;
            let mut incoming: HashSet<&crate::model::CanonicalId> = HashSet::new();
            for edge in &sbom.edges {
                incoming.insert(&edge.to);
            }
            // Count roots among the components that actually exist — edges
            // may reference ids that are not in the component map, so
            // `len() - incoming.len()` would undercount.
            let root_count = sbom
                .components
                .keys()
                .filter(|id| !incoming.contains(id))
                .count();
            if root_count > 1 {
                violations.push(Violation {
                    severity: ViolationSeverity::Warning,
                    category: ViolationCategory::DependencyInfo,
                    message: "[CRA Annex I] SBOM appears to have multiple root components; identify a primary product component for top-level dependencies".to_string(),
                    element: None,
                    requirement: "CRA Annex I: Top-level dependency clarity".to_string(),
                    rule_id: "SBOM-CRA-ANNEX-I-DEPENDENCY",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }
        }
    }

    pub(crate) fn check_vulnerability_metadata(
        &self,
        sbom: &NormalizedSbom,
        violations: &mut Vec<Violation>,
    ) {
        // FDA: surface unresolved critical/high vulnerabilities — premarket
        // submissions must address known vulnerabilities.
        if matches!(self.level, ComplianceLevel::FdaMedicalDevice) {
            use crate::model::Severity;
            use std::collections::HashSet;
            // Count distinct vulnerability ids — one CVE affecting five
            // components is one vulnerability, not five.
            let vulns = sbom.all_vulnerabilities();
            let critical = vulns
                .iter()
                .filter(|(_, v)| matches!(v.severity, Some(Severity::Critical)))
                .map(|(_, v)| v.id.as_str())
                .collect::<HashSet<_>>()
                .len();
            let high = vulns
                .iter()
                .filter(|(_, v)| matches!(v.severity, Some(Severity::High)))
                .map(|(_, v)| v.id.as_str())
                .collect::<HashSet<_>>()
                .len();
            if critical > 0 || high > 0 {
                violations.push(Violation {
                    severity: ViolationSeverity::Warning,
                    category: ViolationCategory::SecurityInfo,
                    message: format!(
                        "SBOM contains {critical} critical and {high} high severity vulnerabilities"
                    ),
                    element: None,
                    requirement: "FDA: Known vulnerability assessment".to_string(),
                    rule_id: "SBOM-FDA-SECURITY",
                    component_id: None,
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }
        }

        if !matches!(self.level, ComplianceLevel::CraPhase2) {
            return;
        }

        for (comp, vuln) in sbom.all_vulnerabilities() {
            if vuln.severity.is_none() && vuln.cvss.is_empty() {
                violations.push(Violation {
                    severity: ViolationSeverity::Warning,
                    category: ViolationCategory::SecurityInfo,
                    message: format!(
                        "[CRA Annex I Part II (4)] Vulnerability '{}' in '{}' lacks severity or CVSS score",
                        vuln.id, comp.name
                    ),
                    element: Some(comp.name.clone()),
                    requirement: "CRA Annex I Part II (4): Vulnerability metadata completeness"
                        .to_string(),
                    rule_id: "SBOM-CRA-VULN-METADATA",
                    component_id: Some(comp.canonical_id.value().to_string()),
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }

            if let Some(remediation) = &vuln.remediation
                && remediation.fixed_version.is_none()
                && remediation.description.is_none()
            {
                violations.push(Violation {
                        severity: ViolationSeverity::Info,
                        category: ViolationCategory::SecurityInfo,
                        message: format!(
                            "[CRA Annex I Part II (4)] Vulnerability '{}' in '{}' has remediation without details",
                            vuln.id, comp.name
                        ),
                        element: Some(comp.name.clone()),
                        requirement: "CRA Annex I Part II (4): Remediation detail".to_string(),
                        rule_id: "SBOM-CRA-VULN-METADATA",
                        component_id: Some(comp.canonical_id.value().to_string()),
                        counts: None,
                        standard_refs: Vec::new(),
                    });
            }
        }
    }

    pub(crate) fn check_format_specific(
        &self,
        sbom: &NormalizedSbom,
        violations: &mut Vec<Violation>,
    ) {
        match sbom.document.format {
            SbomFormat::CycloneDx => {
                self.check_cyclonedx_specific(sbom, violations);
            }
            SbomFormat::Spdx => {
                self.check_spdx_specific(sbom, violations);
            }
        }
    }

    pub(crate) fn check_cyclonedx_specific(
        &self,
        sbom: &NormalizedSbom,
        violations: &mut Vec<Violation>,
    ) {
        // CycloneDX specific checks
        let version = &sbom.document.spec_version;

        // Warn about older versions
        if version.starts_with("1.3") || version.starts_with("1.2") || version.starts_with("1.1") {
            violations.push(Violation {
                severity: ViolationSeverity::Info,
                category: ViolationCategory::FormatSpecific,
                message: format!("CycloneDX {version} is outdated, consider upgrading to 1.7+"),
                element: None,
                requirement: "Current CycloneDX version".to_string(),
                rule_id: generic_rule_id_for_level(self.level),
                component_id: None,
                counts: None,
                standard_refs: Vec::new(),
            });
        }

        // Check for bom-ref on components (important for CycloneDX)
        for comp in sbom.components.values() {
            if comp.identifiers.format_id == comp.name {
                // Likely missing bom-ref
                violations.push(Violation {
                    severity: ViolationSeverity::Info,
                    category: ViolationCategory::FormatSpecific,
                    message: format!("Component '{}' may be missing bom-ref", comp.name),
                    element: Some(comp.name.clone()),
                    requirement: "CycloneDX: bom-ref for dependency tracking".to_string(),
                    rule_id: generic_rule_id_for_level(self.level),
                    component_id: Some(comp.canonical_id.value().to_string()),
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }
        }
    }

    pub(crate) fn check_spdx_specific(
        &self,
        sbom: &NormalizedSbom,
        violations: &mut Vec<Violation>,
    ) {
        // SPDX specific checks
        let version = &sbom.document.spec_version;

        // Check version
        if !version.starts_with("2.") && !version.starts_with("3.") {
            violations.push(Violation {
                severity: ViolationSeverity::Warning,
                category: ViolationCategory::FormatSpecific,
                message: format!("Unknown SPDX version: {version}"),
                element: None,
                requirement: "Valid SPDX version".to_string(),
                rule_id: generic_rule_id_for_level(self.level),
                component_id: None,
                counts: None,
                standard_refs: Vec::new(),
            });
        }

        // SPDX requires element identifiers
        // SPDX 2.x uses SPDXRef- prefix; SPDX 3.0 uses URN-style IDs (e.g., urn:spdx:...)
        let is_spdx3 = version.starts_with("3.");
        for comp in sbom.components.values() {
            let valid_id = if is_spdx3 {
                // SPDX 3.0 uses URN/IRI identifiers
                comp.identifiers.format_id.contains(':')
            } else {
                comp.identifiers.format_id.starts_with("SPDXRef-")
            };
            if !valid_id {
                let expected = if is_spdx3 {
                    "SPDX 3.0: URN/IRI identifier format"
                } else {
                    "SPDX 2.x: SPDXRef- identifier format"
                };
                violations.push(Violation {
                    severity: ViolationSeverity::Info,
                    category: ViolationCategory::FormatSpecific,
                    message: format!(
                        "Component '{}' has non-standard SPDX identifier format",
                        comp.name
                    ),
                    element: Some(comp.name.clone()),
                    requirement: expected.to_string(),
                    rule_id: generic_rule_id_for_level(self.level),
                    component_id: Some(comp.canonical_id.value().to_string()),
                    counts: None,
                    standard_refs: Vec::new(),
                });
            }
        }
    }
}