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
//! CBOM (Cryptographic Bill of Materials) integration tests.
//!
//! Tests end-to-end parsing of CBOM fixtures, crypto property extraction,
//! PQC compliance checking (CNSA 2.0, NIST PQC), and diff engine crypto changes.

use sbom_tools::{
    diff::DiffEngine,
    model::{ComponentType, CryptoAssetType},
    parsers::parse_sbom,
    quality::{ComplianceChecker, ComplianceLevel, CryptographyMetrics, ViolationSeverity},
};
use std::path::Path;

const FIXTURES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures");

fn fixture_path(name: &str) -> std::path::PathBuf {
    Path::new(FIXTURES_DIR).join(name)
}

// ============================================================================
// Parsing Tests
// ============================================================================

#[test]
fn parse_cbom_1_6_all_asset_types() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-1.6.cdx.json")).unwrap();
    let sbom = &parsed;

    // Count crypto components
    let crypto: Vec<_> = sbom
        .components
        .values()
        .filter(|c| c.component_type == ComponentType::Cryptographic)
        .collect();
    assert!(
        crypto.len() >= 10,
        "expected >=10 crypto components, got {}",
        crypto.len()
    );

    // Verify algorithms have crypto_properties
    let aes = crypto
        .iter()
        .find(|c| c.name == "AES-256-GCM")
        .expect("AES-256-GCM not found");
    let cp = aes
        .crypto_properties
        .as_ref()
        .expect("missing crypto_properties");
    assert_eq!(cp.asset_type, CryptoAssetType::Algorithm);
    assert_eq!(cp.oid.as_deref(), Some("2.16.840.1.101.3.4.1.46"));
    let algo = cp
        .algorithm_properties
        .as_ref()
        .expect("missing algorithm_properties");
    assert_eq!(algo.classical_security_level, Some(256));
    assert_eq!(algo.nist_quantum_security_level, Some(1));
    assert!(algo.is_quantum_safe());
    assert!(!algo.is_weak());

    // Verify certificate
    let cert_comp = crypto
        .iter()
        .find(|c| c.name.contains("acme-webapp.example.com"))
        .expect("TLS cert not found");
    let cert_cp = cert_comp.crypto_properties.as_ref().unwrap();
    assert_eq!(cert_cp.asset_type, CryptoAssetType::Certificate);
    let cert = cert_cp
        .certificate_properties
        .as_ref()
        .expect("missing cert_properties");
    assert!(cert.subject_name.as_ref().unwrap().contains("acme-webapp"));
    assert!(cert.not_valid_after.is_some());

    // Verify key material
    let key = crypto
        .iter()
        .find(|c| c.name.contains("webapp-tls-public-key"))
        .expect("TLS public key not found");
    let key_cp = key.crypto_properties.as_ref().unwrap();
    assert_eq!(key_cp.asset_type, CryptoAssetType::RelatedCryptoMaterial);
    let mat = key_cp.related_crypto_material_properties.as_ref().unwrap();
    assert_eq!(mat.size, Some(2048));

    // Verify protocol
    let proto = crypto
        .iter()
        .find(|c| c.name == "TLS 1.2")
        .expect("TLS 1.2 not found");
    let proto_cp = proto.crypto_properties.as_ref().unwrap();
    assert_eq!(proto_cp.asset_type, CryptoAssetType::Protocol);
    let proto_props = proto_cp.protocol_properties.as_ref().unwrap();
    assert_eq!(proto_props.version.as_deref(), Some("1.2"));
    assert!(!proto_props.cipher_suites.is_empty());
}

#[test]
fn parse_cbom_1_7_provides_and_pqc() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-1.7.cdx.json")).unwrap();
    let sbom = &parsed;

    // Verify ML-KEM-1024 (post-quantum)
    let ml_kem = sbom
        .components
        .values()
        .find(|c| c.name == "ML-KEM-1024")
        .expect("ML-KEM-1024 not found");
    let algo = ml_kem
        .crypto_properties
        .as_ref()
        .unwrap()
        .algorithm_properties
        .as_ref()
        .unwrap();
    assert_eq!(algo.nist_quantum_security_level, Some(5));
    assert!(algo.is_quantum_safe());
    assert_eq!(algo.algorithm_family.as_deref(), Some("ML-KEM"));

    // Verify hybrid combiner
    let hybrid = sbom
        .components
        .values()
        .find(|c| c.name == "X25519-ML-KEM-768")
        .expect("Hybrid combiner not found");
    let hybrid_algo = hybrid
        .crypto_properties
        .as_ref()
        .unwrap()
        .algorithm_properties
        .as_ref()
        .unwrap();
    assert!(hybrid_algo.is_hybrid_pqc());
    assert_eq!(hybrid_algo.nist_quantum_security_level, Some(3));

    // Verify 'provides' edges exist
    let provides_edges: Vec<_> = sbom
        .edges
        .iter()
        .filter(|e| e.relationship == sbom_tools::model::DependencyType::Provides)
        .collect();
    assert!(
        !provides_edges.is_empty(),
        "expected Provides dependency edges from crypto-lib"
    );

    // Verify IKEv2 with transform types
    let ipsec = sbom
        .components
        .values()
        .find(|c| c.name.contains("IPsec"))
        .expect("IPsec protocol not found");
    let proto = ipsec
        .crypto_properties
        .as_ref()
        .unwrap()
        .protocol_properties
        .as_ref()
        .unwrap();
    assert!(proto.ikev2_transform_types.is_some());
    let ike = proto.ikev2_transform_types.as_ref().unwrap();
    assert!(!ike.encr.is_empty());
    assert!(!ike.ke.is_empty());
}

#[test]
fn parse_cbom_weak_crypto() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-weak-crypto.cdx.json")).unwrap();
    let sbom = &parsed;

    // Verify weak algorithms are detected
    let md5 = sbom
        .components
        .values()
        .find(|c| c.name == "MD5")
        .expect("MD5 not found");
    let algo = md5
        .crypto_properties
        .as_ref()
        .unwrap()
        .algorithm_properties
        .as_ref()
        .unwrap();
    assert!(algo.is_weak_by_name("MD5"));
    assert!(!algo.is_quantum_safe());

    // Verify expired certificate
    let expired = sbom
        .components
        .values()
        .find(|c| c.name.contains("expired"))
        .expect("expired cert not found");
    let cert = expired
        .crypto_properties
        .as_ref()
        .unwrap()
        .certificate_properties
        .as_ref()
        .unwrap();
    assert!(cert.is_expired());

    // Verify compromised key
    let compromised = sbom
        .components
        .values()
        .find(|c| c.name.contains("compromised"))
        .expect("compromised key not found");
    let mat = compromised
        .crypto_properties
        .as_ref()
        .unwrap()
        .related_crypto_material_properties
        .as_ref()
        .unwrap();
    assert_eq!(
        mat.state,
        Some(sbom_tools::model::CryptoMaterialState::Compromised)
    );
}

// ============================================================================
// Quality Metrics Tests
// ============================================================================

#[test]
fn crypto_metrics_quantum_ready() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-quantum-ready.cdx.json")).unwrap();
    let metrics = CryptographyMetrics::from_sbom(&parsed);

    assert!(metrics.has_data());
    assert!(metrics.algorithms_count >= 10);
    assert_eq!(metrics.weak_algorithm_count, 0);
    assert_eq!(metrics.expired_certificates, 0);
    assert_eq!(metrics.compromised_keys, 0);
    assert!(
        metrics.quantum_readiness_score().expect("has algorithms") > 90.0,
        "expected >90% quantum readiness"
    );
    assert!(metrics.quality_score().unwrap() > 80.0);
}

#[test]
fn crypto_metrics_weak_crypto() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-weak-crypto.cdx.json")).unwrap();
    let metrics = CryptographyMetrics::from_sbom(&parsed);

    assert!(metrics.has_data());
    assert!(metrics.weak_algorithm_count >= 5, "expected >=5 weak algos");
    assert!(metrics.expired_certificates >= 1);
    assert!(metrics.compromised_keys >= 1);
    assert!(
        metrics.quantum_readiness_score().expect("has algorithms") < 20.0,
        "expected <20% quantum readiness"
    );
    assert!(metrics.quality_score().unwrap() < 30.0);
}

#[test]
fn crypto_metrics_no_crypto_returns_none() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/minimal.cdx.json")).unwrap();
    let metrics = CryptographyMetrics::from_sbom(&parsed);

    assert!(!metrics.has_data());
    assert!(metrics.quality_score().is_none());
}

// ============================================================================
// Compliance Tests
// ============================================================================

#[test]
fn cnsa2_compliant_passes() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-cnsa2-compliant.cdx.json")).unwrap();
    let result = ComplianceChecker::new(ComplianceLevel::Cnsa2).check(&parsed);

    let errors: Vec<_> = result
        .violations
        .iter()
        .filter(|v| v.severity == ViolationSeverity::Error)
        .collect();
    assert!(
        errors.is_empty(),
        "CNSA 2.0 compliant fixture should have 0 errors, got {}:\n{}",
        errors.len(),
        errors
            .iter()
            .map(|v| format!("  - {}", v.message))
            .collect::<Vec<_>>()
            .join("\n")
    );
}

#[test]
fn cnsa2_violations_detected() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-cnsa2-violations.cdx.json")).unwrap();
    let result = ComplianceChecker::new(ComplianceLevel::Cnsa2).check(&parsed);

    let errors: Vec<_> = result
        .violations
        .iter()
        .filter(|v| v.severity == ViolationSeverity::Error)
        .collect();
    assert!(
        errors.len() >= 5,
        "expected >=5 CNSA 2.0 errors, got {}:\n{}",
        errors.len(),
        errors
            .iter()
            .map(|v| format!("  - {}", v.message))
            .collect::<Vec<_>>()
            .join("\n")
    );

    // Verify specific violations
    let messages: Vec<_> = errors.iter().map(|v| v.message.as_str()).collect();
    assert!(
        messages.iter().any(|m| m.contains("AES-128")),
        "should flag AES-128"
    );
    assert!(
        messages
            .iter()
            .any(|m| m.contains("ML-KEM-768") || m.contains("ML-KEM-512")),
        "should flag ML-KEM sub-1024"
    );
    assert!(
        messages
            .iter()
            .any(|m| m.contains("RSA") || m.contains("ECDSA") || m.contains("ECDH")),
        "should flag quantum-vulnerable families"
    );
}

#[test]
fn nist_pqc_weak_crypto_violations() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-weak-crypto.cdx.json")).unwrap();
    let result = ComplianceChecker::new(ComplianceLevel::NistPqc).check(&parsed);

    let errors: Vec<_> = result
        .violations
        .iter()
        .filter(|v| v.severity == ViolationSeverity::Error)
        .collect();
    assert!(
        errors.len() >= 5,
        "expected >=5 PQC errors for weak crypto, got {}",
        errors.len()
    );

    // Should detect broken algorithms
    let messages: Vec<_> = errors.iter().map(|v| v.message.as_str()).collect();
    assert!(
        messages
            .iter()
            .any(|m| m.contains("MD5") || m.contains("SHA-1")),
        "should flag broken hashes"
    );
    assert!(
        messages.iter().any(|m| m.contains("quantum-vulnerable")),
        "should flag quantum-vulnerable algorithms"
    );
}

/// A realistic CycloneDX 1.6 CBOM (no `algorithmFamily` anywhere — a 1.7-only
/// field — and no `nistQuantumSecurityLevel`) must fail BOTH standards:
/// RSA-2048 is identified via its OID, AES-128-CBC via its name, and SHA-1
/// via its OID. Previously such CBOMs passed with zero violations.
#[test]
fn cyclonedx_16_cbom_without_family_fails_both_standards() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-1.6-no-family.cdx.json")).unwrap();

    let cnsa = ComplianceChecker::new(ComplianceLevel::Cnsa2).check(&parsed);
    assert!(!cnsa.is_compliant, "1.6 CBOM must not pass CNSA 2.0");
    let messages: Vec<_> = cnsa
        .violations
        .iter()
        .filter(|v| v.severity == ViolationSeverity::Error)
        .map(|v| v.message.as_str())
        .collect();
    assert!(
        messages.iter().any(|m| m.contains("RSA")),
        "RSA-2048 (via OID) must be flagged: {messages:?}"
    );
    assert!(
        messages.iter().any(|m| m.contains("AES-128")),
        "AES-128-CBC (via name) must be flagged: {messages:?}"
    );
    assert!(
        messages.iter().any(|m| m.contains("SHA-1")),
        "SHA-1 (via OID) must be flagged: {messages:?}"
    );

    let pqc = ComplianceChecker::new(ComplianceLevel::NistPqc).check(&parsed);
    assert!(!pqc.is_compliant, "1.6 CBOM must not pass PQC readiness");
    assert!(
        pqc.violations
            .iter()
            .any(|v| v.severity == ViolationSeverity::Error
                && v.message.contains("quantum-vulnerable")
                && v.message.contains("RSA")),
        "RSA-2048 must be flagged quantum-vulnerable without a declared level"
    );
    assert!(
        pqc.violations
            .iter()
            .any(|v| v.severity == ViolationSeverity::Error && v.message.contains("SHA-1")),
        "SHA-1 must be flagged broken via OID"
    );
}

/// Protocol assets are now evaluated: the weak-crypto fixture's TLS 1.0
/// endpoint with RC4/3DES/DES suites must produce protocol violations under
/// both standards (previously protocols satisfied the inventory gate but got
/// zero checks) — and the weak fixture as a whole must fail CNSA 2.0, which
/// used to report it fully compliant.
#[test]
fn weak_crypto_protocols_and_cnsa2_verdict() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-weak-crypto.cdx.json")).unwrap();

    let cnsa = ComplianceChecker::new(ComplianceLevel::Cnsa2).check(&parsed);
    assert!(
        !cnsa.is_compliant,
        "an MD5/SHA-1/DES/RC4 inventory must not be CNSA 2.0 compliant"
    );
    assert!(
        cnsa.violations
            .iter()
            .any(|v| v.rule_id == "SBOM-CNSA2-PROTO-001" && v.message.contains("1.0")),
        "TLS 1.0 must fail the CNSA 2.0 TLS-1.3 gate"
    );
    assert!(
        cnsa.violations
            .iter()
            .any(|v| v.rule_id == "SBOM-CNSA2-PROTO-002" && v.message.contains("RC4")),
        "the RC4 cipher suite must be flagged under CNSA 2.0"
    );
    assert!(
        cnsa.violations
            .iter()
            .any(|v| v.rule_id == "SBOM-CNSA2-ALG-005" && v.message.contains("MD5")),
        "MD5 (broken) must be flagged under the CNSA 2.0 allowlist"
    );

    let pqc = ComplianceChecker::new(ComplianceLevel::NistPqc).check(&parsed);
    assert!(
        pqc.violations
            .iter()
            .any(|v| v.rule_id == "SBOM-PQC-PROTO-001"),
        "TLS 1.0 must fail the PQC minimum-version gate"
    );
    assert!(
        pqc.violations
            .iter()
            .any(|v| v.rule_id == "SBOM-PQC-PROTO-002" && v.message.contains("broken")),
        "legacy cipher suites must be flagged under PQC"
    );
    assert!(
        pqc.violations
            .iter()
            .any(|v| v.rule_id == "SBOM-PQC-CERT-001"),
        "certificates signed with rsa-1024/sha1 must fire the PQC cert rule"
    );
}

/// A CBOM whose only assets carry unclassifiable crypto refs (a certificate
/// with a dangling opaque signatureAlgorithmRef, an IKEv2 protocol with
/// opaque transform refs) must NOT report a clean 100% pass: every
/// unverifiable asset produces a "cannot verify" Warning under both
/// standards. Previously such CBOMs satisfied the inventory gate while
/// receiving zero effective checks — a vacuous compliance claim.
#[test]
fn unclassifiable_refs_warn_instead_of_vacuous_pass() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-unclassifiable-refs.cdx.json")).unwrap();

    for (level, cert_rule, proto_rule) in [
        (
            ComplianceLevel::Cnsa2,
            "SBOM-CNSA2-CERT-UNKNOWN",
            "SBOM-CNSA2-PROTO-UNKNOWN",
        ),
        (
            ComplianceLevel::NistPqc,
            "SBOM-PQC-CERT-UNKNOWN",
            "SBOM-PQC-PROTO-UNKNOWN",
        ),
    ] {
        let result = ComplianceChecker::new(level).check(&parsed);
        assert!(
            result.violations.iter().any(|v| {
                v.severity == ViolationSeverity::Warning
                    && v.rule_id == cert_rule
                    && v.message.contains("sig-algo-42")
            }),
            "{level:?}: opaque cert sig ref must produce {cert_rule}; got {:?}",
            result
                .violations
                .iter()
                .map(|v| (v.rule_id, v.message.clone()))
                .collect::<Vec<_>>()
        );
        assert!(
            result.violations.iter().any(|v| {
                v.severity == ViolationSeverity::Warning
                    && v.rule_id == proto_rule
                    && v.message.contains("transform-encr-7")
            }),
            "{level:?}: opaque IKEv2 transform refs must produce {proto_rule}"
        );
        assert!(
            result.warning_count >= 2,
            "{level:?}: the unverifiable inventory must surface warnings, not a clean pass"
        );
    }
}

#[test]
fn nist_pqc_hybrid_transition_info() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-pqc-transition.cdx.json")).unwrap();
    let result = ComplianceChecker::new(ComplianceLevel::NistPqc).check(&parsed);

    // Should have info-level messages about hybrid combiners
    let infos: Vec<_> = result
        .violations
        .iter()
        .filter(|v| v.severity == ViolationSeverity::Info)
        .collect();
    assert!(
        infos.iter().any(|v| v.message.contains("hybrid")),
        "should recognize hybrid PQC combiners as good practice"
    );

    // Should have info about approved PQC algorithms
    assert!(
        infos
            .iter()
            .any(|v| v.message.contains("NIST-approved PQC")),
        "should recognize approved PQC algorithms"
    );
}

// ============================================================================
// Diff Tests
// ============================================================================

#[test]
fn diff_weak_to_quantum_ready() {
    let old = parse_sbom(&fixture_path("cyclonedx/cbom-weak-crypto.cdx.json")).unwrap();
    let new = parse_sbom(&fixture_path("cyclonedx/cbom-quantum-ready.cdx.json")).unwrap();

    let engine = DiffEngine::default();
    let result = engine.diff(&old, &new).unwrap();

    // Should detect many changes (different algorithms entirely)
    assert!(
        result.summary.total_changes > 0,
        "diff between weak and quantum-ready should detect changes"
    );
}

#[test]
fn parse_all_cbom_fixtures_successfully() {
    let fixtures = [
        "cyclonedx/cbom-1.6.cdx.json",
        "cyclonedx/cbom-1.6-no-family.cdx.json",
        "cyclonedx/cbom-1.7.cdx.json",
        "cyclonedx/cbom-weak-crypto.cdx.json",
        "cyclonedx/cbom-quantum-ready.cdx.json",
        "cyclonedx/cbom-cnsa2-compliant.cdx.json",
        "cyclonedx/cbom-cnsa2-violations.cdx.json",
        "cyclonedx/cbom-pqc-transition.cdx.json",
        "cyclonedx/cbom-unclassifiable-refs.cdx.json",
    ];

    for fixture in &fixtures {
        let result = parse_sbom(&fixture_path(fixture));
        assert!(
            result.is_ok(),
            "Failed to parse {fixture}: {:?}",
            result.err()
        );

        let parsed = result.unwrap();
        let crypto_count = parsed
            .components
            .values()
            .filter(|c| c.component_type == ComponentType::Cryptographic)
            .count();
        assert!(crypto_count > 0, "{fixture} should have crypto components");
    }
}

// ============================================================================
// Bom-ref Index Tests
// ============================================================================

#[test]
fn bom_ref_index_resolves_crypto_refs() {
    let parsed = parse_sbom(&fixture_path("cyclonedx/cbom-1.6.cdx.json")).unwrap();
    let sbom = &parsed;
    let index = sbom.build_index();

    // The cert references an algorithm via signatureAlgorithmRef
    let cert = sbom
        .components
        .values()
        .find(|c| c.name.contains("acme-webapp.example.com"))
        .expect("cert not found");
    let sig_ref = cert
        .crypto_properties
        .as_ref()
        .unwrap()
        .certificate_properties
        .as_ref()
        .unwrap()
        .signature_algorithm_ref
        .as_deref()
        .expect("missing sig ref");

    // Resolve the bom-ref through the index
    let resolved = index.resolve_bom_ref(sig_ref);
    assert!(resolved.is_some(), "should resolve bom-ref '{sig_ref}'");
}