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