fix(sbom): known licence names are exported as SPDX ids (#543)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m51s
CI / Deploy MCP (push) Successful in 3m26s
CI / Deploy Agent (push) Successful in 8m27s

This commit was merged in pull request #543.
This commit is contained in:
sharang committed 2026-10-09 13:39:28 +00:00
1 parent 44b2f38841
commit 2c2fea6222
5 files changed
+552 -103

No files matched your search

@@ -475,54 +475,12 @@ pub(super) fn license_from_url(url: &str) -> Option<String> {
{
return Some(expression);
}
let page = bare
.trim_end_matches(".php")
.trim_end_matches(".html")
.trim_end_matches(".txt")
.trim_end_matches(".md");
let known = WELL_KNOWN_URLS
.iter()
.find(|(prefix, _)| page == *prefix)
.map(|(_, spdx)| (*spdx).to_string());
Some(known.unwrap_or_else(|| url.to_string()))
Some(
compliance_core::spdx_license::spdx_of_url(url)
.map_or_else(|| url.to_string(), str::to_string),
)
}
/// License pages (lowercase, without scheme, `www.`, trailing slash and
/// `.html`/`.php`/`.txt`) and the SPDX id they stand for.
const WELL_KNOWN_URLS: &[(&str, &str)] = &[
("opensource.org/licenses/mit", "MIT"),
("opensource.org/licenses/mit-license", "MIT"),
("opensource.org/license/mit", "MIT"),
("choosealicense.com/licenses/mit", "MIT"),
("opensource.org/licenses/apache-2.0", "Apache-2.0"),
("opensource.org/license/apache-2-0", "Apache-2.0"),
("apache.org/licenses/license-2.0", "Apache-2.0"),
("choosealicense.com/licenses/apache-2.0", "Apache-2.0"),
("opensource.org/licenses/bsd-license", "BSD-3-Clause"),
("opensource.org/licenses/bsd-3-clause", "BSD-3-Clause"),
("opensource.org/licenses/bsd-2-clause", "BSD-2-Clause"),
("opensource.org/licenses/ms-pl", "MS-PL"),
("opensource.org/licenses/ms-rl", "MS-RL"),
("microsoft.com/opensource/licenses.mspx#ms-pl", "MS-PL"),
("opensource.org/licenses/mpl-2.0", "MPL-2.0"),
("mozilla.org/mpl/2.0", "MPL-2.0"),
("opensource.org/licenses/isc", "ISC"),
("opensource.org/licenses/zlib", "Zlib"),
("opensource.org/licenses/lgpl-2.1", "LGPL-2.1-only"),
("opensource.org/licenses/lgpl-3.0", "LGPL-3.0-only"),
("gnu.org/licenses/lgpl-2.1", "LGPL-2.1-only"),
("gnu.org/licenses/old-licenses/lgpl-2.1", "LGPL-2.1-only"),
("gnu.org/licenses/lgpl-3.0", "LGPL-3.0-only"),
("gnu.org/licenses/lgpl", "LGPL-3.0-or-later"),
("gnu.org/licenses/gpl-2.0", "GPL-2.0-only"),
("gnu.org/licenses/old-licenses/gpl-2.0", "GPL-2.0-only"),
("gnu.org/licenses/gpl-3.0", "GPL-3.0-only"),
("gnu.org/licenses/gpl", "GPL-3.0-or-later"),
("gnu.org/licenses/agpl-3.0", "AGPL-3.0-only"),
("gnu.org/licenses/agpl", "AGPL-3.0-or-later"),
("unlicense.org", "Unlicense"),
];
/// `%XX` escapes decoded (the expressions nuget.org puts in a URL path).
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
@@ -762,7 +762,8 @@ fn pom_license(text: &str) -> PomLicense {
let name = child(license, "name");
let url = child(license, "url");
name.as_deref()
.and_then(spdx_of_name)
.and_then(compliance_core::spdx_license::spdx_of_name)
.map(str::to_string)
.or_else(|| {
url.as_deref()
.and_then(license_from_url)
@@ -790,31 +791,6 @@ fn pom_license(text: &str) -> PomLicense {
}
}
/// The SPDX id of a license as POMs commonly name it.
fn spdx_of_name(name: &str) -> Option<String> {
let n = name.to_ascii_lowercase();
let id = if n.contains("apache") && n.contains("2") {
"Apache-2.0"
} else if n == "mit" || n.contains("mit license") {
"MIT"
} else if n.contains("bsd") && (n.contains("3") || n.contains("new") || n.contains("revised")) {
"BSD-3-Clause"
} else if n.contains("bsd") && (n.contains("2") || n.contains("simplified")) {
"BSD-2-Clause"
} else if n.contains("eclipse public license") && n.contains("2") {
"EPL-2.0"
} else if n.contains("eclipse public license") && n.contains("1") {
"EPL-1.0"
} else if n.contains("eclipse distribution license") {
"BSD-3-Clause"
} else if n.contains("mozilla public license") && n.contains("2") {
"MPL-2.0"
} else {
return None;
};
Some(id.to_string())
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
+1
View File
@@ -13,6 +13,7 @@ pub mod net_guard;
pub mod purl;
pub mod sbom_docs;
pub mod scan_matrix;
pub mod spdx_license;
#[cfg(feature = "telemetry")]
pub mod telemetry;
pub mod tenant;
+65 -31
View File
@@ -10,6 +10,7 @@
use crate::models::{advisory_source, is_cve, ComponentHash, SbomEntry};
use crate::purl::Purl;
use crate::spdx_license;
/// The `bom-ref` of a component, which a VEX statement refers to: its purl,
/// or `<package manager>:<name>@<version>` without one.
@@ -35,36 +36,16 @@ pub fn product_ref(subject: &str) -> String {
format!("pkg:generic/{encoded}")
}
/// The SPDX license ids CycloneDX accepts as `license.id` (its own copy of
/// the SPDX list).
fn spdx_ids() -> &'static std::collections::HashSet<String> {
static IDS: std::sync::LazyLock<std::collections::HashSet<String>> =
std::sync::LazyLock::new(|| {
serde_json::from_str::<serde_json::Value>(include_str!("../schemas/spdx.schema.json"))
.ok()
.and_then(|schema| {
schema["enum"].as_array().map(|ids| {
ids.iter()
.filter_map(|id| id.as_str().map(str::to_string))
.collect()
})
})
.unwrap_or_default()
});
&IDS
}
/// A license as CycloneDX writes it: an SPDX id it knows, an SPDX expression
/// (`MIT OR Apache-2.0`), or a named license. It is the license the supplier
/// declares (registry or lockfile metadata): Prüfwerk has not concluded it.
/// A license as CycloneDX writes it: an SPDX id, an SPDX expression
/// (`MIT OR Apache-2.0`), or a named license. A name or URL of a license
/// SPDX lists becomes its id ([`spdx_license::normalise`], BSI TR-03183-2).
/// It is the license the supplier declares (registry or lockfile metadata):
/// Prüfwerk has not concluded it.
fn license_choice(license: &str) -> serde_json::Value {
let license = license.trim();
if spdx_ids().contains(license) {
let license = spdx_license::normalise(license);
if spdx_license::canonical_id(&license) == Some(&*license) {
serde_json::json!([{ "license": { "id": license, "acknowledgement": "declared" } }])
} else if [" OR ", " AND ", " WITH "]
.iter()
.any(|op| license.contains(op))
{
} else if spdx_license::has_operator(&license) {
serde_json::json!([{ "expression": license, "acknowledgement": "declared" }])
} else {
serde_json::json!([{ "license": { "name": license, "acknowledgement": "declared" } }])
@@ -348,18 +329,32 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
.iter()
.enumerate()
.map(|(i, e)| {
serde_json::json!({
// SPDX takes only an expression of listed ids here; another
// license is NOASSERTION, its text kept as a comment.
let raw = e
.license
.as_deref()
.map(str::trim)
.filter(|l| !l.is_empty());
let license = raw
.map(spdx_license::normalise)
.filter(|l| spdx_license::is_spdx_expression(l));
let mut package = serde_json::json!({
"SPDXID": format!("SPDXRef-Package-{i}"),
"name": e.name,
"versionInfo": e.version,
"downloadLocation": "NOASSERTION",
"licenseConcluded": e.license.as_deref().unwrap_or("NOASSERTION"),
"licenseConcluded": license.as_deref().unwrap_or("NOASSERTION"),
"externalRefs": e.purl.as_ref().map(|p| vec![serde_json::json!({
"referenceCategory": "PACKAGE-MANAGER",
"referenceType": "purl",
"referenceLocator": p,
})]).unwrap_or_default(),
})
});
if let (Some(raw), None) = (raw, &license) {
package["licenseComments"] = serde_json::Value::String(format!("Declared: {raw}"));
}
package
})
.collect();
@@ -391,4 +386,43 @@ mod tests {
assert_eq!(spdx["spdxVersion"], "SPDX-2.3");
assert_eq!(spdx["packages"][0]["versionInfo"], "2.1.2");
}
#[test]
fn known_license_names_are_exported_as_spdx_ids() {
let entries: Vec<SbomEntry> = [
"The Apache Software License, Version 2.0",
"https://opensource.org/licenses/MIT",
"Custom Pump License",
"MIT OR Apache-2.0",
]
.into_iter()
.enumerate()
.map(|(i, license)| {
let mut e = SbomEntry::new("t".into(), format!("c{i}"), "1".into(), "maven".into());
e.license = Some(license.into());
e
})
.collect();
let cdx = cyclonedx(&entries, "t");
let licenses = |i: usize| &cdx["components"][i]["licenses"][0];
assert_eq!(licenses(0)["license"]["id"], "Apache-2.0");
assert!(licenses(0)["license"].get("name").is_none());
assert_eq!(licenses(1)["license"]["id"], "MIT");
assert_eq!(licenses(2)["license"]["name"], "Custom Pump License");
assert!(licenses(2)["license"].get("id").is_none());
assert_eq!(licenses(3)["expression"], "MIT OR Apache-2.0");
let spdx = spdx(&entries, "t");
let package = |i: usize| &spdx["packages"][i];
assert_eq!(package(0)["licenseConcluded"], "Apache-2.0");
assert_eq!(package(1)["licenseConcluded"], "MIT");
assert_eq!(package(2)["licenseConcluded"], "NOASSERTION");
assert_eq!(
package(2)["licenseComments"],
"Declared: Custom Pump License"
);
assert_eq!(package(3)["licenseConcluded"], "MIT OR Apache-2.0");
assert!(package(3).get("licenseComments").is_none());
}
}
+480
View File
@@ -0,0 +1,480 @@
//! Licences as SPDX ids (BSI TR-03183-2): the SPDX license list, and the
//! ids of the licences registries and manifests name in prose or by URL.
//!
//! Maven POMs in particular say "The Apache Software License, Version 2.0" or
//! give only `https://www.apache.org/licenses/LICENSE-2.0.txt`; the SBOM
//! exports ([`crate::sbom_docs`]) write those as `Apache-2.0`. A name this
//! module does not know stays as written: a guessed id would be worse than a
//! name.
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::LazyLock;
/// The SPDX license and exception ids (CycloneDX's copy of the SPDX list),
/// keyed by their lowercase form: SPDX ids match case-insensitively.
static SPDX_IDS: LazyLock<HashMap<String, String>> = LazyLock::new(|| {
serde_json::from_str::<serde_json::Value>(include_str!("../schemas/spdx.schema.json"))
.ok()
.and_then(|schema| {
schema["enum"].as_array().map(|ids| {
ids.iter()
.filter_map(serde_json::Value::as_str)
.map(|id| (id.to_ascii_lowercase(), id.to_string()))
.collect()
})
})
.unwrap_or_default()
});
/// The operators of an SPDX license expression.
const OPERATORS: [&str; 3] = ["AND", "OR", "WITH"];
/// The operators as they stand between two terms of an expression.
const SPACED_OPERATORS: [&str; 3] = [" AND ", " OR ", " WITH "];
/// The SPDX id `text` is, in its canonical casing (`apache-2.0` is
/// `Apache-2.0`); `None` when it is no SPDX license or exception id.
pub fn canonical_id(text: &str) -> Option<&'static str> {
SPDX_IDS
.get(&text.trim().to_ascii_lowercase())
.map(String::as_str)
}
/// Whether `text` is an SPDX license expression of known ids
/// (`MIT`, `(MIT OR Apache-2.0)`, `GPL-2.0-only WITH Classpath-exception-2.0`).
/// `LicenseRef-` ids are not, as they need a definition beside them.
pub fn is_spdx_expression(text: &str) -> bool {
let mut tokens = text
.split(|c: char| c.is_whitespace() || c == '(' || c == ')')
.filter(|t| !t.is_empty())
.peekable();
tokens.peek().is_some()
&& tokens.all(|t| {
OPERATORS.contains(&t) || canonical_id(t.strip_suffix('+').unwrap_or(t)).is_some()
})
}
/// The licence written as SPDX where it is known: an SPDX id in canonical
/// casing, the id of a licence name or licence page URL. An expression or a
/// `LicenseRef-` stays as it is, and so does a name or URL this module does
/// not know.
///
/// # Examples
///
/// ```
/// use compliance_core::spdx_license::normalise;
///
/// assert_eq!(normalise("The Apache Software License, Version 2.0"), "Apache-2.0");
/// assert_eq!(normalise("https://opensource.org/licenses/MIT"), "MIT");
/// assert_eq!(normalise("MIT OR Apache-2.0"), "MIT OR Apache-2.0");
/// assert_eq!(normalise("Custom Pump License"), "Custom Pump License");
/// ```
pub fn normalise(license: &str) -> Cow<'_, str> {
let license = license.trim();
if let Some(id) = canonical_id(license) {
return Cow::Borrowed(id);
}
let is_expression = license.starts_with("LicenseRef-") || has_operator(license);
let known = if is_expression {
None
} else if is_url(license) {
spdx_of_url(license)
} else {
spdx_of_name(license)
};
// `Cow` (clone-on-write) lends the input back when nothing changed and
// only owns a value when it did; here every known id is a `'static str`.
known.map_or(Cow::Borrowed(license), Cow::Borrowed)
}
/// Whether `text` joins terms with an SPDX operator (`MIT OR Apache-2.0`),
/// as an expression does.
pub fn has_operator(text: &str) -> bool {
SPACED_OPERATORS.iter().any(|op| text.contains(op))
}
/// Whether `text` looks like a URL rather than a licence name.
fn is_url(text: &str) -> bool {
let lower = text.to_ascii_lowercase();
lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("www.")
}
/// The SPDX id of a licence page: a well-known page, or an
/// `opensource.org/licenses/<id>` or `spdx.org/licenses/<id>` page.
pub fn spdx_of_url(url: &str) -> Option<&'static str> {
let lower = url.trim().to_ascii_lowercase();
let bare = lower
.trim_start_matches("https://")
.trim_start_matches("http://")
.trim_start_matches("www.")
.trim_end_matches('/');
let page = [".php", ".html", ".htm", ".txt", ".md"]
.iter()
.find_map(|ext| bare.strip_suffix(ext))
.unwrap_or(bare);
WELL_KNOWN_URLS
.iter()
.find(|(known, _)| page == *known)
.map(|(_, id)| *id)
.or_else(|| {
[
"opensource.org/licenses/",
"opensource.org/license/",
"spdx.org/licenses/",
]
.iter()
.find_map(|prefix| page.strip_prefix(prefix))
.and_then(canonical_id)
})
}
/// License pages (lowercase, without scheme, `www.`, trailing slash and
/// `.html`/`.php`/`.txt`) and the SPDX id they stand for.
const WELL_KNOWN_URLS: &[(&str, &str)] = &[
("opensource.org/licenses/mit-license", "MIT"),
("opensource.org/license/mit", "MIT"),
("choosealicense.com/licenses/mit", "MIT"),
("opensource.org/license/apache-2-0", "Apache-2.0"),
("apache.org/licenses/license-2.0", "Apache-2.0"),
("choosealicense.com/licenses/apache-2.0", "Apache-2.0"),
("opensource.org/licenses/bsd-license", "BSD-3-Clause"),
("microsoft.com/opensource/licenses.mspx#ms-pl", "MS-PL"),
("mozilla.org/mpl/2.0", "MPL-2.0"),
("opensource.org/licenses/lgpl-2.1", "LGPL-2.1-only"),
("opensource.org/licenses/lgpl-3.0", "LGPL-3.0-only"),
("gnu.org/licenses/lgpl-2.1", "LGPL-2.1-only"),
("gnu.org/licenses/old-licenses/lgpl-2.1", "LGPL-2.1-only"),
("gnu.org/licenses/lgpl-3.0", "LGPL-3.0-only"),
("gnu.org/licenses/lgpl", "LGPL-3.0-or-later"),
("opensource.org/licenses/gpl-2.0", "GPL-2.0-only"),
("opensource.org/licenses/gpl-3.0", "GPL-3.0-only"),
("gnu.org/licenses/gpl-2.0", "GPL-2.0-only"),
("gnu.org/licenses/old-licenses/gpl-2.0", "GPL-2.0-only"),
("gnu.org/licenses/gpl-3.0", "GPL-3.0-only"),
("gnu.org/licenses/gpl", "GPL-3.0-or-later"),
("gnu.org/licenses/agpl-3.0", "AGPL-3.0-only"),
("gnu.org/licenses/agpl", "AGPL-3.0-or-later"),
("eclipse.org/legal/epl-2.0", "EPL-2.0"),
("eclipse.org/legal/epl-v20", "EPL-2.0"),
("eclipse.org/legal/epl-v10", "EPL-1.0"),
("eclipse.org/org/documents/edl-v10", "BSD-3-Clause"),
("creativecommons.org/publicdomain/zero/1.0", "CC0-1.0"),
(
"creativecommons.org/publicdomain/zero/1.0/legalcode",
"CC0-1.0",
),
("boost.org/license_1_0", "BSL-1.0"),
("unlicense.org", "Unlicense"),
];
/// The words of a licence name, lowercase: punctuation separates words, and
/// so does a letter followed by a digit (`GPLv2` is `gpl 2`, `2.1` is
/// `2 1`); a `v` before a version (`v2`, `gplv3`) is dropped.
fn words(name: &str) -> Vec<String> {
let mut spaced = String::with_capacity(name.len() * 2);
let mut previous = ' ';
for c in name.chars().map(|c| c.to_ascii_lowercase()) {
if c.is_ascii_digit() && previous.is_ascii_alphabetic() {
spaced.push(' ');
}
spaced.push(if c.is_ascii_alphanumeric() { c } else { ' ' });
previous = c;
}
spaced
.split_whitespace()
.map(|w| match w.strip_suffix('v') {
// `gplv` (from `gplv3`) is `gpl`; `v` alone is the version mark.
Some(family @ ("gpl" | "lgpl" | "agpl" | "epl" | "mpl" | "")) => family.to_string(),
_ => w.to_string(),
})
.filter(|w| !w.is_empty())
.collect()
}
/// The version a licence name states: the first number and the one after it
/// (`2.1` is `(2, Some(1))`, `Version 2` is `(2, None)`).
fn version(words: &[String]) -> Option<(u32, Option<u32>)> {
let at = words
.iter()
.position(|w| w.chars().all(|c| c.is_ascii_digit()))?;
let major = words[at].parse().ok()?;
let minor = words
.get(at + 1)
.filter(|w| w.chars().all(|c| c.is_ascii_digit()))
.and_then(|w| w.parse().ok());
Some((major, minor))
}
/// The SPDX id (or, for the GPL with the Classpath exception, expression) of
/// a licence as registries and POMs name it: "Apache License, Version 2.0",
/// "The MIT License", "GNU Lesser General Public License v2.1", ... Case,
/// punctuation, "The" and "Version"/"v" do not matter. A family without the
/// version it needs ("GPL", "BSD License") or a name with two licences in it
/// is `None`.
pub fn spdx_of_name(name: &str) -> Option<&'static str> {
let words = words(name);
let has = |w: &str| words.iter().any(|x| x == w);
// Padded with spaces so that a phrase matches whole words only.
let joined = format!(" {} ", words.join(" "));
let phrase = |p: &str| joined.contains(&format!(" {p} "));
let version = version(&words);
let (major, minor) = version.map_or((None, None), |(major, minor)| (Some(major), minor));
let later = has("later") || (name.contains('+') && !name.contains(" + "));
let gnu =
|only: &'static str, or_later: &'static str| Some(if later { or_later } else { only });
let gpl = has("gpl") || phrase("general public");
let lgpl = has("lgpl") || phrase("lesser general public") || phrase("library general public");
let agpl = has("agpl") || has("affero");
// A dual licence ("CDDL + GPLv2 with classpath exception") is two
// licences; its name stays.
if gpl && (has("cddl") || has("mit") || has("apache")) {
return None;
}
if lgpl {
return match (major?, minor) {
(2, Some(1)) => gnu("LGPL-2.1-only", "LGPL-2.1-or-later"),
(2, None | Some(0)) => gnu("LGPL-2.0-only", "LGPL-2.0-or-later"),
(3, None | Some(0)) => gnu("LGPL-3.0-only", "LGPL-3.0-or-later"),
_ => None,
};
}
if agpl {
return match major? {
3 => gnu("AGPL-3.0-only", "AGPL-3.0-or-later"),
_ => None,
};
}
if gpl {
return match major? {
2 if has("classpath") => Some("GPL-2.0-only WITH Classpath-exception-2.0"),
1 => gnu("GPL-1.0-only", "GPL-1.0-or-later"),
2 => gnu("GPL-2.0-only", "GPL-2.0-or-later"),
3 => gnu("GPL-3.0-only", "GPL-3.0-or-later"),
_ => None,
};
}
if has("cc0") || phrase("cc 0") || phrase("creative commons zero") {
return Some("CC0-1.0");
}
if has("apache") || has("asl") {
return match (major?, minor) {
(2, None | Some(0)) => Some("Apache-2.0"),
(1, Some(1)) => Some("Apache-1.1"),
(1, None | Some(0)) => Some("Apache-1.0"),
_ => None,
};
}
if has("mit") {
return Some(if has("attribution") { "MIT-0" } else { "MIT" });
}
if phrase("eclipse distribution") || has("edl") {
return (major == Some(1)).then_some("BSD-3-Clause");
}
if phrase("eclipse public") || has("epl") {
return match major? {
1 => Some("EPL-1.0"),
2 => Some("EPL-2.0"),
_ => None,
};
}
if phrase("mozilla public") || has("mpl") {
return match (major?, minor) {
(2, None | Some(0)) => Some("MPL-2.0"),
(1, Some(1)) => Some("MPL-1.1"),
(1, None | Some(0)) => Some("MPL-1.0"),
_ => None,
};
}
if has("cddl") || phrase("common development and distribution") {
return match (major?, minor) {
(1, None | Some(0)) => Some("CDDL-1.0"),
(1, Some(1)) => Some("CDDL-1.1"),
_ => None,
};
}
if has("eupl") || phrase("european union public") {
return match (major?, minor) {
(1, Some(1)) => Some("EUPL-1.1"),
(1, Some(2)) => Some("EUPL-1.2"),
_ => None,
};
}
if has("0bsd") || (has("bsd") && phrase("zero clause")) {
return Some("0BSD");
}
if has("bsd") || has("freebsd") {
return if major == Some(3) || has("new") || has("revised") {
Some("BSD-3-Clause")
} else if major == Some(2) || has("simplified") || has("freebsd") {
Some("BSD-2-Clause")
} else {
None
};
}
if phrase("boost software") || has("bsl") {
return (major == Some(1)).then_some("BSL-1.0");
}
if has("artistic") {
return (major == Some(2)).then_some("Artistic-2.0");
}
if phrase("python software foundation") || has("psf") {
return Some("PSF-2.0");
}
if phrase("universal permissive") || has("upl") {
return Some("UPL-1.0");
}
if has("isc") {
return Some("ISC");
}
if has("zlib") {
return Some("Zlib");
}
if has("unlicense") {
return Some("Unlicense");
}
if has("wtfpl") {
return Some("WTFPL");
}
None
}
#[cfg(test)]
mod tests {
use super::*;
/// Licence names and URLs as Maven POMs, npm and NuGet give them, and
/// their SPDX id.
const KNOWN: &[(&str, &str)] = &[
("Apache 2.0", "Apache-2.0"),
("Apache 2", "Apache-2.0"),
("Apache License, Version 2.0", "Apache-2.0"),
("The Apache Software License, Version 2.0", "Apache-2.0"),
("The Apache License, Version 2.0", "Apache-2.0"),
("Apache License 2.0", "Apache-2.0"),
("Apache Software License - Version 2.0", "Apache-2.0"),
("ASL 2.0", "Apache-2.0"),
("apache-2.0", "Apache-2.0"),
("Apache License, Version 1.1", "Apache-1.1"),
("MIT", "MIT"),
("MIT License", "MIT"),
("The MIT License", "MIT"),
("The MIT License (MIT)", "MIT"),
("MIT No Attribution", "MIT-0"),
("BSD 3-Clause", "BSD-3-Clause"),
("BSD-3-Clause License", "BSD-3-Clause"),
("New BSD License", "BSD-3-Clause"),
("BSD Zero Clause License", "0BSD"),
("The BSD 3-Clause License", "BSD-3-Clause"),
("BSD 2-Clause \"Simplified\" License", "BSD-2-Clause"),
("Eclipse Public License - v 2.0", "EPL-2.0"),
("Eclipse Public License v2.0", "EPL-2.0"),
("Eclipse Public License - v 1.0", "EPL-1.0"),
("EPL 2.0", "EPL-2.0"),
("Eclipse Distribution License - v 1.0", "BSD-3-Clause"),
("GNU Lesser General Public License v2.1", "LGPL-2.1-only"),
(
"GNU Lesser General Public License, version 2.1",
"LGPL-2.1-only",
),
("LGPL 2.1", "LGPL-2.1-only"),
("LGPLv2.1+", "LGPL-2.1-or-later"),
(
"GNU Lesser General Public License v3.0 or later",
"LGPL-3.0-or-later",
),
("GNU Library General Public License v2", "LGPL-2.0-only"),
("GNU General Public License, version 2", "GPL-2.0-only"),
("GPLv3", "GPL-3.0-only"),
("GNU Affero General Public License v3", "AGPL-3.0-only"),
(
"GNU General Public License, version 2 with the GNU Classpath Exception",
"GPL-2.0-only WITH Classpath-exception-2.0",
),
("Mozilla Public License, Version 2.0", "MPL-2.0"),
("MPL 1.1", "MPL-1.1"),
("CDDL 1.1", "CDDL-1.1"),
(
"Common Development and Distribution License (CDDL) v1.0",
"CDDL-1.0",
),
("European Union Public License 1.2", "EUPL-1.2"),
("CC0 1.0 Universal", "CC0-1.0"),
("Public Domain, per Creative Commons CC0", "CC0-1.0"),
("Boost Software License 1.0", "BSL-1.0"),
("ISC License", "ISC"),
("zlib License", "Zlib"),
("The Unlicense", "Unlicense"),
("Universal Permissive License, Version 1.0", "UPL-1.0"),
("https://www.apache.org/licenses/LICENSE-2.0", "Apache-2.0"),
(
"https://www.apache.org/licenses/LICENSE-2.0.txt",
"Apache-2.0",
),
(
"http://www.apache.org/licenses/LICENSE-2.0.html",
"Apache-2.0",
),
("https://opensource.org/licenses/MIT", "MIT"),
("http://opensource.org/licenses/mit-license.php", "MIT"),
(
"https://opensource.org/licenses/BSD-3-Clause",
"BSD-3-Clause",
),
("https://opensource.org/licenses/MS-PL", "MS-PL"),
("https://spdx.org/licenses/ISC.html", "ISC"),
("https://www.eclipse.org/legal/epl-2.0/", "EPL-2.0"),
("http://www.eclipse.org/legal/epl-v10.html", "EPL-1.0"),
(
"https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html",
"LGPL-2.1-only",
),
(
"https://www.gnu.org/licenses/agpl.html",
"AGPL-3.0-or-later",
),
("www.mozilla.org/MPL/2.0/", "MPL-2.0"),
];
#[test]
fn known_licence_names_and_urls_become_spdx_ids() {
for (input, id) in KNOWN {
assert_eq!(normalise(input), *id, "{input}");
assert!(is_spdx_expression(id), "{id} is no SPDX id");
}
}
#[test]
fn unknown_names_and_spdx_input_stay_as_written() {
for input in [
"Custom Pump License",
"GPL",
"BSD License",
"Eclipse Public License",
"CDDL + GPLv2 with classpath exception",
"Commercial",
"https://example.com/our-license.html",
"MIT OR Apache-2.0",
"(EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0)",
"LicenseRef-file",
"GPL-2.0",
] {
assert_eq!(normalise(input), input, "{input}");
}
// A word that merely contains a family's letters is not that family.
assert_eq!(spdx_of_name("Permit to Limit License"), None);
}
#[test]
fn spdx_expressions_are_recognised() {
assert!(is_spdx_expression("MIT"));
assert!(is_spdx_expression("(MIT OR Apache-2.0)"));
assert!(is_spdx_expression("GPL-2.0-or-later"));
assert!(is_spdx_expression("GPL-2.0+"));
assert!(!is_spdx_expression("Custom Pump License"));
assert!(!is_spdx_expression("MIT OR LicenseRef-file"));
assert!(!is_spdx_expression(""));
}
}