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