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