1#![doc = include_str!("../readme.md")]
2
3pub mod versions;
4
5use indexmap::IndexMap;
6use packageurl::PackageUrl;
7use serde::{Deserialize, Serialize};
8use sha2::{Digest, Sha256};
9use std::collections::{BTreeMap, BTreeSet};
10use std::fmt;
11use std::str::FromStr;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct Sbom {
29 pub metadata: Metadata,
31 pub components: IndexMap<ComponentId, Component>,
33 pub dependencies: BTreeMap<ComponentId, BTreeMap<ComponentId, DependencyKind>>,
35 #[serde(skip)]
40 pub reverse_deps: BTreeMap<ComponentId, BTreeSet<ComponentId>>,
41 #[serde(default, skip_serializing_if = "Vec::is_empty")]
43 pub warnings: Vec<String>,
44}
45
46impl PartialEq for Sbom {
47 fn eq(&self, other: &Self) -> bool {
48 self.metadata == other.metadata
49 && self.components == other.components
50 && self.dependencies == other.dependencies
51 && self.warnings == other.warnings
52 }
53}
54
55impl Eq for Sbom {}
56
57impl Default for Sbom {
58 fn default() -> Self {
59 Self {
60 metadata: Metadata::default(),
61 components: IndexMap::new(),
62 dependencies: BTreeMap::new(),
63 reverse_deps: BTreeMap::new(),
64 warnings: Vec::new(),
65 }
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
75pub struct Metadata {
76 pub timestamp: Option<String>,
78 pub tools: Vec<String>,
80 pub authors: Vec<String>,
82}
83
84#[derive(
94 Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
95)]
96#[serde(rename_all = "lowercase")]
97pub enum DependencyKind {
98 #[default]
100 Runtime,
101 Dev,
103 Build,
105 Test,
107 Optional,
109 Provided,
111}
112
113impl fmt::Display for DependencyKind {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 match self {
116 Self::Runtime => write!(f, "runtime"),
117 Self::Dev => write!(f, "dev"),
118 Self::Build => write!(f, "build"),
119 Self::Test => write!(f, "test"),
120 Self::Optional => write!(f, "optional"),
121 Self::Provided => write!(f, "provided"),
122 }
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
146pub struct ComponentId(String);
147
148impl ComponentId {
149 pub fn new(purl: Option<&str>, properties: &[(&str, &str)]) -> Self {
154 if let Some(purl) = purl {
155 if let Ok(parsed) = PackageUrl::from_str(purl) {
156 return ComponentId(parsed.to_string());
157 }
158 return ComponentId(purl.to_string());
159 }
160
161 let mut hasher = Sha256::new();
163 for (k, v) in properties {
164 hasher.update(k.as_bytes());
165 hasher.update(b":");
166 hasher.update(v.as_bytes());
167 hasher.update(b"|");
168 }
169 let hash = hex::encode(hasher.finalize());
170 ComponentId(format!("h:{}", hash))
171 }
172
173 pub fn as_str(&self) -> &str {
175 &self.0
176 }
177}
178
179impl std::fmt::Display for ComponentId {
180 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181 write!(f, "{}", self.0)
182 }
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
191pub struct Component {
192 pub id: ComponentId,
194 pub name: String,
196 pub version: Option<String>,
198 pub ecosystem: Option<String>,
200 pub supplier: Option<String>,
202 pub description: Option<String>,
204 pub purl: Option<String>,
206 pub licenses: BTreeSet<String>,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub license_expression: Option<String>,
216 pub hashes: BTreeMap<String, String>,
218 pub source_ids: Vec<String>,
220}
221
222impl Component {
223 pub fn new(name: String, version: Option<String>) -> Self {
228 let mut props = vec![("name", name.as_str())];
229 if let Some(v) = &version {
230 props.push(("version", v));
231 }
232 let id = ComponentId::new(None, &props);
233
234 Self {
235 id,
236 name,
237 version,
238 ecosystem: None,
239 supplier: None,
240 description: None,
241 purl: None,
242 licenses: BTreeSet::new(),
243 license_expression: None,
244 hashes: BTreeMap::new(),
245 source_ids: Vec::new(),
246 }
247 }
248
249 pub fn licensing(&self) -> Licensing<'_> {
251 Licensing {
252 expression: self.license_expression.as_deref(),
253 ids: &self.licenses,
254 }
255 }
256}
257
258impl Sbom {
259 pub fn normalize(&mut self) {
269 self.components.sort_keys();
271
272 for component in self.components.values_mut() {
274 component.normalize();
275 }
276
277 self.metadata.timestamp = None;
279 self.metadata.tools.clear();
280 self.metadata.authors.clear();
281
282 self.rebuild_reverse_deps();
283 }
284
285 pub fn rebuild_reverse_deps(&mut self) {
291 self.reverse_deps.clear();
292 for (parent, children) in &self.dependencies {
293 for child in children.keys() {
294 self.reverse_deps
295 .entry(child.clone())
296 .or_default()
297 .insert(parent.clone());
298 }
299 }
300 }
301
302 pub fn insert_component(&mut self, mut component: Component) -> Option<Component> {
308 if let Some(existing) = self.components.get(&component.id) {
309 component
310 .source_ids
311 .extend(existing.source_ids.iter().cloned());
312 component.source_ids.sort();
313 component.source_ids.dedup();
314 }
315 self.components.insert(component.id.clone(), component)
316 }
317
318 pub fn insert_dependency(
324 &mut self,
325 parent: ComponentId,
326 child: ComponentId,
327 kind: DependencyKind,
328 ) {
329 self.dependencies
330 .entry(parent)
331 .or_default()
332 .entry(child)
333 .and_modify(|existing| *existing = (*existing).min(kind))
334 .or_insert(kind);
335 }
336
337 pub fn roots(&self) -> Vec<ComponentId> {
342 self.components
343 .keys()
344 .filter(|id| self.reverse_deps.get(*id).is_none_or(BTreeSet::is_empty))
345 .cloned()
346 .collect()
347 }
348
349 pub fn deps(&self, id: &ComponentId) -> Vec<ComponentId> {
351 self.dependencies
352 .get(id)
353 .map(|d| d.keys().cloned().collect())
354 .unwrap_or_default()
355 }
356
357 pub fn rdeps(&self, id: &ComponentId) -> Vec<ComponentId> {
360 self.reverse_deps
361 .get(id)
362 .map(|parents| parents.iter().cloned().collect())
363 .unwrap_or_default()
364 }
365
366 pub fn transitive_deps(&self, id: &ComponentId) -> BTreeSet<ComponentId> {
370 let mut visited = BTreeSet::new();
371 let mut stack = vec![id.clone()];
372 while let Some(current) = stack.pop() {
373 if let Some(children) = self.dependencies.get(¤t) {
374 for child in children.keys() {
375 if visited.insert(child.clone()) {
376 stack.push(child.clone());
377 }
378 }
379 }
380 }
381 visited
382 }
383
384 pub fn ecosystems(&self) -> BTreeSet<String> {
386 self.components
387 .values()
388 .filter_map(|c| c.ecosystem.clone())
389 .collect()
390 }
391
392 pub fn licenses(&self) -> BTreeSet<String> {
394 self.components
395 .values()
396 .flat_map(|c| c.licenses.iter().cloned())
397 .collect()
398 }
399
400 pub fn missing_hashes(&self) -> Vec<ComponentId> {
404 self.components
405 .iter()
406 .filter(|(_, c)| c.hashes.is_empty())
407 .map(|(id, _)| id.clone())
408 .collect()
409 }
410
411 pub fn by_purl(&self, purl: &str) -> Option<&Component> {
413 let id = ComponentId::new(Some(purl), &[]);
414 self.components.get(&id)
415 }
416
417 pub fn detect_cycles(&self) -> Vec<Vec<ComponentId>> {
426 enum Frame {
427 Enter(ComponentId),
428 Exit(ComponentId),
429 }
430
431 let mut visited = BTreeSet::new();
432 let mut on_stack = BTreeSet::new();
433 let mut path = Vec::new();
434 let mut cycles = Vec::new();
435
436 let mut stack: Vec<Frame> = self
437 .dependencies
438 .keys()
439 .rev()
440 .map(|k| Frame::Enter(k.clone()))
441 .collect();
442
443 while let Some(frame) = stack.pop() {
444 match frame {
445 Frame::Enter(node) => {
446 if visited.contains(&node) {
447 continue;
448 }
449 visited.insert(node.clone());
450 on_stack.insert(node.clone());
451 path.push(node.clone());
452 stack.push(Frame::Exit(node.clone()));
453
454 if let Some(children) = self.dependencies.get(&node) {
455 for child in children.keys().rev() {
456 if !visited.contains(child) {
457 stack.push(Frame::Enter(child.clone()));
458 } else if on_stack.contains(child) {
459 if let Some(start) = path.iter().position(|n| n == child) {
460 let mut cycle: Vec<_> = path[start..].to_vec();
461 cycle.push(child.clone());
462 cycles.push(cycle);
463 }
464 }
465 }
466 }
467 }
468 Frame::Exit(node) => {
469 path.pop();
470 on_stack.remove(&node);
471 }
472 }
473 }
474
475 cycles
476 }
477}
478
479impl Component {
480 pub fn normalize(&mut self) {
485 let normalized_hashes: BTreeMap<String, String> = self
486 .hashes
487 .iter()
488 .map(|(k, v)| (k.to_lowercase(), v.to_lowercase()))
489 .collect();
490 self.hashes = normalized_hashes;
491 }
492}
493
494pub fn ecosystem_from_purl(purl: &str) -> Option<String> {
508 PackageUrl::from_str(purl).ok().map(|p| p.ty().to_string())
509}
510
511pub fn parse_license_expression(license: &str) -> BTreeSet<String> {
531 match spdx::Expression::parse(license) {
532 Ok(expr) => {
533 let ids: BTreeSet<String> = expr
534 .requirements()
535 .map(|r| match &r.req.license {
536 spdx::LicenseItem::Spdx { id, .. } => id.name.to_string(),
537 other => other.to_string(),
538 })
539 .collect();
540 if ids.is_empty() {
541 BTreeSet::from([license.to_string()])
543 } else {
544 ids
545 }
546 }
547 Err(_) => {
548 BTreeSet::from([license.to_string()])
550 }
551 }
552}
553
554#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
557pub struct LicenseRequirement {
558 pub license: String,
560 pub or_later: bool,
562 pub exception: Option<String>,
564}
565
566impl LicenseRequirement {
567 pub fn new(license: impl Into<String>) -> Self {
569 Self {
570 license: license.into(),
571 or_later: false,
572 exception: None,
573 }
574 }
575}
576
577impl std::fmt::Display for LicenseRequirement {
578 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
579 write!(f, "{}", self.license)?;
580 if self.or_later {
581 f.write_str("+")?;
582 }
583 if let Some(exception) = &self.exception {
584 write!(f, " WITH {exception}")?;
585 }
586 Ok(())
587 }
588}
589
590fn to_requirement(req: &spdx::LicenseReq) -> LicenseRequirement {
591 let (license, or_later) = match &req.license {
592 spdx::LicenseItem::Spdx { id, or_later } => (id.name.to_string(), *or_later),
593 other => (other.to_string(), false),
594 };
595 LicenseRequirement {
596 license,
597 or_later,
598 exception: req.addition.as_ref().map(|a| a.to_string()),
599 }
600}
601
602#[derive(Debug, Clone, Copy, PartialEq, Eq)]
608pub struct Licensing<'a> {
609 pub expression: Option<&'a str>,
611 pub ids: &'a BTreeSet<String>,
613}
614
615impl<'a> Licensing<'a> {
616 pub fn from_ids(ids: &'a BTreeSet<String>) -> Self {
618 Self {
619 expression: None,
620 ids,
621 }
622 }
623
624 pub fn satisfiable<F>(&self, mut acceptable: F) -> bool
645 where
646 F: FnMut(&LicenseRequirement) -> bool,
647 {
648 if let Some(expression) = self.expression {
649 if let Ok(expr) = spdx::Expression::parse(expression) {
650 return expr.evaluate(|req| acceptable(&to_requirement(req)));
651 }
652 }
653 self.ids
654 .iter()
655 .all(|id| acceptable(&LicenseRequirement::new(id)))
656 }
657
658 pub fn requirements(&self) -> BTreeSet<LicenseRequirement> {
661 if let Some(expression) = self.expression {
662 if let Ok(expr) = spdx::Expression::parse(expression) {
663 let reqs: BTreeSet<LicenseRequirement> = expr
664 .requirements()
665 .map(|r| to_requirement(&r.req))
666 .collect();
667 if !reqs.is_empty() {
668 return reqs;
669 }
670 }
671 }
672 self.ids.iter().map(LicenseRequirement::new).collect()
673 }
674
675 fn choices(&self) -> Option<Choices> {
678 if let Some(expression) = self.expression {
679 if let Ok(expr) = spdx::Expression::parse(expression) {
680 return expression_choices(&expr);
681 }
682 }
683 Some(BTreeSet::from([self
684 .ids
685 .iter()
686 .map(LicenseRequirement::new)
687 .collect()]))
688 }
689
690 fn mandatory_copyleft(&self) -> BTreeSet<String> {
692 self.requirements()
693 .into_iter()
694 .filter(|r| is_copyleft_license(&r.license))
695 .filter(|r| !self.satisfiable(|other| other.license != r.license))
696 .map(|r| r.license)
697 .collect()
698 }
699
700 fn copyleft_burdens(&self) -> Option<Burdens> {
703 let burdens = self
704 .choices()?
705 .into_iter()
706 .map(|choice| {
707 choice
708 .into_iter()
709 .filter(|r| is_copyleft_license(&r.license))
710 .map(|r| r.license)
711 .collect()
712 })
713 .collect();
714 Some(minimal_sets(burdens))
715 }
716}
717
718type Choices = BTreeSet<BTreeSet<LicenseRequirement>>;
720
721type Burdens = BTreeSet<BTreeSet<String>>;
723
724const MAX_CHOICES: usize = 64;
727
728fn minimal_sets<T: Ord + Clone>(sets: BTreeSet<BTreeSet<T>>) -> BTreeSet<BTreeSet<T>> {
730 sets.iter()
731 .filter(|set| {
732 sets.iter()
733 .all(|other| other == *set || !other.is_subset(set))
734 })
735 .cloned()
736 .collect()
737}
738
739fn expression_choices(expr: &spdx::Expression) -> Option<Choices> {
741 let mut stack: Vec<Choices> = Vec::new();
742
743 for node in expr.iter() {
744 match node {
745 spdx::expression::ExprNode::Req(req) => {
746 stack.push(BTreeSet::from([BTreeSet::from([to_requirement(&req.req)])]));
747 }
748 spdx::expression::ExprNode::Op(op) => {
749 let rhs = stack.pop()?;
750 let lhs = stack.pop()?;
751 let combined: Choices = match op {
752 spdx::expression::Operator::Or => lhs.union(&rhs).cloned().collect(),
753 spdx::expression::Operator::And => lhs
754 .iter()
755 .flat_map(|l| rhs.iter().map(|r| l.union(r).cloned().collect()))
756 .collect(),
757 };
758 if combined.len() > MAX_CHOICES {
759 return None;
760 }
761 stack.push(minimal_sets(combined));
762 }
763 }
764 }
765
766 let choices = stack.pop()?;
767 stack.is_empty().then_some(choices)
768}
769
770pub fn licensings_equivalent(a: Licensing<'_>, b: Licensing<'_>) -> bool {
793 match (a.choices(), b.choices()) {
794 (Some(x), Some(y)) => x == y,
795 _ => match (a.expression, b.expression) {
796 (Some(x), Some(y)) => license_expressions_equivalent(x, y),
797 _ => false,
798 },
799 }
800}
801
802pub fn copyleft_obligations_added(old: Licensing<'_>, new: Licensing<'_>) -> BTreeSet<String> {
832 match (old.copyleft_burdens(), new.copyleft_burdens()) {
833 (Some(offered), Some(demanded)) => {
834 if demanded
835 .iter()
836 .any(|burden| offered.iter().any(|had| burden.is_subset(had)))
837 {
838 return BTreeSet::new();
839 }
840 let unavoidable = offered
841 .into_iter()
842 .reduce(|acc, had| acc.intersection(&had).cloned().collect())
843 .unwrap_or_default();
844 demanded
845 .into_iter()
846 .flatten()
847 .filter(|license| !unavoidable.contains(license))
848 .collect()
849 }
850 _ => {
851 let already = old.mandatory_copyleft();
852 if new.satisfiable(|r| !is_copyleft_license(&r.license) || already.contains(&r.license))
853 {
854 return BTreeSet::new();
855 }
856 new.requirements()
857 .into_iter()
858 .filter(|r| is_copyleft_license(&r.license) && !already.contains(&r.license))
859 .map(|r| r.license)
860 .collect()
861 }
862 }
863}
864
865pub fn license_expressions_equivalent(a: &str, b: &str) -> bool {
885 match (spdx::Expression::parse(a), spdx::Expression::parse(b)) {
886 (Ok(x), Ok(y)) => match (expression_choices(&x), expression_choices(&y)) {
887 (Some(cx), Some(cy)) => cx == cy,
888 _ => x == y,
889 },
890 _ => a == b,
891 }
892}
893
894pub fn canonical_algorithm_name(name: &str) -> String {
909 match name.replace('-', "").to_uppercase().as_str() {
910 "MD2" => "MD2",
911 "MD4" => "MD4",
912 "MD5" => "MD5",
913 "MD6" => "MD6",
914 "SHA1" => "SHA-1",
915 "SHA224" => "SHA-224",
916 "SHA256" => "SHA-256",
917 "SHA384" => "SHA-384",
918 "SHA512" => "SHA-512",
919 "SHA3256" => "SHA3-256",
920 "SHA3384" => "SHA3-384",
921 "SHA3512" => "SHA3-512",
922 "BLAKE2B256" => "BLAKE2b-256",
923 "BLAKE2B384" => "BLAKE2b-384",
924 "BLAKE2B512" => "BLAKE2b-512",
925 "BLAKE3" => "BLAKE3",
926 "ADLER32" => "ADLER-32",
927 _ => return name.to_string(),
928 }
929 .to_string()
930}
931
932pub fn hash_algorithm_strength(name: &str) -> Option<u8> {
954 let canonical = canonical_algorithm_name(name);
955 match canonical.as_str() {
956 "ADLER-32" => Some(0),
957 "MD2" | "MD4" | "MD5" => Some(1),
958 "SHA-1" => Some(2),
959 "SHA-224" => Some(3),
960 "SHA-256" | "SHA3-256" | "BLAKE2b-256" | "BLAKE3" | "MD6" => Some(4),
961 "SHA-384" | "SHA3-384" | "BLAKE2b-384" => Some(5),
962 "SHA-512" | "SHA3-512" | "BLAKE2b-512" => Some(6),
963 _ => None,
964 }
965}
966
967pub fn is_hash_algorithm_downgrade(
992 old_hashes: &BTreeMap<String, String>,
993 new_hashes: &BTreeMap<String, String>,
994) -> bool {
995 if old_hashes.is_empty() || new_hashes.is_empty() {
996 return false;
997 }
998
999 let old_max = old_hashes
1000 .keys()
1001 .filter_map(|k| hash_algorithm_strength(k))
1002 .max();
1003 let new_max = new_hashes
1004 .keys()
1005 .filter_map(|k| hash_algorithm_strength(k))
1006 .max();
1007
1008 match (old_max, new_max) {
1009 (Some(old_strength), Some(new_strength)) => new_strength < old_strength,
1010 _ => false,
1011 }
1012}
1013
1014fn checksums_by_algorithm(hashes: &BTreeMap<String, String>) -> BTreeMap<String, &str> {
1015 hashes
1016 .iter()
1017 .map(|(algo, value)| (canonical_algorithm_name(algo), value.trim()))
1018 .collect()
1019}
1020
1021pub fn changed_checksums(
1045 old_hashes: &BTreeMap<String, String>,
1046 new_hashes: &BTreeMap<String, String>,
1047) -> Vec<(String, String, String)> {
1048 let new_side = checksums_by_algorithm(new_hashes);
1049
1050 checksums_by_algorithm(old_hashes)
1051 .into_iter()
1052 .filter_map(|(algo, old_value)| {
1053 let new_value = new_side.get(algo.as_str())?;
1054 (!old_value.eq_ignore_ascii_case(new_value))
1055 .then(|| (algo, old_value.to_string(), (*new_value).to_string()))
1056 })
1057 .collect()
1058}
1059
1060pub fn is_copyleft_license(id: &str) -> bool {
1080 spdx::license_id(id)
1081 .map(|l| l.is_copyleft())
1082 .unwrap_or(false)
1083}
1084
1085pub fn copyleft_introduced(old: &BTreeSet<String>, new: &BTreeSet<String>) -> bool {
1106 new.iter()
1107 .any(|id| is_copyleft_license(id) && !old.contains(id))
1108}
1109
1110#[cfg(test)]
1111mod tests {
1112 use super::*;
1113
1114 #[test]
1115 fn test_component_id_purl() {
1116 let purl = "pkg:npm/left-pad@1.3.0";
1117 let id = ComponentId::new(Some(purl), &[]);
1118 assert_eq!(id.as_str(), purl);
1119 }
1120
1121 #[test]
1122 fn test_component_id_hash_stability() {
1123 let props = [("name", "foo"), ("version", "1.0")];
1124 let id1 = ComponentId::new(None, &props);
1125 let id2 = ComponentId::new(None, &props);
1126 assert_eq!(id1, id2);
1127 assert!(id1.as_str().starts_with("h:"));
1128 }
1129
1130 #[test]
1131 fn test_normalization() {
1132 let mut comp = Component::new("test".to_string(), Some("1.0".to_string()));
1133 comp.licenses.insert("MIT".to_string());
1134 comp.licenses.insert("Apache-2.0".to_string());
1135 comp.hashes.insert("SHA-256".to_string(), "ABC".to_string());
1136
1137 comp.normalize();
1138
1139 assert_eq!(
1140 comp.licenses,
1141 BTreeSet::from(["Apache-2.0".to_string(), "MIT".to_string()])
1142 );
1143 assert_eq!(comp.hashes.get("sha-256").unwrap(), "abc");
1144 }
1145
1146 fn licensing<'a>(expression: &'a str, ids: &'a BTreeSet<String>) -> Licensing<'a> {
1147 Licensing {
1148 expression: Some(expression),
1149 ids,
1150 }
1151 }
1152
1153 #[test]
1154 fn test_licensing_satisfiable_operators() {
1155 let ids: BTreeSet<String> = ["Apache-2.0".into(), "MIT".into()].into();
1156 let only_mit = |r: &LicenseRequirement| r.license == "MIT";
1157
1158 assert!(licensing("MIT OR Apache-2.0", &ids).satisfiable(only_mit));
1159 assert!(!licensing("MIT AND Apache-2.0", &ids).satisfiable(only_mit));
1160
1161 let nested: BTreeSet<String> =
1162 ["Apache-2.0".into(), "BSD-3-Clause".into(), "MIT".into()].into();
1163 let allowed: BTreeSet<String> = ["BSD-3-Clause".into(), "MIT".into()].into();
1164 assert!(licensing("(MIT OR Apache-2.0) AND BSD-3-Clause", &nested)
1165 .satisfiable(|r| allowed.contains(&r.license)));
1166 assert!(!licensing("(MIT AND Apache-2.0) AND BSD-3-Clause", &nested)
1167 .satisfiable(|r| allowed.contains(&r.license)));
1168 }
1169
1170 #[test]
1171 fn test_licensing_without_expression_is_a_conjunction() {
1172 let ids: BTreeSet<String> = ["Apache-2.0".into(), "MIT".into()].into();
1173 assert!(!Licensing::from_ids(&ids).satisfiable(|r| r.license == "MIT"));
1174 assert!(Licensing::from_ids(&ids).satisfiable(|_| true));
1175 }
1176
1177 #[test]
1178 fn test_licensing_falls_back_on_free_text() {
1179 let ids: BTreeSet<String> = ["Custom License".into()].into();
1180 let free_text = licensing("Custom License", &ids);
1181 assert!(free_text.satisfiable(|r| r.license == "Custom License"));
1182 assert!(!free_text.satisfiable(|_| false));
1183 }
1184
1185 #[test]
1186 fn test_licensing_requirements_keep_exceptions() {
1187 let ids: BTreeSet<String> = ["GPL-2.0-only".into()].into();
1188 let reqs = licensing("GPL-2.0-only WITH Classpath-exception-2.0", &ids).requirements();
1189
1190 assert_eq!(reqs.len(), 1);
1191 let req = reqs.iter().next().unwrap();
1192 assert_eq!(req.license, "GPL-2.0-only");
1193 assert_eq!(req.exception.as_deref(), Some("Classpath-exception-2.0"));
1194 assert_eq!(req.to_string(), "GPL-2.0-only WITH Classpath-exception-2.0");
1195 }
1196
1197 #[test]
1198 fn test_licensing_requirements_keep_or_later() {
1199 let ids: BTreeSet<String> = ["Apache-2.0".into()].into();
1200 let req = licensing("Apache-2.0+", &ids)
1201 .requirements()
1202 .into_iter()
1203 .next()
1204 .unwrap();
1205
1206 assert_eq!(req.license, "Apache-2.0");
1207 assert!(req.or_later);
1208 assert_eq!(req.to_string(), "Apache-2.0+");
1209 }
1210
1211 #[test]
1212 fn test_copyleft_obligations_added_respects_choice() {
1213 let mit: BTreeSet<String> = ["MIT".into()].into();
1214 let both: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1215 let old = licensing("MIT", &mit);
1216
1217 assert!(
1218 copyleft_obligations_added(old, licensing("MIT OR GPL-3.0-only", &both)).is_empty()
1219 );
1220 assert_eq!(
1221 copyleft_obligations_added(old, licensing("MIT AND GPL-3.0-only", &both)),
1222 BTreeSet::from(["GPL-3.0-only".to_string()])
1223 );
1224 }
1225
1226 #[test]
1227 fn test_copyleft_obligations_added_carried_over() {
1228 let gpl: BTreeSet<String> = ["GPL-3.0-only".into()].into();
1229 let both: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1230
1231 assert!(copyleft_obligations_added(
1232 licensing("GPL-3.0-only", &gpl),
1233 licensing("GPL-3.0-only AND MIT", &both)
1234 )
1235 .is_empty());
1236
1237 let agpl: BTreeSet<String> = ["AGPL-3.0-only".into()].into();
1239 assert_eq!(
1240 copyleft_obligations_added(
1241 licensing("GPL-3.0-only", &gpl),
1242 licensing("AGPL-3.0-only", &agpl)
1243 ),
1244 BTreeSet::from(["AGPL-3.0-only".to_string()])
1245 );
1246 }
1247
1248 #[test]
1249 fn test_copyleft_obligations_added_losing_the_permissive_choice() {
1250 let both: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1251 let gpl: BTreeSet<String> = ["GPL-3.0-only".into()].into();
1252
1253 assert_eq!(
1254 copyleft_obligations_added(
1255 licensing("MIT OR GPL-3.0-only", &both),
1256 licensing("GPL-3.0-only", &gpl)
1257 ),
1258 BTreeSet::from(["GPL-3.0-only".to_string()])
1259 );
1260 }
1261
1262 fn copyleft_added(old: &str, new: &str) -> BTreeSet<String> {
1263 let old_ids = parse_license_expression(old);
1264 let new_ids = parse_license_expression(new);
1265 copyleft_obligations_added(licensing(old, &old_ids), licensing(new, &new_ids))
1266 }
1267
1268 fn licenses(names: &[&str]) -> BTreeSet<String> {
1269 names.iter().map(|n| n.to_string()).collect()
1270 }
1271
1272 #[test]
1273 fn test_copyleft_obligations_added_ignores_a_choice_between_copyleft_licenses() {
1274 for (old, new) in [
1275 (
1276 "GPL-2.0-only OR GPL-3.0-only",
1277 "GPL-2.0-only OR GPL-3.0-only OR LGPL-3.0-only",
1278 ),
1279 (
1280 "MIT AND (GPL-2.0-only OR GPL-3.0-only)",
1281 "Apache-2.0 AND (GPL-2.0-only OR GPL-3.0-only)",
1282 ),
1283 (
1284 "MPL-2.0 OR GPL-2.0-only OR LGPL-2.1-only",
1285 "MPL-2.0 OR GPL-2.0-only OR LGPL-2.1-only",
1286 ),
1287 ] {
1288 assert!(
1289 copyleft_added(old, new).is_empty(),
1290 "{old} -> {new} forces no copyleft the consumer could not already have taken"
1291 );
1292 }
1293 }
1294
1295 #[test]
1296 fn test_copyleft_obligations_added_fires_on_every_tightening() {
1297 for (old, new, introduced) in [
1298 (
1299 "GPL-2.0-only OR GPL-3.0-only",
1300 "GPL-2.0-only AND GPL-3.0-only",
1301 &["GPL-2.0-only", "GPL-3.0-only"][..],
1302 ),
1303 ("MIT OR GPL-3.0-only", "GPL-3.0-only", &["GPL-3.0-only"]),
1304 ("GPL-3.0-only", "AGPL-3.0-only", &["AGPL-3.0-only"]),
1305 ("MIT", "MIT AND GPL-3.0-only", &["GPL-3.0-only"]),
1306 (
1307 "GPL-2.0-only OR GPL-3.0-only",
1308 "AGPL-3.0-only",
1309 &["AGPL-3.0-only"],
1310 ),
1311 ] {
1312 assert_eq!(
1313 copyleft_added(old, new),
1314 licenses(introduced),
1315 "{old} -> {new}"
1316 );
1317 }
1318 }
1319
1320 #[test]
1321 fn test_copyleft_obligations_added_spans_the_minimal_choices_less_what_old_forced() {
1322 for (old, new, introduced) in [
1323 (
1324 "MIT",
1325 "GPL-3.0-only AND (MPL-2.0 OR ISC)",
1326 &["GPL-3.0-only"][..],
1327 ),
1328 (
1329 "GPL-2.0-only",
1330 "GPL-2.0-only AND GPL-3.0-only",
1331 &["GPL-3.0-only"],
1332 ),
1333 (
1334 "MIT",
1335 "GPL-2.0-only OR AGPL-3.0-only",
1336 &["AGPL-3.0-only", "GPL-2.0-only"],
1337 ),
1338 (
1339 "MIT",
1340 "(GPL-3.0-only AND MPL-2.0) OR (AGPL-3.0-only AND EPL-2.0)",
1341 &["AGPL-3.0-only", "GPL-3.0-only", "MPL-2.0"],
1342 ),
1343 ] {
1344 assert_eq!(
1345 copyleft_added(old, new),
1346 licenses(introduced),
1347 "{old} -> {new}"
1348 );
1349 }
1350 }
1351
1352 #[test]
1353 fn test_copyleft_obligations_added_falls_back_past_max_choices() {
1354 let wide = "(MIT OR Apache-2.0) AND (BSD-2-Clause OR BSD-3-Clause) \
1355 AND (ISC OR Zlib) AND (MPL-2.0 OR EPL-2.0) \
1356 AND (GPL-2.0-only OR GPL-3.0-only) AND (LGPL-2.1-only OR LGPL-3.0-only) \
1357 AND (CC0-1.0 OR Unlicense)";
1358
1359 assert_eq!(
1360 copyleft_added("MIT", wide),
1361 licenses(&[
1362 "GPL-2.0-only",
1363 "GPL-3.0-only",
1364 "LGPL-2.1-only",
1365 "LGPL-3.0-only",
1366 "MPL-2.0",
1367 ])
1368 );
1369 }
1370
1371 #[test]
1372 fn test_copyleft_obligations_added_matches_flat_sets() {
1373 let old: BTreeSet<String> = ["MIT".into()].into();
1374 let new: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1375
1376 assert_eq!(
1377 copyleft_obligations_added(Licensing::from_ids(&old), Licensing::from_ids(&new)),
1378 BTreeSet::from(["GPL-3.0-only".to_string()])
1379 );
1380 assert!(copyleft_introduced(&old, &new));
1381
1382 assert!(
1383 copyleft_obligations_added(Licensing::from_ids(&new), Licensing::from_ids(&new))
1384 .is_empty()
1385 );
1386 assert!(!copyleft_introduced(&new, &new));
1387 }
1388
1389 #[test]
1390 fn test_license_expressions_equivalent() {
1391 assert!(license_expressions_equivalent(
1392 "MIT OR Apache-2.0",
1393 "( MIT OR (Apache-2.0) )"
1394 ));
1395 assert!(!license_expressions_equivalent(
1396 "MIT OR Apache-2.0",
1397 "MIT AND Apache-2.0"
1398 ));
1399 assert!(!license_expressions_equivalent(
1400 "GPL-2.0-only",
1401 "GPL-2.0-only WITH Classpath-exception-2.0"
1402 ));
1403 assert!(license_expressions_equivalent("Custom Text", "Custom Text"));
1404 assert!(!license_expressions_equivalent("Custom Text", "Other Text"));
1405 }
1406
1407 #[test]
1408 fn test_license_expressions_equivalent_falls_back_past_max_choices() {
1409 let wide = "(MIT OR Apache-2.0) AND (BSD-2-Clause OR BSD-3-Clause) \
1410 AND (ISC OR Zlib) AND (MPL-2.0 OR EPL-2.0) \
1411 AND (GPL-2.0-only OR GPL-3.0-only) AND (LGPL-2.1-only OR LGPL-3.0-only) \
1412 AND (CC0-1.0 OR Unlicense)";
1413
1414 assert!(license_expressions_equivalent(wide, wide));
1415 assert!(license_expressions_equivalent(
1416 wide,
1417 &wide.replace("(MIT OR Apache-2.0)", "((MIT OR Apache-2.0))")
1418 ));
1419 assert!(!license_expressions_equivalent(
1420 wide,
1421 &wide.replace("MIT OR Apache-2.0", "Apache-2.0 OR MIT")
1422 ));
1423
1424 let ids: BTreeSet<String> = wide
1425 .split_whitespace()
1426 .map(|word| word.trim_matches(['(', ')']).to_string())
1427 .filter(|word| word != "AND" && word != "OR")
1428 .collect();
1429 assert!(!licensings_equivalent(
1430 Licensing {
1431 expression: Some(wide),
1432 ids: &ids,
1433 },
1434 Licensing::from_ids(&ids)
1435 ));
1436 }
1437
1438 #[test]
1439 fn test_license_expressions_equivalent_ignores_operand_order() {
1440 assert!(license_expressions_equivalent(
1441 "MIT OR Apache-2.0",
1442 "Apache-2.0 OR MIT"
1443 ));
1444 assert!(license_expressions_equivalent(
1445 "(MIT OR Apache-2.0) AND BSD-3-Clause",
1446 "(BSD-3-Clause AND Apache-2.0) OR (BSD-3-Clause AND MIT)"
1447 ));
1448 assert!(license_expressions_equivalent(
1449 "MIT",
1450 "MIT OR (MIT AND Apache-2.0)"
1451 ));
1452 assert!(!license_expressions_equivalent(
1453 "MIT OR Apache-2.0",
1454 "MIT OR BSD-3-Clause"
1455 ));
1456 }
1457
1458 #[test]
1459 fn test_licensings_equivalent_reads_a_bare_set_as_a_conjunction() {
1460 let ids: BTreeSet<String> = ["GPL-3.0-only".to_string(), "MIT".to_string()].into();
1461 let flat = Licensing::from_ids(&ids);
1462
1463 assert!(licensings_equivalent(
1464 Licensing {
1465 expression: Some("MIT AND GPL-3.0-only"),
1466 ids: &ids,
1467 },
1468 flat
1469 ));
1470 assert!(!licensings_equivalent(
1471 Licensing {
1472 expression: Some("MIT OR GPL-3.0-only"),
1473 ids: &ids,
1474 },
1475 flat
1476 ));
1477 assert!(licensings_equivalent(flat, flat));
1478 }
1479
1480 #[test]
1481 fn test_licensings_equivalent_keeps_decorated_requirements() {
1482 let gpl: BTreeSet<String> = ["GPL-2.0-only".to_string()].into();
1483 assert!(!licensings_equivalent(
1484 Licensing {
1485 expression: Some("GPL-2.0-only WITH Classpath-exception-2.0"),
1486 ids: &gpl,
1487 },
1488 Licensing::from_ids(&gpl)
1489 ));
1490 let apache: BTreeSet<String> = ["Apache-2.0".to_string()].into();
1491 assert!(!licensings_equivalent(
1492 Licensing {
1493 expression: Some("Apache-2.0+"),
1494 ids: &apache,
1495 },
1496 Licensing::from_ids(&apache)
1497 ));
1498 }
1499
1500 #[test]
1501 fn test_licensings_equivalent_falls_back_to_the_identifier_set() {
1502 let ids: BTreeSet<String> = ["Custom Text".to_string()].into();
1503 assert!(licensings_equivalent(
1504 Licensing {
1505 expression: Some("Custom Text"),
1506 ids: &ids,
1507 },
1508 Licensing::from_ids(&ids)
1509 ));
1510 }
1511
1512 #[test]
1513 fn test_component_licensing_defaults_to_ids() {
1514 let mut comp = Component::new("demo".into(), None);
1515 comp.licenses.insert("MIT".into());
1516
1517 assert_eq!(comp.licensing().expression, None);
1518 assert_eq!(
1519 comp.licensing().requirements(),
1520 BTreeSet::from([LicenseRequirement::new("MIT")])
1521 );
1522 }
1523
1524 #[test]
1525 fn test_parse_license_expression() {
1526 let ids = parse_license_expression("MIT OR Apache-2.0");
1528 assert!(ids.contains("MIT"));
1529 assert!(ids.contains("Apache-2.0"));
1530 assert_eq!(ids.len(), 2);
1531
1532 let ids = parse_license_expression("MIT");
1534 assert_eq!(ids, BTreeSet::from(["MIT".to_string()]));
1535
1536 let ids = parse_license_expression("MIT AND Apache-2.0");
1538 assert!(ids.contains("MIT"));
1539 assert!(ids.contains("Apache-2.0"));
1540
1541 let ids = parse_license_expression("Custom License");
1543 assert_eq!(ids, BTreeSet::from(["Custom License".to_string()]));
1544
1545 let ids = parse_license_expression("LicenseRef-proprietary");
1547 assert_eq!(ids, BTreeSet::from(["LicenseRef-proprietary".to_string()]));
1548 }
1549
1550 #[test]
1551 fn test_parse_license_expression_licenseref_and_spdx() {
1552 let ids = parse_license_expression("LicenseRef-proprietary AND Apache-2.0");
1554 assert!(ids.contains("LicenseRef-proprietary"));
1555 assert!(ids.contains("Apache-2.0"));
1556 assert_eq!(ids.len(), 2);
1557 }
1558
1559 #[test]
1560 fn test_parse_license_expression_licenseref_or_spdx() {
1561 let ids = parse_license_expression("LicenseRef-custom OR MIT");
1563 assert!(ids.contains("LicenseRef-custom"));
1564 assert!(ids.contains("MIT"));
1565 assert_eq!(ids.len(), 2);
1566 }
1567
1568 #[test]
1569 fn test_parse_license_expression_multiple_licenserefs() {
1570 let ids = parse_license_expression("LicenseRef-a AND LicenseRef-b");
1572 assert!(ids.contains("LicenseRef-a"));
1573 assert!(ids.contains("LicenseRef-b"));
1574 assert_eq!(ids.len(), 2);
1575 }
1576
1577 #[test]
1578 fn test_parse_license_expression_complex_mixed() {
1579 let ids = parse_license_expression("(MIT OR LicenseRef-custom) AND Apache-2.0");
1581 assert!(ids.contains("MIT"));
1582 assert!(ids.contains("LicenseRef-custom"));
1583 assert!(ids.contains("Apache-2.0"));
1584 assert_eq!(ids.len(), 3);
1585 }
1586
1587 #[test]
1588 fn test_parse_license_expression_documentref() {
1589 let ids = parse_license_expression("DocumentRef-ext:LicenseRef-custom");
1591 assert_eq!(
1592 ids,
1593 BTreeSet::from(["DocumentRef-ext:LicenseRef-custom".to_string()])
1594 );
1595 }
1596
1597 #[test]
1598 fn test_license_set_equality() {
1599 let mut c1 = Component::new("test".into(), None);
1601 c1.licenses.insert("MIT".into());
1602 c1.licenses.insert("Apache-2.0".into());
1603
1604 let mut c2 = Component::new("test".into(), None);
1605 c2.licenses.insert("Apache-2.0".into());
1606 c2.licenses.insert("MIT".into());
1607
1608 assert_eq!(c1.licenses, c2.licenses);
1609 }
1610
1611 #[test]
1612 fn test_query_api() {
1613 let mut sbom = Sbom::default();
1614 let c1 = Component::new("a".into(), Some("1".into()));
1615 let c2 = Component::new("b".into(), Some("1".into()));
1616 let c3 = Component::new("c".into(), Some("1".into()));
1617
1618 let id1 = c1.id.clone();
1619 let id2 = c2.id.clone();
1620 let id3 = c3.id.clone();
1621
1622 sbom.components.insert(id1.clone(), c1);
1623 sbom.components.insert(id2.clone(), c2);
1624 sbom.components.insert(id3.clone(), c3);
1625
1626 sbom.dependencies
1628 .entry(id1.clone())
1629 .or_default()
1630 .insert(id2.clone(), DependencyKind::Runtime);
1631 sbom.dependencies
1632 .entry(id2.clone())
1633 .or_default()
1634 .insert(id3.clone(), DependencyKind::Runtime);
1635 sbom.rebuild_reverse_deps();
1636
1637 assert_eq!(sbom.roots(), vec![id1.clone()]);
1638 assert_eq!(sbom.deps(&id1), vec![id2.clone()]);
1639 assert_eq!(sbom.rdeps(&id2), vec![id1.clone()]);
1640
1641 let transitive = sbom.transitive_deps(&id1);
1642 assert!(transitive.contains(&id2));
1643 assert!(transitive.contains(&id3));
1644 assert_eq!(transitive.len(), 2);
1645
1646 assert_eq!(sbom.missing_hashes().len(), 3);
1647 }
1648
1649 #[test]
1650 fn test_ecosystems_query() {
1651 let mut sbom = Sbom::default();
1652
1653 let mut c1 = Component::new("lodash".into(), Some("1.0".into()));
1654 c1.ecosystem = Some("npm".into());
1655 let mut c2 = Component::new("serde".into(), Some("1.0".into()));
1656 c2.ecosystem = Some("cargo".into());
1657 let mut c3 = Component::new("other-npm".into(), Some("1.0".into()));
1658 c3.ecosystem = Some("npm".into());
1659 let c4 = Component::new("no-ecosystem".into(), Some("1.0".into()));
1660
1661 sbom.components.insert(c1.id.clone(), c1);
1662 sbom.components.insert(c2.id.clone(), c2);
1663 sbom.components.insert(c3.id.clone(), c3);
1664 sbom.components.insert(c4.id.clone(), c4);
1665
1666 let ecosystems = sbom.ecosystems();
1667 assert_eq!(ecosystems.len(), 2);
1668 assert!(ecosystems.contains("npm"));
1669 assert!(ecosystems.contains("cargo"));
1670 }
1671
1672 #[test]
1673 fn test_licenses_query() {
1674 let mut sbom = Sbom::default();
1675
1676 let mut c1 = Component::new("a".into(), Some("1.0".into()));
1677 c1.licenses.insert("MIT".into());
1678 c1.licenses.insert("Apache-2.0".into());
1679 let mut c2 = Component::new("b".into(), Some("1.0".into()));
1680 c2.licenses.insert("MIT".into());
1681 c2.licenses.insert("GPL-3.0-only".into());
1682 let c3 = Component::new("c".into(), Some("1.0".into()));
1683
1684 sbom.components.insert(c1.id.clone(), c1);
1685 sbom.components.insert(c2.id.clone(), c2);
1686 sbom.components.insert(c3.id.clone(), c3);
1687
1688 let licenses = sbom.licenses();
1689 assert_eq!(licenses.len(), 3);
1690 assert!(licenses.contains("MIT"));
1691 assert!(licenses.contains("Apache-2.0"));
1692 assert!(licenses.contains("GPL-3.0-only"));
1693 }
1694
1695 #[test]
1696 fn test_by_purl() {
1697 let mut sbom = Sbom::default();
1698
1699 let mut c1 = Component::new("lodash".into(), Some("4.17.21".into()));
1700 c1.purl = Some("pkg:npm/lodash@4.17.21".into());
1701 c1.id = ComponentId::new(c1.purl.as_deref(), &[]);
1702 let c2 = Component::new("no-purl".into(), Some("1.0".into()));
1703
1704 sbom.components.insert(c1.id.clone(), c1);
1705 sbom.components.insert(c2.id.clone(), c2);
1706
1707 let found = sbom.by_purl("pkg:npm/lodash@4.17.21");
1708 assert!(found.is_some());
1709 assert_eq!(found.unwrap().name, "lodash");
1710
1711 assert!(sbom.by_purl("pkg:npm/nonexistent@1.0").is_none());
1712 }
1713
1714 #[test]
1715 fn test_component_id_unparseable_purl() {
1716 let id = ComponentId::new(Some("not-a-valid-purl-but-still-a-string"), &[]);
1718 assert_eq!(id.as_str(), "not-a-valid-purl-but-still-a-string");
1719 }
1720
1721 #[test]
1722 fn test_component_id_display() {
1723 let id = ComponentId::new(Some("pkg:npm/foo@1.0"), &[]);
1724 assert_eq!(format!("{}", id), "pkg:npm/foo@1.0");
1725 }
1726
1727 #[test]
1728 fn test_sbom_normalize_clears_metadata() {
1729 let mut sbom = Sbom::default();
1730 sbom.metadata.timestamp = Some("2024-01-01T00:00:00Z".into());
1731 sbom.metadata.tools.push("syft".into());
1732 sbom.metadata.authors.push("alice".into());
1733
1734 let c = Component::new("a".into(), Some("1".into()));
1735 sbom.components.insert(c.id.clone(), c);
1736
1737 sbom.normalize();
1738
1739 assert!(sbom.metadata.timestamp.is_none());
1740 assert!(sbom.metadata.tools.is_empty());
1741 assert!(sbom.metadata.authors.is_empty());
1742 }
1743
1744 #[test]
1745 fn test_missing_hashes_mixed() {
1746 let mut sbom = Sbom::default();
1747
1748 let c1 = Component::new("no-hash".into(), Some("1.0".into()));
1749 let mut c2 = Component::new("has-hash".into(), Some("1.0".into()));
1750 c2.hashes.insert("sha256".into(), "abc".into());
1751
1752 sbom.components.insert(c1.id.clone(), c1);
1753 sbom.components.insert(c2.id.clone(), c2);
1754
1755 let missing = sbom.missing_hashes();
1756 assert_eq!(missing.len(), 1);
1757 }
1758
1759 #[test]
1760 fn test_ecosystem_from_purl() {
1761 use super::ecosystem_from_purl;
1762
1763 assert_eq!(
1764 ecosystem_from_purl("pkg:npm/lodash@4.17.21"),
1765 Some("npm".to_string())
1766 );
1767 assert_eq!(
1768 ecosystem_from_purl("pkg:cargo/serde@1.0.0"),
1769 Some("cargo".to_string())
1770 );
1771 assert_eq!(
1772 ecosystem_from_purl("pkg:pypi/requests@2.28.0"),
1773 Some("pypi".to_string())
1774 );
1775 assert_eq!(
1776 ecosystem_from_purl("pkg:maven/org.apache/commons@1.0"),
1777 Some("maven".to_string())
1778 );
1779 assert_eq!(ecosystem_from_purl("invalid-purl"), None);
1780 assert_eq!(ecosystem_from_purl(""), None);
1781 }
1782
1783 #[test]
1784 fn test_canonical_algorithm_name() {
1785 assert_eq!(canonical_algorithm_name("SHA256"), "SHA-256");
1787 assert_eq!(canonical_algorithm_name("SHA1"), "SHA-1");
1788 assert_eq!(canonical_algorithm_name("SHA384"), "SHA-384");
1789 assert_eq!(canonical_algorithm_name("SHA512"), "SHA-512");
1790 assert_eq!(canonical_algorithm_name("SHA224"), "SHA-224");
1791
1792 assert_eq!(canonical_algorithm_name("SHA-256"), "SHA-256");
1794 assert_eq!(canonical_algorithm_name("SHA-1"), "SHA-1");
1795 assert_eq!(canonical_algorithm_name("SHA-384"), "SHA-384");
1796
1797 assert_eq!(canonical_algorithm_name("sha256"), "SHA-256");
1799 assert_eq!(canonical_algorithm_name("sha-256"), "SHA-256");
1800
1801 assert_eq!(canonical_algorithm_name("SHA3-256"), "SHA3-256");
1803 assert_eq!(canonical_algorithm_name("SHA3256"), "SHA3-256");
1804
1805 assert_eq!(canonical_algorithm_name("MD5"), "MD5");
1807 assert_eq!(canonical_algorithm_name("md5"), "MD5");
1808
1809 assert_eq!(canonical_algorithm_name("BLAKE2b-256"), "BLAKE2b-256");
1811 assert_eq!(canonical_algorithm_name("BLAKE2B256"), "BLAKE2b-256");
1812 assert_eq!(canonical_algorithm_name("BLAKE3"), "BLAKE3");
1813
1814 assert_eq!(canonical_algorithm_name("ADLER32"), "ADLER-32");
1816 assert_eq!(canonical_algorithm_name("ADLER-32"), "ADLER-32");
1817
1818 assert_eq!(canonical_algorithm_name("TIGER"), "TIGER");
1820 }
1821
1822 #[test]
1823 fn test_hash_algorithm_strength_ordering() {
1824 let md5 = hash_algorithm_strength("MD5").unwrap();
1826 let sha1 = hash_algorithm_strength("SHA-1").unwrap();
1827 let sha224 = hash_algorithm_strength("SHA-224").unwrap();
1828 let sha256 = hash_algorithm_strength("SHA-256").unwrap();
1829 let sha384 = hash_algorithm_strength("SHA-384").unwrap();
1830 let sha512 = hash_algorithm_strength("SHA-512").unwrap();
1831
1832 assert!(md5 < sha1);
1833 assert!(sha1 < sha224);
1834 assert!(sha224 < sha256);
1835 assert!(sha256 < sha384);
1836 assert!(sha384 < sha512);
1837 }
1838
1839 #[test]
1840 fn test_hash_algorithm_strength_variants() {
1841 assert_eq!(
1843 hash_algorithm_strength("sha256"),
1844 hash_algorithm_strength("SHA-256")
1845 );
1846 assert_eq!(
1847 hash_algorithm_strength("sha-1"),
1848 hash_algorithm_strength("SHA1")
1849 );
1850
1851 assert_eq!(
1853 hash_algorithm_strength("SHA3-256"),
1854 hash_algorithm_strength("SHA-256")
1855 );
1856 assert_eq!(
1857 hash_algorithm_strength("SHA3-512"),
1858 hash_algorithm_strength("SHA-512")
1859 );
1860
1861 assert_eq!(
1863 hash_algorithm_strength("BLAKE2b-256"),
1864 hash_algorithm_strength("SHA-256")
1865 );
1866 assert_eq!(
1867 hash_algorithm_strength("BLAKE3"),
1868 hash_algorithm_strength("SHA-256")
1869 );
1870
1871 assert_eq!(hash_algorithm_strength("TIGER"), None);
1873 assert_eq!(hash_algorithm_strength("UNKNOWN"), None);
1874 }
1875
1876 #[test]
1877 fn test_hash_algorithm_strength_adler() {
1878 let adler = hash_algorithm_strength("ADLER-32").unwrap();
1879 let md5 = hash_algorithm_strength("MD5").unwrap();
1880 assert!(adler < md5);
1881 }
1882
1883 #[test]
1884 fn test_is_hash_algorithm_downgrade_sha256_to_md5() {
1885 let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
1886 let new: BTreeMap<String, String> = [("md5".into(), "def".into())].into();
1887 assert!(is_hash_algorithm_downgrade(&old, &new));
1888 }
1889
1890 #[test]
1891 fn test_is_hash_algorithm_downgrade_upgrade_not_flagged() {
1892 let old: BTreeMap<String, String> = [("sha-1".into(), "abc".into())].into();
1893 let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
1894 assert!(!is_hash_algorithm_downgrade(&old, &new));
1895 }
1896
1897 #[test]
1898 fn test_is_hash_algorithm_downgrade_same_algorithm() {
1899 let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
1900 let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
1901 assert!(!is_hash_algorithm_downgrade(&old, &new));
1902 }
1903
1904 #[test]
1905 fn test_is_hash_algorithm_downgrade_empty_old() {
1906 let old: BTreeMap<String, String> = BTreeMap::new();
1907 let new: BTreeMap<String, String> = [("md5".into(), "def".into())].into();
1908 assert!(!is_hash_algorithm_downgrade(&old, &new));
1909 }
1910
1911 #[test]
1912 fn test_is_hash_algorithm_downgrade_empty_new() {
1913 let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
1914 let new: BTreeMap<String, String> = BTreeMap::new();
1915 assert!(!is_hash_algorithm_downgrade(&old, &new));
1916 }
1917
1918 #[test]
1919 fn test_is_hash_algorithm_downgrade_multi_algorithm() {
1920 let old: BTreeMap<String, String> = [
1922 ("sha-256".into(), "abc".into()),
1923 ("md5".into(), "xyz".into()),
1924 ]
1925 .into();
1926 let new: BTreeMap<String, String> = [("md5".into(), "def".into())].into();
1927 assert!(is_hash_algorithm_downgrade(&old, &new));
1928 }
1929
1930 #[test]
1931 fn test_is_hash_algorithm_downgrade_multi_algorithm_kept() {
1932 let old: BTreeMap<String, String> = [
1934 ("sha-256".into(), "abc".into()),
1935 ("md5".into(), "xyz".into()),
1936 ]
1937 .into();
1938 let new: BTreeMap<String, String> = [
1939 ("sha-256".into(), "def".into()),
1940 ("sha-1".into(), "ghi".into()),
1941 ]
1942 .into();
1943 assert!(!is_hash_algorithm_downgrade(&old, &new));
1944 }
1945
1946 #[test]
1947 fn test_detect_cycles_none() {
1948 let mut sbom = Sbom::default();
1949 let c1 = Component::new("a".into(), Some("1".into()));
1950 let c2 = Component::new("b".into(), Some("1".into()));
1951 let c3 = Component::new("c".into(), Some("1".into()));
1952
1953 let id1 = c1.id.clone();
1954 let id2 = c2.id.clone();
1955 let id3 = c3.id.clone();
1956
1957 sbom.components.insert(id1.clone(), c1);
1958 sbom.components.insert(id2.clone(), c2);
1959 sbom.components.insert(id3.clone(), c3);
1960
1961 sbom.dependencies
1963 .entry(id1.clone())
1964 .or_default()
1965 .insert(id2.clone(), DependencyKind::Runtime);
1966 sbom.dependencies
1967 .entry(id2.clone())
1968 .or_default()
1969 .insert(id3.clone(), DependencyKind::Runtime);
1970
1971 assert!(sbom.detect_cycles().is_empty());
1972 }
1973
1974 #[test]
1975 fn test_detect_cycles_simple() {
1976 let mut sbom = Sbom::default();
1977 let c1 = Component::new("a".into(), Some("1".into()));
1978 let c2 = Component::new("b".into(), Some("1".into()));
1979
1980 let id1 = c1.id.clone();
1981 let id2 = c2.id.clone();
1982
1983 sbom.components.insert(id1.clone(), c1);
1984 sbom.components.insert(id2.clone(), c2);
1985
1986 sbom.dependencies
1988 .entry(id1.clone())
1989 .or_default()
1990 .insert(id2.clone(), DependencyKind::Runtime);
1991 sbom.dependencies
1992 .entry(id2.clone())
1993 .or_default()
1994 .insert(id1.clone(), DependencyKind::Runtime);
1995
1996 let cycles = sbom.detect_cycles();
1997 assert_eq!(cycles.len(), 1);
1998 assert_eq!(cycles[0].first(), cycles[0].last());
2000 }
2001
2002 #[test]
2003 fn test_detect_cycles_self_loop() {
2004 let mut sbom = Sbom::default();
2005 let c1 = Component::new("a".into(), Some("1".into()));
2006 let id1 = c1.id.clone();
2007 sbom.components.insert(id1.clone(), c1);
2008
2009 sbom.dependencies
2011 .entry(id1.clone())
2012 .or_default()
2013 .insert(id1.clone(), DependencyKind::Runtime);
2014
2015 let cycles = sbom.detect_cycles();
2016 assert_eq!(cycles.len(), 1);
2017 assert_eq!(cycles[0].len(), 2); }
2019
2020 #[test]
2021 fn test_detect_cycles_empty_graph() {
2022 let sbom = Sbom::default();
2023 assert!(sbom.detect_cycles().is_empty());
2024 }
2025
2026 #[test]
2027 fn test_insert_component_keeps_replaced_source_ids() {
2028 let entry = |name: &str, source_ids: &[&str]| {
2029 let mut c = Component::new("dup".into(), Some("1".into()));
2030 c.description = Some(name.into());
2031 c.source_ids = source_ids.iter().map(|s| s.to_string()).collect();
2032 c
2033 };
2034 let mut sbom = Sbom::default();
2035 assert!(sbom
2036 .insert_component(entry("first", &["ref-c", "ref-a"]))
2037 .is_none());
2038 let replaced = sbom
2039 .insert_component(entry("second", &["ref-b", "ref-a"]))
2040 .unwrap();
2041 assert_eq!(replaced.description.as_deref(), Some("first"));
2042 assert_eq!(sbom.components.len(), 1);
2043 assert_eq!(sbom.components[0].description.as_deref(), Some("second"));
2044 assert_eq!(
2045 sbom.components[0].source_ids,
2046 vec!["ref-a", "ref-b", "ref-c"]
2047 );
2048 }
2049
2050 #[test]
2051 fn test_insert_dependency_kind_does_not_depend_on_order() {
2052 let parent = Component::new("parent".into(), None).id;
2053 let child = Component::new("child".into(), None).id;
2054 for kinds in [
2055 [DependencyKind::Optional, DependencyKind::Runtime],
2056 [DependencyKind::Runtime, DependencyKind::Optional],
2057 ] {
2058 let mut sbom = Sbom::default();
2059 for kind in kinds {
2060 sbom.insert_dependency(parent.clone(), child.clone(), kind);
2061 }
2062 assert_eq!(
2063 sbom.dependencies[&parent],
2064 BTreeMap::from([(child.clone(), DependencyKind::Runtime)])
2065 );
2066 }
2067
2068 let mut sbom = Sbom::default();
2069 sbom.insert_dependency(parent.clone(), child.clone(), DependencyKind::Test);
2070 sbom.insert_dependency(parent.clone(), child.clone(), DependencyKind::Dev);
2071 assert_eq!(sbom.dependencies[&parent][&child], DependencyKind::Dev);
2072 }
2073
2074 #[test]
2075 fn test_detect_cycles_three_node() {
2076 let mut sbom = Sbom::default();
2077 let c1 = Component::new("a".into(), Some("1".into()));
2078 let c2 = Component::new("b".into(), Some("1".into()));
2079 let c3 = Component::new("c".into(), Some("1".into()));
2080
2081 let id1 = c1.id.clone();
2082 let id2 = c2.id.clone();
2083 let id3 = c3.id.clone();
2084
2085 sbom.components.insert(id1.clone(), c1);
2086 sbom.components.insert(id2.clone(), c2);
2087 sbom.components.insert(id3.clone(), c3);
2088
2089 sbom.dependencies
2091 .entry(id1.clone())
2092 .or_default()
2093 .insert(id2.clone(), DependencyKind::Runtime);
2094 sbom.dependencies
2095 .entry(id2.clone())
2096 .or_default()
2097 .insert(id3.clone(), DependencyKind::Runtime);
2098 sbom.dependencies
2099 .entry(id3.clone())
2100 .or_default()
2101 .insert(id1.clone(), DependencyKind::Runtime);
2102
2103 let cycles = sbom.detect_cycles();
2104 assert_eq!(cycles.len(), 1);
2105 assert_eq!(cycles[0].first(), cycles[0].last());
2106 assert_eq!(cycles[0].len(), 4); }
2108
2109 #[test]
2110 fn test_is_hash_algorithm_downgrade_unknown_algorithms() {
2111 let old: BTreeMap<String, String> = [("TIGER".into(), "abc".into())].into();
2113 let new: BTreeMap<String, String> = [("WHIRLPOOL".into(), "def".into())].into();
2114 assert!(!is_hash_algorithm_downgrade(&old, &new));
2115 }
2116
2117 #[test]
2118 fn test_changed_checksums_same_algorithm_different_value() {
2119 let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2120 let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
2121 assert_eq!(
2122 changed_checksums(&old, &new),
2123 vec![("SHA-256".to_string(), "abc".to_string(), "def".to_string())]
2124 );
2125 }
2126
2127 #[test]
2128 fn test_changed_checksums_identical_values() {
2129 let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2130 assert!(changed_checksums(&old, &old).is_empty());
2131 }
2132
2133 #[test]
2134 fn test_changed_checksums_case_only_difference() {
2135 let old: BTreeMap<String, String> = [("sha-256".into(), "ABCDEF".into())].into();
2136 let new: BTreeMap<String, String> = [("sha-256".into(), "abcdef".into())].into();
2137 assert!(changed_checksums(&old, &new).is_empty());
2138 }
2139
2140 #[test]
2141 fn test_changed_checksums_ignores_surrounding_whitespace() {
2142 let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2143 let new: BTreeMap<String, String> = [("sha-256".into(), " abc\n".into())].into();
2144 assert!(changed_checksums(&old, &new).is_empty());
2145 }
2146
2147 #[test]
2148 fn test_changed_checksums_disjoint_algorithms() {
2149 let old: BTreeMap<String, String> = [("sha-1".into(), "abc".into())].into();
2150 let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
2151 assert!(changed_checksums(&old, &new).is_empty());
2152 }
2153
2154 #[test]
2155 fn test_changed_checksums_only_compares_shared_algorithms() {
2156 let old: BTreeMap<String, String> = [
2157 ("sha-1".into(), "aaa".into()),
2158 ("sha-256".into(), "bbb".into()),
2159 ]
2160 .into();
2161 let new: BTreeMap<String, String> = [
2162 ("sha-256".into(), "ccc".into()),
2163 ("sha-512".into(), "ddd".into()),
2164 ]
2165 .into();
2166 assert_eq!(
2167 changed_checksums(&old, &new),
2168 vec![("SHA-256".to_string(), "bbb".to_string(), "ccc".to_string())]
2169 );
2170 }
2171
2172 #[test]
2173 fn test_changed_checksums_pairs_across_algorithm_spellings() {
2174 let old: BTreeMap<String, String> = [("SHA256".into(), "abc".into())].into();
2175 let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
2176 assert_eq!(
2177 changed_checksums(&old, &new),
2178 vec![("SHA-256".to_string(), "abc".to_string(), "def".to_string())]
2179 );
2180 }
2181
2182 #[test]
2183 fn test_changed_checksums_unknown_algorithm_pairs_by_name() {
2184 let old: BTreeMap<String, String> = [("tiger".into(), "abc".into())].into();
2185 let new: BTreeMap<String, String> = [("tiger".into(), "def".into())].into();
2186 assert_eq!(
2187 changed_checksums(&old, &new),
2188 vec![("tiger".to_string(), "abc".to_string(), "def".to_string())]
2189 );
2190 }
2191
2192 #[test]
2193 fn test_changed_checksums_empty_sides() {
2194 let empty: BTreeMap<String, String> = BTreeMap::new();
2195 let some: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2196 assert!(changed_checksums(&empty, &some).is_empty());
2197 assert!(changed_checksums(&some, &empty).is_empty());
2198 }
2199
2200 #[test]
2201 fn test_changed_checksums_reports_every_mismatching_algorithm() {
2202 let old: BTreeMap<String, String> = [
2203 ("sha-256".into(), "aaa".into()),
2204 ("sha-512".into(), "bbb".into()),
2205 ]
2206 .into();
2207 let new: BTreeMap<String, String> = [
2208 ("sha-256".into(), "ccc".into()),
2209 ("sha-512".into(), "ddd".into()),
2210 ]
2211 .into();
2212 assert_eq!(
2213 changed_checksums(&old, &new),
2214 vec![
2215 ("SHA-256".to_string(), "aaa".to_string(), "ccc".to_string()),
2216 ("SHA-512".to_string(), "bbb".to_string(), "ddd".to_string()),
2217 ]
2218 );
2219 }
2220
2221 #[test]
2222 fn test_is_copyleft_license() {
2223 assert!(is_copyleft_license("GPL-3.0-only"));
2225 assert!(is_copyleft_license("AGPL-3.0-only"));
2226 assert!(is_copyleft_license("LGPL-3.0-only"));
2227 assert!(!is_copyleft_license("MIT"));
2229 assert!(!is_copyleft_license("Apache-2.0"));
2230 assert!(!is_copyleft_license("BSD-3-Clause"));
2231 assert!(!is_copyleft_license("LicenseRef-proprietary"));
2233 assert!(!is_copyleft_license("NOT-A-LICENSE"));
2234 }
2235
2236 #[test]
2237 fn test_copyleft_introduced_permissive_to_copyleft() {
2238 let old: BTreeSet<String> = ["MIT".into()].into();
2239 let new: BTreeSet<String> = ["GPL-3.0-only".into()].into();
2240 assert!(copyleft_introduced(&old, &new));
2241 }
2242
2243 #[test]
2244 fn test_copyleft_introduced_permissive_to_permissive() {
2245 let old: BTreeSet<String> = ["MIT".into()].into();
2246 let new: BTreeSet<String> = ["Apache-2.0".into()].into();
2247 assert!(!copyleft_introduced(&old, &new));
2248 }
2249
2250 #[test]
2251 fn test_copyleft_introduced_carried_over_not_flagged() {
2252 let old: BTreeSet<String> = ["GPL-3.0-only".into()].into();
2254 let new: BTreeSet<String> = ["GPL-3.0-only".into()].into();
2255 assert!(!copyleft_introduced(&old, &new));
2256 }
2257
2258 #[test]
2259 fn test_copyleft_introduced_added_alongside_existing() {
2260 let old: BTreeSet<String> = ["GPL-3.0-only".into()].into();
2262 let new: BTreeSet<String> = ["GPL-3.0-only".into(), "AGPL-3.0-only".into()].into();
2263 assert!(copyleft_introduced(&old, &new));
2264 }
2265}