Skip to main content

sbom_model/
lib.rs

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/// format-agnostic SBOM (Software Bill of Materials) representation.
15///
16/// this is the central type that holds all components and their relationships.
17/// it abstracts over format-specific details from CycloneDX, SPDX, and other formats.
18///
19/// # Example
20///
21/// ```
22/// use sbom_model::{Sbom, Component};
23///
24/// let mut sbom = Sbom::default();
25/// let component = Component::new("serde".into(), Some("1.0.0".into()));
26/// sbom.components.insert(component.id.clone(), component);
27/// ```
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct Sbom {
30    /// document-level metadata (creation time, tools, authors).
31    pub metadata: Metadata,
32    /// all components indexed by their stable identifier.
33    pub components: IndexMap<ComponentId, Component>,
34    /// dependency graph as adjacency list: parent -> (child -> kind).
35    pub dependencies: BTreeMap<ComponentId, BTreeMap<ComponentId, DependencyKind>>,
36    /// reverse dependency index: child -> set of parents.
37    ///
38    /// derived from `dependencies`; call [`rebuild_reverse_deps`](Sbom::rebuild_reverse_deps)
39    /// after modifying `dependencies` to keep it in sync.
40    #[serde(skip)]
41    pub reverse_deps: BTreeMap<ComponentId, BTreeSet<ComponentId>>,
42    /// non-fatal warnings produced during parsing (e.g. orphaned dependency refs).
43    #[serde(default, skip_serializing_if = "Vec::is_empty")]
44    pub warnings: Vec<String>,
45}
46
47impl PartialEq for Sbom {
48    fn eq(&self, other: &Self) -> bool {
49        self.metadata == other.metadata
50            && self.components == other.components
51            && self.dependencies == other.dependencies
52            && self.warnings == other.warnings
53    }
54}
55
56impl Eq for Sbom {}
57
58impl Default for Sbom {
59    fn default() -> Self {
60        Self {
61            metadata: Metadata::default(),
62            components: IndexMap::new(),
63            dependencies: BTreeMap::new(),
64            reverse_deps: BTreeMap::new(),
65            warnings: Vec::new(),
66        }
67    }
68}
69
70/// SBOM document metadata.
71///
72/// contains information about when and how the SBOM was created.
73/// this data is stripped during normalization since it varies between
74/// tool runs and shouldn't affect diff comparisons.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
76pub struct Metadata {
77    /// ISO 8601 timestamp of document creation.
78    pub timestamp: Option<String>,
79    /// tools used to generate the SBOM (e.g., "syft", "trivy").
80    pub tools: Vec<String>,
81    /// document authors or organizations.
82    pub authors: Vec<String>,
83}
84
85/// the semantic type of a dependency relationship.
86///
87/// SPDX distinguishes between runtime, dev, build, test, optional, and
88/// provided dependencies via typed relationship names. CycloneDX encodes
89/// scope on the component itself (`required` / `optional` / `excluded`),
90/// which is mapped to the appropriate variant when constructing edges.
91///
92/// the default is `Runtime`, which also covers generic relationships
93/// like `DEPENDS_ON` or `CONTAINS` that don't specify a scope.
94#[derive(
95    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
96)]
97#[serde(rename_all = "lowercase")]
98pub enum DependencyKind {
99    /// runtime or unspecified dependency (the default).
100    #[default]
101    Runtime,
102    /// development-only dependency.
103    Dev,
104    /// build-time dependency.
105    Build,
106    /// test-only dependency.
107    Test,
108    /// optional dependency.
109    Optional,
110    /// provided by the runtime environment.
111    Provided,
112}
113
114impl fmt::Display for DependencyKind {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        match self {
117            Self::Runtime => write!(f, "runtime"),
118            Self::Dev => write!(f, "dev"),
119            Self::Build => write!(f, "build"),
120            Self::Test => write!(f, "test"),
121            Self::Optional => write!(f, "optional"),
122            Self::Provided => write!(f, "provided"),
123        }
124    }
125}
126
127/// stable identifier for a component.
128///
129/// used as a key in the component map and dependency graph. prefers package URLs
130/// (purls) when available since they provide globally unique identifiers. falls
131/// back to a deterministic SHA-256 hash of component properties when no purl exists.
132///
133/// # Example
134///
135/// ```
136/// use sbom_model::ComponentId;
137///
138/// // with a purl (preferred)
139/// let id = ComponentId::new(Some("pkg:npm/lodash@4.17.21"), &[]);
140/// assert_eq!(id.as_str(), "pkg:npm/lodash@4.17.21");
141///
142/// // without a purl (hash fallback)
143/// let id = ComponentId::new(None, &[("name", "foo"), ("version", "1.0")]);
144/// assert!(id.as_str().starts_with("h:"));
145/// ```
146#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
147pub struct ComponentId(String);
148
149impl ComponentId {
150    /// creates a new identifier from a purl or property hash.
151    ///
152    /// if a purl is provided, it will be canonicalized. otherwise, a deterministic
153    /// SHA-256 hash is computed from the provided key-value properties.
154    pub fn new(purl: Option<&str>, properties: &[(&str, &str)]) -> Self {
155        if let Some(purl) = purl {
156            if let Ok(parsed) = PackageUrl::from_str(purl) {
157                return ComponentId(parsed.to_string());
158            }
159            return ComponentId(purl.to_string());
160        }
161
162        // deterministic hash fallback
163        let mut hasher = Sha256::new();
164        for (k, v) in properties {
165            hasher.update(k.as_bytes());
166            hasher.update(b":");
167            hasher.update(v.as_bytes());
168            hasher.update(b"|");
169        }
170        let hash = hex::encode(hasher.finalize());
171        ComponentId(format!("h:{}", hash))
172    }
173
174    /// returns the identifier as a string slice.
175    pub fn as_str(&self) -> &str {
176        &self.0
177    }
178}
179
180impl std::fmt::Display for ComponentId {
181    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        write!(f, "{}", self.0)
183    }
184}
185
186/// a software component (package, library, or application).
187///
188/// represents a single entry in the SBOM with all its metadata.
189/// components are identified by their [`ComponentId`] and can have
190/// relationships to other components via the dependency graph.
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192pub struct Component {
193    /// stable identifier for this component.
194    pub id: ComponentId,
195    /// package name (e.g., "serde", "lodash").
196    pub name: String,
197    /// package version (e.g., "1.0.0", "4.17.21").
198    pub version: Option<String>,
199    /// package ecosystem (e.g., "cargo", "npm", "pypi").
200    pub ecosystem: Option<String>,
201    /// package supplier or publisher.
202    pub supplier: Option<String>,
203    /// human-readable description.
204    pub description: Option<String>,
205    /// package URL per the [purl spec](https://github.com/package-url/purl-spec).
206    pub purl: Option<String>,
207    /// SPDX license identifiers (e.g., "MIT", "Apache-2.0").
208    pub licenses: BTreeSet<String>,
209    /// the SPDX license expression the source document declared, when it
210    /// declared one (e.g., "MIT OR Apache-2.0").
211    ///
212    /// [`licenses`](Self::licenses) is the flattened identifier set of this
213    /// expression and stays populated either way; policy decisions should go
214    /// through [`licensing`](Self::licensing), which keeps the operators.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub license_expression: Option<String>,
217    /// checksums keyed by algorithm (e.g., "sha256" -> "abc123...").
218    pub hashes: BTreeMap<String, String>,
219    /// original identifiers from the source document (e.g., SPDX SPDXRef, CycloneDX bom-ref).
220    pub source_ids: Vec<String>,
221}
222
223impl Component {
224    /// creates a new component with the given name and optional version.
225    ///
226    /// the component ID is generated from a hash of the name and version.
227    /// use this for simple cases; for full control, construct the struct directly.
228    pub fn new(name: String, version: Option<String>) -> Self {
229        let mut props = vec![("name", name.as_str())];
230        if let Some(v) = &version {
231            props.push(("version", v));
232        }
233        let id = ComponentId::new(None, &props);
234
235        Self {
236            id,
237            name,
238            version,
239            ecosystem: None,
240            supplier: None,
241            description: None,
242            purl: None,
243            licenses: BTreeSet::new(),
244            license_expression: None,
245            hashes: BTreeMap::new(),
246            source_ids: Vec::new(),
247        }
248    }
249
250    /// returns the licensing this component declares, for policy evaluation.
251    pub fn licensing(&self) -> Licensing<'_> {
252        Licensing {
253            expression: self.license_expression.as_deref(),
254            ids: &self.licenses,
255        }
256    }
257}
258
259impl Sbom {
260    /// normalizes the SBOM for deterministic comparison.
261    ///
262    /// this method:
263    /// - sorts components by ID
264    /// - deduplicates and sorts licenses within each component
265    /// - lowercases hash algorithms and values
266    /// - clears volatile metadata (timestamps, tools, authors)
267    ///
268    /// call this before comparing two SBOMs to ignore irrelevant differences.
269    pub fn normalize(&mut self) {
270        // sort components by ID for deterministic output
271        self.components.sort_keys();
272
273        // normalize components
274        for component in self.components.values_mut() {
275            component.normalize();
276        }
277
278        // strip volatile metadata
279        self.metadata.timestamp = None;
280        self.metadata.tools.clear();
281        self.metadata.authors.clear();
282
283        self.rebuild_reverse_deps();
284    }
285
286    /// rebuilds the reverse dependency index from the forward `dependencies` map.
287    ///
288    /// must be called after modifying `dependencies` for `rdeps()` and `roots()`
289    /// to return correct results. Parsers call this automatically; call it
290    /// explicitly when constructing an `Sbom` by hand.
291    pub fn rebuild_reverse_deps(&mut self) {
292        self.reverse_deps.clear();
293        for (parent, children) in &self.dependencies {
294            for child in children.keys() {
295                self.reverse_deps
296                    .entry(child.clone())
297                    .or_default()
298                    .insert(parent.clone());
299            }
300        }
301    }
302
303    /// inserts a component, replacing any component with the same id.
304    ///
305    /// the replaced component's [`source_ids`](Component::source_ids) are
306    /// merged into the new one's, sorted and deduplicated. returns the
307    /// replaced component.
308    pub fn insert_component(&mut self, mut component: Component) -> Option<Component> {
309        if let Some(existing) = self.components.get(&component.id) {
310            component
311                .source_ids
312                .extend(existing.source_ids.iter().cloned());
313            component.source_ids.sort();
314            component.source_ids.dedup();
315        }
316        self.components.insert(component.id.clone(), component)
317    }
318
319    /// adds a `parent -> child` dependency edge.
320    ///
321    /// an edge added twice with different kinds keeps the kind declared first
322    /// in [`DependencyKind`], so `Runtime` wins over every other kind. call
323    /// [`rebuild_reverse_deps`](Self::rebuild_reverse_deps) afterwards.
324    pub fn insert_dependency(
325        &mut self,
326        parent: ComponentId,
327        child: ComponentId,
328        kind: DependencyKind,
329    ) {
330        self.dependencies
331            .entry(parent)
332            .or_default()
333            .entry(child)
334            .and_modify(|existing| *existing = (*existing).min(kind))
335            .or_insert(kind);
336    }
337
338    /// returns root components (those not depended on by any other component).
339    ///
340    /// these are typically the top-level packages or applications in the SBOM.
341    /// uses the precomputed `reverse_deps` index.
342    pub fn roots(&self) -> Vec<ComponentId> {
343        self.components
344            .keys()
345            .filter(|id| self.reverse_deps.get(*id).is_none_or(BTreeSet::is_empty))
346            .cloned()
347            .collect()
348    }
349
350    /// returns direct dependencies of the given component.
351    pub fn deps(&self, id: &ComponentId) -> Vec<ComponentId> {
352        self.dependencies
353            .get(id)
354            .map(|d| d.keys().cloned().collect())
355            .unwrap_or_default()
356    }
357
358    /// returns reverse dependencies (components that depend on the given component).
359    /// uses the precomputed `reverse_deps` index.
360    pub fn rdeps(&self, id: &ComponentId) -> Vec<ComponentId> {
361        self.reverse_deps
362            .get(id)
363            .map(|parents| parents.iter().cloned().collect())
364            .unwrap_or_default()
365    }
366
367    /// returns all transitive dependencies of the given component.
368    ///
369    /// traverses the dependency graph depth-first and returns all reachable components.
370    pub fn transitive_deps(&self, id: &ComponentId) -> BTreeSet<ComponentId> {
371        let mut visited = BTreeSet::new();
372        let mut stack = vec![id.clone()];
373        while let Some(current) = stack.pop() {
374            if let Some(children) = self.dependencies.get(&current) {
375                for child in children.keys() {
376                    if visited.insert(child.clone()) {
377                        stack.push(child.clone());
378                    }
379                }
380            }
381        }
382        visited
383    }
384
385    /// returns all unique ecosystems present in the SBOM.
386    pub fn ecosystems(&self) -> BTreeSet<String> {
387        self.components
388            .values()
389            .filter_map(|c| c.ecosystem.clone())
390            .collect()
391    }
392
393    /// returns all unique licenses present across all components.
394    pub fn licenses(&self) -> BTreeSet<String> {
395        self.components
396            .values()
397            .flat_map(|c| c.licenses.iter().cloned())
398            .collect()
399    }
400
401    /// returns components that have no checksums/hashes.
402    ///
403    /// useful for identifying components that may need integrity verification.
404    pub fn missing_hashes(&self) -> Vec<ComponentId> {
405        self.components
406            .iter()
407            .filter(|(_, c)| c.hashes.is_empty())
408            .map(|(id, _)| id.clone())
409            .collect()
410    }
411
412    /// finds a component by its package URL.
413    pub fn by_purl(&self, purl: &str) -> Option<&Component> {
414        let id = ComponentId::new(Some(purl), &[]);
415        self.components.get(&id)
416    }
417
418    /// detects dependency cycles in the SBOM's dependency graph.
419    ///
420    /// uses iterative stack-based depth-first search with three-color marking
421    /// (white/gray/black) to find all distinct cycles. each returned vector
422    /// contains the component IDs forming a cycle, starting and ending with
423    /// the same ID.
424    ///
425    /// returns an empty vector if the graph is acyclic.
426    pub fn detect_cycles(&self) -> Vec<Vec<ComponentId>> {
427        enum Frame {
428            Enter(ComponentId),
429            Exit(ComponentId),
430        }
431
432        let mut visited = BTreeSet::new();
433        let mut on_stack = BTreeSet::new();
434        let mut path = Vec::new();
435        let mut cycles = Vec::new();
436
437        let mut stack: Vec<Frame> = self
438            .dependencies
439            .keys()
440            .rev()
441            .map(|k| Frame::Enter(k.clone()))
442            .collect();
443
444        while let Some(frame) = stack.pop() {
445            match frame {
446                Frame::Enter(node) => {
447                    if visited.contains(&node) {
448                        continue;
449                    }
450                    visited.insert(node.clone());
451                    on_stack.insert(node.clone());
452                    path.push(node.clone());
453                    stack.push(Frame::Exit(node.clone()));
454
455                    if let Some(children) = self.dependencies.get(&node) {
456                        for child in children.keys().rev() {
457                            if !visited.contains(child) {
458                                stack.push(Frame::Enter(child.clone()));
459                            } else if on_stack.contains(child) {
460                                if let Some(start) = path.iter().position(|n| n == child) {
461                                    let mut cycle: Vec<_> = path[start..].to_vec();
462                                    cycle.push(child.clone());
463                                    cycles.push(cycle);
464                                }
465                            }
466                        }
467                    }
468                }
469                Frame::Exit(node) => {
470                    path.pop();
471                    on_stack.remove(&node);
472                }
473            }
474        }
475
476        cycles
477    }
478}
479
480impl Component {
481    /// normalizes the component for deterministic comparison.
482    ///
483    /// lowercases hash keys and values. licenses are stored as a BTreeSet
484    /// so they're already sorted and deduplicated.
485    pub fn normalize(&mut self) {
486        let normalized_hashes: BTreeMap<String, String> = self
487            .hashes
488            .iter()
489            .map(|(k, v)| (k.to_lowercase(), v.to_lowercase()))
490            .collect();
491        self.hashes = normalized_hashes;
492    }
493}
494
495/// extracts the ecosystem (package type) from a purl string.
496///
497/// returns `None` if the purl is invalid or cannot be parsed.
498///
499/// # Example
500///
501/// ```
502/// use sbom_model::ecosystem_from_purl;
503///
504/// assert_eq!(ecosystem_from_purl("pkg:npm/lodash@4.17.21"), Some("npm".to_string()));
505/// assert_eq!(ecosystem_from_purl("pkg:cargo/serde@1.0.0"), Some("cargo".to_string()));
506/// assert_eq!(ecosystem_from_purl("invalid"), None);
507/// ```
508pub fn ecosystem_from_purl(purl: &str) -> Option<String> {
509    PackageUrl::from_str(purl).ok().map(|p| p.ty().to_string())
510}
511
512/// respells every SPDX license and exception identifier in an expression the
513/// way the SPDX license list does.
514///
515/// SPDX identifiers match case-insensitively, so `mit` and `MIT` name the same
516/// license. operators, `LicenseRef-` and `DocumentRef-` references, and terms
517/// the list doesn't know are left as written.
518///
519/// # Example
520///
521/// ```
522/// use sbom_model::canonical_license_case;
523///
524/// assert_eq!(canonical_license_case("mit OR apache-2.0"), "MIT OR Apache-2.0");
525/// assert_eq!(canonical_license_case("LicenseRef-mit"), "LicenseRef-mit");
526/// ```
527pub fn canonical_license_case(expression: &str) -> String {
528    let is_id_char = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | ':');
529    let mut canonical = String::with_capacity(expression.len());
530    for piece in expression.split_inclusive(|c: char| !is_id_char(c)) {
531        let id = piece.trim_end_matches(|c: char| !is_id_char(c));
532        canonical.push_str(spdx_spelling(id).unwrap_or(id));
533        canonical.push_str(&piece[id.len()..]);
534    }
535    canonical
536}
537
538/// finds the SPDX list's spelling of a license or exception identifier, ignoring case.
539fn spdx_spelling(id: &str) -> Option<&'static str> {
540    static SPELLINGS: OnceLock<HashMap<String, &'static str>> = OnceLock::new();
541    let spellings = SPELLINGS.get_or_init(|| {
542        let licenses = spdx::identifiers::LICENSES.iter().map(|l| l.name);
543        let exceptions = spdx::identifiers::EXCEPTIONS.iter().map(|e| e.name);
544        licenses
545            .chain(exceptions)
546            .map(|name| (name.to_ascii_lowercase(), name))
547            .collect()
548    });
549    spellings.get(&id.to_ascii_lowercase()).copied()
550}
551
552fn parse_expression(expression: &str) -> Result<spdx::Expression, spdx::ParseError> {
553    spdx::Expression::parse(&canonical_license_case(expression))
554}
555
556/// extracts individual license IDs from an SPDX expression.
557///
558/// parses the expression and returns all license IDs found, including
559/// `LicenseRef-` identifiers. if parsing fails, returns the string,
560/// respelled by [`canonical_license_case`], as a single-element set.
561///
562/// # Example
563///
564/// ```
565/// use sbom_model::parse_license_expression;
566///
567/// let ids = parse_license_expression("MIT OR Apache-2.0");
568/// assert!(ids.contains("MIT"));
569/// assert!(ids.contains("Apache-2.0"));
570///
571/// let ids = parse_license_expression("LicenseRef-proprietary AND Apache-2.0");
572/// assert!(ids.contains("LicenseRef-proprietary"));
573/// assert!(ids.contains("Apache-2.0"));
574/// ```
575pub fn parse_license_expression(license: &str) -> BTreeSet<String> {
576    match parse_expression(license) {
577        Ok(expr) => {
578            let ids: BTreeSet<String> = expr
579                .requirements()
580                .map(|r| match &r.req.license {
581                    spdx::LicenseItem::Spdx { id, .. } => id.name.to_string(),
582                    other => other.to_string(),
583                })
584                .collect();
585            if ids.is_empty() {
586                // expression parsed but no IDs found, keep original
587                BTreeSet::from([license.to_string()])
588            } else {
589                ids
590            }
591        }
592        Err(_) => {
593            // not a valid SPDX expression, keep it whole
594            BTreeSet::from([canonical_license_case(license)])
595        }
596    }
597}
598
599/// a single license requirement: one identifier plus the `WITH` exception
600/// bound to it, if any.
601#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
602pub struct LicenseRequirement {
603    /// the license identifier, e.g. `GPL-2.0-only` or `LicenseRef-proprietary`.
604    pub license: String,
605    /// whether the identifier carried a `+` suffix.
606    pub or_later: bool,
607    /// the exception identifier following `WITH`.
608    pub exception: Option<String>,
609}
610
611impl LicenseRequirement {
612    /// builds a bare requirement from a license identifier.
613    pub fn new(license: impl Into<String>) -> Self {
614        Self {
615            license: license.into(),
616            or_later: false,
617            exception: None,
618        }
619    }
620}
621
622impl std::fmt::Display for LicenseRequirement {
623    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
624        write!(f, "{}", self.license)?;
625        if self.or_later {
626            f.write_str("+")?;
627        }
628        if let Some(exception) = &self.exception {
629            write!(f, " WITH {exception}")?;
630        }
631        Ok(())
632    }
633}
634
635fn to_requirement(req: &spdx::LicenseReq) -> LicenseRequirement {
636    let (license, or_later) = match &req.license {
637        spdx::LicenseItem::Spdx { id, or_later } => (id.name.to_string(), *or_later),
638        other => (other.to_string(), false),
639    };
640    LicenseRequirement {
641        license,
642        or_later,
643        exception: req.addition.as_ref().map(|a| a.to_string()),
644    }
645}
646
647/// the licensing a component declares.
648///
649/// carries the SPDX expression when the source document had one, so `AND`/`OR`
650/// and `WITH` survive; otherwise it falls back to the flattened identifier set,
651/// which is read as a conjunction (every identifier applies).
652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
653pub struct Licensing<'a> {
654    /// the declared SPDX expression, if any.
655    pub expression: Option<&'a str>,
656    /// the flattened license identifiers.
657    pub ids: &'a BTreeSet<String>,
658}
659
660impl<'a> Licensing<'a> {
661    /// builds a licensing view from a flat identifier set.
662    pub fn from_ids(ids: &'a BTreeSet<String>) -> Self {
663        Self {
664            expression: None,
665            ids,
666        }
667    }
668
669    /// reports whether the licensing can be satisfied by taking on only
670    /// requirements `acceptable` approves of.
671    ///
672    /// `OR` lets the consumer pick one side, `AND` demands both. an expression
673    /// that fails to parse, or an absent expression, falls back to requiring
674    /// every identifier in the flat set.
675    ///
676    /// # Example
677    ///
678    /// ```
679    /// use sbom_model::Licensing;
680    /// use std::collections::BTreeSet;
681    ///
682    /// let ids: BTreeSet<String> = ["Apache-2.0".into(), "MIT".into()].into();
683    /// let choice = Licensing { expression: Some("MIT OR Apache-2.0"), ids: &ids };
684    /// assert!(choice.satisfiable(|r| r.license == "MIT"));
685    ///
686    /// let both = Licensing { expression: Some("MIT AND Apache-2.0"), ids: &ids };
687    /// assert!(!both.satisfiable(|r| r.license == "MIT"));
688    /// ```
689    pub fn satisfiable<F>(&self, mut acceptable: F) -> bool
690    where
691        F: FnMut(&LicenseRequirement) -> bool,
692    {
693        if let Some(expression) = self.expression {
694            if let Ok(expr) = parse_expression(expression) {
695                return expr.evaluate(|req| acceptable(&to_requirement(req)));
696            }
697        }
698        self.ids
699            .iter()
700            .all(|id| acceptable(&LicenseRequirement::new(id)))
701    }
702
703    /// returns every requirement the licensing mentions, whether or not a
704    /// consumer must accept it.
705    pub fn requirements(&self) -> BTreeSet<LicenseRequirement> {
706        if let Some(expression) = self.expression {
707            if let Ok(expr) = parse_expression(expression) {
708                let reqs: BTreeSet<LicenseRequirement> = expr
709                    .requirements()
710                    .map(|r| to_requirement(&r.req))
711                    .collect();
712                if !reqs.is_empty() {
713                    return reqs;
714                }
715            }
716        }
717        self.ids.iter().map(LicenseRequirement::new).collect()
718    }
719
720    /// returns the minimal requirement sets that satisfy the licensing, or
721    /// `None` when the expression expands past `MAX_CHOICES`.
722    fn choices(&self) -> Option<Choices> {
723        if let Some(expression) = self.expression {
724            if let Ok(expr) = parse_expression(expression) {
725                return expression_choices(&expr);
726            }
727        }
728        Some(BTreeSet::from([self
729            .ids
730            .iter()
731            .map(LicenseRequirement::new)
732            .collect()]))
733    }
734
735    /// returns the copyleft identifiers no satisfying choice can avoid.
736    fn mandatory_copyleft(&self) -> BTreeSet<String> {
737        self.requirements()
738            .into_iter()
739            .filter(|r| is_copyleft_license(&r.license))
740            .filter(|r| !self.satisfiable(|other| other.license != r.license))
741            .map(|r| canonical_license_case(&r.license))
742            .collect()
743    }
744
745    /// returns the minimal copyleft burdens the licensing's satisfying choices
746    /// carry, or `None` when the expression expands past `MAX_CHOICES`.
747    fn copyleft_burdens(&self) -> Option<Burdens> {
748        let burdens = self
749            .choices()?
750            .into_iter()
751            .map(|choice| {
752                choice
753                    .into_iter()
754                    .filter(|r| is_copyleft_license(&r.license))
755                    .map(|r| canonical_license_case(&r.license))
756                    .collect()
757            })
758            .collect();
759        Some(minimal_sets(burdens))
760    }
761}
762
763/// the alternative requirement sets an expression offers a consumer.
764type Choices = BTreeSet<BTreeSet<LicenseRequirement>>;
765
766/// the copyleft identifiers each alternative an expression offers carries.
767type Burdens = BTreeSet<BTreeSet<String>>;
768
769/// the largest number of alternatives an expression is expanded into before it
770/// is compared by spelling instead.
771const MAX_CHOICES: usize = 64;
772
773/// drops every set that another set in the collection is a strict subset of.
774fn minimal_sets<T: Ord + Clone>(sets: BTreeSet<BTreeSet<T>>) -> BTreeSet<BTreeSet<T>> {
775    sets.iter()
776        .filter(|set| {
777            sets.iter()
778                .all(|other| other == *set || !other.is_subset(set))
779        })
780        .cloned()
781        .collect()
782}
783
784/// expands a parsed expression into its minimal satisfying requirement sets.
785fn expression_choices(expr: &spdx::Expression) -> Option<Choices> {
786    let mut stack: Vec<Choices> = Vec::new();
787
788    for node in expr.iter() {
789        match node {
790            spdx::expression::ExprNode::Req(req) => {
791                stack.push(BTreeSet::from([BTreeSet::from([to_requirement(&req.req)])]));
792            }
793            spdx::expression::ExprNode::Op(op) => {
794                let rhs = stack.pop()?;
795                let lhs = stack.pop()?;
796                let combined: Choices = match op {
797                    spdx::expression::Operator::Or => lhs.union(&rhs).cloned().collect(),
798                    spdx::expression::Operator::And => lhs
799                        .iter()
800                        .flat_map(|l| rhs.iter().map(|r| l.union(r).cloned().collect()))
801                        .collect(),
802                };
803                if combined.len() > MAX_CHOICES {
804                    return None;
805                }
806                stack.push(minimal_sets(combined));
807            }
808        }
809    }
810
811    let choices = stack.pop()?;
812    stack.is_empty().then_some(choices)
813}
814
815/// reports whether two licensings impose the same obligations.
816///
817/// a licensing without a declared expression is read as a conjunction of its
818/// identifiers, so it differs from one with an expression only when that
819/// expression means something a bare identifier set cannot. an expression too
820/// wide to expand is compared by spelling and never matches a bare set.
821///
822/// # Example
823///
824/// ```
825/// use sbom_model::{licensings_equivalent, Licensing};
826/// use std::collections::BTreeSet;
827///
828/// let ids: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
829/// let flat = Licensing::from_ids(&ids);
830///
831/// let both = Licensing { expression: Some("MIT AND GPL-3.0-only"), ids: &ids };
832/// assert!(licensings_equivalent(both, flat));
833///
834/// let choice = Licensing { expression: Some("MIT OR GPL-3.0-only"), ids: &ids };
835/// assert!(!licensings_equivalent(choice, flat));
836/// ```
837pub fn licensings_equivalent(a: Licensing<'_>, b: Licensing<'_>) -> bool {
838    match (a.choices(), b.choices()) {
839        (Some(x), Some(y)) => x == y,
840        _ => match (a.expression, b.expression) {
841            (Some(x), Some(y)) => license_expressions_equivalent(x, y),
842            _ => false,
843        },
844    }
845}
846
847/// returns the copyleft licenses `new` can put a consumer under that `old`
848/// could not.
849///
850/// empty when `new` offers a way to satisfy it whose copyleft obligations `old`
851/// already offered — so a dual license like `MIT OR GPL-3.0-only` is not an
852/// introduction, while `MIT AND GPL-3.0-only` is, and an unchanged
853/// `GPL-2.0-only OR GPL-3.0-only` choice is neither. otherwise it is the
854/// copyleft carried by `new`'s minimal satisfying choices, minus the copyleft
855/// every choice of `old` already carried; those choices need not be comparable,
856/// so a consumer may end up under only some of the returned licenses. an
857/// expression too wide to expand is measured against the copyleft `old` made
858/// individually unavoidable.
859///
860/// # Example
861///
862/// ```
863/// use sbom_model::{copyleft_obligations_added, Licensing};
864/// use std::collections::BTreeSet;
865///
866/// let old_ids: BTreeSet<String> = ["MIT".into()].into();
867/// let new_ids: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
868/// let old = Licensing { expression: Some("MIT"), ids: &old_ids };
869///
870/// let choice = Licensing { expression: Some("MIT OR GPL-3.0-only"), ids: &new_ids };
871/// assert!(copyleft_obligations_added(old, choice).is_empty());
872///
873/// let both = Licensing { expression: Some("MIT AND GPL-3.0-only"), ids: &new_ids };
874/// assert!(copyleft_obligations_added(old, both).contains("GPL-3.0-only"));
875/// ```
876pub fn copyleft_obligations_added(old: Licensing<'_>, new: Licensing<'_>) -> BTreeSet<String> {
877    match (old.copyleft_burdens(), new.copyleft_burdens()) {
878        (Some(offered), Some(demanded)) => {
879            if demanded
880                .iter()
881                .any(|burden| offered.iter().any(|had| burden.is_subset(had)))
882            {
883                return BTreeSet::new();
884            }
885            let unavoidable = offered
886                .into_iter()
887                .reduce(|acc, had| acc.intersection(&had).cloned().collect())
888                .unwrap_or_default();
889            demanded
890                .into_iter()
891                .flatten()
892                .filter(|license| !unavoidable.contains(license))
893                .collect()
894        }
895        _ => {
896            let already = old.mandatory_copyleft();
897            let carried =
898                |r: &LicenseRequirement| already.contains(&canonical_license_case(&r.license));
899            if new.satisfiable(|r| !is_copyleft_license(&r.license) || carried(r)) {
900                return BTreeSet::new();
901            }
902            new.requirements()
903                .into_iter()
904                .filter(|r| is_copyleft_license(&r.license) && !carried(r))
905                .map(|r| canonical_license_case(&r.license))
906                .collect()
907        }
908    }
909}
910
911/// reports whether two SPDX license expressions impose the same obligations.
912///
913/// spelling that does not change which licenses satisfy the expression —
914/// redundant parentheses, whitespace, operand order — is not a difference;
915/// `AND` against `OR`, `WITH` exceptions and `+` are. an expression too wide to
916/// expand compares by parse tree, and one that fails to parse as a plain string.
917///
918/// # Example
919///
920/// ```
921/// use sbom_model::license_expressions_equivalent;
922///
923/// assert!(license_expressions_equivalent("MIT OR Apache-2.0", "(Apache-2.0 OR MIT)"));
924/// assert!(!license_expressions_equivalent("MIT OR Apache-2.0", "MIT AND Apache-2.0"));
925/// assert!(!license_expressions_equivalent(
926///     "GPL-2.0-only",
927///     "GPL-2.0-only WITH Classpath-exception-2.0",
928/// ));
929/// ```
930pub fn license_expressions_equivalent(a: &str, b: &str) -> bool {
931    match (parse_expression(a), parse_expression(b)) {
932        (Ok(x), Ok(y)) => match (expression_choices(&x), expression_choices(&y)) {
933            (Some(cx), Some(cy)) => cx == cy,
934            _ => x == y,
935        },
936        _ => a == b,
937    }
938}
939
940/// normalizes a hash algorithm name to its canonical form.
941///
942/// handles variations in casing and hyphenation so that algorithm names
943/// from different SBOM formats (SPDX, CycloneDX) compare equal.
944///
945/// # Example
946///
947/// ```
948/// use sbom_model::canonical_algorithm_name;
949///
950/// assert_eq!(canonical_algorithm_name("SHA256"), "SHA-256");
951/// assert_eq!(canonical_algorithm_name("SHA-256"), "SHA-256");
952/// assert_eq!(canonical_algorithm_name("sha256"), "SHA-256");
953/// ```
954pub fn canonical_algorithm_name(name: &str) -> String {
955    match name.replace('-', "").to_uppercase().as_str() {
956        "MD2" => "MD2",
957        "MD4" => "MD4",
958        "MD5" => "MD5",
959        "MD6" => "MD6",
960        "SHA1" => "SHA-1",
961        "SHA224" => "SHA-224",
962        "SHA256" => "SHA-256",
963        "SHA384" => "SHA-384",
964        "SHA512" => "SHA-512",
965        "SHA3256" => "SHA3-256",
966        "SHA3384" => "SHA3-384",
967        "SHA3512" => "SHA3-512",
968        "BLAKE2B256" => "BLAKE2b-256",
969        "BLAKE2B384" => "BLAKE2b-384",
970        "BLAKE2B512" => "BLAKE2b-512",
971        "BLAKE3" => "BLAKE3",
972        "ADLER32" => "ADLER-32",
973        _ => return name.to_string(),
974    }
975    .to_string()
976}
977
978/// returns the strength tier of a hash algorithm, where higher values
979/// indicate stronger algorithms.
980///
981/// returns `None` for unrecognized algorithms. The tiers are:
982/// - 0: Non-cryptographic checksums (ADLER-32)
983/// - 1: Broken cryptographic hashes (MD2, MD4, MD5)
984/// - 2: Weak cryptographic hashes (SHA-1)
985/// - 3: 112-bit security (SHA-224)
986/// - 4: 128-bit security (SHA-256, SHA3-256, BLAKE2b-256, BLAKE3, MD6)
987/// - 5: 192-bit security (SHA-384, SHA3-384, BLAKE2b-384)
988/// - 6: 256-bit security (SHA-512, SHA3-512, BLAKE2b-512)
989///
990/// # Example
991///
992/// ```
993/// use sbom_model::hash_algorithm_strength;
994///
995/// assert!(hash_algorithm_strength("SHA-256").unwrap() > hash_algorithm_strength("MD5").unwrap());
996/// assert!(hash_algorithm_strength("SHA-512").unwrap() > hash_algorithm_strength("SHA-256").unwrap());
997/// assert_eq!(hash_algorithm_strength("UNKNOWN"), None);
998/// ```
999pub fn hash_algorithm_strength(name: &str) -> Option<u8> {
1000    let canonical = canonical_algorithm_name(name);
1001    match canonical.as_str() {
1002        "ADLER-32" => Some(0),
1003        "MD2" | "MD4" | "MD5" => Some(1),
1004        "SHA-1" => Some(2),
1005        "SHA-224" => Some(3),
1006        "SHA-256" | "SHA3-256" | "BLAKE2b-256" | "BLAKE3" | "MD6" => Some(4),
1007        "SHA-384" | "SHA3-384" | "BLAKE2b-384" => Some(5),
1008        "SHA-512" | "SHA3-512" | "BLAKE2b-512" => Some(6),
1009        _ => None,
1010    }
1011}
1012
1013/// detects whether the hash algorithms in a component were downgraded.
1014///
1015/// compares the strongest known algorithm in `old_hashes` against the
1016/// strongest known algorithm in `new_hashes`. Returns `true` if the new
1017/// set's strongest algorithm is weaker than the old set's strongest.
1018///
1019/// returns `false` when:
1020/// - either hash set is empty (use `missing-hashes` for that)
1021/// - neither set contains a recognized algorithm
1022/// - the new set is at least as strong as the old set
1023///
1024/// # Example
1025///
1026/// ```
1027/// use sbom_model::is_hash_algorithm_downgrade;
1028/// use std::collections::BTreeMap;
1029///
1030/// let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
1031/// let new: BTreeMap<String, String> = [("md5".into(), "def".into())].into();
1032/// assert!(is_hash_algorithm_downgrade(&old, &new));
1033///
1034/// let new_strong: BTreeMap<String, String> = [("sha-512".into(), "ghi".into())].into();
1035/// assert!(!is_hash_algorithm_downgrade(&old, &new_strong));
1036/// ```
1037pub fn is_hash_algorithm_downgrade(
1038    old_hashes: &BTreeMap<String, String>,
1039    new_hashes: &BTreeMap<String, String>,
1040) -> bool {
1041    if old_hashes.is_empty() || new_hashes.is_empty() {
1042        return false;
1043    }
1044
1045    let old_max = old_hashes
1046        .keys()
1047        .filter_map(|k| hash_algorithm_strength(k))
1048        .max();
1049    let new_max = new_hashes
1050        .keys()
1051        .filter_map(|k| hash_algorithm_strength(k))
1052        .max();
1053
1054    match (old_max, new_max) {
1055        (Some(old_strength), Some(new_strength)) => new_strength < old_strength,
1056        _ => false,
1057    }
1058}
1059
1060fn checksums_by_algorithm(hashes: &BTreeMap<String, String>) -> BTreeMap<String, &str> {
1061    hashes
1062        .iter()
1063        .map(|(algo, value)| (canonical_algorithm_name(algo), value.trim()))
1064        .collect()
1065}
1066
1067/// finds checksums whose value changed under an algorithm both sides carry.
1068///
1069/// returns `(algorithm, old value, new value)` triples ordered by canonical
1070/// algorithm name. an algorithm only one side carries is ignored, so two sets
1071/// sharing no algorithm yield nothing. values are compared case-insensitively
1072/// and ignoring surrounding whitespace.
1073///
1074/// # Example
1075///
1076/// ```
1077/// use sbom_model::changed_checksums;
1078/// use std::collections::BTreeMap;
1079///
1080/// let old: BTreeMap<String, String> = [("SHA-256".into(), "abc".into())].into();
1081/// let new: BTreeMap<String, String> = [("sha256".into(), "def".into())].into();
1082/// assert_eq!(
1083///     changed_checksums(&old, &new),
1084///     vec![("SHA-256".to_string(), "abc".to_string(), "def".to_string())]
1085/// );
1086///
1087/// let recased: BTreeMap<String, String> = [("SHA-256".into(), "ABC".into())].into();
1088/// assert!(changed_checksums(&old, &recased).is_empty());
1089/// ```
1090pub fn changed_checksums(
1091    old_hashes: &BTreeMap<String, String>,
1092    new_hashes: &BTreeMap<String, String>,
1093) -> Vec<(String, String, String)> {
1094    let new_side = checksums_by_algorithm(new_hashes);
1095
1096    checksums_by_algorithm(old_hashes)
1097        .into_iter()
1098        .filter_map(|(algo, old_value)| {
1099            let new_value = new_side.get(algo.as_str())?;
1100            (!old_value.eq_ignore_ascii_case(new_value))
1101                .then(|| (algo, old_value.to_string(), (*new_value).to_string()))
1102        })
1103        .collect()
1104}
1105
1106/// classifies an SPDX license identifier as copyleft.
1107///
1108/// looks the ID up, ignoring case, in the compile-time SPDX license list and
1109/// returns whether it carries the copyleft flag (the GPL/AGPL/LGPL family, MPL,
1110/// etc.).
1111///
1112/// returns `false` for anything SPDX doesn't recognize — `LicenseRef-`
1113/// identifiers, full license expressions, and free-text names — a conservative
1114/// default so unknown terms never trip a copyleft gate.
1115///
1116/// # Example
1117///
1118/// ```
1119/// use sbom_model::is_copyleft_license;
1120///
1121/// assert!(is_copyleft_license("GPL-3.0-only"));
1122/// assert!(is_copyleft_license("AGPL-3.0-only"));
1123/// assert!(!is_copyleft_license("MIT"));
1124/// assert!(!is_copyleft_license("LicenseRef-proprietary"));
1125/// ```
1126pub fn is_copyleft_license(id: &str) -> bool {
1127    spdx_spelling(id.trim_end_matches('+'))
1128        .and_then(spdx::license_id)
1129        .is_some_and(|l| l.is_copyleft())
1130}
1131
1132/// detects whether a copyleft license was newly introduced between two license sets.
1133///
1134/// returns `true` iff `new` contains a copyleft license (per
1135/// [`is_copyleft_license`]) that is not present in `old`, ignoring case. A
1136/// copyleft license carried over from `old` is not an introduction, and
1137/// permissive-only changes never fire.
1138///
1139/// # Example
1140///
1141/// ```
1142/// use sbom_model::copyleft_introduced;
1143/// use std::collections::BTreeSet;
1144///
1145/// let old: BTreeSet<String> = ["MIT".into()].into();
1146/// let new: BTreeSet<String> = ["GPL-3.0-only".into()].into();
1147/// assert!(copyleft_introduced(&old, &new));
1148///
1149/// let permissive: BTreeSet<String> = ["Apache-2.0".into()].into();
1150/// assert!(!copyleft_introduced(&old, &permissive));
1151/// ```
1152pub fn copyleft_introduced(old: &BTreeSet<String>, new: &BTreeSet<String>) -> bool {
1153    let old: BTreeSet<String> = old.iter().map(|id| canonical_license_case(id)).collect();
1154    new.iter()
1155        .any(|id| is_copyleft_license(id) && !old.contains(&canonical_license_case(id)))
1156}
1157
1158#[cfg(test)]
1159mod tests {
1160    use super::*;
1161
1162    #[test]
1163    fn test_component_id_purl() {
1164        let purl = "pkg:npm/left-pad@1.3.0";
1165        let id = ComponentId::new(Some(purl), &[]);
1166        assert_eq!(id.as_str(), purl);
1167    }
1168
1169    #[test]
1170    fn test_component_id_hash_stability() {
1171        // sha-256 of "name:foo|version:1.0|", pinned so a hasher that varies
1172        // between runs or releases fails here
1173        let id = ComponentId::new(None, &[("name", "foo"), ("version", "1.0")]);
1174        assert_eq!(
1175            id.as_str(),
1176            "h:eed73da1effa1cc3ee0960cb8ab57f84e0994c81c8835e9fb5abd82f47f91aa6"
1177        );
1178    }
1179
1180    #[test]
1181    fn test_normalization() {
1182        let mut comp = Component::new("test".to_string(), Some("1.0".to_string()));
1183        comp.licenses.insert("MIT".to_string());
1184        comp.licenses.insert("Apache-2.0".to_string());
1185        comp.hashes.insert("SHA-256".to_string(), "ABC".to_string());
1186
1187        comp.normalize();
1188
1189        assert_eq!(
1190            comp.licenses,
1191            BTreeSet::from(["Apache-2.0".to_string(), "MIT".to_string()])
1192        );
1193        assert_eq!(comp.hashes.get("sha-256").unwrap(), "abc");
1194    }
1195
1196    fn licensing<'a>(expression: &'a str, ids: &'a BTreeSet<String>) -> Licensing<'a> {
1197        Licensing {
1198            expression: Some(expression),
1199            ids,
1200        }
1201    }
1202
1203    #[test]
1204    fn test_licensing_satisfiable_operators() {
1205        let ids: BTreeSet<String> = ["Apache-2.0".into(), "MIT".into()].into();
1206        let only_mit = |r: &LicenseRequirement| r.license == "MIT";
1207
1208        assert!(licensing("MIT OR Apache-2.0", &ids).satisfiable(only_mit));
1209        assert!(!licensing("MIT AND Apache-2.0", &ids).satisfiable(only_mit));
1210        assert!(licensing("mit OR Apache-2.0", &ids).satisfiable(only_mit));
1211
1212        let nested: BTreeSet<String> =
1213            ["Apache-2.0".into(), "BSD-3-Clause".into(), "MIT".into()].into();
1214        let allowed: BTreeSet<String> = ["BSD-3-Clause".into(), "MIT".into()].into();
1215        assert!(licensing("(MIT OR Apache-2.0) AND BSD-3-Clause", &nested)
1216            .satisfiable(|r| allowed.contains(&r.license)));
1217        assert!(!licensing("(MIT AND Apache-2.0) AND BSD-3-Clause", &nested)
1218            .satisfiable(|r| allowed.contains(&r.license)));
1219    }
1220
1221    #[test]
1222    fn test_licensing_without_expression_is_a_conjunction() {
1223        let ids: BTreeSet<String> = ["Apache-2.0".into(), "MIT".into()].into();
1224        assert!(!Licensing::from_ids(&ids).satisfiable(|r| r.license == "MIT"));
1225        assert!(Licensing::from_ids(&ids).satisfiable(|_| true));
1226    }
1227
1228    #[test]
1229    fn test_licensing_falls_back_on_free_text() {
1230        let ids: BTreeSet<String> = ["Custom License".into()].into();
1231        let free_text = licensing("Custom License", &ids);
1232        assert!(free_text.satisfiable(|r| r.license == "Custom License"));
1233        assert!(!free_text.satisfiable(|_| false));
1234    }
1235
1236    #[test]
1237    fn test_licensing_requirements_keep_exceptions() {
1238        let ids: BTreeSet<String> = ["GPL-2.0-only".into()].into();
1239        let reqs = licensing("GPL-2.0-only WITH Classpath-exception-2.0", &ids).requirements();
1240
1241        assert_eq!(reqs.len(), 1);
1242        let req = reqs.iter().next().unwrap();
1243        assert_eq!(req.license, "GPL-2.0-only");
1244        assert_eq!(req.exception.as_deref(), Some("Classpath-exception-2.0"));
1245        assert_eq!(req.to_string(), "GPL-2.0-only WITH Classpath-exception-2.0");
1246        assert_eq!(
1247            licensing("gpl-2.0-only WITH classpath-exception-2.0", &ids).requirements(),
1248            reqs
1249        );
1250    }
1251
1252    #[test]
1253    fn test_licensing_requirements_keep_or_later() {
1254        let ids: BTreeSet<String> = ["Apache-2.0".into()].into();
1255        let req = licensing("Apache-2.0+", &ids)
1256            .requirements()
1257            .into_iter()
1258            .next()
1259            .unwrap();
1260
1261        assert_eq!(req.license, "Apache-2.0");
1262        assert!(req.or_later);
1263        assert_eq!(req.to_string(), "Apache-2.0+");
1264    }
1265
1266    #[test]
1267    fn test_copyleft_obligations_added_respects_choice() {
1268        let mit: BTreeSet<String> = ["MIT".into()].into();
1269        let both: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1270        let old = licensing("MIT", &mit);
1271
1272        assert!(
1273            copyleft_obligations_added(old, licensing("MIT OR GPL-3.0-only", &both)).is_empty()
1274        );
1275        assert_eq!(
1276            copyleft_obligations_added(old, licensing("MIT AND GPL-3.0-only", &both)),
1277            BTreeSet::from(["GPL-3.0-only".to_string()])
1278        );
1279    }
1280
1281    #[test]
1282    fn test_copyleft_obligations_added_carried_over() {
1283        let gpl: BTreeSet<String> = ["GPL-3.0-only".into()].into();
1284        let both: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1285
1286        assert!(copyleft_obligations_added(
1287            licensing("GPL-3.0-only", &gpl),
1288            licensing("GPL-3.0-only AND MIT", &both)
1289        )
1290        .is_empty());
1291
1292        // a different copyleft license is still a new obligation
1293        let agpl: BTreeSet<String> = ["AGPL-3.0-only".into()].into();
1294        assert_eq!(
1295            copyleft_obligations_added(
1296                licensing("GPL-3.0-only", &gpl),
1297                licensing("AGPL-3.0-only", &agpl)
1298            ),
1299            BTreeSet::from(["AGPL-3.0-only".to_string()])
1300        );
1301    }
1302
1303    #[test]
1304    fn test_copyleft_obligations_added_losing_the_permissive_choice() {
1305        let both: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1306        let gpl: BTreeSet<String> = ["GPL-3.0-only".into()].into();
1307
1308        assert_eq!(
1309            copyleft_obligations_added(
1310                licensing("MIT OR GPL-3.0-only", &both),
1311                licensing("GPL-3.0-only", &gpl)
1312            ),
1313            BTreeSet::from(["GPL-3.0-only".to_string()])
1314        );
1315    }
1316
1317    fn copyleft_added(old: &str, new: &str) -> BTreeSet<String> {
1318        let old_ids = parse_license_expression(old);
1319        let new_ids = parse_license_expression(new);
1320        copyleft_obligations_added(licensing(old, &old_ids), licensing(new, &new_ids))
1321    }
1322
1323    fn licenses(names: &[&str]) -> BTreeSet<String> {
1324        names.iter().map(|n| n.to_string()).collect()
1325    }
1326
1327    #[test]
1328    fn test_copyleft_obligations_added_ignores_a_choice_between_copyleft_licenses() {
1329        for (old, new) in [
1330            (
1331                "GPL-2.0-only OR GPL-3.0-only",
1332                "GPL-2.0-only OR GPL-3.0-only OR LGPL-3.0-only",
1333            ),
1334            (
1335                "MIT AND (GPL-2.0-only OR GPL-3.0-only)",
1336                "Apache-2.0 AND (GPL-2.0-only OR GPL-3.0-only)",
1337            ),
1338            (
1339                "MPL-2.0 OR GPL-2.0-only OR LGPL-2.1-only",
1340                "MPL-2.0 OR GPL-2.0-only OR LGPL-2.1-only",
1341            ),
1342        ] {
1343            assert!(
1344                copyleft_added(old, new).is_empty(),
1345                "{old} -> {new} forces no copyleft the consumer could not already have taken"
1346            );
1347        }
1348    }
1349
1350    #[test]
1351    fn test_copyleft_obligations_added_fires_on_every_tightening() {
1352        for (old, new, introduced) in [
1353            (
1354                "GPL-2.0-only OR GPL-3.0-only",
1355                "GPL-2.0-only AND GPL-3.0-only",
1356                &["GPL-2.0-only", "GPL-3.0-only"][..],
1357            ),
1358            ("MIT OR GPL-3.0-only", "GPL-3.0-only", &["GPL-3.0-only"]),
1359            ("GPL-3.0-only", "AGPL-3.0-only", &["AGPL-3.0-only"]),
1360            ("MIT", "MIT AND GPL-3.0-only", &["GPL-3.0-only"]),
1361            (
1362                "GPL-2.0-only OR GPL-3.0-only",
1363                "AGPL-3.0-only",
1364                &["AGPL-3.0-only"],
1365            ),
1366        ] {
1367            assert_eq!(
1368                copyleft_added(old, new),
1369                licenses(introduced),
1370                "{old} -> {new}"
1371            );
1372        }
1373    }
1374
1375    #[test]
1376    fn test_copyleft_obligations_added_spans_the_minimal_choices_less_what_old_forced() {
1377        for (old, new, introduced) in [
1378            (
1379                "MIT",
1380                "GPL-3.0-only AND (MPL-2.0 OR ISC)",
1381                &["GPL-3.0-only"][..],
1382            ),
1383            (
1384                "GPL-2.0-only",
1385                "GPL-2.0-only AND GPL-3.0-only",
1386                &["GPL-3.0-only"],
1387            ),
1388            (
1389                "MIT",
1390                "GPL-2.0-only OR AGPL-3.0-only",
1391                &["AGPL-3.0-only", "GPL-2.0-only"],
1392            ),
1393            (
1394                "MIT",
1395                "(GPL-3.0-only AND MPL-2.0) OR (AGPL-3.0-only AND EPL-2.0)",
1396                &["AGPL-3.0-only", "GPL-3.0-only", "MPL-2.0"],
1397            ),
1398            ("MIT", "(mit OR gpl-3.0-only) AND mpl-2.0", &["MPL-2.0"]),
1399            ("GPL-2.0+", "gpl-2.0+", &[]),
1400        ] {
1401            assert_eq!(
1402                copyleft_added(old, new),
1403                licenses(introduced),
1404                "{old} -> {new}"
1405            );
1406        }
1407    }
1408
1409    #[test]
1410    fn test_copyleft_obligations_added_falls_back_past_max_choices() {
1411        let wide = "(MIT OR Apache-2.0) AND (BSD-2-Clause OR BSD-3-Clause) \
1412                    AND (ISC OR Zlib) AND (MPL-2.0 OR EPL-2.0) \
1413                    AND (GPL-2.0-only OR GPL-3.0-only) AND (LGPL-2.1-only OR LGPL-3.0-only) \
1414                    AND (CC0-1.0 OR Unlicense)";
1415
1416        assert_eq!(
1417            copyleft_added("MIT", wide),
1418            licenses(&[
1419                "GPL-2.0-only",
1420                "GPL-3.0-only",
1421                "LGPL-2.1-only",
1422                "LGPL-3.0-only",
1423                "MPL-2.0",
1424            ])
1425        );
1426    }
1427
1428    #[test]
1429    fn test_copyleft_obligations_added_matches_flat_sets() {
1430        let old: BTreeSet<String> = ["MIT".into()].into();
1431        let new: BTreeSet<String> = ["GPL-3.0-only".into(), "MIT".into()].into();
1432
1433        assert_eq!(
1434            copyleft_obligations_added(Licensing::from_ids(&old), Licensing::from_ids(&new)),
1435            BTreeSet::from(["GPL-3.0-only".to_string()])
1436        );
1437        assert!(copyleft_introduced(&old, &new));
1438
1439        assert!(
1440            copyleft_obligations_added(Licensing::from_ids(&new), Licensing::from_ids(&new))
1441                .is_empty()
1442        );
1443        assert!(!copyleft_introduced(&new, &new));
1444
1445        let respelled: BTreeSet<String> = ["gpl-3.0-only".into(), "MIT".into()].into();
1446        assert!(copyleft_obligations_added(
1447            Licensing::from_ids(&new),
1448            Licensing::from_ids(&respelled)
1449        )
1450        .is_empty());
1451        assert!(!copyleft_introduced(&new, &respelled));
1452    }
1453
1454    #[test]
1455    fn test_license_expressions_equivalent() {
1456        assert!(license_expressions_equivalent(
1457            "MIT OR Apache-2.0",
1458            "( MIT OR (Apache-2.0) )"
1459        ));
1460        assert!(!license_expressions_equivalent(
1461            "MIT OR Apache-2.0",
1462            "MIT AND Apache-2.0"
1463        ));
1464        assert!(!license_expressions_equivalent(
1465            "GPL-2.0-only",
1466            "GPL-2.0-only WITH Classpath-exception-2.0"
1467        ));
1468        assert!(license_expressions_equivalent("Custom Text", "Custom Text"));
1469        assert!(!license_expressions_equivalent("Custom Text", "Other Text"));
1470    }
1471
1472    #[test]
1473    fn test_license_expressions_equivalent_falls_back_past_max_choices() {
1474        let wide = "(MIT OR Apache-2.0) AND (BSD-2-Clause OR BSD-3-Clause) \
1475                    AND (ISC OR Zlib) AND (MPL-2.0 OR EPL-2.0) \
1476                    AND (GPL-2.0-only OR GPL-3.0-only) AND (LGPL-2.1-only OR LGPL-3.0-only) \
1477                    AND (CC0-1.0 OR Unlicense)";
1478
1479        assert!(license_expressions_equivalent(wide, wide));
1480        assert!(license_expressions_equivalent(
1481            wide,
1482            &wide.replace("(MIT OR Apache-2.0)", "((MIT OR Apache-2.0))")
1483        ));
1484        assert!(!license_expressions_equivalent(
1485            wide,
1486            &wide.replace("MIT OR Apache-2.0", "Apache-2.0 OR MIT")
1487        ));
1488
1489        let ids: BTreeSet<String> = wide
1490            .split_whitespace()
1491            .map(|word| word.trim_matches(['(', ')']).to_string())
1492            .filter(|word| word != "AND" && word != "OR")
1493            .collect();
1494        assert!(!licensings_equivalent(
1495            Licensing {
1496                expression: Some(wide),
1497                ids: &ids,
1498            },
1499            Licensing::from_ids(&ids)
1500        ));
1501    }
1502
1503    #[test]
1504    fn test_license_expressions_equivalent_ignores_operand_order() {
1505        assert!(license_expressions_equivalent(
1506            "MIT OR Apache-2.0",
1507            "Apache-2.0 OR MIT"
1508        ));
1509        assert!(license_expressions_equivalent(
1510            "(MIT OR Apache-2.0) AND BSD-3-Clause",
1511            "(BSD-3-Clause AND Apache-2.0) OR (BSD-3-Clause AND MIT)"
1512        ));
1513        assert!(license_expressions_equivalent(
1514            "MIT",
1515            "MIT OR (MIT AND Apache-2.0)"
1516        ));
1517        assert!(license_expressions_equivalent(
1518            "mit or apache-2.0",
1519            "apache-2.0 or mit"
1520        ));
1521        assert!(!license_expressions_equivalent(
1522            "MIT OR Apache-2.0",
1523            "MIT OR BSD-3-Clause"
1524        ));
1525    }
1526
1527    #[test]
1528    fn test_licensings_equivalent_reads_a_bare_set_as_a_conjunction() {
1529        let ids: BTreeSet<String> = ["GPL-3.0-only".to_string(), "MIT".to_string()].into();
1530        let flat = Licensing::from_ids(&ids);
1531
1532        assert!(licensings_equivalent(
1533            Licensing {
1534                expression: Some("MIT AND GPL-3.0-only"),
1535                ids: &ids,
1536            },
1537            flat
1538        ));
1539        assert!(!licensings_equivalent(
1540            Licensing {
1541                expression: Some("MIT OR GPL-3.0-only"),
1542                ids: &ids,
1543            },
1544            flat
1545        ));
1546        assert!(licensings_equivalent(flat, flat));
1547    }
1548
1549    #[test]
1550    fn test_licensings_equivalent_keeps_decorated_requirements() {
1551        let gpl: BTreeSet<String> = ["GPL-2.0-only".to_string()].into();
1552        assert!(!licensings_equivalent(
1553            Licensing {
1554                expression: Some("GPL-2.0-only WITH Classpath-exception-2.0"),
1555                ids: &gpl,
1556            },
1557            Licensing::from_ids(&gpl)
1558        ));
1559        let apache: BTreeSet<String> = ["Apache-2.0".to_string()].into();
1560        assert!(!licensings_equivalent(
1561            Licensing {
1562                expression: Some("Apache-2.0+"),
1563                ids: &apache,
1564            },
1565            Licensing::from_ids(&apache)
1566        ));
1567    }
1568
1569    #[test]
1570    fn test_licensings_equivalent_falls_back_to_the_identifier_set() {
1571        let ids: BTreeSet<String> = ["Custom Text".to_string()].into();
1572        assert!(licensings_equivalent(
1573            Licensing {
1574                expression: Some("Custom Text"),
1575                ids: &ids,
1576            },
1577            Licensing::from_ids(&ids)
1578        ));
1579    }
1580
1581    #[test]
1582    fn test_component_licensing_defaults_to_ids() {
1583        let mut comp = Component::new("demo".into(), None);
1584        comp.licenses.insert("MIT".into());
1585
1586        assert_eq!(comp.licensing().expression, None);
1587        assert_eq!(
1588            comp.licensing().requirements(),
1589            BTreeSet::from([LicenseRequirement::new("MIT")])
1590        );
1591    }
1592
1593    #[test]
1594    fn test_parse_license_expression() {
1595        for (expr, expected) in [
1596            ("MIT OR Apache-2.0", &["Apache-2.0", "MIT"][..]),
1597            ("MIT", &["MIT"]),
1598            ("MIT AND Apache-2.0", &["Apache-2.0", "MIT"]),
1599            ("mit OR apache-2.0", &["Apache-2.0", "MIT"]),
1600            // invalid expression kept as-is
1601            ("Custom License", &["Custom License"]),
1602            ("LicenseRef-proprietary", &["LicenseRef-proprietary"]),
1603            // LicenseRef mixed with SPDX ids, and several LicenseRefs
1604            (
1605                "LicenseRef-proprietary AND Apache-2.0",
1606                &["Apache-2.0", "LicenseRef-proprietary"],
1607            ),
1608            ("LicenseRef-custom OR MIT", &["LicenseRef-custom", "MIT"]),
1609            (
1610                "LicenseRef-a AND LicenseRef-b",
1611                &["LicenseRef-a", "LicenseRef-b"],
1612            ),
1613            (
1614                "(MIT OR LicenseRef-custom) AND Apache-2.0",
1615                &["Apache-2.0", "LicenseRef-custom", "MIT"],
1616            ),
1617        ] {
1618            let expected: BTreeSet<String> = expected.iter().map(|s| s.to_string()).collect();
1619            assert_eq!(parse_license_expression(expr), expected, "{expr}");
1620        }
1621    }
1622
1623    #[test]
1624    fn test_parse_license_expression_documentref() {
1625        // DocumentRef-prefixed LicenseRef
1626        let ids = parse_license_expression("DocumentRef-ext:LicenseRef-custom");
1627        assert_eq!(
1628            ids,
1629            BTreeSet::from(["DocumentRef-ext:LicenseRef-custom".to_string()])
1630        );
1631    }
1632
1633    #[test]
1634    fn test_query_api() {
1635        let mut sbom = Sbom::default();
1636        let c1 = Component::new("a".into(), Some("1".into()));
1637        let c2 = Component::new("b".into(), Some("1".into()));
1638        let c3 = Component::new("c".into(), Some("1".into()));
1639
1640        let id1 = c1.id.clone();
1641        let id2 = c2.id.clone();
1642        let id3 = c3.id.clone();
1643
1644        sbom.components.insert(id1.clone(), c1);
1645        sbom.components.insert(id2.clone(), c2);
1646        sbom.components.insert(id3.clone(), c3);
1647
1648        // id1 -> id2 -> id3
1649        sbom.dependencies
1650            .entry(id1.clone())
1651            .or_default()
1652            .insert(id2.clone(), DependencyKind::Runtime);
1653        sbom.dependencies
1654            .entry(id2.clone())
1655            .or_default()
1656            .insert(id3.clone(), DependencyKind::Runtime);
1657        sbom.rebuild_reverse_deps();
1658
1659        assert_eq!(sbom.roots(), vec![id1.clone()]);
1660        assert_eq!(sbom.deps(&id1), vec![id2.clone()]);
1661        assert_eq!(sbom.rdeps(&id2), vec![id1.clone()]);
1662
1663        let transitive = sbom.transitive_deps(&id1);
1664        assert!(transitive.contains(&id2));
1665        assert!(transitive.contains(&id3));
1666        assert_eq!(transitive.len(), 2);
1667
1668        assert_eq!(sbom.missing_hashes().len(), 3);
1669    }
1670
1671    #[test]
1672    fn test_ecosystems_query() {
1673        let mut sbom = Sbom::default();
1674
1675        let mut c1 = Component::new("lodash".into(), Some("1.0".into()));
1676        c1.ecosystem = Some("npm".into());
1677        let mut c2 = Component::new("serde".into(), Some("1.0".into()));
1678        c2.ecosystem = Some("cargo".into());
1679        let mut c3 = Component::new("other-npm".into(), Some("1.0".into()));
1680        c3.ecosystem = Some("npm".into());
1681        let c4 = Component::new("no-ecosystem".into(), Some("1.0".into()));
1682
1683        sbom.components.insert(c1.id.clone(), c1);
1684        sbom.components.insert(c2.id.clone(), c2);
1685        sbom.components.insert(c3.id.clone(), c3);
1686        sbom.components.insert(c4.id.clone(), c4);
1687
1688        let ecosystems = sbom.ecosystems();
1689        assert_eq!(ecosystems.len(), 2);
1690        assert!(ecosystems.contains("npm"));
1691        assert!(ecosystems.contains("cargo"));
1692    }
1693
1694    #[test]
1695    fn test_licenses_query() {
1696        let mut sbom = Sbom::default();
1697
1698        let mut c1 = Component::new("a".into(), Some("1.0".into()));
1699        c1.licenses.insert("MIT".into());
1700        c1.licenses.insert("Apache-2.0".into());
1701        let mut c2 = Component::new("b".into(), Some("1.0".into()));
1702        c2.licenses.insert("MIT".into());
1703        c2.licenses.insert("GPL-3.0-only".into());
1704        let c3 = Component::new("c".into(), Some("1.0".into()));
1705
1706        sbom.components.insert(c1.id.clone(), c1);
1707        sbom.components.insert(c2.id.clone(), c2);
1708        sbom.components.insert(c3.id.clone(), c3);
1709
1710        let licenses = sbom.licenses();
1711        assert_eq!(licenses.len(), 3);
1712        assert!(licenses.contains("MIT"));
1713        assert!(licenses.contains("Apache-2.0"));
1714        assert!(licenses.contains("GPL-3.0-only"));
1715    }
1716
1717    #[test]
1718    fn test_by_purl() {
1719        let mut sbom = Sbom::default();
1720
1721        let mut c1 = Component::new("lodash".into(), Some("4.17.21".into()));
1722        c1.purl = Some("pkg:npm/lodash@4.17.21".into());
1723        c1.id = ComponentId::new(c1.purl.as_deref(), &[]);
1724        let c2 = Component::new("no-purl".into(), Some("1.0".into()));
1725
1726        sbom.components.insert(c1.id.clone(), c1);
1727        sbom.components.insert(c2.id.clone(), c2);
1728
1729        let found = sbom.by_purl("pkg:npm/lodash@4.17.21");
1730        assert!(found.is_some());
1731        assert_eq!(found.unwrap().name, "lodash");
1732
1733        assert!(sbom.by_purl("pkg:npm/nonexistent@1.0").is_none());
1734    }
1735
1736    #[test]
1737    fn test_component_id_unparseable_purl() {
1738        // a purl string that can't be parsed should still be used as-is
1739        let id = ComponentId::new(Some("not-a-valid-purl-but-still-a-string"), &[]);
1740        assert_eq!(id.as_str(), "not-a-valid-purl-but-still-a-string");
1741    }
1742
1743    #[test]
1744    fn test_component_id_display() {
1745        let id = ComponentId::new(Some("pkg:npm/foo@1.0"), &[]);
1746        assert_eq!(format!("{}", id), "pkg:npm/foo@1.0");
1747    }
1748
1749    #[test]
1750    fn test_sbom_normalize_clears_metadata() {
1751        let mut sbom = Sbom::default();
1752        sbom.metadata.timestamp = Some("2024-01-01T00:00:00Z".into());
1753        sbom.metadata.tools.push("syft".into());
1754        sbom.metadata.authors.push("alice".into());
1755
1756        let c = Component::new("a".into(), Some("1".into()));
1757        sbom.components.insert(c.id.clone(), c);
1758
1759        sbom.normalize();
1760
1761        assert!(sbom.metadata.timestamp.is_none());
1762        assert!(sbom.metadata.tools.is_empty());
1763        assert!(sbom.metadata.authors.is_empty());
1764    }
1765
1766    #[test]
1767    fn test_missing_hashes_mixed() {
1768        let mut sbom = Sbom::default();
1769
1770        let c1 = Component::new("no-hash".into(), Some("1.0".into()));
1771        let mut c2 = Component::new("has-hash".into(), Some("1.0".into()));
1772        c2.hashes.insert("sha256".into(), "abc".into());
1773
1774        sbom.components.insert(c1.id.clone(), c1);
1775        sbom.components.insert(c2.id.clone(), c2);
1776
1777        let missing = sbom.missing_hashes();
1778        assert_eq!(missing.len(), 1);
1779    }
1780
1781    #[test]
1782    fn test_ecosystem_from_purl() {
1783        use super::ecosystem_from_purl;
1784
1785        assert_eq!(
1786            ecosystem_from_purl("pkg:npm/lodash@4.17.21"),
1787            Some("npm".to_string())
1788        );
1789        assert_eq!(
1790            ecosystem_from_purl("pkg:cargo/serde@1.0.0"),
1791            Some("cargo".to_string())
1792        );
1793        assert_eq!(
1794            ecosystem_from_purl("pkg:pypi/requests@2.28.0"),
1795            Some("pypi".to_string())
1796        );
1797        assert_eq!(
1798            ecosystem_from_purl("pkg:maven/org.apache/commons@1.0"),
1799            Some("maven".to_string())
1800        );
1801        assert_eq!(ecosystem_from_purl("invalid-purl"), None);
1802        assert_eq!(ecosystem_from_purl(""), None);
1803    }
1804
1805    #[test]
1806    fn test_canonical_algorithm_name() {
1807        // SHA family without hyphens (SPDX style)
1808        assert_eq!(canonical_algorithm_name("SHA256"), "SHA-256");
1809        assert_eq!(canonical_algorithm_name("SHA1"), "SHA-1");
1810        assert_eq!(canonical_algorithm_name("SHA384"), "SHA-384");
1811        assert_eq!(canonical_algorithm_name("SHA512"), "SHA-512");
1812        assert_eq!(canonical_algorithm_name("SHA224"), "SHA-224");
1813
1814        // SHA family with hyphens (CycloneDX style)
1815        assert_eq!(canonical_algorithm_name("SHA-256"), "SHA-256");
1816        assert_eq!(canonical_algorithm_name("SHA-1"), "SHA-1");
1817        assert_eq!(canonical_algorithm_name("SHA-384"), "SHA-384");
1818
1819        // case-insensitive
1820        assert_eq!(canonical_algorithm_name("sha256"), "SHA-256");
1821        assert_eq!(canonical_algorithm_name("sha-256"), "SHA-256");
1822
1823        // SHA-3
1824        assert_eq!(canonical_algorithm_name("SHA3-256"), "SHA3-256");
1825        assert_eq!(canonical_algorithm_name("SHA3256"), "SHA3-256");
1826
1827        // MD family
1828        assert_eq!(canonical_algorithm_name("MD5"), "MD5");
1829        assert_eq!(canonical_algorithm_name("md5"), "MD5");
1830
1831        // BLAKE
1832        assert_eq!(canonical_algorithm_name("BLAKE2b-256"), "BLAKE2b-256");
1833        assert_eq!(canonical_algorithm_name("BLAKE2B256"), "BLAKE2b-256");
1834        assert_eq!(canonical_algorithm_name("BLAKE3"), "BLAKE3");
1835
1836        // ADLER
1837        assert_eq!(canonical_algorithm_name("ADLER32"), "ADLER-32");
1838        assert_eq!(canonical_algorithm_name("ADLER-32"), "ADLER-32");
1839
1840        // unknown algorithm passes through
1841        assert_eq!(canonical_algorithm_name("TIGER"), "TIGER");
1842    }
1843
1844    #[test]
1845    fn test_hash_algorithm_strength_ordering() {
1846        // ordering: MD5 < SHA-1 < SHA-224 < SHA-256 < SHA-384 < SHA-512
1847        let md5 = hash_algorithm_strength("MD5").unwrap();
1848        let sha1 = hash_algorithm_strength("SHA-1").unwrap();
1849        let sha224 = hash_algorithm_strength("SHA-224").unwrap();
1850        let sha256 = hash_algorithm_strength("SHA-256").unwrap();
1851        let sha384 = hash_algorithm_strength("SHA-384").unwrap();
1852        let sha512 = hash_algorithm_strength("SHA-512").unwrap();
1853
1854        assert!(md5 < sha1);
1855        assert!(sha1 < sha224);
1856        assert!(sha224 < sha256);
1857        assert!(sha256 < sha384);
1858        assert!(sha384 < sha512);
1859    }
1860
1861    #[test]
1862    fn test_hash_algorithm_strength_variants() {
1863        // case and hyphenation variants resolve to same strength
1864        assert_eq!(
1865            hash_algorithm_strength("sha256"),
1866            hash_algorithm_strength("SHA-256")
1867        );
1868        assert_eq!(
1869            hash_algorithm_strength("sha-1"),
1870            hash_algorithm_strength("SHA1")
1871        );
1872
1873        // SHA-3 at same tier as SHA-2 equivalent
1874        assert_eq!(
1875            hash_algorithm_strength("SHA3-256"),
1876            hash_algorithm_strength("SHA-256")
1877        );
1878        assert_eq!(
1879            hash_algorithm_strength("SHA3-512"),
1880            hash_algorithm_strength("SHA-512")
1881        );
1882
1883        // BLAKE at same tier as SHA-2 equivalent
1884        assert_eq!(
1885            hash_algorithm_strength("BLAKE2b-256"),
1886            hash_algorithm_strength("SHA-256")
1887        );
1888        assert_eq!(
1889            hash_algorithm_strength("BLAKE3"),
1890            hash_algorithm_strength("SHA-256")
1891        );
1892
1893        // unknown returns None
1894        assert_eq!(hash_algorithm_strength("TIGER"), None);
1895        assert_eq!(hash_algorithm_strength("UNKNOWN"), None);
1896    }
1897
1898    #[test]
1899    fn test_hash_algorithm_strength_adler() {
1900        let adler = hash_algorithm_strength("ADLER-32").unwrap();
1901        let md5 = hash_algorithm_strength("MD5").unwrap();
1902        assert!(adler < md5);
1903    }
1904
1905    #[test]
1906    fn test_is_hash_algorithm_downgrade() {
1907        fn hashes(algs: &[&str]) -> BTreeMap<String, String> {
1908            algs.iter()
1909                .map(|a| (a.to_string(), "abc".to_string()))
1910                .collect()
1911        }
1912        for (old, new, expected) in [
1913            (&["sha-256"][..], &["md5"][..], true),
1914            (&["sha-1"], &["sha-256"], false),
1915            (&["sha-256"], &["sha-256"], false),
1916            (&[], &["md5"], false),
1917            (&["sha-256"], &[], false),
1918            // the strongest algorithm was dropped
1919            (&["sha-256", "md5"], &["md5"], true),
1920            // the strongest algorithm was kept
1921            (&["sha-256", "md5"], &["sha-256", "sha-1"], false),
1922            // only unknown algorithms: no ordering
1923            (&["TIGER"], &["WHIRLPOOL"], false),
1924        ] {
1925            assert_eq!(
1926                is_hash_algorithm_downgrade(&hashes(old), &hashes(new)),
1927                expected,
1928                "{old:?} -> {new:?}"
1929            );
1930        }
1931    }
1932
1933    #[test]
1934    fn test_detect_cycles_none() {
1935        let mut sbom = Sbom::default();
1936        let c1 = Component::new("a".into(), Some("1".into()));
1937        let c2 = Component::new("b".into(), Some("1".into()));
1938        let c3 = Component::new("c".into(), Some("1".into()));
1939
1940        let id1 = c1.id.clone();
1941        let id2 = c2.id.clone();
1942        let id3 = c3.id.clone();
1943
1944        sbom.components.insert(id1.clone(), c1);
1945        sbom.components.insert(id2.clone(), c2);
1946        sbom.components.insert(id3.clone(), c3);
1947
1948        // a -> b -> c (no cycle)
1949        sbom.dependencies
1950            .entry(id1.clone())
1951            .or_default()
1952            .insert(id2.clone(), DependencyKind::Runtime);
1953        sbom.dependencies
1954            .entry(id2.clone())
1955            .or_default()
1956            .insert(id3.clone(), DependencyKind::Runtime);
1957
1958        assert!(sbom.detect_cycles().is_empty());
1959    }
1960
1961    #[test]
1962    fn test_detect_cycles_simple() {
1963        let mut sbom = Sbom::default();
1964        let c1 = Component::new("a".into(), Some("1".into()));
1965        let c2 = Component::new("b".into(), Some("1".into()));
1966
1967        let id1 = c1.id.clone();
1968        let id2 = c2.id.clone();
1969
1970        sbom.components.insert(id1.clone(), c1);
1971        sbom.components.insert(id2.clone(), c2);
1972
1973        // a -> b -> a (cycle)
1974        sbom.dependencies
1975            .entry(id1.clone())
1976            .or_default()
1977            .insert(id2.clone(), DependencyKind::Runtime);
1978        sbom.dependencies
1979            .entry(id2.clone())
1980            .or_default()
1981            .insert(id1.clone(), DependencyKind::Runtime);
1982
1983        let cycles = sbom.detect_cycles();
1984        assert_eq!(cycles.len(), 1);
1985        // cycle should start and end with the same node
1986        assert_eq!(cycles[0].first(), cycles[0].last());
1987    }
1988
1989    #[test]
1990    fn test_detect_cycles_self_loop() {
1991        let mut sbom = Sbom::default();
1992        let c1 = Component::new("a".into(), Some("1".into()));
1993        let id1 = c1.id.clone();
1994        sbom.components.insert(id1.clone(), c1);
1995
1996        // a -> a (self-loop)
1997        sbom.dependencies
1998            .entry(id1.clone())
1999            .or_default()
2000            .insert(id1.clone(), DependencyKind::Runtime);
2001
2002        let cycles = sbom.detect_cycles();
2003        assert_eq!(cycles.len(), 1);
2004        assert_eq!(cycles[0].len(), 2); // [a, a]
2005    }
2006
2007    #[test]
2008    fn test_detect_cycles_empty_graph() {
2009        let sbom = Sbom::default();
2010        assert!(sbom.detect_cycles().is_empty());
2011    }
2012
2013    #[test]
2014    fn test_insert_component_keeps_replaced_source_ids() {
2015        let entry = |name: &str, source_ids: &[&str]| {
2016            let mut c = Component::new("dup".into(), Some("1".into()));
2017            c.description = Some(name.into());
2018            c.source_ids = source_ids.iter().map(|s| s.to_string()).collect();
2019            c
2020        };
2021        let mut sbom = Sbom::default();
2022        assert!(sbom
2023            .insert_component(entry("first", &["ref-c", "ref-a"]))
2024            .is_none());
2025        let replaced = sbom
2026            .insert_component(entry("second", &["ref-b", "ref-a"]))
2027            .unwrap();
2028        assert_eq!(replaced.description.as_deref(), Some("first"));
2029        assert_eq!(sbom.components.len(), 1);
2030        assert_eq!(sbom.components[0].description.as_deref(), Some("second"));
2031        assert_eq!(
2032            sbom.components[0].source_ids,
2033            vec!["ref-a", "ref-b", "ref-c"]
2034        );
2035    }
2036
2037    #[test]
2038    fn test_insert_dependency_kind_does_not_depend_on_order() {
2039        let parent = Component::new("parent".into(), None).id;
2040        let child = Component::new("child".into(), None).id;
2041        for kinds in [
2042            [DependencyKind::Optional, DependencyKind::Runtime],
2043            [DependencyKind::Runtime, DependencyKind::Optional],
2044        ] {
2045            let mut sbom = Sbom::default();
2046            for kind in kinds {
2047                sbom.insert_dependency(parent.clone(), child.clone(), kind);
2048            }
2049            assert_eq!(
2050                sbom.dependencies[&parent],
2051                BTreeMap::from([(child.clone(), DependencyKind::Runtime)])
2052            );
2053        }
2054
2055        let mut sbom = Sbom::default();
2056        sbom.insert_dependency(parent.clone(), child.clone(), DependencyKind::Test);
2057        sbom.insert_dependency(parent.clone(), child.clone(), DependencyKind::Dev);
2058        assert_eq!(sbom.dependencies[&parent][&child], DependencyKind::Dev);
2059    }
2060
2061    #[test]
2062    fn test_detect_cycles_three_node() {
2063        let mut sbom = Sbom::default();
2064        let c1 = Component::new("a".into(), Some("1".into()));
2065        let c2 = Component::new("b".into(), Some("1".into()));
2066        let c3 = Component::new("c".into(), Some("1".into()));
2067
2068        let id1 = c1.id.clone();
2069        let id2 = c2.id.clone();
2070        let id3 = c3.id.clone();
2071
2072        sbom.components.insert(id1.clone(), c1);
2073        sbom.components.insert(id2.clone(), c2);
2074        sbom.components.insert(id3.clone(), c3);
2075
2076        // a -> b -> c -> a (three-node cycle)
2077        sbom.dependencies
2078            .entry(id1.clone())
2079            .or_default()
2080            .insert(id2.clone(), DependencyKind::Runtime);
2081        sbom.dependencies
2082            .entry(id2.clone())
2083            .or_default()
2084            .insert(id3.clone(), DependencyKind::Runtime);
2085        sbom.dependencies
2086            .entry(id3.clone())
2087            .or_default()
2088            .insert(id1.clone(), DependencyKind::Runtime);
2089
2090        let cycles = sbom.detect_cycles();
2091        assert_eq!(cycles.len(), 1);
2092        assert_eq!(cycles[0].first(), cycles[0].last());
2093        assert_eq!(cycles[0].len(), 4); // [a, b, c, a]
2094    }
2095
2096    #[test]
2097    fn test_changed_checksums_same_algorithm_different_value() {
2098        let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2099        let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
2100        assert_eq!(
2101            changed_checksums(&old, &new),
2102            vec![("SHA-256".to_string(), "abc".to_string(), "def".to_string())]
2103        );
2104    }
2105
2106    #[test]
2107    fn test_changed_checksums_identical_values() {
2108        let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2109        assert!(changed_checksums(&old, &old).is_empty());
2110    }
2111
2112    #[test]
2113    fn test_changed_checksums_case_only_difference() {
2114        let old: BTreeMap<String, String> = [("sha-256".into(), "ABCDEF".into())].into();
2115        let new: BTreeMap<String, String> = [("sha-256".into(), "abcdef".into())].into();
2116        assert!(changed_checksums(&old, &new).is_empty());
2117    }
2118
2119    #[test]
2120    fn test_changed_checksums_ignores_surrounding_whitespace() {
2121        let old: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2122        let new: BTreeMap<String, String> = [("sha-256".into(), "  abc\n".into())].into();
2123        assert!(changed_checksums(&old, &new).is_empty());
2124    }
2125
2126    #[test]
2127    fn test_changed_checksums_disjoint_algorithms() {
2128        let old: BTreeMap<String, String> = [("sha-1".into(), "abc".into())].into();
2129        let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
2130        assert!(changed_checksums(&old, &new).is_empty());
2131    }
2132
2133    #[test]
2134    fn test_changed_checksums_only_compares_shared_algorithms() {
2135        let old: BTreeMap<String, String> = [
2136            ("sha-1".into(), "aaa".into()),
2137            ("sha-256".into(), "bbb".into()),
2138        ]
2139        .into();
2140        let new: BTreeMap<String, String> = [
2141            ("sha-256".into(), "ccc".into()),
2142            ("sha-512".into(), "ddd".into()),
2143        ]
2144        .into();
2145        assert_eq!(
2146            changed_checksums(&old, &new),
2147            vec![("SHA-256".to_string(), "bbb".to_string(), "ccc".to_string())]
2148        );
2149    }
2150
2151    #[test]
2152    fn test_changed_checksums_pairs_across_algorithm_spellings() {
2153        let old: BTreeMap<String, String> = [("SHA256".into(), "abc".into())].into();
2154        let new: BTreeMap<String, String> = [("sha-256".into(), "def".into())].into();
2155        assert_eq!(
2156            changed_checksums(&old, &new),
2157            vec![("SHA-256".to_string(), "abc".to_string(), "def".to_string())]
2158        );
2159    }
2160
2161    #[test]
2162    fn test_changed_checksums_unknown_algorithm_pairs_by_name() {
2163        let old: BTreeMap<String, String> = [("tiger".into(), "abc".into())].into();
2164        let new: BTreeMap<String, String> = [("tiger".into(), "def".into())].into();
2165        assert_eq!(
2166            changed_checksums(&old, &new),
2167            vec![("tiger".to_string(), "abc".to_string(), "def".to_string())]
2168        );
2169    }
2170
2171    #[test]
2172    fn test_changed_checksums_empty_sides() {
2173        let empty: BTreeMap<String, String> = BTreeMap::new();
2174        let some: BTreeMap<String, String> = [("sha-256".into(), "abc".into())].into();
2175        assert!(changed_checksums(&empty, &some).is_empty());
2176        assert!(changed_checksums(&some, &empty).is_empty());
2177    }
2178
2179    #[test]
2180    fn test_changed_checksums_reports_every_mismatching_algorithm() {
2181        let old: BTreeMap<String, String> = [
2182            ("sha-256".into(), "aaa".into()),
2183            ("sha-512".into(), "bbb".into()),
2184        ]
2185        .into();
2186        let new: BTreeMap<String, String> = [
2187            ("sha-256".into(), "ccc".into()),
2188            ("sha-512".into(), "ddd".into()),
2189        ]
2190        .into();
2191        assert_eq!(
2192            changed_checksums(&old, &new),
2193            vec![
2194                ("SHA-256".to_string(), "aaa".to_string(), "ccc".to_string()),
2195                ("SHA-512".to_string(), "bbb".to_string(), "ddd".to_string()),
2196            ]
2197        );
2198    }
2199
2200    #[test]
2201    fn test_is_copyleft_license() {
2202        // GPL family and its relatives are copyleft
2203        assert!(is_copyleft_license("GPL-3.0-only"));
2204        assert!(is_copyleft_license("AGPL-3.0-only"));
2205        assert!(is_copyleft_license("LGPL-3.0-only"));
2206        assert!(is_copyleft_license("gpl-3.0-only"));
2207        assert!(is_copyleft_license("mpl-2.0+"));
2208        // permissive licenses are not
2209        assert!(!is_copyleft_license("MIT"));
2210        assert!(!is_copyleft_license("Apache-2.0"));
2211        assert!(!is_copyleft_license("BSD-3-Clause"));
2212        // LicenseRef and unrecognized ids are conservatively not copyleft
2213        assert!(!is_copyleft_license("LicenseRef-proprietary"));
2214        assert!(!is_copyleft_license("NOT-A-LICENSE"));
2215    }
2216
2217    #[test]
2218    fn test_copyleft_introduced_added_alongside_existing() {
2219        // a second, newly added copyleft id fires even when old already had one
2220        let old: BTreeSet<String> = ["GPL-3.0-only".into()].into();
2221        let new: BTreeSet<String> = ["GPL-3.0-only".into(), "AGPL-3.0-only".into()].into();
2222        assert!(copyleft_introduced(&old, &new));
2223    }
2224}