feat(sbom): component creator from registries and purls (#508, part B2) #512
No files matched your search
@@ -177,10 +177,14 @@ impl SbomScanner {
|
||||
nuget::merge_nuget(&mut entries, resolution.entries);
|
||||
resolved_nuget = resolution.resolved;
|
||||
}
|
||||
// Their licenses: from the restored packages' .nuspec, then nuget.org.
|
||||
// Project URLs the purls name (GitHub, Go modules, Swift packages).
|
||||
registry_license::fill_repository_pages(&mut entries);
|
||||
// Their licenses and project URLs: from the restored packages' .nuspec,
|
||||
// then nuget.org.
|
||||
nuget_license::enrich_nuget_licenses(repo_path, &mut entries, self.nuget_registry.as_ref())
|
||||
.await;
|
||||
// npm and Maven licenses, which no lockfile names (#467 follow-up).
|
||||
// npm and Maven licenses, which no lockfile names (#467 follow-up),
|
||||
// and their project URLs (#508).
|
||||
registry_license::enrich_registry_licenses(
|
||||
repo_path,
|
||||
&mut entries,
|
||||
|
||||
@@ -102,6 +102,90 @@ pub(crate) trait LicenseCache: Send + Sync {
|
||||
) -> BoxFuture<'a, Result<(), String>>;
|
||||
}
|
||||
|
||||
/// What a registry says about one package version: its license and its
|
||||
/// project's web page (the TR-03183-2 component creator, #508).
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub(crate) struct PackageFacts {
|
||||
/// The license it declares.
|
||||
pub license: Option<String>,
|
||||
/// Its project's homepage or repository, an http(s) URL.
|
||||
pub homepage: Option<String>,
|
||||
}
|
||||
|
||||
/// The cache key of a package version's homepage, beside its license's.
|
||||
fn homepage_key((id, version): &PackageKey) -> PackageKey {
|
||||
(format!("homepage:{id}"), version.clone())
|
||||
}
|
||||
|
||||
/// The facts the cache holds for `keys`: a package is known once both its
|
||||
/// license and its homepage are (rows from before #508 hold the license
|
||||
/// only, so such a package is asked once more).
|
||||
pub(super) async fn cached_facts(
|
||||
cache: &dyn LicenseCache,
|
||||
keys: &[PackageKey],
|
||||
) -> Result<HashMap<PackageKey, PackageFacts>, String> {
|
||||
let mut asked: Vec<PackageKey> = keys.to_vec();
|
||||
asked.extend(keys.iter().map(homepage_key));
|
||||
let hits = cache.get_many(&asked).await?;
|
||||
Ok(keys
|
||||
.iter()
|
||||
.filter_map(|key| {
|
||||
let license = hits.get(key)?.clone();
|
||||
let homepage = hits.get(&homepage_key(key))?.clone();
|
||||
Some((key.clone(), PackageFacts { license, homepage }))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Cache the facts of `answers`.
|
||||
pub(super) async fn cache_facts(
|
||||
cache: &dyn LicenseCache,
|
||||
answers: &[(PackageKey, PackageFacts)],
|
||||
) -> Result<(), String> {
|
||||
let rows: Vec<(PackageKey, Option<String>)> = answers
|
||||
.iter()
|
||||
.flat_map(|(key, facts)| {
|
||||
[
|
||||
(key.clone(), facts.license.clone()),
|
||||
(homepage_key(key), facts.homepage.clone()),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
cache.put(&rows).await
|
||||
}
|
||||
|
||||
/// `url` when it is a web address to show as a project's page: http(s),
|
||||
/// without credentials, at most 2048 characters.
|
||||
pub(super) fn web_page(url: &str) -> Option<String> {
|
||||
let url = url.trim();
|
||||
let parsed = reqwest::Url::parse(url).ok()?;
|
||||
(matches!(parsed.scheme(), "http" | "https")
|
||||
&& parsed.username().is_empty()
|
||||
&& parsed.password().is_none()
|
||||
&& url.len() <= 2048)
|
||||
.then(|| parsed.to_string())
|
||||
}
|
||||
|
||||
/// Fill what `found` knows into `entries[i]` for each `(i, key)` of
|
||||
/// `wanted`: the license where it has none, the homepage where it has none.
|
||||
pub(super) fn apply_facts(
|
||||
entries: &mut [SbomEntry],
|
||||
wanted: &[(usize, PackageKey)],
|
||||
found: &HashMap<PackageKey, PackageFacts>,
|
||||
) {
|
||||
for (i, key) in wanted {
|
||||
let (Some(entry), Some(facts)) = (entries.get_mut(*i), found.get(key)) else {
|
||||
continue;
|
||||
};
|
||||
if entry.license.is_none() {
|
||||
entry.license.clone_from(&facts.license);
|
||||
}
|
||||
if entry.manufacturer_url.is_none() {
|
||||
entry.manufacturer_url.clone_from(&facts.homepage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The nuget.org step: where to fetch, what is cached, how far to go.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct NugetRegistry {
|
||||
@@ -151,8 +235,9 @@ pub(super) fn lookup_enabled(value: Option<&str>) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Fill the license of every NuGet entry that has none: from the tree's
|
||||
/// `.nuspec` files, then (with a `registry`) from nuget.org.
|
||||
/// Fill the license and project URL of every NuGet entry that lacks one: the
|
||||
/// license from the tree's `.nuspec` files, then (with a `registry`) both
|
||||
/// from nuget.org.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub(crate) async fn enrich_nuget_licenses(
|
||||
root: &Path,
|
||||
@@ -162,27 +247,35 @@ pub(crate) async fn enrich_nuget_licenses(
|
||||
let wanted: Vec<(usize, PackageKey)> = entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, e)| e.license.is_none())
|
||||
.filter(|(_, e)| e.license.is_none() || e.manufacturer_url.is_none())
|
||||
.filter_map(|(i, e)| lookup_key(e).map(|k| (i, k)))
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// The restored packages' .nuspec give licenses; nuget.org the rest and
|
||||
// every project URL.
|
||||
let local = local_licenses(root);
|
||||
let mut found: HashMap<PackageKey, Option<String>> = HashMap::new();
|
||||
for (_, key) in &wanted {
|
||||
if let Some(license) = local.get(key) {
|
||||
found.insert(key.clone(), Some(license.clone()));
|
||||
for (i, key) in &wanted {
|
||||
if let (Some(entry), Some(license)) = (entries.get_mut(*i), local.get(key)) {
|
||||
if entry.license.is_none() {
|
||||
entry.license = Some(license.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut found: HashMap<PackageKey, PackageFacts> = HashMap::new();
|
||||
|
||||
if let Some(registry) = registry {
|
||||
let missing: Vec<PackageKey> = unique(
|
||||
wanted
|
||||
.iter()
|
||||
.map(|(_, k)| k)
|
||||
.filter(|k| !found.contains_key(*k)),
|
||||
.filter(|(i, _)| {
|
||||
entries
|
||||
.get(*i)
|
||||
.is_some_and(|e| e.license.is_none() || e.manufacturer_url.is_none())
|
||||
})
|
||||
.map(|(_, k)| k),
|
||||
);
|
||||
match registry_policy(root) {
|
||||
RegistryPolicy::Skip(why) => {
|
||||
@@ -193,16 +286,11 @@ pub(crate) async fn enrich_nuget_licenses(
|
||||
.into_iter()
|
||||
.filter(|(id, _)| policy.allows(id))
|
||||
.collect();
|
||||
found.extend(registry.licenses(allowed).await);
|
||||
found.extend(registry.facts(allowed).await);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (i, key) in wanted {
|
||||
if let (Some(entry), Some(Some(license))) = (entries.get_mut(i), found.get(&key)) {
|
||||
entry.license = Some(license.clone());
|
||||
}
|
||||
}
|
||||
apply_facts(entries, &wanted, &found);
|
||||
}
|
||||
|
||||
/// The distinct keys of `keys`, in their first order.
|
||||
@@ -613,22 +701,22 @@ pub(super) fn registry_policy(root: &Path) -> RegistryPolicy {
|
||||
|
||||
/// How one package's lookup ended.
|
||||
enum Outcome {
|
||||
/// nuget.org answered: the license, or none.
|
||||
Answer(Option<String>),
|
||||
/// nuget.org answered: the license and project URL, or none.
|
||||
Answer(PackageFacts),
|
||||
/// It could not be asked or its answer not read.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl NugetRegistry {
|
||||
/// The licenses nuget.org (or the cache) knows for `keys`. A key missing
|
||||
/// from the result is unknown this time.
|
||||
async fn licenses(&self, keys: Vec<PackageKey>) -> HashMap<PackageKey, Option<String>> {
|
||||
/// The licenses and project URLs nuget.org (or the cache) knows for
|
||||
/// `keys`. A key missing from the result is unknown this time.
|
||||
async fn facts(&self, keys: Vec<PackageKey>) -> HashMap<PackageKey, PackageFacts> {
|
||||
if keys.is_empty() {
|
||||
return HashMap::new();
|
||||
}
|
||||
let mut out = HashMap::new();
|
||||
if let Some(cache) = &self.cache {
|
||||
match cache.get_many(&keys).await {
|
||||
match cached_facts(cache.as_ref(), &keys).await {
|
||||
Ok(hits) => out.extend(hits),
|
||||
Err(e) => tracing::warn!("NuGet license cache not read: {e}"),
|
||||
}
|
||||
@@ -654,7 +742,7 @@ impl NugetRegistry {
|
||||
let mut fresh = Vec::new();
|
||||
for (key, outcome) in answers {
|
||||
match outcome {
|
||||
Outcome::Answer(license) => fresh.push((key, license)),
|
||||
Outcome::Answer(facts) => fresh.push((key, facts)),
|
||||
Outcome::Failed(e) => {
|
||||
failed += 1;
|
||||
first_error.get_or_insert(e);
|
||||
@@ -678,7 +766,7 @@ impl NugetRegistry {
|
||||
}
|
||||
if let Some(cache) = &self.cache {
|
||||
if !fresh.is_empty() {
|
||||
if let Err(e) = cache.put(&fresh).await {
|
||||
if let Err(e) = cache_facts(cache.as_ref(), &fresh).await {
|
||||
tracing::warn!("NuGet license cache not written: {e}");
|
||||
}
|
||||
}
|
||||
@@ -687,12 +775,18 @@ impl NugetRegistry {
|
||||
out
|
||||
}
|
||||
|
||||
/// The license nuget.org holds for one package version.
|
||||
/// The license and project URL nuget.org holds for one package version.
|
||||
async fn lookup(&self, key: &PackageKey) -> Outcome {
|
||||
match self.catalog(key).await {
|
||||
Ok(Some(catalog)) => Outcome::Answer(catalog_license(&catalog)),
|
||||
Ok(Some(catalog)) => Outcome::Answer(PackageFacts {
|
||||
license: catalog_license(&catalog),
|
||||
homepage: catalog
|
||||
.get("projectUrl")
|
||||
.and_then(|u| u.as_str())
|
||||
.and_then(web_page),
|
||||
}),
|
||||
// Not on nuget.org (another feed's package, or unlisted for good).
|
||||
Ok(None) => Outcome::Answer(None),
|
||||
Ok(None) => Outcome::Answer(PackageFacts::default()),
|
||||
Err(e) => Outcome::Failed(e),
|
||||
}
|
||||
}
|
||||
@@ -1267,6 +1361,12 @@ mod tests {
|
||||
let mut entries = vec![entry("Newtonsoft.Json", "13.0.1")];
|
||||
enrich_nuget_licenses(&t.0, &mut entries, Some(®istry(fetch.clone(), None))).await;
|
||||
assert_eq!(entries[0].license.as_deref(), Some("MIT"));
|
||||
// nuget.org is still asked, for the project URL (#508).
|
||||
assert_eq!(fetch.calls.load(Ordering::SeqCst), 1);
|
||||
let mut known = vec![entry("Newtonsoft.Json", "13.0.1")];
|
||||
known[0].manufacturer_url = Some("https://www.newtonsoft.com/json".into());
|
||||
let fetch = Arc::new(FakeFetch::default());
|
||||
enrich_nuget_licenses(&t.0, &mut known, Some(®istry(fetch.clone(), None))).await;
|
||||
assert_eq!(fetch.calls.load(Ordering::SeqCst), 0, "nuget.org was asked");
|
||||
}
|
||||
|
||||
@@ -1279,7 +1379,7 @@ mod tests {
|
||||
.with(
|
||||
NEWTONSOFT_CATALOG,
|
||||
Ok(Some(
|
||||
br#"{"id":"Newtonsoft.Json","licenseExpression":"MIT","licenseUrl":"https://licenses.nuget.org/MIT"}"#
|
||||
br#"{"id":"Newtonsoft.Json","licenseExpression":"MIT","licenseUrl":"https://licenses.nuget.org/MIT","projectUrl":"https://www.newtonsoft.com/json"}"#
|
||||
.to_vec(),
|
||||
)),
|
||||
)
|
||||
@@ -1293,8 +1393,13 @@ mod tests {
|
||||
let reg = registry(fetch.clone(), Some(cache.clone()));
|
||||
enrich_nuget_licenses(&t.0, &mut entries, Some(®)).await;
|
||||
assert_eq!(entries[0].license.as_deref(), Some("MIT"));
|
||||
assert_eq!(
|
||||
entries[0].manufacturer_url.as_deref(),
|
||||
Some("https://www.newtonsoft.com/json")
|
||||
);
|
||||
assert!(entries[1].license.as_deref().unwrap().contains("DotNetZip"));
|
||||
assert_eq!(cache.0.lock().unwrap().len(), 2);
|
||||
// A license and a project URL per package.
|
||||
assert_eq!(cache.0.lock().unwrap().len(), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1306,6 +1411,10 @@ mod tests {
|
||||
("newtonsoft.json".into(), "13.0.1".into()),
|
||||
Some("MIT".into()),
|
||||
);
|
||||
cache.0.lock().unwrap().insert(
|
||||
("homepage:newtonsoft.json".into(), "13.0.1".into()),
|
||||
Some("https://www.newtonsoft.com/json".into()),
|
||||
);
|
||||
let mut entries = vec![entry("Newtonsoft.Json", "13.0.1.0")];
|
||||
enrich_nuget_licenses(
|
||||
&t.0,
|
||||
@@ -1314,6 +1423,10 @@ mod tests {
|
||||
)
|
||||
.await;
|
||||
assert_eq!(entries[0].license.as_deref(), Some("MIT"));
|
||||
assert_eq!(
|
||||
entries[0].manufacturer_url.as_deref(),
|
||||
Some("https://www.newtonsoft.com/json")
|
||||
);
|
||||
assert_eq!(fetch.calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
|
||||
@@ -30,8 +30,8 @@ use compliance_core::NetGuard;
|
||||
use futures_util::StreamExt;
|
||||
|
||||
use super::nuget_license::{
|
||||
decode_body, license_from_url, lookup_enabled, Fetch, HttpFetch, LicenseCache, Limits,
|
||||
PackageKey, LICENSE_FILE,
|
||||
apply_facts, cache_facts, cached_facts, decode_body, license_from_url, lookup_enabled,
|
||||
web_page, Fetch, HttpFetch, LicenseCache, Limits, PackageFacts, PackageKey, LICENSE_FILE,
|
||||
};
|
||||
use crate::pipeline::dotnet::{parse_xml, read_text};
|
||||
|
||||
@@ -304,8 +304,8 @@ fn public_maven_url(url: &str) -> bool {
|
||||
PUBLIC_MAVEN_HOSTS.iter().any(|h| host.starts_with(h))
|
||||
}
|
||||
|
||||
/// Fill the license of every npm and Maven entry that has none, from their
|
||||
/// public registries.
|
||||
/// Fill the license and project URL of every npm and Maven entry that lacks
|
||||
/// one, from their public registries.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub(crate) async fn enrich_registry_licenses(
|
||||
root: &Path,
|
||||
@@ -318,7 +318,7 @@ pub(crate) async fn enrich_registry_licenses(
|
||||
let wanted: Vec<(usize, Ecosystem, PackageKey)> = entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, e)| e.license.is_none())
|
||||
.filter(|(_, e)| e.license.is_none() || e.manufacturer_url.is_none())
|
||||
.filter_map(|(i, e)| lookup_key(e).map(|(eco, key)| (i, eco, key)))
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
@@ -341,28 +341,22 @@ pub(crate) async fn enrich_registry_licenses(
|
||||
keys.push((*eco, key.clone()));
|
||||
}
|
||||
}
|
||||
let found = registry.licenses(keys).await;
|
||||
for (i, _, key) in wanted {
|
||||
if let (Some(entry), Some(Some(license))) = (entries.get_mut(i), found.get(&key)) {
|
||||
entry.license = Some(license.clone());
|
||||
}
|
||||
}
|
||||
let found = registry.facts(keys).await;
|
||||
let wanted: Vec<(usize, PackageKey)> = wanted.into_iter().map(|(i, _, k)| (i, k)).collect();
|
||||
apply_facts(entries, &wanted, &found);
|
||||
}
|
||||
|
||||
impl RegistryLicenses {
|
||||
/// The licenses the cache or the registries know for `keys`; a key
|
||||
/// missing from the result is unknown this time.
|
||||
async fn licenses(
|
||||
&self,
|
||||
keys: Vec<(Ecosystem, PackageKey)>,
|
||||
) -> HashMap<PackageKey, Option<String>> {
|
||||
/// The licenses and project URLs the cache or the registries know for
|
||||
/// `keys`; a key missing from the result is unknown this time.
|
||||
async fn facts(&self, keys: Vec<(Ecosystem, PackageKey)>) -> HashMap<PackageKey, PackageFacts> {
|
||||
let mut out = HashMap::new();
|
||||
if keys.is_empty() {
|
||||
return out;
|
||||
}
|
||||
if let Some(cache) = &self.cache {
|
||||
let plain: Vec<PackageKey> = keys.iter().map(|(_, k)| k.clone()).collect();
|
||||
match cache.get_many(&plain).await {
|
||||
match cached_facts(cache.as_ref(), &plain).await {
|
||||
Ok(hits) => out.extend(hits),
|
||||
Err(e) => tracing::warn!("registry license cache not read: {e}"),
|
||||
}
|
||||
@@ -375,14 +369,14 @@ impl RegistryLicenses {
|
||||
let asked: Vec<(Ecosystem, PackageKey)> =
|
||||
uncached.into_iter().take(self.limits.max_lookups).collect();
|
||||
let count = asked.len();
|
||||
let answers: Vec<(PackageKey, Result<Option<String>, String>)> =
|
||||
let answers: Vec<(PackageKey, Result<PackageFacts, String>)> =
|
||||
futures_util::stream::iter(asked)
|
||||
.map(|(eco, key)| async move {
|
||||
let license = match eco {
|
||||
Ecosystem::Npm => self.npm_license(&key).await,
|
||||
Ecosystem::Maven => self.maven_license(&key).await,
|
||||
let facts = match eco {
|
||||
Ecosystem::Npm => self.npm_facts(&key).await,
|
||||
Ecosystem::Maven => self.maven_facts(&key).await,
|
||||
};
|
||||
(key, license)
|
||||
(key, facts)
|
||||
})
|
||||
.buffer_unordered(self.limits.concurrency.max(1))
|
||||
.take_until(tokio::time::sleep(self.limits.budget))
|
||||
@@ -394,7 +388,7 @@ impl RegistryLicenses {
|
||||
let mut first_error = None;
|
||||
for (key, answer) in answers {
|
||||
match answer {
|
||||
Ok(license) => fresh.push((key, license)),
|
||||
Ok(facts) => fresh.push((key, facts)),
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
first_error.get_or_insert(e);
|
||||
@@ -414,7 +408,7 @@ impl RegistryLicenses {
|
||||
}
|
||||
if let Some(cache) = &self.cache {
|
||||
if !fresh.is_empty() {
|
||||
if let Err(e) = cache.put(&fresh).await {
|
||||
if let Err(e) = cache_facts(cache.as_ref(), &fresh).await {
|
||||
tracing::warn!("registry license cache not written: {e}");
|
||||
}
|
||||
}
|
||||
@@ -431,8 +425,8 @@ impl RegistryLicenses {
|
||||
.and_then(|b| b.map(decode_body).transpose())
|
||||
}
|
||||
|
||||
/// The license npm's registry holds for a version.
|
||||
async fn npm_license(&self, (key, version): &PackageKey) -> Result<Option<String>, String> {
|
||||
/// The license and project URL npm's registry holds for a version.
|
||||
async fn npm_facts(&self, (key, version): &PackageKey) -> Result<PackageFacts, String> {
|
||||
let name = key.trim_start_matches("npm:");
|
||||
// A scoped name keeps its `@` and encodes its slash.
|
||||
let url = format!("{NPM_REGISTRY}/{}/{version}", name.replacen('/', "%2f", 1));
|
||||
@@ -441,17 +435,22 @@ impl RegistryLicenses {
|
||||
.await
|
||||
.map_err(|e| format!("{name} {version}: {e}"))?
|
||||
else {
|
||||
return Ok(None);
|
||||
return Ok(PackageFacts::default());
|
||||
};
|
||||
let doc: serde_json::Value =
|
||||
serde_json::from_slice(&body).map_err(|e| format!("{name} {version}: {e}"))?;
|
||||
Ok(npm_document_license(&doc))
|
||||
Ok(PackageFacts {
|
||||
license: npm_document_license(&doc),
|
||||
homepage: npm_document_homepage(&doc),
|
||||
})
|
||||
}
|
||||
|
||||
/// The license a Maven POM (or one of its parents) declares.
|
||||
async fn maven_license(&self, (key, version): &PackageKey) -> Result<Option<String>, String> {
|
||||
/// The license a Maven POM (or one of its parents) declares, and the
|
||||
/// project URL of the first of them that names one.
|
||||
async fn maven_facts(&self, (key, version): &PackageKey) -> Result<PackageFacts, String> {
|
||||
let mut coordinate = key.trim_start_matches("maven:").to_string();
|
||||
let mut version = version.clone();
|
||||
let mut facts = PackageFacts::default();
|
||||
for _ in 0..=MAX_PARENTS {
|
||||
let (group, artifact) = coordinate
|
||||
.split_once(':')
|
||||
@@ -471,19 +470,25 @@ impl RegistryLicenses {
|
||||
.await
|
||||
.map_err(|e| format!("{coordinate} {version}: {e}"))?
|
||||
else {
|
||||
return Ok(None);
|
||||
return Ok(facts);
|
||||
};
|
||||
let text = String::from_utf8_lossy(&body);
|
||||
if facts.homepage.is_none() {
|
||||
facts.homepage = pom_homepage(&text);
|
||||
}
|
||||
match pom_license(&text) {
|
||||
PomLicense::Found(license) => return Ok(Some(license)),
|
||||
PomLicense::Found(license) => {
|
||||
facts.license = Some(license);
|
||||
return Ok(facts);
|
||||
}
|
||||
PomLicense::Parent(parent, parent_version) => {
|
||||
coordinate = parent;
|
||||
version = parent_version;
|
||||
}
|
||||
PomLicense::None => return Ok(None),
|
||||
PomLicense::None => return Ok(facts),
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
Ok(facts)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,6 +526,99 @@ fn npm_document_license(doc: &serde_json::Value) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Code hosts whose repository path is `<host>/<owner>/<repo>`.
|
||||
const CODE_HOSTS: &[&str] = &["github.com", "gitlab.com", "bitbucket.org"];
|
||||
|
||||
/// The repository page a purl names, no request needed: a GitHub or
|
||||
/// Bitbucket purl, a Go module or Swift package on a code host.
|
||||
fn purl_repository_page(purl: &str) -> Option<String> {
|
||||
let p = compliance_core::purl::Purl::parse(purl)?;
|
||||
let namespace = p.namespace.as_deref()?;
|
||||
let page = match p.ty.as_str() {
|
||||
"github" => format!("https://github.com/{namespace}/{}", p.name),
|
||||
"bitbucket" => format!("https://bitbucket.org/{namespace}/{}", p.name),
|
||||
"golang" | "swift" => {
|
||||
let path = format!("{namespace}/{}", p.name);
|
||||
let mut parts = path.split('/');
|
||||
let (host, owner, repo) = (parts.next()?, parts.next()?, parts.next()?);
|
||||
if !CODE_HOSTS.contains(&host) {
|
||||
return None;
|
||||
}
|
||||
format!("https://{host}/{owner}/{repo}")
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
web_page(&page)
|
||||
}
|
||||
|
||||
/// Give every entry without a project URL the repository page its purl
|
||||
/// names (see [`purl_repository_page`]).
|
||||
pub(crate) fn fill_repository_pages(entries: &mut [SbomEntry]) {
|
||||
for entry in entries.iter_mut().filter(|e| e.manufacturer_url.is_none()) {
|
||||
entry.manufacturer_url = entry.purl.as_deref().and_then(purl_repository_page);
|
||||
}
|
||||
}
|
||||
|
||||
/// The project URL of an npm version document: its `homepage`, else its
|
||||
/// `repository` as a web address (`git+https://…/x.git`, `github:o/r` and
|
||||
/// `o/r` forms included).
|
||||
fn npm_document_homepage(doc: &serde_json::Value) -> Option<String> {
|
||||
if let Some(page) = doc
|
||||
.get("homepage")
|
||||
.and_then(|h| h.as_str())
|
||||
.and_then(web_page)
|
||||
{
|
||||
return Some(page);
|
||||
}
|
||||
let repository = doc.get("repository")?;
|
||||
let url = repository
|
||||
.as_str()
|
||||
.or_else(|| repository.get("url").and_then(|u| u.as_str()))?
|
||||
.trim();
|
||||
repository_page(url)
|
||||
}
|
||||
|
||||
/// A repository reference as a web page: `git+https://github.com/o/r.git`,
|
||||
/// `git://…`, `git@github.com:o/r.git`, `github:o/r` and `o/r` become
|
||||
/// `https://github.com/o/r`.
|
||||
fn repository_page(url: &str) -> Option<String> {
|
||||
let url = url.strip_prefix("git+").unwrap_or(url);
|
||||
let url = url.strip_suffix(".git").unwrap_or(url);
|
||||
let https = if let Some(rest) = url.strip_prefix("git://") {
|
||||
format!("https://{rest}")
|
||||
} else if let Some(rest) = url.strip_prefix("ssh://git@") {
|
||||
format!("https://{rest}")
|
||||
} else if let Some(rest) = url.strip_prefix("git@") {
|
||||
format!("https://{}", rest.replacen(':', "/", 1))
|
||||
} else if let Some(rest) = url.strip_prefix("github:") {
|
||||
format!("https://github.com/{rest}")
|
||||
} else if !url.contains(':') && url.matches('/').count() == 1 {
|
||||
format!("https://github.com/{url}")
|
||||
} else {
|
||||
url.to_string()
|
||||
};
|
||||
web_page(&https)
|
||||
}
|
||||
|
||||
/// The project URL of a POM: its `<url>`, else its `<scm><url>`. A URL with
|
||||
/// a property in it (`${project.url}`) is not one.
|
||||
fn pom_homepage(text: &str) -> Option<String> {
|
||||
let doc = parse_xml(text)?;
|
||||
let root = doc.root_element();
|
||||
let url_of = |node: roxmltree::Node<'_, '_>| {
|
||||
node.children()
|
||||
.find(|c| c.is_element() && c.tag_name().name() == "url")
|
||||
.and_then(|c| c.text())
|
||||
.filter(|t| !t.contains("${"))
|
||||
.and_then(web_page)
|
||||
};
|
||||
url_of(root).or_else(|| {
|
||||
root.children()
|
||||
.find(|c| c.is_element() && c.tag_name().name() == "scm")
|
||||
.and_then(url_of)
|
||||
})
|
||||
}
|
||||
|
||||
/// What a POM says about its license.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum PomLicense {
|
||||
@@ -658,7 +756,7 @@ mod tests {
|
||||
let table: HashMap<String, String> = [
|
||||
(
|
||||
"https://registry.npmjs.org/lodash/4.17.20".to_string(),
|
||||
r#"{"name":"lodash","license":"MIT"}"#.to_string(),
|
||||
r#"{"name":"lodash","license":"MIT","homepage":"https://lodash.com/"}"#.to_string(),
|
||||
),
|
||||
(
|
||||
"https://registry.npmjs.org/@babel%2fcore/7.0.0".to_string(),
|
||||
@@ -696,6 +794,10 @@ mod tests {
|
||||
licenses,
|
||||
[Some("MIT"), Some("MIT"), Some("Apache-2.0"), None]
|
||||
);
|
||||
assert_eq!(
|
||||
entries[0].manufacturer_url.as_deref(),
|
||||
Some("https://lodash.com/")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -741,6 +843,56 @@ mod tests {
|
||||
assert!(licenses.iter().all(Option::is_some), "{licenses:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_urls_are_read() {
|
||||
assert_eq!(
|
||||
npm_document_homepage(&serde_json::json!({"homepage": "https://lodash.com/"}))
|
||||
.as_deref(),
|
||||
Some("https://lodash.com/")
|
||||
);
|
||||
assert_eq!(
|
||||
npm_document_homepage(&serde_json::json!({
|
||||
"repository": {"type": "git", "url": "git+https://github.com/lodash/lodash.git"}
|
||||
}))
|
||||
.as_deref(),
|
||||
Some("https://github.com/lodash/lodash")
|
||||
);
|
||||
assert_eq!(
|
||||
repository_page("git@github.com:expressjs/express.git").as_deref(),
|
||||
Some("https://github.com/expressjs/express")
|
||||
);
|
||||
assert_eq!(
|
||||
repository_page("github:axios/axios").as_deref(),
|
||||
Some("https://github.com/axios/axios")
|
||||
);
|
||||
assert_eq!(
|
||||
repository_page("chalk/chalk").as_deref(),
|
||||
Some("https://github.com/chalk/chalk")
|
||||
);
|
||||
// No credentials, no other schemes.
|
||||
assert_eq!(web_page("https://user:secret@example.com/x"), None);
|
||||
assert_eq!(repository_page("file:../local"), None);
|
||||
let pom = r#"<project><url>${project.parent.url}</url>
|
||||
<scm><url>https://github.com/square/okhttp</url></scm></project>"#;
|
||||
assert_eq!(
|
||||
pom_homepage(pom).as_deref(),
|
||||
Some("https://github.com/square/okhttp")
|
||||
);
|
||||
assert_eq!(
|
||||
purl_repository_page("pkg:golang/github.com/gin-gonic/gin/v2@v2.0.0").as_deref(),
|
||||
Some("https://github.com/gin-gonic/gin")
|
||||
);
|
||||
assert_eq!(
|
||||
purl_repository_page("pkg:swift/github.com/apple/swift-nio@2.40.0").as_deref(),
|
||||
Some("https://github.com/apple/swift-nio")
|
||||
);
|
||||
assert_eq!(
|
||||
purl_repository_page("pkg:golang/golang.org/x/net@v0.1.0"),
|
||||
None
|
||||
);
|
||||
assert_eq!(purl_repository_page("pkg:npm/lodash@4.17.21"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn license_shapes_are_read() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -42,6 +42,11 @@ pub struct SbomEntry {
|
||||
/// registry's when the project uses no other.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub download_url: Option<String>,
|
||||
/// The web page of whoever makes and maintains the component: its
|
||||
/// project's homepage or repository, from its registry or purl (BSI
|
||||
/// TR-03183-2's component creator; #508). A URL only, never a person.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub manufacturer_url: Option<String>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
pub created_at: DateTime<Utc>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
@@ -73,6 +78,7 @@ impl SbomEntry {
|
||||
evidence: Vec::new(),
|
||||
hashes: Vec::new(),
|
||||
download_url: None,
|
||||
manufacturer_url: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
|
||||
@@ -161,6 +161,9 @@ pub fn cdx_components(entries: &[SbomEntry]) -> Vec<serde_json::Value> {
|
||||
if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) {
|
||||
comp["licenses"] = license_choice(license);
|
||||
}
|
||||
if let Some(url) = &e.manufacturer_url {
|
||||
comp["manufacturer"] = serde_json::json!({ "url": [url] });
|
||||
}
|
||||
if !e.hashes.is_empty() {
|
||||
let hashes = cdx_hashes(&e.hashes);
|
||||
// The file and where it is downloaded from: the TR's hash of
|
||||
|
||||
@@ -47,6 +47,7 @@ fn entries() -> Vec<SbomEntry> {
|
||||
let mut e = SbomEntry::new("t".into(), name.into(), version.into(), manager.into());
|
||||
e.purl = Some(purl.into());
|
||||
e.license = Some(license.into());
|
||||
e.manufacturer_url = Some(format!("https://project.example/{name}"));
|
||||
// What the lockfiles give (#508): npm and NuGet a SHA-512, Cargo a
|
||||
// SHA-256, Maven nothing.
|
||||
let (alg, len) = match manager {
|
||||
@@ -118,9 +119,11 @@ fn the_document_shape_meets_the_bsi_checks_it_can() {
|
||||
}
|
||||
// Met by every component but the product. The product is a logical
|
||||
// component in the TR's terms (section 3.2.2): it has no file, so no
|
||||
// filename or file properties, and Prüfwerk does not know its licence.
|
||||
// filename or file properties, and Prüfwerk knows neither its licence nor
|
||||
// its manufacturer's web address.
|
||||
// sbomqs 2.1.2 counts it like the others.
|
||||
for key in [
|
||||
"comp_creator",
|
||||
"comp_filename",
|
||||
"comp_executable_prop",
|
||||
"comp_archive_prop",
|
||||
|
||||
@@ -87,6 +87,7 @@ fn sbom() -> Vec<SbomEntry> {
|
||||
content: "bf690311ee7b95e713ba568322e3533f2dd1cb880b189e99d4edef13592b81764daec43e2c54c61d5c558dc5cfb35ecb85b65519e74026ff17675b6f8f916f4a".into(),
|
||||
}];
|
||||
lodash.download_url = Some("https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz".into());
|
||||
lodash.manufacturer_url = Some("https://lodash.com/".into());
|
||||
let mut fw = SbomEntry::new(
|
||||
"t".into(),
|
||||
"PumpSDK".into(),
|
||||
@@ -208,6 +209,10 @@ fn the_cyclonedx_sbom_is_valid_and_its_vulnerabilities_point_at_components() {
|
||||
"SHA-512"
|
||||
);
|
||||
assert!(doc["components"][0].get("hashes").is_none());
|
||||
assert_eq!(
|
||||
doc["components"][1]["manufacturer"]["url"][0],
|
||||
"https://lodash.com/"
|
||||
);
|
||||
assert_eq!(doc["components"][0]["group"], "org.apache.logging.log4j");
|
||||
assert!(doc["components"][2].get("group").is_none());
|
||||
assert_eq!(
|
||||
|
||||
+8
-2
@@ -223,6 +223,9 @@ Prüfwerk has the data, BSI TR-03183-2 v2.1:
|
||||
(npm, yarn, pnpm), or the public registry's (npmjs, nuget.org, crates.io)
|
||||
when the project takes the package from there and the lockfile names
|
||||
none.
|
||||
- Each component's creator (`manufacturer.url`) is its project's web page:
|
||||
the homepage or repository its registry names, or the repository its
|
||||
purl names. Never a person's name or email.
|
||||
- Licenses are an SPDX id, an SPDX expression or a named license, marked
|
||||
`acknowledgement: declared`: they are what the package declares, not a
|
||||
licence Prüfwerk concluded.
|
||||
@@ -304,8 +307,11 @@ export meets the format, creator, timestamp, name, version, dependency and
|
||||
identifier checks, and the file properties for registry packages. Still
|
||||
open, and why:
|
||||
|
||||
- **Component creator**: the email or URL of each package's maintainer.
|
||||
Prüfwerk does not record it yet.
|
||||
- **Component creator**: met where the project URL is known: npm, Maven
|
||||
and NuGet packages from their public registries (homepage or
|
||||
repository), GitHub, Go-module and Swift packages from their purl. Other
|
||||
ecosystems and private packages have none yet; the product itself has
|
||||
none (the workspace's web address is not recorded).
|
||||
- **Hash of the deployable component** (SHA-512) and its download URL: met
|
||||
for npm, yarn and pnpm packages (the lockfile's `integrity`) and NuGet
|
||||
packages with a `packages.lock.json` (its `contentHash`). Cargo's lockfile
|
||||
|
||||
@@ -208,13 +208,15 @@ The answers are attached to the alert (`exploitation`) and to the SBOM's referen
|
||||
|
||||
`CVE_EXPLOIT_LOOKUP=false` keeps the agent from contacting the three sources.
|
||||
|
||||
**Registry metadata (#508):** the nuget.org, npm and Maven lookups also fetch each package's project URL (the SBOM's component creator), so they now ask for packages that already have a license too, once per package version and within the same per-scan bounds; the cache fills the rest over later scans. Only URLs are kept, never maintainer names or emails. GitHub, Go-module and Swift purls give their repository page without any request.
|
||||
|
||||
## nuget.org -- NuGet Licenses
|
||||
|
||||
Licenses of NuGet packages that no `.nuspec` in the tree gives are read from the [nuget.org registration API](https://learn.microsoft.com/nuget/api/registration-base-url-resource) (`api.nuget.org`). Only the package id and version are sent, never for an id a `nuget.config` routes to another feed (see [.NET projects](/guide/dotnet-en)). The lookup is bounded per scan (8 requests at once, 10 s per request, 60 s and 300 uncached packages in total); answers are cached for all tenants. Set `NUGET_LICENSE_LOOKUP=false` to keep the agent from contacting nuget.org.
|
||||
Licenses of NuGet packages that no `.nuspec` in the tree gives, and the project URL (`projectUrl`) of every package, are read from the [nuget.org registration API](https://learn.microsoft.com/nuget/api/registration-base-url-resource) (`api.nuget.org`). Only the package id and version are sent, never for an id a `nuget.config` routes to another feed (see [.NET projects](/guide/dotnet-en)). The lookup is bounded per scan (8 requests at once, 10 s per request, 60 s and 300 uncached packages in total); answers are cached for all tenants. Set `NUGET_LICENSE_LOOKUP=false` to keep the agent from contacting nuget.org.
|
||||
|
||||
## npm and Maven -- Licenses
|
||||
|
||||
Licenses of npm packages come from their version document on `registry.npmjs.org` (`license`, or the older `licenses` list), those of Maven and Gradle dependencies from their POM on Maven Central or, for AndroidX and Google Play services, Google's Maven repository; a POM without `<licenses>` inherits its parent's (followed up to three levels). Only names and versions are sent, never for a scope or registry the tree's `.npmrc`/`.yarnrc.yml` routes elsewhere, and no Maven name at all when a build names a repository besides the public ones. Bounded and cached like the NuGet lookup; `REGISTRY_LICENSE_LOOKUP=false` turns it off.
|
||||
Licenses of npm packages come from their version document on `registry.npmjs.org` (`license`, or the older `licenses` list), with the project URL (`homepage`, else `repository`); those of Maven and Gradle dependencies, with the project URL (`<url>`, else `<scm><url>`), from their POM on Maven Central or, for AndroidX and Google Play services, Google's Maven repository; a POM without `<licenses>` inherits its parent's (followed up to three levels). Only names and versions are sent, never for a scope or registry the tree's `.npmrc`/`.yarnrc.yml` routes elsewhere, and no Maven name at all when a build names a repository besides the public ones. Bounded and cached like the NuGet lookup; `REGISTRY_LICENSE_LOOKUP=false` turns it off.
|
||||
|
||||
## ClamAV -- Malware
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ together on stage in one pass before the next prod promotion.
|
||||
| #508 (A) | CycloneDX 1.6 SBOM with BSI TR-03183-2 properties |
|
||||
| #498 (3/4) | CSAF 2.0 VEX advisory draft |
|
||||
| #508 (B1) | Lockfile hashes and download URLs in the SBOM |
|
||||
| #508 (B2) | Component creator (project URL) in the SBOM |
|
||||
|
||||
**Customer-visible on the next prod rescan** is marked **[visible]**: these
|
||||
change what a customer sees on their existing targets, without them doing
|
||||
@@ -629,6 +630,22 @@ Rust target.
|
||||
- **[visible]** SBOM exports and evidence packs carry the hashes and URLs
|
||||
after the next rescan.
|
||||
|
||||
### 30. #508 part B2: component creator
|
||||
|
||||
Use the targets of check 29 and a Go module.
|
||||
|
||||
- **Do:** rescan; export **CycloneDX 1.6**. **Expect:** npm, Maven and
|
||||
NuGet components carry `manufacturer.url` with their project page
|
||||
(e.g. lodash `https://lodash.com/`, okhttp its GitHub repository,
|
||||
Newtonsoft.Json `https://www.newtonsoft.com/json`); Go modules on
|
||||
GitHub their repository; Python packages none. No names or emails.
|
||||
- **Log:** the npm/Maven and nuget.org lookups now ask for packages that
|
||||
already had a license too (more requests on the first scan, within the
|
||||
per-scan bounds); a second scan is answered from the cache.
|
||||
- **Expect:** SBOM-Qualität: "Component Creator" met for those shares.
|
||||
- **[visible]** SBOM exports and evidence packs name component creators
|
||||
after the next rescan.
|
||||
|
||||
## After the pass
|
||||
|
||||
- The nightly job on `main` is green with the new mobile targets.
|
||||
|
||||
Reference in new issue
Block a user