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, HashMap};
10use std::fmt;
11use std::str::FromStr;
12use std::sync::OnceLock;
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
29#[serde(from = "fields::Sbom")]
30pub struct Sbom {
31 pub metadata: Metadata,
33 pub components: IndexMap<ComponentId, Component>,
35 pub dependencies: BTreeMap<ComponentId, BTreeMap<ComponentId, DependencyKind>>,
37 #[serde(skip)]
39 reverse_deps: BTreeMap<ComponentId, BTreeSet<ComponentId>>,
40 #[serde(skip_serializing_if = "Vec::is_empty")]
42 pub warnings: Vec<String>,
43}
44
45mod fields {
47 use super::*;
48
49 #[derive(Deserialize)]
50 pub(super) struct Sbom {
51 pub(super) metadata: Metadata,
52 pub(super) components: IndexMap<ComponentId, Component>,
53 pub(super) dependencies: BTreeMap<ComponentId, BTreeMap<ComponentId, DependencyKind>>,
54 #[serde(default)]
55 pub(super) warnings: Vec<String>,
56 }
57}
58
59impl From<fields::Sbom> for Sbom {
60 fn from(fields: fields::Sbom) -> Self {
61 let mut sbom = Self {
62 metadata: fields.metadata,
63 components: fields.components,
64 dependencies: fields.dependencies,
65 reverse_deps: BTreeMap::new(),
66 warnings: fields.warnings,
67 };
68 sbom.rebuild_reverse_deps();
69 sbom
70 }
71}
72
73impl PartialEq for Sbom {
74 fn eq(&self, other: &Self) -> bool {
75 self.metadata == other.metadata
76 && self.components == other.components
77 && self.dependencies == other.dependencies
78 && self.warnings == other.warnings
79 }
80}
81
82impl Eq for Sbom {}
83
84impl Default for Sbom {
85 fn default() -> Self {
86 Self {
87 metadata: Metadata::default(),
88 components: IndexMap::new(),
89 dependencies: BTreeMap::new(),
90 reverse_deps: BTreeMap::new(),
91 warnings: Vec::new(),
92 }
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
102pub struct Metadata {
103 pub timestamp: Option<String>,
105 pub tools: Vec<String>,
107 pub authors: Vec<String>,
109}
110
111#[derive(
121 Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
122)]
123#[serde(rename_all = "lowercase")]
124pub enum DependencyKind {
125 #[default]
127 Runtime,
128 Dev,
130 Build,
132 Test,
134 Optional,
136 Provided,
138}
139
140impl fmt::Display for DependencyKind {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 match self {
143 Self::Runtime => write!(f, "runtime"),
144 Self::Dev => write!(f, "dev"),
145 Self::Build => write!(f, "build"),
146 Self::Test => write!(f, "test"),
147 Self::Optional => write!(f, "optional"),
148 Self::Provided => write!(f, "provided"),
149 }
150 }
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
173pub struct ComponentId(String);
174
175impl ComponentId {
176 pub fn new(purl: Option<&str>, properties: &[(&str, &str)]) -> Self {
181 if let Some(purl) = purl {
182 if let Some(parsed) = parse_purl(purl) {
183 return ComponentId(parsed.to_string());
184 }
185 return ComponentId(purl.to_string());
186 }
187
188 let mut hasher = Sha256::new();
190 for (k, v) in properties {
191 hasher.update(k.as_bytes());
192 hasher.update(b":");
193 hasher.update(v.as_bytes());
194 hasher.update(b"|");
195 }
196 let hash = hex::encode(hasher.finalize());
197 ComponentId(format!("h:{}", hash))
198 }
199
200 pub fn from_parts(
203 purl: Option<&str>,
204 name: &str,
205 version: Option<&str>,
206 supplier: Option<&str>,
207 ) -> Self {
208 let mut properties = vec![("name", name)];
209 if let Some(version) = version {
210 properties.push(("version", version));
211 }
212 if let Some(supplier) = supplier {
213 properties.push(("supplier", supplier));
214 }
215 Self::new(purl, &properties)
216 }
217
218 pub fn as_str(&self) -> &str {
220 &self.0
221 }
222}
223
224impl std::fmt::Display for ComponentId {
225 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226 write!(f, "{}", self.0)
227 }
228}
229
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236pub struct Component {
237 pub id: ComponentId,
239 pub name: String,
241 pub version: Option<String>,
243 pub ecosystem: Option<String>,
245 pub supplier: Option<String>,
247 pub description: Option<String>,
249 pub purl: Option<String>,
251 pub licenses: BTreeSet<String>,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub license_expression: Option<String>,
261 pub hashes: BTreeMap<String, String>,
263 pub source_ids: Vec<String>,
265}
266
267impl Component {
268 pub fn new(name: String, version: Option<String>) -> Self {
274 let id = ComponentId::from_parts(None, &name, version.as_deref(), None);
275
276 Self {
277 id,
278 name,
279 version,
280 ecosystem: None,
281 supplier: None,
282 description: None,
283 purl: None,
284 licenses: BTreeSet::new(),
285 license_expression: None,
286 hashes: BTreeMap::new(),
287 source_ids: Vec::new(),
288 }
289 }
290
291 pub fn parsed_purl(&self) -> Option<PackageUrl<'static>> {
293 self.purl.as_deref().and_then(parse_purl)
294 }
295
296 pub fn licensing(&self) -> Licensing<'_> {
298 Licensing {
299 expression: self.license_expression.as_deref(),
300 ids: &self.licenses,
301 }
302 }
303}
304
305impl Sbom {
306 pub fn normalize(&mut self) {
316 self.components.sort_keys();
318
319 for component in self.components.values_mut() {
321 component.normalize();
322 }
323
324 self.metadata.timestamp = None;
326 self.metadata.tools.clear();
327 self.metadata.authors.clear();
328
329 self.rebuild_reverse_deps();
330 }
331
332 pub fn rebuild_reverse_deps(&mut self) {
338 self.reverse_deps.clear();
339 for (parent, children) in &self.dependencies {
340 for child in children.keys() {
341 self.reverse_deps
342 .entry(child.clone())
343 .or_default()
344 .insert(parent.clone());
345 }
346 }
347 }
348
349 pub fn insert_component(&mut self, mut component: Component) -> Option<Component> {
355 if let Some(existing) = self.components.get(&component.id) {
356 component
357 .source_ids
358 .extend(existing.source_ids.iter().cloned());
359 component.source_ids.sort();
360 component.source_ids.dedup();
361 }
362 self.components.insert(component.id.clone(), component)
363 }
364
365 pub fn insert_dependency(
371 &mut self,
372 parent: ComponentId,
373 child: ComponentId,
374 kind: DependencyKind,
375 ) {
376 self.reverse_deps
377 .entry(child.clone())
378 .or_default()
379 .insert(parent.clone());
380 self.dependencies
381 .entry(parent)
382 .or_default()
383 .entry(child)
384 .and_modify(|existing| *existing = (*existing).min(kind))
385 .or_insert(kind);
386 }
387
388 pub fn roots(&self) -> Vec<ComponentId> {
393 self.components
394 .keys()
395 .filter(|id| self.reverse_deps.get(*id).is_none_or(BTreeSet::is_empty))
396 .cloned()
397 .collect()
398 }
399
400 pub fn deps(&self, id: &ComponentId) -> Vec<ComponentId> {
402 self.dependencies
403 .get(id)
404 .map(|d| d.keys().cloned().collect())
405 .unwrap_or_default()
406 }
407
408 pub fn rdeps(&self, id: &ComponentId) -> Vec<ComponentId> {
411 self.reverse_deps
412 .get(id)
413 .map(|parents| parents.iter().cloned().collect())
414 .unwrap_or_default()
415 }
416
417 pub fn transitive_deps(&self, id: &ComponentId) -> BTreeSet<ComponentId> {
421 let mut visited = BTreeSet::new();
422 let mut stack = vec![id.clone()];
423 while let Some(current) = stack.pop() {
424 if let Some(children) = self.dependencies.get(¤t) {
425 for child in children.keys() {
426 if visited.insert(child.clone()) {
427 stack.push(child.clone());
428 }
429 }
430 }
431 }
432 visited
433 }
434
435 pub fn ecosystems(&self) -> BTreeSet<String> {
437 self.components
438 .values()
439 .filter_map(|c| c.ecosystem.clone())
440 .collect()
441 }
442
443 pub fn licenses(&self) -> BTreeSet<String> {
445 self.components
446 .values()
447 .flat_map(|c| c.licenses.iter().cloned())
448 .collect()
449 }
450
451 pub fn missing_hashes(&self) -> Vec<ComponentId> {
455 self.components
456 .iter()
457 .filter(|(_, c)| c.hashes.is_empty())
458 .map(|(id, _)| id.clone())
459 .collect()
460 }
461
462 pub fn by_purl(&self, purl: &str) -> Option<&Component> {
464 let id = ComponentId::new(Some(purl), &[]);
465 self.components.get(&id)
466 }
467
468 pub fn detect_cycles(&self) -> Vec<Vec<ComponentId>> {
477 enum Frame {
478 Enter(ComponentId),
479 Exit(ComponentId),
480 }
481
482 let mut visited = BTreeSet::new();
483 let mut on_stack = BTreeSet::new();
484 let mut path = Vec::new();
485 let mut cycles = Vec::new();
486
487 let mut stack: Vec<Frame> = self
488 .dependencies
489 .keys()
490 .rev()
491 .map(|k| Frame::Enter(k.clone()))
492 .collect();
493
494 while let Some(frame) = stack.pop() {
495 match frame {
496 Frame::Enter(node) => {
497 if visited.contains(&node) {
498 continue;
499 }
500 visited.insert(node.clone());
501 on_stack.insert(node.clone());
502 path.push(node.clone());
503 stack.push(Frame::Exit(node.clone()));
504
505 if let Some(children) = self.dependencies.get(&node) {
506 for child in children.keys().rev() {
507 if !visited.contains(child) {
508 stack.push(Frame::Enter(child.clone()));
509 } else if on_stack.contains(child) {
510 if let Some(start) = path.iter().position(|n| n == child) {
511 let mut cycle: Vec<_> = path[start..].to_vec();
512 cycle.push(child.clone());
513 cycles.push(cycle);
514 }
515 }
516 }
517 }
518 }
519 Frame::Exit(node) => {
520 path.pop();
521 on_stack.remove(&node);
522 }
523 }
524 }
525
526 cycles
527 }
528}
529
530impl Component {
531 pub fn normalize(&mut self) {
536 let normalized_hashes: BTreeMap<String, String> = self
537 .hashes
538 .iter()
539 .map(|(k, v)| (k.to_lowercase(), v.to_lowercase()))
540 .collect();
541 self.hashes = normalized_hashes;
542 }
543}
544
545pub fn ecosystem_from_purl(purl: &str) -> Option<String> {
559 parse_purl(purl).map(|p| p.ty().to_string())
560}
561
562pub fn parse_purl(purl: &str) -> Option<PackageUrl<'static>> {
564 PackageUrl::from_str(purl).ok()
565}
566
567pub fn canonical_license_case(expression: &str) -> String {
583 let is_id_char = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | ':');
584 let mut canonical = String::with_capacity(expression.len());
585 for piece in expression.split_inclusive(|c: char| !is_id_char(c)) {
586 let id = piece.trim_end_matches(|c: char| !is_id_char(c));
587 canonical.push_str(spdx_spelling(id).unwrap_or(id));
588 canonical.push_str(&piece[id.len()..]);
589 }
590 canonical
591}
592
593fn spdx_spelling(id: &str) -> Option<&'static str> {
595 static SPELLINGS: OnceLock<HashMap<String, &'static str>> = OnceLock::new();
596 let spellings = SPELLINGS.get_or_init(|| {
597 let licenses = spdx::identifiers::LICENSES.iter().map(|l| l.name);
598 let exceptions = spdx::identifiers::EXCEPTIONS.iter().map(|e| e.name);
599 licenses
600 .chain(exceptions)
601 .map(|name| (name.to_ascii_lowercase(), name))
602 .collect()
603 });
604 spellings.get(&id.to_ascii_lowercase()).copied()
605}
606
607fn parse_expression(expression: &str) -> Result<spdx::Expression, spdx::ParseError> {
608 let mode = spdx::ParseMode {
609 allow_deprecated: true,
610 allow_postfix_plus_on_gpl: true,
611 ..spdx::ParseMode::STRICT
612 };
613 spdx::Expression::parse_mode(&canonical_license_case(expression), mode)
614}
615
616pub fn parse_license_expression(license: &str) -> BTreeSet<String> {
637 match parse_expression(license) {
638 Ok(expr) => {
639 let ids: BTreeSet<String> = expr
640 .requirements()
641 .map(|r| match &r.req.license {
642 spdx::LicenseItem::Spdx { id, .. } => id.name.to_string(),
643 other => other.to_string(),
644 })
645 .collect();
646 if ids.is_empty() {
647 BTreeSet::from([license.to_string()])
649 } else {
650 ids
651 }
652 }
653 Err(_) => {
654 BTreeSet::from([canonical_license_case(license)])
656 }
657 }
658}
659
660pub fn is_spdx_expression(expression: &str) -> bool {
672 parse_expression(expression).is_ok()
673}
674
675#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
678pub struct LicenseRequirement {
679 pub license: String,
681 pub or_later: bool,
683 pub exception: Option<String>,
685}
686
687impl LicenseRequirement {
688 pub fn new(license: impl Into<String>) -> Self {
690 Self {
691 license: license.into(),
692 or_later: false,
693 exception: None,
694 }
695 }
696}
697
698impl std::fmt::Display for LicenseRequirement {
699 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
700 write!(f, "{}", self.license)?;
701 if self.or_later {
702 f.write_str("+")?;
703 }
704 if let Some(exception) = &self.exception {
705 write!(f, " WITH {exception}")?;
706 }
707 Ok(())
708 }
709}
710
711fn to_requirement(req: &spdx::LicenseReq) -> LicenseRequirement {
712 let (license, or_later) = match &req.license {
713 spdx::LicenseItem::Spdx { id, or_later } => (id.name.to_string(), *or_later),
714 other => (other.to_string(), false),
715 };
716 LicenseRequirement {
717 license,
718 or_later,
719 exception: req.addition.as_ref().map(|a| a.to_string()),
720 }
721}
722
723fn copyleft_spelling(id: &str) -> String {
725 let id = canonical_license_case(id);
726 spdx::license_id(&id)
727 .filter(|l| l.is_gnu() && l.is_deprecated() && !id.ends_with('+'))
728 .and_then(|l| {
729 spdx::gnu_license_id(
730 l.name.split_once("-with-").map_or(l.name, |(base, _)| base),
731 false,
732 )
733 })
734 .map_or(id, |l| l.name.to_string())
735}
736
737fn flat_requirement(id: &str) -> LicenseRequirement {
739 if let Ok(expr) = parse_expression(id) {
740 let mut reqs = expr.requirements();
741 if let (Some(req), None) = (reqs.next(), reqs.next()) {
742 return to_requirement(&req.req);
743 }
744 }
745 LicenseRequirement::new(id)
746}
747
748#[derive(Debug, Clone, Copy, PartialEq, Eq)]
754pub struct Licensing<'a> {
755 pub expression: Option<&'a str>,
757 pub ids: &'a BTreeSet<String>,
759}
760
761impl<'a> Licensing<'a> {
762 pub fn from_ids(ids: &'a BTreeSet<String>) -> Self {
764 Self {
765 expression: None,
766 ids,
767 }
768 }
769
770 pub fn satisfiable<F>(&self, mut acceptable: F) -> bool
791 where
792 F: FnMut(&LicenseRequirement) -> bool,
793 {
794 if let Some(expression) = self.expression {
795 if let Ok(expr) = parse_expression(expression) {
796 return expr.evaluate(|req| acceptable(&to_requirement(req)));
797 }
798 }
799 self.ids.iter().all(|id| acceptable(&flat_requirement(id)))
800 }
801
802 pub fn requirements(&self) -> BTreeSet<LicenseRequirement> {
805 if let Some(expression) = self.expression {
806 if let Ok(expr) = parse_expression(expression) {
807 let reqs: BTreeSet<LicenseRequirement> = expr
808 .requirements()
809 .map(|r| to_requirement(&r.req))
810 .collect();
811 if !reqs.is_empty() {
812 return reqs;
813 }
814 }
815 }
816 self.ids.iter().map(|id| flat_requirement(id)).collect()
817 }
818
819 fn choices(&self) -> Option<Choices> {
822 if let Some(expression) = self.expression {
823 if let Ok(expr) = parse_expression(expression) {
824 return expression_choices(&expr);
825 }
826 }
827 Some(BTreeSet::from([self
828 .ids
829 .iter()
830 .map(|id| flat_requirement(id))
831 .collect()]))
832 }
833
834 fn mandatory_copyleft(&self) -> BTreeSet<String> {
836 self.requirements()
837 .into_iter()
838 .filter(|r| is_copyleft_license(&r.license))
839 .filter(|r| !self.satisfiable(|other| other.license != r.license))
840 .map(|r| copyleft_spelling(&r.license))
841 .collect()
842 }
843
844 fn copyleft_burdens(&self) -> Option<Burdens> {
847 let burdens = self
848 .choices()?
849 .into_iter()
850 .map(|choice| {
851 choice
852 .into_iter()
853 .filter(|r| is_copyleft_license(&r.license))
854 .map(|r| copyleft_spelling(&r.license))
855 .collect()
856 })
857 .collect();
858 Some(minimal_sets(burdens))
859 }
860}
861
862type Choices = BTreeSet<BTreeSet<LicenseRequirement>>;
864
865type Burdens = BTreeSet<BTreeSet<String>>;
867
868const MAX_CHOICES: usize = 64;
871
872fn minimal_sets<T: Ord + Clone>(sets: BTreeSet<BTreeSet<T>>) -> BTreeSet<BTreeSet<T>> {
874 sets.iter()
875 .filter(|set| {
876 sets.iter()
877 .all(|other| other == *set || !other.is_subset(set))
878 })
879 .cloned()
880 .collect()
881}
882
883fn expression_choices(expr: &spdx::Expression) -> Option<Choices> {
885 let mut stack: Vec<Choices> = Vec::new();
886
887 for node in expr.iter() {
888 match node {
889 spdx::expression::ExprNode::Req(req) => {
890 stack.push(BTreeSet::from([BTreeSet::from([to_requirement(&req.req)])]));
891 }
892 spdx::expression::ExprNode::Op(op) => {
893 let rhs = stack.pop()?;
894 let lhs = stack.pop()?;
895 let combined: Choices = match op {
896 spdx::expression::Operator::Or => lhs.union(&rhs).cloned().collect(),
897 spdx::expression::Operator::And => lhs
898 .iter()
899 .flat_map(|l| rhs.iter().map(|r| l.union(r).cloned().collect()))
900 .collect(),
901 };
902 if combined.len() > MAX_CHOICES {
903 return None;
904 }
905 stack.push(minimal_sets(combined));
906 }
907 }
908 }
909
910 let choices = stack.pop()?;
911 stack.is_empty().then_some(choices)
912}
913
914pub fn licensings_equivalent(a: Licensing<'_>, b: Licensing<'_>) -> bool {
937 match (a.choices(), b.choices()) {
938 (Some(x), Some(y)) => x == y,
939 _ => match (a.expression, b.expression) {
940 (Some(x), Some(y)) => license_expressions_equivalent(x, y),
941 _ => false,
942 },
943 }
944}
945
946pub fn copyleft_obligations_added(old: Licensing<'_>, new: Licensing<'_>) -> BTreeSet<String> {
976 match (old.copyleft_burdens(), new.copyleft_burdens()) {
977 (Some(offered), Some(demanded)) => {
978 if demanded
979 .iter()
980 .any(|burden| offered.iter().any(|had| burden.is_subset(had)))
981 {
982 return BTreeSet::new();
983 }
984 let unavoidable = offered
985 .into_iter()
986 .reduce(|acc, had| acc.intersection(&had).cloned().collect())
987 .unwrap_or_default();
988 demanded
989 .into_iter()
990 .flatten()
991 .filter(|license| !unavoidable.contains(license))
992 .collect()
993 }
994 _ => {
995 let already = old.mandatory_copyleft();
996 let carried = |r: &LicenseRequirement| already.contains(©left_spelling(&r.license));
997 if new.satisfiable(|r| !is_copyleft_license(&r.license) || carried(r)) {
998 return BTreeSet::new();
999 }
1000 new.requirements()
1001 .into_iter()
1002 .filter(|r| is_copyleft_license(&r.license) && !carried(r))
1003 .map(|r| copyleft_spelling(&r.license))
1004 .collect()
1005 }
1006 }
1007}
1008
1009pub fn license_expressions_equivalent(a: &str, b: &str) -> bool {
1029 match (parse_expression(a), parse_expression(b)) {
1030 (Ok(x), Ok(y)) => match (expression_choices(&x), expression_choices(&y)) {
1031 (Some(cx), Some(cy)) => cx == cy,
1032 _ => x == y,
1033 },
1034 _ => a == b,
1035 }
1036}
1037
1038pub fn canonical_algorithm_name(name: &str) -> String {
1053 match name.replace('-', "").to_uppercase().as_str() {
1054 "MD2" => "MD2",
1055 "MD4" => "MD4",
1056 "MD5" => "MD5",
1057 "MD6" => "MD6",
1058 "SHA1" => "SHA-1",
1059 "SHA224" => "SHA-224",
1060 "SHA256" => "SHA-256",
1061 "SHA384" => "SHA-384",
1062 "SHA512" => "SHA-512",
1063 "SHA3256" => "SHA3-256",
1064 "SHA3384" => "SHA3-384",
1065 "SHA3512" => "SHA3-512",
1066 "BLAKE2B256" => "BLAKE2b-256",
1067 "BLAKE2B384" => "BLAKE2b-384",
1068 "BLAKE2B512" => "BLAKE2b-512",
1069 "BLAKE3" => "BLAKE3",
1070 "ADLER32" => "ADLER-32",
1071 _ => return name.to_string(),
1072 }
1073 .to_string()
1074}
1075
1076pub fn hash_algorithm_strength(name: &str) -> Option<u8> {
1098 let canonical = canonical_algorithm_name(name);
1099 match canonical.as_str() {
1100 "ADLER-32" => Some(0),
1101 "MD2" | "MD4" | "MD5" => Some(1),
1102 "SHA-1" => Some(2),
1103 "SHA-224" => Some(3),
1104 "SHA-256" | "SHA3-256" | "BLAKE2b-256" | "BLAKE3" | "MD6" => Some(4),
1105 "SHA-384" | "SHA3-384" | "BLAKE2b-384" => Some(5),
1106 "SHA-512" | "SHA3-512" | "BLAKE2b-512" => Some(6),
1107 _ => None,
1108 }
1109}
1110
1111pub fn is_hash_algorithm_downgrade(
1136 old_hashes: &BTreeMap<String, String>,
1137 new_hashes: &BTreeMap<String, String>,
1138) -> bool {
1139 if old_hashes.is_empty() || new_hashes.is_empty() {
1140 return false;
1141 }
1142
1143 let old_max = old_hashes
1144 .keys()
1145 .filter_map(|k| hash_algorithm_strength(k))
1146 .max();
1147 let new_max = new_hashes
1148 .keys()
1149 .filter_map(|k| hash_algorithm_strength(k))
1150 .max();
1151
1152 match (old_max, new_max) {
1153 (Some(old_strength), Some(new_strength)) => new_strength < old_strength,
1154 _ => false,
1155 }
1156}
1157
1158fn checksums_by_algorithm(hashes: &BTreeMap<String, String>) -> BTreeMap<String, &str> {
1159 hashes
1160 .iter()
1161 .map(|(algo, value)| (canonical_algorithm_name(algo), value.trim()))
1162 .collect()
1163}
1164
1165pub fn changed_checksums(
1189 old_hashes: &BTreeMap<String, String>,
1190 new_hashes: &BTreeMap<String, String>,
1191) -> Vec<(String, String, String)> {
1192 let new_side = checksums_by_algorithm(new_hashes);
1193
1194 checksums_by_algorithm(old_hashes)
1195 .into_iter()
1196 .filter_map(|(algo, old_value)| {
1197 let new_value = new_side.get(algo.as_str())?;
1198 (!old_value.eq_ignore_ascii_case(new_value))
1199 .then(|| (algo, old_value.to_string(), (*new_value).to_string()))
1200 })
1201 .collect()
1202}
1203
1204pub fn is_copyleft_license(id: &str) -> bool {
1225 spdx_spelling(id.trim_end_matches('+'))
1226 .and_then(spdx::license_id)
1227 .is_some_and(|l| l.is_copyleft())
1228}
1229
1230pub fn copyleft_introduced(old: &BTreeSet<String>, new: &BTreeSet<String>) -> bool {
1251 let old: BTreeSet<String> = old.iter().map(|id| copyleft_spelling(id)).collect();
1252 new.iter()
1253 .any(|id| is_copyleft_license(id) && !old.contains(©left_spelling(id)))
1254}
1255
1256#[cfg(test)]
1257mod tests {
1258 use super::*;
1259
1260 #[test]
1261 fn test_component_id_purl() {
1262 let purl = "pkg:npm/left-pad@1.3.0";
1263 let id = ComponentId::new(Some(purl), &[]);
1264 assert_eq!(id.as_str(), purl);
1265 }
1266
1267 #[test]
1268 fn test_component_id_hash_stability() {
1269 let id = ComponentId::new(None, &[("name", "foo"), ("version", "1.0")]);
1272 assert_eq!(
1273 id.as_str(),
1274 "h:eed73da1effa1cc3ee0960cb8ab57f84e0994c81c8835e9fb5abd82f47f91aa6"
1275 );
1276 }
1277
1278 #[test]
1279 fn test_normalization() {
1280 let mut comp = Component::new("test".to_string(), Some("1.0".to_string()));
1281 comp.licenses.insert("MIT".to_string());
1282 comp.licenses.insert("Apache-2.0".to_string());
1283 comp.hashes.insert("SHA-256".to_string(), "ABC".to_string());
1284
1285 comp.normalize();
1286
1287 assert_eq!(
1288 comp.licenses,
1289 BTreeSet::from(["Apache-2.0".to_string(), "MIT".to_string()])
1290 );
1291 assert_eq!(comp.hashes.get("sha-256").unwrap(), "abc");
1292 }
1293
1294 fn licensing<'a>(expression: &'a str, ids: &'a BTreeSet<String>) -> Licensing<'a> {
1295 Licensing {
1296 expression: Some(expression),
1297 ids,
1298 }
1299 }
1300
1301 #[test]
1302 fn test_licensing_satisfiable_operators() {
1303 let ids: BTreeSet<String> = ["Apache-2.0".into(), "MIT".into()].into();
1304 let only_mit = |r: &LicenseRequirement| r.license == "MIT";
1305
1306 assert!(licensing("MIT OR Apache-2.0", &ids).satisfiable(only_mit));
1307 assert!(!licensing("MIT AND Apache-2.0", &ids).satisfiable(only_mit));
1308 assert!(licensing("mit OR Apache-2.0", &ids).satisfiable(only_mit));
1309 assert!(licensing("MIT OR GPL-2.0", &ids).satisfiable(only_mit));
1310
1311 let nested: BTreeSet<String> =
1312 ["Apache-2.0".into(), "BSD-3-Clause".into(), "MIT".into()].into();
1313 let allowed: BTreeSet<String> = ["BSD-3-Clause".into(), "MIT".into()].into();
1314 assert!(licensing("(MIT OR Apache-2.0) AND BSD-3-Clause", &nested)
1315 .satisfiable(|r| allowed.contains(&r.license)));
1316 assert!(!licensing("(MIT AND Apache-2.0) AND BSD-3-Clause", &nested)
1317 .satisfiable(|r| allowed.contains(&r.license)));
1318 }
1319
1320 #[test]
1321 fn test_licensing_without_expression_is_a_conjunction() {
1322 let ids: BTreeSet<String> = ["Apache-2.0".into(), "MIT".into()].into();
1323 assert!(!Licensing::from_ids(&ids).satisfiable(|r| r.license == "MIT"));
1324 assert!(Licensing::from_ids(&ids).satisfiable(|_| true));
1325 }
1326
1327 #[test]
1328 fn test_licensing_falls_back_on_free_text() {
1329 let ids: BTreeSet<String> = ["Custom License".into()].into();
1330 let free_text = licensing("Custom License", &ids);
1331 assert!(free_text.satisfiable(|r| r.license == "Custom License"));
1332 assert!(!free_text.satisfiable(|_| false));
1333 }
1334
1335 #[test]
1336 fn test_licensing_reads_a_flat_id_as_an_expression_does() {
1337 for (flat, expression) in [
1338 ("GPL-2.0+", "GPL-2.0-or-later"),
1339 ("lgpl-2.1+", "LGPL-2.1-or-later"),
1340 ] {
1341 let ids = BTreeSet::from([flat.to_string()]);
1342 let read = Licensing::from_ids(&ids);
1343 let expected = licensing(expression, &ids);
1344 assert_eq!(read.requirements(), expected.requirements(), "{flat}");
1345 assert!(licensings_equivalent(read, expected), "{flat}");
1346 assert!(read.satisfiable(|r| r.license == expression), "{flat}");
1347 }
1348 let compound = BTreeSet::from(["MIT AND GPL-3.0-only".to_string()]);
1350 assert!(!Licensing::from_ids(&compound).satisfiable(|r| r.license == "MIT"));
1351 }
1352
1353 #[test]
1354 fn test_licensing_requirements_keep_exceptions() {
1355 let ids: BTreeSet<String> = ["GPL-2.0-only".into()].into();
1356 let reqs = licensing("GPL-2.0-only WITH Classpath-exception-2.0", &ids).requirements();
1357
1358 assert_eq!(reqs.len(), 1);
1359 let req = reqs.iter().next().unwrap();
1360 assert_eq!(req.license, "GPL-2.0-only");
1361 assert_eq!(req.exception.as_deref(), Some("Classpath-exception-2.0"));
1362 assert_eq!(req.to_string(), "GPL-2.0-only WITH Classpath-exception-2.0");
1363 assert_eq!(
1364 licensing("gpl-2.0-only WITH classpath-exception-2.0", &ids).requirements(),
1365 reqs
1366 );
1367 }
1368
1369 #[test]
1370 fn test_licensing_requirements_keep_or_later() {
1371 let ids: BTreeSet<String> = ["Apache-2.0".into()].into();
1372 let req = licensing("Apache-2.0+", &ids)
1373 .requirements()
1374 .into_iter()
1375 .next()
1376 .unwrap();
1377
1378 assert_eq!(req.license, "Apache-2.0");
1379 assert!(req.or_later);
1380 assert_eq!(req.to_string(), "Apache-2.0+");
1381 }
1382
1383 #[test]
1384 fn test_copyleft_obligations_added_respects_choice() {
1385 let mit: BTreeSet<String> = ["MIT".into()].into();
1386 let both: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1387 let old = licensing("MIT", &mit);
1388
1389 assert!(
1390 copyleft_obligations_added(old, licensing("MIT OR GPL-3.0-only", &both)).is_empty()
1391 );
1392 assert_eq!(
1393 copyleft_obligations_added(old, licensing("MIT AND GPL-3.0-only", &both)),
1394 BTreeSet::from(["GPL-3.0-only".to_string()])
1395 );
1396 }
1397
1398 #[test]
1399 fn test_copyleft_obligations_added_carried_over() {
1400 let gpl: BTreeSet<String> = ["GPL-3.0-only".into()].into();
1401 let both: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1402
1403 assert!(copyleft_obligations_added(
1404 licensing("GPL-3.0-only", &gpl),
1405 licensing("GPL-3.0-only AND MIT", &both)
1406 )
1407 .is_empty());
1408
1409 let agpl: BTreeSet<String> = ["AGPL-3.0-only".into()].into();
1411 assert_eq!(
1412 copyleft_obligations_added(
1413 licensing("GPL-3.0-only", &gpl),
1414 licensing("AGPL-3.0-only", &agpl)
1415 ),
1416 BTreeSet::from(["AGPL-3.0-only".to_string()])
1417 );
1418 }
1419
1420 #[test]
1421 fn test_copyleft_obligations_added_losing_the_permissive_choice() {
1422 let both: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1423 let gpl: BTreeSet<String> = ["GPL-3.0-only".into()].into();
1424
1425 assert_eq!(
1426 copyleft_obligations_added(
1427 licensing("MIT OR GPL-3.0-only", &both),
1428 licensing("GPL-3.0-only", &gpl)
1429 ),
1430 BTreeSet::from(["GPL-3.0-only".to_string()])
1431 );
1432 }
1433
1434 fn copyleft_added(old: &str, new: &str) -> BTreeSet<String> {
1435 let old_ids = parse_license_expression(old);
1436 let new_ids = parse_license_expression(new);
1437 copyleft_obligations_added(licensing(old, &old_ids), licensing(new, &new_ids))
1438 }
1439
1440 fn licenses(names: &[&str]) -> BTreeSet<String> {
1441 names.iter().map(|n| n.to_string()).collect()
1442 }
1443
1444 #[test]
1445 fn test_copyleft_obligations_added_ignores_a_choice_between_copyleft_licenses() {
1446 for (old, new) in [
1447 (
1448 "GPL-2.0-only OR GPL-3.0-only",
1449 "GPL-2.0-only OR GPL-3.0-only OR LGPL-3.0-only",
1450 ),
1451 (
1452 "MIT AND (GPL-2.0-only OR GPL-3.0-only)",
1453 "Apache-2.0 AND (GPL-2.0-only OR GPL-3.0-only)",
1454 ),
1455 (
1456 "MPL-2.0 OR GPL-2.0-only OR LGPL-2.1-only",
1457 "MPL-2.0 OR GPL-2.0-only OR LGPL-2.1-only",
1458 ),
1459 ] {
1460 assert!(
1461 copyleft_added(old, new).is_empty(),
1462 "{old} -> {new} forces no copyleft the consumer could not already have taken"
1463 );
1464 }
1465 }
1466
1467 #[test]
1468 fn test_copyleft_obligations_added_fires_on_every_tightening() {
1469 for (old, new, introduced) in [
1470 (
1471 "GPL-2.0-only OR GPL-3.0-only",
1472 "GPL-2.0-only AND GPL-3.0-only",
1473 &["GPL-2.0-only", "GPL-3.0-only"][..],
1474 ),
1475 ("MIT OR GPL-3.0-only", "GPL-3.0-only", &["GPL-3.0-only"]),
1476 ("GPL-3.0-only", "AGPL-3.0-only", &["AGPL-3.0-only"]),
1477 ("MIT", "MIT AND GPL-3.0-only", &["GPL-3.0-only"]),
1478 ("MIT", "MIT AND GPL-2.0", &["GPL-2.0-only"]),
1479 (
1480 "MIT",
1481 "GPL-2.0+ WITH Classpath-exception-2.0",
1482 &["GPL-2.0-or-later"],
1483 ),
1484 (
1485 "GPL-2.0-only OR GPL-3.0-only",
1486 "AGPL-3.0-only",
1487 &["AGPL-3.0-only"],
1488 ),
1489 ] {
1490 assert_eq!(
1491 copyleft_added(old, new),
1492 licenses(introduced),
1493 "{old} -> {new}"
1494 );
1495 }
1496 }
1497
1498 #[test]
1499 fn test_copyleft_obligations_added_spans_the_minimal_choices_less_what_old_forced() {
1500 for (old, new, introduced) in [
1501 (
1502 "MIT",
1503 "GPL-3.0-only AND (MPL-2.0 OR ISC)",
1504 &["GPL-3.0-only"][..],
1505 ),
1506 (
1507 "GPL-2.0-only",
1508 "GPL-2.0-only AND GPL-3.0-only",
1509 &["GPL-3.0-only"],
1510 ),
1511 (
1512 "MIT",
1513 "GPL-2.0-only OR AGPL-3.0-only",
1514 &["AGPL-3.0-only", "GPL-2.0-only"],
1515 ),
1516 (
1517 "MIT",
1518 "(GPL-3.0-only AND MPL-2.0) OR (AGPL-3.0-only AND EPL-2.0)",
1519 &["AGPL-3.0-only", "GPL-3.0-only", "MPL-2.0"],
1520 ),
1521 ("MIT", "(mit OR gpl-3.0-only) AND mpl-2.0", &["MPL-2.0"]),
1522 ("GPL-2.0+", "gpl-2.0+", &[]),
1523 ("GPL-3.0+", "GPL-3.0-or-later", &[]),
1524 ("GPL-2.0-only AND MIT", "MIT AND GPL-2.0", &[]),
1525 (
1526 "GPL-2.0-only WITH Classpath-exception-2.0",
1527 "GPL-2.0 WITH Classpath-exception-2.0",
1528 &[],
1529 ),
1530 ] {
1531 assert_eq!(
1532 copyleft_added(old, new),
1533 licenses(introduced),
1534 "{old} -> {new}"
1535 );
1536 }
1537 }
1538
1539 #[test]
1540 fn test_copyleft_obligations_added_falls_back_past_max_choices() {
1541 let wide = "(MIT OR Apache-2.0) AND (BSD-2-Clause OR BSD-3-Clause) \
1542 AND (ISC OR Zlib) AND (MPL-2.0 OR EPL-2.0) \
1543 AND (GPL-2.0-only OR GPL-3.0-only) AND (LGPL-2.1-only OR LGPL-3.0-only) \
1544 AND (CC0-1.0 OR Unlicense)";
1545
1546 assert_eq!(
1547 copyleft_added("MIT", wide),
1548 licenses(&[
1549 "GPL-2.0-only",
1550 "GPL-3.0-only",
1551 "LGPL-2.1-only",
1552 "LGPL-3.0-only",
1553 "MPL-2.0",
1554 ])
1555 );
1556 }
1557
1558 #[test]
1559 fn test_copyleft_obligations_added_matches_flat_sets() {
1560 let old: BTreeSet<String> = ["MIT".into()].into();
1561 let new: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1562
1563 assert_eq!(
1564 copyleft_obligations_added(Licensing::from_ids(&old), Licensing::from_ids(&new)),
1565 BTreeSet::from(["GPL-3.0-only".to_string()])
1566 );
1567 assert!(copyleft_introduced(&old, &new));
1568
1569 assert!(
1570 copyleft_obligations_added(Licensing::from_ids(&new), Licensing::from_ids(&new))
1571 .is_empty()
1572 );
1573 assert!(!copyleft_introduced(&new, &new));
1574
1575 let respelled: BTreeSet<String> = ["gpl-3.0-only".into(), "MIT".into()].into();
1576 assert!(copyleft_obligations_added(
1577 Licensing::from_ids(&new),
1578 Licensing::from_ids(&respelled)
1579 )
1580 .is_empty());
1581 assert!(!copyleft_introduced(&new, &respelled));
1582
1583 let gnu_plus: BTreeSet<String> = ["GPL-2.0+".into()].into();
1584 let only: BTreeSet<String> = ["GPL-2.0-only".into()].into();
1585 assert_eq!(
1586 copyleft_obligations_added(Licensing::from_ids(&gnu_plus), Licensing::from_ids(&only)),
1587 BTreeSet::from(["GPL-2.0-only".to_string()])
1588 );
1589 assert!(copyleft_introduced(&gnu_plus, &only));
1590 }
1591
1592 #[test]
1593 fn test_license_expressions_equivalent() {
1594 assert!(license_expressions_equivalent(
1595 "MIT OR Apache-2.0",
1596 "( MIT OR (Apache-2.0) )"
1597 ));
1598 assert!(!license_expressions_equivalent(
1599 "MIT OR Apache-2.0",
1600 "MIT AND Apache-2.0"
1601 ));
1602 assert!(!license_expressions_equivalent(
1603 "GPL-2.0-only",
1604 "GPL-2.0-only WITH Classpath-exception-2.0"
1605 ));
1606 assert!(license_expressions_equivalent("Custom Text", "Custom Text"));
1607 assert!(!license_expressions_equivalent("Custom Text", "Other Text"));
1608 }
1609
1610 #[test]
1611 fn test_license_expressions_equivalent_falls_back_past_max_choices() {
1612 let wide = "(MIT OR Apache-2.0) AND (BSD-2-Clause OR BSD-3-Clause) \
1613 AND (ISC OR Zlib) AND (MPL-2.0 OR EPL-2.0) \
1614 AND (GPL-2.0-only OR GPL-3.0-only) AND (LGPL-2.1-only OR LGPL-3.0-only) \
1615 AND (CC0-1.0 OR Unlicense)";
1616
1617 assert!(license_expressions_equivalent(wide, wide));
1618 assert!(license_expressions_equivalent(
1619 wide,
1620 &wide.replace("(MIT OR Apache-2.0)", "((MIT OR Apache-2.0))")
1621 ));
1622 assert!(!license_expressions_equivalent(
1623 wide,
1624 &wide.replace("MIT OR Apache-2.0", "Apache-2.0 OR MIT")
1625 ));
1626
1627 let ids: BTreeSet<String> = wide
1628 .split_whitespace()
1629 .map(|word| word.trim_matches(['(', ')']).to_string())
1630 .filter(|word| word != "AND" && word != "OR")
1631 .collect();
1632 assert!(!licensings_equivalent(
1633 Licensing {
1634 expression: Some(wide),
1635 ids: &ids,
1636 },
1637 Licensing::from_ids(&ids)
1638 ));
1639 }
1640
1641 #[test]
1642 fn test_license_expressions_equivalent_ignores_operand_order() {
1643 assert!(license_expressions_equivalent(
1644 "MIT OR Apache-2.0",
1645 "Apache-2.0 OR MIT"
1646 ));
1647 assert!(license_expressions_equivalent(
1648 "(MIT OR Apache-2.0) AND BSD-3-Clause",
1649 "(BSD-3-Clause AND Apache-2.0) OR (BSD-3-Clause AND MIT)"
1650 ));
1651 assert!(license_expressions_equivalent(
1652 "MIT",
1653 "MIT OR (MIT AND Apache-2.0)"
1654 ));
1655 assert!(license_expressions_equivalent(
1656 "mit or apache-2.0",
1657 "apache-2.0 or mit"
1658 ));
1659 assert!(license_expressions_equivalent(
1660 "MIT AND GPL-2.0",
1661 "GPL-2.0 AND MIT"
1662 ));
1663 assert!(!license_expressions_equivalent(
1664 "MIT OR Apache-2.0",
1665 "MIT OR BSD-3-Clause"
1666 ));
1667 }
1668
1669 #[test]
1670 fn test_licensings_equivalent_reads_a_bare_set_as_a_conjunction() {
1671 let ids: BTreeSet<String> = ["GPL-3.0-only".to_string(), "MIT".to_string()].into();
1672 let flat = Licensing::from_ids(&ids);
1673
1674 assert!(licensings_equivalent(
1675 Licensing {
1676 expression: Some("MIT AND GPL-3.0-only"),
1677 ids: &ids,
1678 },
1679 flat
1680 ));
1681 assert!(!licensings_equivalent(
1682 Licensing {
1683 expression: Some("MIT OR GPL-3.0-only"),
1684 ids: &ids,
1685 },
1686 flat
1687 ));
1688 assert!(licensings_equivalent(flat, flat));
1689 }
1690
1691 #[test]
1692 fn test_licensings_equivalent_keeps_decorated_requirements() {
1693 let gpl: BTreeSet<String> = ["GPL-2.0-only".to_string()].into();
1694 assert!(!licensings_equivalent(
1695 Licensing {
1696 expression: Some("GPL-2.0-only WITH Classpath-exception-2.0"),
1697 ids: &gpl,
1698 },
1699 Licensing::from_ids(&gpl)
1700 ));
1701 let apache: BTreeSet<String> = ["Apache-2.0".to_string()].into();
1702 assert!(!licensings_equivalent(
1703 Licensing {
1704 expression: Some("Apache-2.0+"),
1705 ids: &apache,
1706 },
1707 Licensing::from_ids(&apache)
1708 ));
1709 }
1710
1711 #[test]
1712 fn test_licensings_equivalent_falls_back_to_the_identifier_set() {
1713 let ids: BTreeSet<String> = ["Custom Text".to_string()].into();
1714 assert!(licensings_equivalent(
1715 Licensing {
1716 expression: Some("Custom Text"),
1717 ids: &ids,
1718 },
1719 Licensing::from_ids(&ids)
1720 ));
1721 }
1722
1723 #[test]
1724 fn test_component_licensing_defaults_to_ids() {
1725 let mut comp = Component::new("demo".into(), None);
1726 comp.licenses.insert("MIT".into());
1727
1728 assert_eq!(comp.licensing().expression, None);
1729 assert_eq!(
1730 comp.licensing().requirements(),
1731 BTreeSet::from([LicenseRequirement::new("MIT")])
1732 );
1733 }
1734
1735 #[test]
1736 fn test_parse_license_expression() {
1737 for (expr, expected) in [
1738 ("MIT OR Apache-2.0", &["Apache-2.0", "MIT"][..]),
1739 ("MIT", &["MIT"]),
1740 ("MIT AND Apache-2.0", &["Apache-2.0", "MIT"]),
1741 ("mit OR apache-2.0", &["Apache-2.0", "MIT"]),
1742 ("MIT AND GPL-2.0", &["GPL-2.0", "MIT"]),
1743 ("GPL-3.0+", &["GPL-3.0-or-later"]),
1744 (
1745 "gpl-2.0+ WITH classpath-exception-2.0",
1746 &["GPL-2.0-or-later"],
1747 ),
1748 ("Custom License", &["Custom License"]),
1750 ("LicenseRef-proprietary", &["LicenseRef-proprietary"]),
1751 (
1753 "LicenseRef-proprietary AND Apache-2.0",
1754 &["Apache-2.0", "LicenseRef-proprietary"],
1755 ),
1756 ("LicenseRef-custom OR MIT", &["LicenseRef-custom", "MIT"]),
1757 (
1758 "LicenseRef-a AND LicenseRef-b",
1759 &["LicenseRef-a", "LicenseRef-b"],
1760 ),
1761 (
1762 "(MIT OR LicenseRef-custom) AND Apache-2.0",
1763 &["Apache-2.0", "LicenseRef-custom", "MIT"],
1764 ),
1765 ] {
1766 let expected: BTreeSet<String> = expected.iter().map(|s| s.to_string()).collect();
1767 assert_eq!(parse_license_expression(expr), expected, "{expr}");
1768 }
1769 }
1770
1771 #[test]
1772 fn test_parse_license_expression_documentref() {
1773 let ids = parse_license_expression("DocumentRef-ext:LicenseRef-custom");
1775 assert_eq!(
1776 ids,
1777 BTreeSet::from(["DocumentRef-ext:LicenseRef-custom".to_string()])
1778 );
1779 }
1780
1781 #[test]
1782 fn test_query_api() {
1783 let mut sbom = Sbom::default();
1784 let c1 = Component::new("a".into(), Some("1".into()));
1785 let c2 = Component::new("b".into(), Some("1".into()));
1786 let c3 = Component::new("c".into(), Some("1".into()));
1787
1788 let id1 = c1.id.clone();
1789 let id2 = c2.id.clone();
1790 let id3 = c3.id.clone();
1791
1792 sbom.components.insert(id1.clone(), c1);
1793 sbom.components.insert(id2.clone(), c2);
1794 sbom.components.insert(id3.clone(), c3);
1795
1796 sbom.insert_dependency(id1.clone(), id2.clone(), DependencyKind::Runtime);
1798 sbom.insert_dependency(id2.clone(), id3.clone(), DependencyKind::Runtime);
1799
1800 assert_eq!(sbom.roots(), vec![id1.clone()]);
1801 assert_eq!(sbom.deps(&id1), vec![id2.clone()]);
1802 assert_eq!(sbom.rdeps(&id2), vec![id1.clone()]);
1803
1804 let transitive = sbom.transitive_deps(&id1);
1805 assert!(transitive.contains(&id2));
1806 assert!(transitive.contains(&id3));
1807 assert_eq!(transitive.len(), 2);
1808
1809 assert_eq!(sbom.missing_hashes().len(), 3);
1810
1811 let json = serde_json::to_string(&sbom).unwrap();
1812 let sbom: Sbom = serde_json::from_str(&json).unwrap();
1813 assert_eq!(sbom.roots(), vec![id1.clone()]);
1814 assert_eq!(sbom.rdeps(&id2), vec![id1.clone()]);
1815 }
1816
1817 #[test]
1818 fn test_ecosystems_query() {
1819 let mut sbom = Sbom::default();
1820
1821 let mut c1 = Component::new("lodash".into(), Some("1.0".into()));
1822 c1.ecosystem = Some("npm".into());
1823 let mut c2 = Component::new("serde".into(), Some("1.0".into()));
1824 c2.ecosystem = Some("cargo".into());
1825 let mut c3 = Component::new("other-npm".into(), Some("1.0".into()));
1826 c3.ecosystem = Some("npm".into());
1827 let c4 = Component::new("no-ecosystem".into(), Some("1.0".into()));
1828
1829 sbom.components.insert(c1.id.clone(), c1);
1830 sbom.components.insert(c2.id.clone(), c2);
1831 sbom.components.insert(c3.id.clone(), c3);
1832 sbom.components.insert(c4.id.clone(), c4);
1833
1834 let ecosystems = sbom.ecosystems();
1835 assert_eq!(ecosystems.len(), 2);
1836 assert!(ecosystems.contains("npm"));
1837 assert!(ecosystems.contains("cargo"));
1838 }
1839
1840 #[test]
1841 fn test_licenses_query() {
1842 let mut sbom = Sbom::default();
1843
1844 let mut c1 = Component::new("a".into(), Some("1.0".into()));
1845 c1.licenses.insert("MIT".into());
1846 c1.licenses.insert("Apache-2.0".into());
1847 let mut c2 = Component::new("b".into(), Some("1.0".into()));
1848 c2.licenses.insert("MIT".into());
1849 c2.licenses.insert("GPL-3.0-only".into());
1850 let c3 = Component::new("c".into(), Some("1.0".into()));
1851
1852 sbom.components.insert(c1.id.clone(), c1);
1853 sbom.components.insert(c2.id.clone(), c2);
1854 sbom.components.insert(c3.id.clone(), c3);
1855
1856 let licenses = sbom.licenses();
1857 assert_eq!(licenses.len(), 3);
1858 assert!(licenses.contains("MIT"));
1859 assert!(licenses.contains("Apache-2.0"));
1860 assert!(licenses.contains("GPL-3.0-only"));
1861 }
1862
1863 #[test]
1864 fn test_by_purl() {
1865 let mut sbom = Sbom::default();
1866
1867 let mut c1 = Component::new("lodash".into(), Some("4.17.21".into()));
1868 c1.purl = Some("pkg:npm/lodash@4.17.21".into());
1869 c1.id = ComponentId::new(c1.purl.as_deref(), &[]);
1870 let c2 = Component::new("no-purl".into(), Some("1.0".into()));
1871
1872 sbom.components.insert(c1.id.clone(), c1);
1873 sbom.components.insert(c2.id.clone(), c2);
1874
1875 let found = sbom.by_purl("pkg:npm/lodash@4.17.21");
1876 assert!(found.is_some());
1877 assert_eq!(found.unwrap().name, "lodash");
1878
1879 assert!(sbom.by_purl("pkg:npm/nonexistent@1.0").is_none());
1880 }
1881
1882 #[test]
1883 fn test_component_id_unparseable_purl() {
1884 let id = ComponentId::new(Some("not-a-valid-purl-but-still-a-string"), &[]);
1886 assert_eq!(id.as_str(), "not-a-valid-purl-but-still-a-string");
1887 }
1888
1889 #[test]
1890 fn test_component_id_display() {
1891 let id = ComponentId::new(Some("pkg:npm/foo@1.0"), &[]);
1892 assert_eq!(format!("{}", id), "pkg:npm/foo@1.0");
1893 }
1894
1895 #[test]
1896 fn test_sbom_normalize_clears_metadata() {
1897 let mut sbom = Sbom::default();
1898 sbom.metadata.timestamp = Some("2024-01-01T00:00:00Z".into());
1899 sbom.metadata.tools.push("syft".into());
1900 sbom.metadata.authors.push("alice".into());
1901
1902 let c = Component::new("a".into(), Some("1".into()));
1903 sbom.components.insert(c.id.clone(), c);
1904
1905 sbom.normalize();
1906
1907 assert!(sbom.metadata.timestamp.is_none());
1908 assert!(sbom.metadata.tools.is_empty());
1909 assert!(sbom.metadata.authors.is_empty());
1910 }
1911
1912 #[test]
1913 fn test_missing_hashes_mixed() {
1914 let mut sbom = Sbom::default();
1915
1916 let c1 = Component::new("no-hash".into(), Some("1.0".into()));
1917 let mut c2 = Component::new("has-hash".into(), Some("1.0".into()));
1918 c2.hashes.insert("sha256".into(), "abc".into());
1919
1920 sbom.components.insert(c1.id.clone(), c1);
1921 sbom.components.insert(c2.id.clone(), c2);
1922
1923 let missing = sbom.missing_hashes();
1924 assert_eq!(missing.len(), 1);
1925 }
1926
1927 #[test]
1928 fn test_ecosystem_from_purl() {
1929 use super::ecosystem_from_purl;
1930
1931 assert_eq!(
1932 ecosystem_from_purl("pkg:npm/lodash@4.17.21"),
1933 Some("npm".to_string())
1934 );
1935 assert_eq!(
1936 ecosystem_from_purl("pkg:cargo/serde@1.0.0"),
1937 Some("cargo".to_string())
1938 );
1939 assert_eq!(
1940 ecosystem_from_purl("pkg:pypi/requests@2.28.0"),
1941 Some("pypi".to_string())
1942 );
1943 assert_eq!(
1944 ecosystem_from_purl("pkg:maven/org.apache/commons@1.0"),
1945 Some("maven".to_string())
1946 );
1947 assert_eq!(ecosystem_from_purl("invalid-purl"), None);
1948 assert_eq!(ecosystem_from_purl(""), None);
1949 }
1950
1951 #[test]
1952 fn test_parsed_purl() {
1953 for (purl, coordinates, canonical) in [
1954 (None, None, None),
1955 (Some("not-a-purl"), None, None),
1956 (
1957 Some("pkg:cargo/serde@1.0.0"),
1958 Some(("cargo", None, "serde", Some("1.0.0"))),
1959 Some("pkg:cargo/serde@1.0.0"),
1960 ),
1961 (
1962 Some("pkg:npm/@angular/core@17.0.0"),
1963 Some(("npm", Some("@angular"), "core", Some("17.0.0"))),
1964 Some("pkg:npm/%40angular/core@17.0.0"),
1965 ),
1966 (
1967 Some("pkg:maven/org.apache/commons@1.0?type=jar"),
1968 Some(("maven", Some("org.apache"), "commons", Some("1.0"))),
1969 Some("pkg:maven/org.apache/commons@1.0?type=jar"),
1970 ),
1971 ] {
1972 let mut component = Component::new("x".into(), None);
1973 component.purl = purl.map(str::to_string);
1974 let parsed = component.parsed_purl();
1975 assert_eq!(
1976 parsed
1977 .as_ref()
1978 .map(|p| (p.ty(), p.namespace(), p.name(), p.version())),
1979 coordinates
1980 );
1981 assert_eq!(parsed.map(|p| p.to_string()).as_deref(), canonical);
1982 }
1983 }
1984
1985 #[test]
1986 fn test_canonical_algorithm_name() {
1987 assert_eq!(canonical_algorithm_name("SHA256"), "SHA-256");
1989 assert_eq!(canonical_algorithm_name("SHA1"), "SHA-1");
1990 assert_eq!(canonical_algorithm_name("SHA384"), "SHA-384");
1991 assert_eq!(canonical_algorithm_name("SHA512"), "SHA-512");
1992 assert_eq!(canonical_algorithm_name("SHA224"), "SHA-224");
1993
1994 assert_eq!(canonical_algorithm_name("SHA-256"), "SHA-256");
1996 assert_eq!(canonical_algorithm_name("SHA-1"), "SHA-1");
1997 assert_eq!(canonical_algorithm_name("SHA-384"), "SHA-384");
1998
1999 assert_eq!(canonical_algorithm_name("sha256"), "SHA-256");
2001 assert_eq!(canonical_algorithm_name("sha-256"), "SHA-256");
2002
2003 assert_eq!(canonical_algorithm_name("SHA3-256"), "SHA3-256");
2005 assert_eq!(canonical_algorithm_name("SHA3256"), "SHA3-256");
2006
2007 assert_eq!(canonical_algorithm_name("MD5"), "MD5");
2009 assert_eq!(canonical_algorithm_name("md5"), "MD5");
2010
2011 assert_eq!(canonical_algorithm_name("BLAKE2b-256"), "BLAKE2b-256");
2013 assert_eq!(canonical_algorithm_name("BLAKE2B256"), "BLAKE2b-256");
2014 assert_eq!(canonical_algorithm_name("BLAKE3"), "BLAKE3");
2015
2016 assert_eq!(canonical_algorithm_name("ADLER32"), "ADLER-32");
2018 assert_eq!(canonical_algorithm_name("ADLER-32"), "ADLER-32");
2019
2020 assert_eq!(canonical_algorithm_name("TIGER"), "TIGER");
2022 }
2023
2024 #[test]
2025 fn test_hash_algorithm_strength_ordering() {
2026 let md5 = hash_algorithm_strength("MD5").unwrap();
2028 let sha1 = hash_algorithm_strength("SHA-1").unwrap();
2029 let sha224 = hash_algorithm_strength("SHA-224").unwrap();
2030 let sha256 = hash_algorithm_strength("SHA-256").unwrap();
2031 let sha384 = hash_algorithm_strength("SHA-384").unwrap();
2032 let sha512 = hash_algorithm_strength("SHA-512").unwrap();
2033
2034 assert!(md5 < sha1);
2035 assert!(sha1 < sha224);
2036 assert!(sha224 < sha256);
2037 assert!(sha256 < sha384);
2038 assert!(sha384 < sha512);
2039 }
2040
2041 #[test]
2042 fn test_hash_algorithm_strength_variants() {
2043 assert_eq!(
2045 hash_algorithm_strength("sha256"),
2046 hash_algorithm_strength("SHA-256")
2047 );
2048 assert_eq!(
2049 hash_algorithm_strength("sha-1"),
2050 hash_algorithm_strength("SHA1")
2051 );
2052
2053 assert_eq!(
2055 hash_algorithm_strength("SHA3-256"),
2056 hash_algorithm_strength("SHA-256")
2057 );
2058 assert_eq!(
2059 hash_algorithm_strength("SHA3-512"),
2060 hash_algorithm_strength("SHA-512")
2061 );
2062
2063 assert_eq!(
2065 hash_algorithm_strength("BLAKE2b-256"),
2066 hash_algorithm_strength("SHA-256")
2067 );
2068 assert_eq!(
2069 hash_algorithm_strength("BLAKE3"),
2070 hash_algorithm_strength("SHA-256")
2071 );
2072
2073 assert_eq!(hash_algorithm_strength("TIGER"), None);
2075 assert_eq!(hash_algorithm_strength("UNKNOWN"), None);
2076 }
2077
2078 #[test]
2079 fn test_hash_algorithm_strength_adler() {
2080 let adler = hash_algorithm_strength("ADLER-32").unwrap();
2081 let md5 = hash_algorithm_strength("MD5").unwrap();
2082 assert!(adler < md5);
2083 }
2084
2085 #[test]
2086 fn test_is_hash_algorithm_downgrade() {
2087 fn hashes(algs: &[&str]) -> BTreeMap<String, String> {
2088 algs.iter()
2089 .map(|a| (a.to_string(), "abc".to_string()))
2090 .collect()
2091 }
2092 for (old, new, expected) in [
2093 (&["sha-256"][..], &["md5"][..], true),
2094 (&["sha-1"], &["sha-256"], false),
2095 (&["sha-256"], &["sha-256"], false),
2096 (&[], &["md5"], false),
2097 (&["sha-256"], &[], false),
2098 (&["sha-256", "md5"], &["md5"], true),
2100 (&["sha-256", "md5"], &["sha-256", "sha-1"], false),
2102 (&["TIGER"], &["WHIRLPOOL"], false),
2104 ] {
2105 assert_eq!(
2106 is_hash_algorithm_downgrade(&hashes(old), &hashes(new)),
2107 expected,
2108 "{old:?} -> {new:?}"
2109 );
2110 }
2111 }
2112
2113 #[test]
2114 fn test_detect_cycles_none() {
2115 let mut sbom = Sbom::default();
2116 let c1 = Component::new("a".into(), Some("1".into()));
2117 let c2 = Component::new("b".into(), Some("1".into()));
2118 let c3 = Component::new("c".into(), Some("1".into()));
2119
2120 let id1 = c1.id.clone();
2121 let id2 = c2.id.clone();
2122 let id3 = c3.id.clone();
2123
2124 sbom.components.insert(id1.clone(), c1);
2125 sbom.components.insert(id2.clone(), c2);
2126 sbom.components.insert(id3.clone(), c3);
2127
2128 sbom.dependencies
2130 .entry(id1.clone())
2131 .or_default()
2132 .insert(id2.clone(), DependencyKind::Runtime);
2133 sbom.dependencies
2134 .entry(id2.clone())
2135 .or_default()
2136 .insert(id3.clone(), DependencyKind::Runtime);
2137
2138 assert!(sbom.detect_cycles().is_empty());
2139 }
2140
2141 #[test]
2142 fn test_detect_cycles_simple() {
2143 let mut sbom = Sbom::default();
2144 let c1 = Component::new("a".into(), Some("1".into()));
2145 let c2 = Component::new("b".into(), Some("1".into()));
2146
2147 let id1 = c1.id.clone();
2148 let id2 = c2.id.clone();
2149
2150 sbom.components.insert(id1.clone(), c1);
2151 sbom.components.insert(id2.clone(), c2);
2152
2153 sbom.dependencies
2155 .entry(id1.clone())
2156 .or_default()
2157 .insert(id2.clone(), DependencyKind::Runtime);
2158 sbom.dependencies
2159 .entry(id2.clone())
2160 .or_default()
2161 .insert(id1.clone(), DependencyKind::Runtime);
2162
2163 let cycles = sbom.detect_cycles();
2164 assert_eq!(cycles.len(), 1);
2165 assert_eq!(cycles[0].first(), cycles[0].last());
2167 }
2168
2169 #[test]
2170 fn test_detect_cycles_self_loop() {
2171 let mut sbom = Sbom::default();
2172 let c1 = Component::new("a".into(), Some("1".into()));
2173 let id1 = c1.id.clone();
2174 sbom.components.insert(id1.clone(), c1);
2175
2176 sbom.dependencies
2178 .entry(id1.clone())
2179 .or_default()
2180 .insert(id1.clone(), DependencyKind::Runtime);
2181
2182 let cycles = sbom.detect_cycles();
2183 assert_eq!(cycles.len(), 1);
2184 assert_eq!(cycles[0].len(), 2); }
2186
2187 #[test]
2188 fn test_detect_cycles_empty_graph() {
2189 let sbom = Sbom::default();
2190 assert!(sbom.detect_cycles().is_empty());
2191 }
2192
2193 #[test]
2194 fn test_insert_component_keeps_replaced_source_ids() {
2195 let entry = |name: &str, source_ids: &[&str]| {
2196 let mut c = Component::new("dup".into(), Some("1".into()));
2197 c.description = Some(name.into());
2198 c.source_ids = source_ids.iter().map(|s| s.to_string()).collect();
2199 c
2200 };
2201 let mut sbom = Sbom::default();
2202 assert!(sbom
2203 .insert_component(entry("first", &["ref-c", "ref-a"]))
2204 .is_none());
2205 let replaced = sbom
2206 .insert_component(entry("second", &["ref-b", "ref-a"]))
2207 .unwrap();
2208 assert_eq!(replaced.description.as_deref(), Some("first"));
2209 assert_eq!(sbom.components.len(), 1);
2210 assert_eq!(sbom.components[0].description.as_deref(), Some("second"));
2211 assert_eq!(
2212 sbom.components[0].source_ids,
2213 vec!["ref-a", "ref-b", "ref-c"]
2214 );
2215 }
2216
2217 #[test]
2218 fn test_insert_dependency_kind_does_not_depend_on_order() {
2219 let parent = Component::new("parent".into(), None).id;
2220 let child = Component::new("child".into(), None).id;
2221 for kinds in [
2222 [DependencyKind::Optional, DependencyKind::Runtime],
2223 [DependencyKind::Runtime, DependencyKind::Optional],
2224 ] {
2225 let mut sbom = Sbom::default();
2226 for kind in kinds {
2227 sbom.insert_dependency(parent.clone(), child.clone(), kind);
2228 }
2229 assert_eq!(
2230 sbom.dependencies[&parent],
2231 BTreeMap::from([(child.clone(), DependencyKind::Runtime)])
2232 );
2233 }
2234
2235 let mut sbom = Sbom::default();
2236 sbom.insert_dependency(parent.clone(), child.clone(), DependencyKind::Test);
2237 sbom.insert_dependency(parent.clone(), child.clone(), DependencyKind::Dev);
2238 assert_eq!(sbom.dependencies[&parent][&child], DependencyKind::Dev);
2239 }
2240
2241 #[test]
2242 fn test_detect_cycles_three_node() {
2243 let mut sbom = Sbom::default();
2244 let c1 = Component::new("a".into(), Some("1".into()));
2245 let c2 = Component::new("b".into(), Some("1".into()));
2246 let c3 = Component::new("c".into(), Some("1".into()));
2247
2248 let id1 = c1.id.clone();
2249 let id2 = c2.id.clone();
2250 let id3 = c3.id.clone();
2251
2252 sbom.components.insert(id1.clone(), c1);
2253 sbom.components.insert(id2.clone(), c2);
2254 sbom.components.insert(id3.clone(), c3);
2255
2256 sbom.dependencies
2258 .entry(id1.clone())
2259 .or_default()
2260 .insert(id2.clone(), DependencyKind::Runtime);
2261 sbom.dependencies
2262 .entry(id2.clone())
2263 .or_default()
2264 .insert(id3.clone(), DependencyKind::Runtime);
2265 sbom.dependencies
2266 .entry(id3.clone())
2267 .or_default()
2268 .insert(id1.clone(), DependencyKind::Runtime);
2269
2270 let cycles = sbom.detect_cycles();
2271 assert_eq!(cycles.len(), 1);
2272 assert_eq!(cycles[0].first(), cycles[0].last());
2273 assert_eq!(cycles[0].len(), 4); }
2275
2276 #[test]
2277 fn test_changed_checksums_same_algorithm_different_value() {
2278 let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2279 let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
2280 assert_eq!(
2281 changed_checksums(&old, &new),
2282 vec![("SHA-256".to_string(), "abc".to_string(), "def".to_string())]
2283 );
2284 }
2285
2286 #[test]
2287 fn test_changed_checksums_identical_values() {
2288 let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2289 assert!(changed_checksums(&old, &old).is_empty());
2290 }
2291
2292 #[test]
2293 fn test_changed_checksums_case_only_difference() {
2294 let old: BTreeMap<String, String> = [("sha-256".into(), "ABCDEF".into())].into();
2295 let new: BTreeMap<String, String> = [("sha-256".into(), "abcdef".into())].into();
2296 assert!(changed_checksums(&old, &new).is_empty());
2297 }
2298
2299 #[test]
2300 fn test_changed_checksums_ignores_surrounding_whitespace() {
2301 let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2302 let new: BTreeMap<String, String> = [("sha-256".into(), " abc\n".into())].into();
2303 assert!(changed_checksums(&old, &new).is_empty());
2304 }
2305
2306 #[test]
2307 fn test_changed_checksums_disjoint_algorithms() {
2308 let old: BTreeMap<String, String> = [("sha-1".into(), "abc".into())].into();
2309 let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
2310 assert!(changed_checksums(&old, &new).is_empty());
2311 }
2312
2313 #[test]
2314 fn test_changed_checksums_only_compares_shared_algorithms() {
2315 let old: BTreeMap<String, String> = [
2316 ("sha-1".into(), "aaa".into()),
2317 ("sha-256".into(), "bbb".into()),
2318 ]
2319 .into();
2320 let new: BTreeMap<String, String> = [
2321 ("sha-256".into(), "ccc".into()),
2322 ("sha-512".into(), "ddd".into()),
2323 ]
2324 .into();
2325 assert_eq!(
2326 changed_checksums(&old, &new),
2327 vec![("SHA-256".to_string(), "bbb".to_string(), "ccc".to_string())]
2328 );
2329 }
2330
2331 #[test]
2332 fn test_changed_checksums_pairs_across_algorithm_spellings() {
2333 let old: BTreeMap<String, String> = [("SHA256".into(), "abc".into())].into();
2334 let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
2335 assert_eq!(
2336 changed_checksums(&old, &new),
2337 vec![("SHA-256".to_string(), "abc".to_string(), "def".to_string())]
2338 );
2339 }
2340
2341 #[test]
2342 fn test_changed_checksums_unknown_algorithm_pairs_by_name() {
2343 let old: BTreeMap<String, String> = [("tiger".into(), "abc".into())].into();
2344 let new: BTreeMap<String, String> = [("tiger".into(), "def".into())].into();
2345 assert_eq!(
2346 changed_checksums(&old, &new),
2347 vec![("tiger".to_string(), "abc".to_string(), "def".to_string())]
2348 );
2349 }
2350
2351 #[test]
2352 fn test_changed_checksums_empty_sides() {
2353 let empty: BTreeMap<String, String> = BTreeMap::new();
2354 let some: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2355 assert!(changed_checksums(&empty, &some).is_empty());
2356 assert!(changed_checksums(&some, &empty).is_empty());
2357 }
2358
2359 #[test]
2360 fn test_changed_checksums_reports_every_mismatching_algorithm() {
2361 let old: BTreeMap<String, String> = [
2362 ("sha-256".into(), "aaa".into()),
2363 ("sha-512".into(), "bbb".into()),
2364 ]
2365 .into();
2366 let new: BTreeMap<String, String> = [
2367 ("sha-256".into(), "ccc".into()),
2368 ("sha-512".into(), "ddd".into()),
2369 ]
2370 .into();
2371 assert_eq!(
2372 changed_checksums(&old, &new),
2373 vec![
2374 ("SHA-256".to_string(), "aaa".to_string(), "ccc".to_string()),
2375 ("SHA-512".to_string(), "bbb".to_string(), "ddd".to_string()),
2376 ]
2377 );
2378 }
2379
2380 #[test]
2381 fn test_is_copyleft_license() {
2382 assert!(is_copyleft_license("GPL-3.0-only"));
2384 assert!(is_copyleft_license("AGPL-3.0-only"));
2385 assert!(is_copyleft_license("LGPL-3.0-only"));
2386 assert!(is_copyleft_license("gpl-3.0-only"));
2387 assert!(is_copyleft_license("mpl-2.0+"));
2388 assert!(!is_copyleft_license("MIT"));
2390 assert!(!is_copyleft_license("Apache-2.0"));
2391 assert!(!is_copyleft_license("BSD-3-Clause"));
2392 assert!(!is_copyleft_license("LicenseRef-proprietary"));
2394 assert!(!is_copyleft_license("NOT-A-LICENSE"));
2395 }
2396
2397 #[test]
2398 fn test_copyleft_introduced_added_alongside_existing() {
2399 let old: BTreeSet<String> = ["GPL-3.0-only".into()].into();
2401 let new: BTreeSet<String> = ["GPL-3.0-only".into(), "AGPL-3.0-only".into()].into();
2402 assert!(copyleft_introduced(&old, &new));
2403 }
2404}