Skip to main content

sbom_model/
lib.rs

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