lens3329 0.2.1

Cryptographic inventory scanner: crypto library discovery, lockfile version resolution (Cargo/npm/PyPI), offline advisory/CVE correlation, and CycloneDX CBOM / SARIF export.
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
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
/*
 * CycloneDX CBOM (Cryptographic Bill of Materials) Module - Defensive Security
 *
 * Serde data model for emitting CycloneDX 1.6 documents from scanner findings.
 * This is a *subset* of the CycloneDX 1.6 spec, scoped to what the cryptographic
 * library scanner can populate:
 *   - `library` components (one per detected library / dependency)
 *   - `cryptographic-asset` components (algorithms inferred from library identity)
 *   - dependency links between libraries and the algorithms they imply
 *
 * Spec reference: https://cyclonedx.org/docs/1.6/json/
 *
 * NOTE (scaffold): These structs define the output shape only. The conversion
 * from `scanner::CryptoFinding` and the algorithm-inference table are not yet
 * implemented (Phase A/B). Nothing in the binary constructs a `Bom` yet, hence
 * the module-level `dead_code` allowance.
 *
 * Part of the Slow Lynx Cryptography Discovery project.
 */

#![allow(dead_code)]

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

use crate::scanner::{CryptoFinding, CryptoType, Ecosystem};
use crate::tool::ToolInfo;

/// Top-level CycloneDX BOM document.
///
/// Serializes to the envelope expected by CycloneDX 1.6 tooling, e.g.:
/// ```jsonc
/// { "bomFormat": "CycloneDX", "specVersion": "1.6", "version": 1, ... }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Bom {
    /// Always the literal string "CycloneDX".
    pub bom_format: String,
    /// CycloneDX spec version this document targets (e.g. "1.6").
    pub spec_version: String,
    /// Optional unique identifier, conventionally `urn:uuid:<uuid>`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub serial_number: Option<String>,
    /// Revision of this BOM for the given serial number (starts at 1).
    pub version: u32,
    pub metadata: Metadata,
    /// Inventory: `library` and `cryptographic-asset` components.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub components: Vec<Component>,
    /// Links between components (library -> algorithms it implies).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub dependencies: Vec<Dependency>,
    /// Known vulnerabilities affecting components, from advisory correlation.
    /// Empty (and omitted) unless a `--advisory-db` was supplied.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub vulnerabilities: Vec<Vulnerability>,
}

impl Bom {
    /// Create an empty BOM envelope for a scan of `target`.
    ///
    /// Populates `bomFormat`, `specVersion`, `version`, and a `metadata` block
    /// with the current timestamp and 3329lens as the generating tool.
    /// Components and dependencies start empty. Use [`Bom::with_tool`] to name
    /// a different tool.
    pub fn new(target: &str) -> Self {
        Self::with_tool(target, &ToolInfo::default())
    }

    /// Like [`Bom::new`], but records `tool` as the generating tool in
    /// `metadata.tools`.
    pub fn with_tool(target: &str, tool: &ToolInfo) -> Self {
        Self {
            bom_format: "CycloneDX".to_string(),
            spec_version: "1.6".to_string(),
            serial_number: None,
            version: 1,
            metadata: Metadata::for_target(target, tool),
            components: Vec::new(),
            dependencies: Vec::new(),
            vulnerabilities: Vec::new(),
        }
    }

    /// The `bom-ref` of the `library` component matching `name`/`version`, if
    /// present. Used to link a vulnerability to the component it affects.
    pub fn library_ref(&self, name: &str, version: Option<&str>) -> Option<String> {
        self.components
            .iter()
            .find(|c| {
                c.component_type == ComponentType::Library
                    && c.name == name
                    && c.version.as_deref() == version
            })
            .and_then(|c| c.bom_ref.clone())
    }
}

/// BOM metadata: when it was produced, by what, and about what.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Metadata {
    /// ISO 8601 / RFC 3339 timestamp of BOM creation.
    pub timestamp: String,
    /// Tools that produced this BOM.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tools: Vec<Tool>,
    /// The subject of the BOM (the scanned target).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub component: Option<Component>,
}

impl Metadata {
    fn for_target(target: &str, tool: &ToolInfo) -> Self {
        Self {
            timestamp: chrono::Utc::now().to_rfc3339(),
            tools: vec![Tool {
                name: tool.name.clone(),
                version: Some(tool.version.clone()),
            }],
            component: Some(Component {
                component_type: ComponentType::Application,
                bom_ref: None,
                name: target.to_string(),
                version: None,
                purl: None,
                evidence: None,
                crypto_properties: None,
            }),
        }
    }
}

/// A tool that generated the BOM.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Tool {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}

/// A CycloneDX component. Used for the scanned application, detected
/// `library` entries, and `cryptographic-asset` entries.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Component {
    #[serde(rename = "type")]
    pub component_type: ComponentType,
    /// Stable reference used as the target of `dependencies` links.
    #[serde(rename = "bom-ref", skip_serializing_if = "Option::is_none")]
    pub bom_ref: Option<String>,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// Package URL, e.g. `pkg:cargo/ring@0.17`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub purl: Option<String>,
    /// Where the component was observed (file locations).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evidence: Option<Evidence>,
    /// Present only for `cryptographic-asset` components.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub crypto_properties: Option<CryptoProperties>,
}

/// CycloneDX component types relevant to this scanner.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum ComponentType {
    Application,
    Library,
    CryptographicAsset,
}

/// Evidence of where/how a component was detected.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Evidence {
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub occurrences: Vec<Occurrence>,
}

/// A single observed location of a component (e.g. a file path).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Occurrence {
    pub location: String,
}

/// Cryptographic properties for a `cryptographic-asset` component.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CryptoProperties {
    pub asset_type: AssetType,
    /// Present when `assetType == algorithm`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algorithm_properties: Option<AlgorithmProperties>,
    /// ASN.1 object identifier, when known (e.g. RSA = 1.2.840.113549.1.1.1).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oid: Option<String>,
}

/// The kind of cryptographic asset a component represents.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum AssetType {
    Algorithm,
    Certificate,
    Protocol,
    RelatedCryptoMaterial,
}

/// Properties describing a cryptographic algorithm asset.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlgorithmProperties {
    /// Cryptographic primitive class (kem, signature, pke, hash, ...).
    pub primitive: Primitive,
    /// Parameter set / key size identifier, e.g. "2048", "256", "ML-KEM-768".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameter_set_identifier: Option<String>,
    /// Named elliptic curve, when applicable (e.g. "P-256", "Curve25519").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub curve: Option<String>,
    /// Classical security strength in bits (e.g. RSA-2048 -> 112).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub classical_security_level: Option<u32>,
    /// NIST PQC security level. 0 indicates no quantum resistance.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nist_quantum_security_level: Option<u32>,
}

/// CycloneDX cryptographic primitive classes (1.6 subset).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum Primitive {
    /// Key encapsulation mechanism (e.g. ML-KEM / Kyber).
    Kem,
    /// Digital signature (e.g. ECDSA, ML-DSA / Dilithium).
    Signature,
    /// Public-key encryption (e.g. RSA encryption).
    Pke,
    /// Key agreement (e.g. ECDH, X25519).
    KeyAgree,
    /// Block cipher (e.g. AES).
    BlockCipher,
    /// Stream cipher (e.g. ChaCha20).
    StreamCipher,
    /// Hash function (e.g. SHA-256, SHA-3).
    Hash,
    /// Message authentication code (e.g. HMAC, Poly1305).
    Mac,
    /// Key derivation function (e.g. HKDF, Argon2).
    Kdf,
    /// Deterministic random bit generator / CSPRNG.
    Drbg,
    /// Anything not classifiable into the above.
    Other,
}

/// A dependency relationship between components, keyed by `bom-ref`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Dependency {
    /// The `bom-ref` of the dependent component.
    #[serde(rename = "ref")]
    pub bom_ref: String,
    /// `bom-ref`s this component depends on.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub depends_on: Vec<String>,
}

/// A vulnerability affecting one or more components (CycloneDX 1.6
/// `vulnerabilities[]`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Vulnerability {
    /// Advisory identifier, e.g. `RUSTSEC-2023-0001`.
    pub id: String,
    /// Severity/score ratings for this vulnerability.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ratings: Vec<Rating>,
    /// Human-readable description / title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// `bom-ref`s of the components this vulnerability affects.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub affects: Vec<Affects>,
}

/// A severity rating for a vulnerability.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Rating {
    /// CVSS base score, when available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub score: Option<f32>,
    /// Qualitative severity (critical/high/medium/low/none).
    pub severity: String,
    /// Scoring method, e.g. "CVSSv3".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
}

/// Reference to a component affected by a vulnerability.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Affects {
    #[serde(rename = "ref")]
    pub bom_ref: String,
}

/// Build a CycloneDX 1.6 CBOM from scanner findings.
///
/// Emits two kinds of components:
///   - `library`: one per unique (ecosystem, name, version), with every
///     detection location recorded as an `evidence.occurrences` entry and a
///     synthesized purl for known ecosystems (binary libraries carry no purl).
///   - `cryptographic-asset`: algorithms *inferred* from each library's
///     identity (see [`algorithms_for_library`]), de-duplicated so a shared
///     algorithm (e.g. SHA-256) is a single component referenced by many libs.
///
/// Libraries are linked to the algorithms they imply via `dependencies`.
///
/// IMPORTANT: algorithm assets are inferred from library *identity*, not from
/// observed runtime calls. This is a teaching-grade CBOM: presence of an
/// algorithm asset means "this library can do X", not "X is actually invoked".
///
/// The BOM names 3329lens as the generating tool; use
/// [`findings_to_cbom_with_tool`] to name a different one.
pub fn findings_to_cbom(findings: &[CryptoFinding], target: &str) -> Bom {
    findings_to_cbom_with_tool(findings, target, &ToolInfo::default())
}

/// Like [`findings_to_cbom`], but records `tool` as the generating tool in
/// `metadata.tools`.
pub fn findings_to_cbom_with_tool(
    findings: &[CryptoFinding],
    target: &str,
    tool: &ToolInfo,
) -> Bom {
    let mut bom = Bom::with_tool(target, tool);
    // (ecosystem, name, version) -> index of the library component.
    let mut lib_index: HashMap<String, usize> = HashMap::new();
    // algorithm bom-ref -> already emitted as a component (dedup across libs).
    let mut algo_emitted: HashSet<String> = HashSet::new();
    // library bom-ref -> index into `deps`.
    let mut dep_index: HashMap<String, usize> = HashMap::new();
    let mut deps: Vec<Dependency> = Vec::new();

    for finding in findings {
        // --- library component (one per unique ecosystem/name/version) ---
        let version = finding.version.clone();
        let lib_key = format!(
            "{:?}|{}|{}",
            finding.ecosystem,
            finding.name,
            version.as_deref().unwrap_or("")
        );

        let lib_idx = *lib_index.entry(lib_key).or_insert_with(|| {
            let purl = build_purl(&finding.ecosystem, &finding.name, version.as_deref());
            let bom_ref = purl
                .clone()
                .unwrap_or_else(|| format!("lib/{}", finding.name));
            bom.components.push(Component {
                component_type: ComponentType::Library,
                bom_ref: Some(bom_ref),
                name: finding.name.clone(),
                version: version.clone(),
                purl,
                evidence: Some(Evidence {
                    occurrences: Vec::new(),
                }),
                crypto_properties: None,
            });
            bom.components.len() - 1
        });

        // Record this detection location, de-duplicating repeats.
        if let Some(evidence) = bom.components[lib_idx].evidence.as_mut() {
            if !evidence
                .occurrences
                .iter()
                .any(|o| o.location == finding.path)
            {
                evidence.occurrences.push(Occurrence {
                    location: finding.path.clone(),
                });
            }
        }

        let lib_ref = bom.components[lib_idx]
            .bom_ref
            .clone()
            .expect("library components always carry a bom-ref");

        // --- inferred algorithm assets + dependency links ---
        for spec in algorithms_for_library(&finding.name) {
            let algo_ref = format!("crypto/algorithm/{}", slug(spec.name));

            // Emit the algorithm component once, shared across libraries.
            if algo_emitted.insert(algo_ref.clone()) {
                bom.components.push(Component {
                    component_type: ComponentType::CryptographicAsset,
                    bom_ref: Some(algo_ref.clone()),
                    name: spec.name.to_string(),
                    version: None,
                    purl: None,
                    evidence: None,
                    crypto_properties: Some(CryptoProperties {
                        asset_type: AssetType::Algorithm,
                        algorithm_properties: Some(AlgorithmProperties {
                            primitive: spec.primitive.clone(),
                            parameter_set_identifier: spec.parameter_set.map(str::to_string),
                            curve: spec.curve.map(str::to_string),
                            classical_security_level: spec.classical_security_level,
                            nist_quantum_security_level: spec.nist_quantum_security_level,
                        }),
                        oid: spec.oid.map(str::to_string),
                    }),
                });
            }

            // Link this library to the algorithm it implies.
            add_dependency(&mut deps, &mut dep_index, &lib_ref, algo_ref);
        }

        // --- SSL/TLS libraries additionally expose the TLS protocol ---
        if finding.crypto_type == CryptoType::SslTls {
            let proto_ref = "crypto/protocol/tls".to_string();
            if algo_emitted.insert(proto_ref.clone()) {
                bom.components.push(Component {
                    component_type: ComponentType::CryptographicAsset,
                    bom_ref: Some(proto_ref.clone()),
                    name: "TLS".to_string(),
                    version: None,
                    purl: None,
                    evidence: None,
                    crypto_properties: Some(CryptoProperties {
                        asset_type: AssetType::Protocol,
                        algorithm_properties: None,
                        oid: None,
                    }),
                });
            }
            add_dependency(&mut deps, &mut dep_index, &lib_ref, proto_ref);
        }
    }

    bom.dependencies = deps;
    bom
}

/// Append `target_ref` to the dependency entry for `lib_ref`, creating the
/// entry if needed and de-duplicating repeated links.
fn add_dependency(
    deps: &mut Vec<Dependency>,
    dep_index: &mut HashMap<String, usize>,
    lib_ref: &str,
    target_ref: String,
) {
    let idx = *dep_index.entry(lib_ref.to_string()).or_insert_with(|| {
        deps.push(Dependency {
            bom_ref: lib_ref.to_string(),
            depends_on: Vec::new(),
        });
        deps.len() - 1
    });
    if !deps[idx].depends_on.contains(&target_ref) {
        deps[idx].depends_on.push(target_ref);
    }
}

/// Synthesize a Package URL (purl) for a finding, when its ecosystem has one.
/// Binary/static libraries on disk (`System`) have no package coordinate.
fn build_purl(ecosystem: &Ecosystem, name: &str, version: Option<&str>) -> Option<String> {
    let kind = match ecosystem {
        Ecosystem::Cargo => "cargo",
        Ecosystem::Npm => "npm",
        Ecosystem::PyPI => "pypi",
        Ecosystem::System => return None,
    };
    // Scoped npm names (`@scope/pkg`) encode the leading `@` as `%40` per the
    // purl spec; the namespace separator `/` stays literal.
    let encoded_name = if *ecosystem == Ecosystem::Npm {
        if let Some(rest) = name.strip_prefix('@') {
            format!("%40{}", rest)
        } else {
            name.to_string()
        }
    } else {
        name.to_string()
    };
    let version_suffix = version.map(|v| format!("@{}", v)).unwrap_or_default();
    Some(format!("pkg:{}/{}{}", kind, encoded_name, version_suffix))
}

/// Format 16 random bytes as an RFC 4122 version-4 UUID string (no `urn:uuid:`
/// prefix). The caller supplies the entropy (the 3329lens CLI uses `getrandom`)
/// so this stays a pure, testable transform. Sets the version (4) and variant bits.
pub fn format_uuid_v4(mut bytes: [u8; 16]) -> String {
    bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
    bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10xx
    format!(
        "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
        bytes[0], bytes[1], bytes[2], bytes[3],
        bytes[4], bytes[5],
        bytes[6], bytes[7],
        bytes[8], bytes[9],
        bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
    )
}

/// A cryptographic algorithm asset inferred from a library's identity.
#[derive(Debug)]
struct AlgorithmSpec {
    name: &'static str,
    primitive: Primitive,
    parameter_set: Option<&'static str>,
    curve: Option<&'static str>,
    classical_security_level: Option<u32>,
    /// NIST PQC security category. `Some(0)` flags a Shor-breakable asymmetric
    /// algorithm; symmetric/hash use their residual category; `None` where the
    /// notion does not cleanly apply (e.g. KDFs).
    nist_quantum_security_level: Option<u32>,
    oid: Option<&'static str>,
}

#[allow(clippy::too_many_arguments)]
fn algo(
    name: &'static str,
    primitive: Primitive,
    parameter_set: Option<&'static str>,
    curve: Option<&'static str>,
    classical_security_level: Option<u32>,
    nist_quantum_security_level: Option<u32>,
    oid: Option<&'static str>,
) -> AlgorithmSpec {
    AlgorithmSpec {
        name,
        primitive,
        parameter_set,
        curve,
        classical_security_level,
        nist_quantum_security_level,
        oid,
    }
}

// Reusable specs for algorithms shared across many libraries. The Shor-breakable
// asymmetric algorithms carry nistQuantumSecurityLevel = 0.
fn rsa() -> AlgorithmSpec {
    algo(
        "RSA-2048",
        Primitive::Pke,
        Some("2048"),
        None,
        Some(112),
        Some(0),
        Some("1.2.840.113549.1.1.1"),
    )
}
fn ecdsa() -> AlgorithmSpec {
    algo(
        "ECDSA-P256",
        Primitive::Signature,
        Some("P-256"),
        Some("P-256"),
        Some(128),
        Some(0),
        Some("1.2.840.10045.2.1"),
    )
}
/// Classical finite-field Diffie-Hellman. Shor-breakable, hence quantum level 0.
fn dh() -> AlgorithmSpec {
    algo(
        "DH-2048",
        Primitive::KeyAgree,
        Some("2048"),
        None,
        Some(112),
        Some(0),
        None,
    )
}
fn ecdh() -> AlgorithmSpec {
    algo(
        "ECDH-P256",
        Primitive::KeyAgree,
        Some("P-256"),
        Some("P-256"),
        Some(128),
        Some(0),
        None,
    )
}
fn ed25519() -> AlgorithmSpec {
    algo(
        "Ed25519",
        Primitive::Signature,
        None,
        Some("Curve25519"),
        Some(128),
        Some(0),
        Some("1.3.101.112"),
    )
}
fn x25519() -> AlgorithmSpec {
    algo(
        "X25519",
        Primitive::KeyAgree,
        None,
        Some("Curve25519"),
        Some(128),
        Some(0),
        Some("1.3.101.110"),
    )
}
fn aes256() -> AlgorithmSpec {
    algo(
        "AES-256",
        Primitive::BlockCipher,
        Some("256"),
        None,
        Some(256),
        Some(5),
        Some("2.16.840.1.101.3.4.1"),
    )
}
fn chacha20() -> AlgorithmSpec {
    algo(
        "ChaCha20",
        Primitive::StreamCipher,
        Some("256"),
        None,
        Some(256),
        Some(5),
        None,
    )
}
fn poly1305() -> AlgorithmSpec {
    algo(
        "Poly1305",
        Primitive::Mac,
        None,
        None,
        Some(128),
        Some(5),
        None,
    )
}
fn sha256() -> AlgorithmSpec {
    algo(
        "SHA-256",
        Primitive::Hash,
        Some("256"),
        None,
        Some(128),
        Some(2),
        Some("2.16.840.1.101.3.4.2.1"),
    )
}
fn hmac() -> AlgorithmSpec {
    algo("HMAC", Primitive::Mac, None, None, None, None, None)
}
fn mlkem768() -> AlgorithmSpec {
    algo(
        "ML-KEM-768",
        Primitive::Kem,
        Some("ML-KEM-768"),
        None,
        None,
        Some(3),
        None,
    )
}
fn mldsa65() -> AlgorithmSpec {
    algo(
        "ML-DSA-65",
        Primitive::Signature,
        Some("ML-DSA-65"),
        None,
        None,
        Some(3),
        None,
    )
}

/// Infer the cryptographic algorithms a library is capable of, from its name.
///
/// Umbrella libraries (OpenSSL, ring, rustls, libsodium, ...) map to a
/// representative set; single-primitive crates map to one algorithm. Unknown
/// libraries return an empty set rather than fabricating assets.
fn algorithms_for_library(name: &str) -> Vec<AlgorithmSpec> {
    let n = name.to_lowercase();

    // Exact npm package names are resolved before the substring cascade below.
    // Several are ordinary words (`jose`, `pem`, `md5`) that must not be matched
    // as substrings of unrelated names, and several would otherwise fall through
    // to an empty set despite being plainly asymmetric — which would hide them
    // from the quantum-risk count, the one number this report exists to produce.
    match n.as_str() {
        // JOSE/JWT: RS256, ES256 and HS256 are the algorithms actually in use.
        "jose" | "node-jose" | "jsonwebtoken" | "jws" | "jwa" | "jsrsasign" => {
            return vec![rsa(), ecdsa(), hmac(), sha256()];
        }
        // Elliptic-curve primitives.
        "elliptic" | "@noble/curves" => return vec![ecdsa(), ecdh()],
        "secp256k1" | "@noble/secp256k1" | "eccrypto" => return vec![ecdsa()],
        // Finite-field and RSA primitives.
        "node-rsa" | "public-encrypt" => return vec![rsa()],
        "browserify-sign" => return vec![rsa(), ecdsa()],
        "diffie-hellman" => return vec![dh()],
        // Symmetric and umbrella shims. `crypto` is the npm package that stands
        // in for Node's built-in module, which exposes essentially everything.
        "@noble/ciphers" => return vec![aes256(), chacha20()],
        "crypto" => return vec![rsa(), ecdsa(), ecdh(), aes256(), sha256(), hmac()],
        "crypto-browserify" => return vec![rsa(), aes256(), sha256(), hmac()],
        "openpgp" => return vec![rsa(), ecdsa(), aes256(), sha256()],
        // X.509 tooling generates RSA keys and SHA-256 signatures.
        "selfsigned" | "pem" => return vec![rsa(), sha256()],
        // Key derivation.
        "pbkdf2" => {
            return vec![algo("PBKDF2", Primitive::Kdf, None, None, None, None, None)];
        }
        "scrypt-js" => {
            return vec![algo("scrypt", Primitive::Kdf, None, None, None, None, None)];
        }
        // Hashes.
        "@noble/hashes" | "hash.js" | "sha.js" | "create-hash" => return vec![sha256()],
        "create-hmac" => return vec![hmac()],
        "keccak" => return vec![sha256_variant("SHA3-256")],
        "blakejs" => {
            return vec![algo(
                "BLAKE2",
                Primitive::Hash,
                None,
                None,
                Some(128),
                Some(2),
                None,
            )];
        }
        // MD5 is broken, but *classically* — collision resistance, not Shor.
        // classicalSecurityLevel 0 records that; nistQuantumSecurityLevel is
        // deliberately left unset, because the CLI reports level 0 as
        // "Quantum-vulnerable (Shor-breakable)" and folding a broken hash into
        // that count would misstate the post-quantum migration scope.
        "md5" => {
            return vec![algo(
                "MD5",
                Primitive::Hash,
                Some("128"),
                None,
                Some(0),
                None,
                Some("1.2.840.113549.2.5"),
            )];
        }
        "@noble/post-quantum" => return vec![mlkem768(), mldsa65()],
        // Deliberately no algorithm assets: these are crypto building blocks
        // with no algorithm of their own. Naming them here documents that the
        // empty set is a decision, not an oversight.
        "randombytes" | "buffer-equal-constant-time" => return Vec::new(),
        _ => {}
    }

    // Post-quantum: umbrella crates/libs, then specific primitives.
    if n.contains("oqs") || n.contains("pqcrypto") {
        return vec![mlkem768(), mldsa65()];
    }
    if n.contains("kyber") {
        return vec![mlkem768()];
    }
    if n.contains("dilithium") {
        return vec![mldsa65()];
    }
    if n.contains("falcon") {
        return vec![algo(
            "Falcon-512",
            Primitive::Signature,
            Some("Falcon-512"),
            None,
            None,
            Some(1),
            None,
        )];
    }
    if n.contains("sphincs") {
        return vec![algo(
            "SLH-DSA (SPHINCS+)",
            Primitive::Signature,
            Some("SPHINCS+-128s"),
            None,
            None,
            Some(1),
            None,
        )];
    }

    // SSL/TLS umbrella libraries.
    if n.contains("openssl")
        || n.contains("libssl")
        || n.contains("libcrypto")
        || n.contains("boringssl")
        || n.contains("libressl")
        || n.contains("mbedtls")
        || n.contains("wolfssl")
    {
        return vec![rsa(), ecdsa(), ecdh(), aes256(), sha256()];
    }
    if n.contains("rustls") {
        return vec![x25519(), ecdsa(), aes256(), chacha20(), sha256()];
    }

    // General-purpose umbrella libraries.
    if n.contains("sodium") || n == "nacl" || n.contains("tweetnacl") {
        return vec![x25519(), ed25519(), chacha20(), poly1305()];
    }
    if n == "ring" {
        return vec![ed25519(), x25519(), aes256(), chacha20(), sha256(), hmac()];
    }
    if n.contains("bouncycastle")
        || n.contains("cryptopp")
        || n.contains("libgcrypt")
        || n.contains("node-forge")
        || n.contains("crypto-js")
        || n.contains("cryptography")
        || n.contains("pycryptodome")
    {
        return vec![rsa(), aes256(), sha256()];
    }

    // Single-primitive crates. Order matters: check ECDSA/ECDH before "dsa".
    if n.contains("ed25519") {
        return vec![ed25519()];
    }
    if n.contains("x25519") {
        return vec![x25519()];
    }
    if n.contains("ecdsa") || n.contains("ecc") {
        return vec![ecdsa()];
    }
    if n.contains("ecdh") {
        return vec![ecdh()];
    }
    if n == "rsa" {
        return vec![rsa()];
    }
    if n.contains("dsa") {
        return vec![algo(
            "DSA",
            Primitive::Signature,
            None,
            None,
            Some(112),
            Some(0),
            Some("1.2.840.10040.4.1"),
        )];
    }
    if n.contains("chacha20") {
        return vec![chacha20()];
    }
    if n.contains("aes") {
        return vec![aes256()];
    }
    if n.contains("sha3") {
        return vec![sha256_variant("SHA3-256")];
    }
    if n.contains("sha2") {
        return vec![sha256()];
    }
    if n.contains("blake2") {
        return vec![algo(
            "BLAKE2",
            Primitive::Hash,
            None,
            None,
            Some(128),
            Some(2),
            None,
        )];
    }
    if n.contains("blake3") {
        return vec![algo(
            "BLAKE3",
            Primitive::Hash,
            None,
            None,
            Some(128),
            Some(2),
            None,
        )];
    }
    if n.contains("argon2") {
        return vec![algo("Argon2", Primitive::Kdf, None, None, None, None, None)];
    }
    if n.contains("bcrypt") {
        return vec![algo("bcrypt", Primitive::Kdf, None, None, None, None, None)];
    }
    if n.contains("hashlib") {
        return vec![sha256()];
    }

    // Unknown library: do not fabricate algorithm assets.
    Vec::new()
}

/// A SHA-2-family hash with a different display name (e.g. SHA3-256).
fn sha256_variant(name: &'static str) -> AlgorithmSpec {
    algo(
        name,
        Primitive::Hash,
        Some("256"),
        None,
        Some(128),
        Some(2),
        None,
    )
}

/// Lowercase a name and replace any non-alphanumeric run with single hyphens,
/// for use in stable `bom-ref` identifiers.
fn slug(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut last_hyphen = false;
    for c in s.chars() {
        if c.is_alphanumeric() {
            out.extend(c.to_lowercase());
            last_hyphen = false;
        } else if !last_hyphen {
            out.push('-');
            last_hyphen = true;
        }
    }
    out.trim_matches('-').to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scanner::{CryptoType, FindingType, VersionSource};
    use std::collections::HashSet;

    fn finding(
        name: &str,
        eco: Ecosystem,
        ctype: CryptoType,
        ver: Option<&str>,
        path: &str,
    ) -> CryptoFinding {
        CryptoFinding {
            path: path.to_string(),
            name: name.to_string(),
            finding_type: FindingType::DependencyManifest,
            crypto_type: ctype,
            ecosystem: eco,
            version: ver.map(str::to_string),
            version_source: VersionSource::Declared,
            details: String::new(),
        }
    }

    #[test]
    fn envelope_is_cyclonedx_1_6() {
        let bom = findings_to_cbom(&[], "target");
        assert_eq!(bom.bom_format, "CycloneDX");
        assert_eq!(bom.spec_version, "1.6");
        assert_eq!(bom.version, 1);
    }

    #[test]
    fn default_tool_is_3329lens() {
        let bom = findings_to_cbom(&[], "target");
        assert_eq!(bom.metadata.tools.len(), 1);
        assert_eq!(bom.metadata.tools[0].name, "3329lens");
        assert_eq!(
            bom.metadata.tools[0].version.as_deref(),
            Some(env!("CARGO_PKG_VERSION"))
        );
    }

    #[test]
    fn caller_supplied_tool_is_used() {
        let findings = vec![finding(
            "ring",
            Ecosystem::Cargo,
            CryptoType::GeneralCrypto,
            Some("0.17"),
            "/p/Cargo.toml",
        )];
        let tool = ToolInfo::new("other-tool", "9.9.9", "https://example.com/other");
        let bom = findings_to_cbom_with_tool(&findings, "target", &tool);
        assert_eq!(bom.metadata.tools.len(), 1);
        assert_eq!(bom.metadata.tools[0].name, "other-tool");
        assert_eq!(bom.metadata.tools[0].version.as_deref(), Some("9.9.9"));
        // Only the tool identity differs; the inventory itself is unchanged.
        let default = findings_to_cbom(&findings, "target");
        assert_eq!(bom.components.len(), default.components.len());
        assert_eq!(bom.dependencies.len(), default.dependencies.len());
    }

    #[test]
    fn every_dependency_ref_resolves_to_a_component() {
        let findings = vec![
            finding(
                "ring",
                Ecosystem::Cargo,
                CryptoType::GeneralCrypto,
                Some("0.17"),
                "/p/Cargo.toml",
            ),
            finding(
                "openssl",
                Ecosystem::Cargo,
                CryptoType::SslTls,
                Some("0.10"),
                "/p/Cargo.toml",
            ),
        ];
        let bom = findings_to_cbom(&findings, "target");
        let refs: HashSet<&str> = bom
            .components
            .iter()
            .filter_map(|c| c.bom_ref.as_deref())
            .collect();
        for dep in &bom.dependencies {
            assert!(
                refs.contains(dep.bom_ref.as_str()),
                "dangling ref {}",
                dep.bom_ref
            );
            for target in &dep.depends_on {
                assert!(
                    refs.contains(target.as_str()),
                    "dangling dependsOn {}",
                    target
                );
            }
        }
    }

    #[test]
    fn shared_algorithms_are_deduplicated() {
        // ring and openssl both imply SHA-256 / AES-256.
        let findings = vec![
            finding(
                "ring",
                Ecosystem::Cargo,
                CryptoType::GeneralCrypto,
                None,
                "/a",
            ),
            finding("openssl", Ecosystem::Cargo, CryptoType::SslTls, None, "/b"),
        ];
        let bom = findings_to_cbom(&findings, "t");
        let sha = bom
            .components
            .iter()
            .filter(|c| c.name == "SHA-256")
            .count();
        assert_eq!(sha, 1, "SHA-256 should be a single shared component");
    }

    #[test]
    fn unknown_library_infers_no_algorithms() {
        let findings = vec![finding(
            "totally-unknown-lib",
            Ecosystem::Cargo,
            CryptoType::Unknown,
            None,
            "/a",
        )];
        let bom = findings_to_cbom(&findings, "t");
        let assets = bom
            .components
            .iter()
            .filter(|c| c.component_type == ComponentType::CryptographicAsset)
            .count();
        assert_eq!(assets, 0);
    }

    #[test]
    fn tls_library_emits_protocol_asset() {
        let findings = vec![finding(
            "openssl",
            Ecosystem::System,
            CryptoType::SslTls,
            None,
            "/lib/libssl.so",
        )];
        let bom = findings_to_cbom(&findings, "t");
        let has_tls = bom.components.iter().any(|c| {
            c.component_type == ComponentType::CryptographicAsset
                && c.name == "TLS"
                && matches!(
                    c.crypto_properties.as_ref().map(|p| &p.asset_type),
                    Some(AssetType::Protocol)
                )
        });
        assert!(
            has_tls,
            "SSL/TLS library should expose a TLS protocol asset"
        );
    }

    #[test]
    fn purls_only_for_packaged_ecosystems() {
        let findings = vec![
            finding(
                "ring",
                Ecosystem::Cargo,
                CryptoType::GeneralCrypto,
                Some("0.17"),
                "/a",
            ),
            finding(
                "libssl.so",
                Ecosystem::System,
                CryptoType::SslTls,
                None,
                "/lib/libssl.so",
            ),
        ];
        let bom = findings_to_cbom(&findings, "t");
        let ring = bom.components.iter().find(|c| c.name == "ring").unwrap();
        assert_eq!(ring.purl.as_deref(), Some("pkg:cargo/ring@0.17"));
        let sys = bom
            .components
            .iter()
            .find(|c| c.name == "libssl.so")
            .unwrap();
        assert_eq!(sys.purl, None);
    }

    #[test]
    fn scoped_npm_name_encodes_at_sign_in_purl() {
        let findings = vec![
            finding(
                "@scope/cryptolib",
                Ecosystem::Npm,
                CryptoType::GeneralCrypto,
                Some("2.4.0"),
                "/p/package.json",
            ),
            finding(
                "node-forge",
                Ecosystem::Npm,
                CryptoType::GeneralCrypto,
                Some("1.3.1"),
                "/p/package.json",
            ),
        ];
        let bom = findings_to_cbom(&findings, "t");
        let scoped = bom
            .components
            .iter()
            .find(|c| c.name == "@scope/cryptolib")
            .unwrap();
        assert_eq!(
            scoped.purl.as_deref(),
            Some("pkg:npm/%40scope/cryptolib@2.4.0")
        );
        let plain = bom
            .components
            .iter()
            .find(|c| c.name == "node-forge")
            .unwrap();
        assert_eq!(plain.purl.as_deref(), Some("pkg:npm/node-forge@1.3.1"));
    }

    #[test]
    fn vulnerabilities_omitted_when_empty_and_present_when_populated() {
        // No advisory DB supplied: findings_to_cbom must not emit a key.
        let findings = vec![finding(
            "ring",
            Ecosystem::Cargo,
            CryptoType::GeneralCrypto,
            Some("0.16.0"),
            "/p/Cargo.toml",
        )];
        let mut bom = findings_to_cbom(&findings, "t");
        assert!(bom.vulnerabilities.is_empty());
        let json = serde_json::to_value(&bom).unwrap();
        assert!(
            json.get("vulnerabilities").is_none(),
            "key omitted when empty"
        );

        // Populated: links to the affected library's bom-ref and serializes.
        let lib_ref = bom
            .library_ref("ring", Some("0.16.0"))
            .expect("ring library component exists");
        bom.vulnerabilities.push(Vulnerability {
            id: "RUSTSEC-TEST-0001".to_string(),
            ratings: vec![Rating {
                score: Some(9.8),
                severity: "critical".to_string(),
                method: Some("CVSSv3".to_string()),
            }],
            description: Some("test".to_string()),
            affects: vec![Affects {
                bom_ref: lib_ref.clone(),
            }],
        });
        let json = serde_json::to_value(&bom).unwrap();
        let vulns = json["vulnerabilities"].as_array().expect("array present");
        assert_eq!(vulns.len(), 1);
        assert_eq!(vulns[0]["id"], "RUSTSEC-TEST-0001");
        assert_eq!(vulns[0]["affects"][0]["ref"], serde_json::json!(lib_ref));
        assert_eq!(vulns[0]["ratings"][0]["severity"], "critical");
    }

    #[test]
    fn uuid_v4_has_correct_shape_and_bits() {
        let u = format_uuid_v4([0u8; 16]);
        assert_eq!(u.len(), 36);
        let b = u.as_bytes();
        assert_eq!(b[8], b'-');
        assert_eq!(b[13], b'-');
        assert_eq!(b[18], b'-');
        assert_eq!(b[23], b'-');
        assert_eq!(b[14], b'4', "version nibble must be 4");
        assert!(
            matches!(b[19], b'8' | b'9' | b'a' | b'b'),
            "variant bits must be 10xx"
        );
    }

    #[test]
    fn serialized_keys_are_cyclonedx_shaped() {
        let findings = vec![finding(
            "openssl",
            Ecosystem::Cargo,
            CryptoType::SslTls,
            Some("0.10"),
            "/p/Cargo.toml",
        )];
        let bom = findings_to_cbom(&findings, "t");
        let json = serde_json::to_value(&bom).unwrap();
        assert_eq!(json["bomFormat"], "CycloneDX");
        assert_eq!(json["specVersion"], "1.6");
        // A crypto-asset must serialize with camelCase + kebab-case enum values.
        let asset = json["components"]
            .as_array()
            .unwrap()
            .iter()
            .find(|c| c["type"] == "cryptographic-asset")
            .expect("expected a cryptographic-asset component");
        assert_eq!(asset["cryptoProperties"]["assetType"], "algorithm");
        assert!(asset["bom-ref"].is_string());
    }

    // --- npm crypto packages present in real dependency trees ----------------

    /// Every npm package the scanner recognises must infer at least one
    /// algorithm, or be one of the two building blocks that deliberately have
    /// none. A recognised library with an empty asset set is invisible to the
    /// quantum-risk count, which is the report's headline number.
    #[test]
    fn every_recognised_npm_package_infers_algorithms_or_is_exempt() {
        // Blocks with no algorithm of their own: a CSPRNG shim and a
        // constant-time comparison helper.
        const EXEMPT: [&str; 2] = ["randombytes", "buffer-equal-constant-time"];

        for (name, _) in crate::scanner::npm_crypto_packages_for_test() {
            let algos = algorithms_for_library(name);
            if EXEMPT.contains(&name) {
                assert!(algos.is_empty(), "{name} is exempt but inferred {algos:?}");
            } else {
                assert!(
                    !algos.is_empty(),
                    "{name} is recognised as crypto but infers no algorithms, so it \
                     would never appear in the quantum-risk assessment"
                );
            }
        }
    }

    /// The asymmetric npm packages are the ones a post-quantum migration is
    /// actually about, so pin that each is flagged Shor-breakable.
    #[test]
    fn asymmetric_npm_packages_are_flagged_quantum_vulnerable() {
        for name in [
            "jose",
            "jsonwebtoken",
            "jws",
            "elliptic",
            "secp256k1",
            "node-rsa",
            "diffie-hellman",
            "public-encrypt",
            "browserify-sign",
            "selfsigned",
            "@noble/curves",
        ] {
            let algos = algorithms_for_library(name);
            assert!(
                algos
                    .iter()
                    .any(|a| a.nist_quantum_security_level == Some(0)),
                "{name} should carry a Shor-breakable algorithm, got {algos:?}"
            );
        }
    }

    /// MD5 is broken classically, not by Shor. It must not inflate the count
    /// the CLI prints as "Quantum-vulnerable (Shor-breakable)".
    #[test]
    fn md5_is_classically_broken_but_not_counted_as_shor_breakable() {
        let algos = algorithms_for_library("md5");
        assert_eq!(algos.len(), 1);
        assert_eq!(algos[0].name, "MD5");
        assert_eq!(algos[0].classical_security_level, Some(0));
        assert_eq!(algos[0].nist_quantum_security_level, None);
    }

    /// Generic-looking entries are exact package names, and must not match as
    /// substrings of unrelated libraries.
    #[test]
    fn generic_npm_names_do_not_match_as_substrings() {
        // `jose` must not swallow these, nor `pem`/`md5` match by containment.
        assert!(algorithms_for_library("morose-utils").is_empty());
        assert!(algorithms_for_library("temperature").is_empty());
        assert!(algorithms_for_library("command5").is_empty());
    }
}