feat(sbom): npm and Maven licenses from their public registries (#467 follow-up) #490
No files matched your search
@@ -312,6 +312,10 @@ impl PipelineOrchestrator {
|
||||
))
|
||||
.with_nuget_resolution(crate::pipeline::sbom::nuget_resolution_enabled(
|
||||
self.config.app_env,
|
||||
))
|
||||
.with_registry_licenses(crate::pipeline::sbom::RegistryLicenses::from_env(
|
||||
self.net_guard,
|
||||
self.nuget_license_cache.clone(),
|
||||
));
|
||||
sbom_scanner.generate(&repo_path, &repo_id).await
|
||||
}
|
||||
|
||||
@@ -6,12 +6,14 @@ mod nuget;
|
||||
mod nuget_assembly;
|
||||
mod nuget_license;
|
||||
mod nuget_resolve;
|
||||
mod registry_license;
|
||||
|
||||
pub(crate) use nuget::is_restored_package;
|
||||
#[cfg(test)]
|
||||
pub(crate) use nuget::nuget_components;
|
||||
pub(crate) use nuget_license::{LicenseCache, MongoLicenseCache, NugetRegistry};
|
||||
pub(crate) use nuget_resolve::enabled as nuget_resolution_enabled;
|
||||
pub(crate) use registry_license::RegistryLicenses;
|
||||
mod syft;
|
||||
pub(crate) mod unity;
|
||||
|
||||
@@ -31,6 +33,8 @@ pub struct SbomScanner {
|
||||
/// Whether the transitive packages of unlocked `<PackageReference>`
|
||||
/// projects are resolved on that registry (#461).
|
||||
resolve_nuget: bool,
|
||||
/// Where npm and Maven licenses are looked up (#467 follow-up).
|
||||
registry_licenses: Option<RegistryLicenses>,
|
||||
}
|
||||
|
||||
impl SbomScanner {
|
||||
@@ -39,9 +43,16 @@ impl SbomScanner {
|
||||
exec,
|
||||
nuget_registry: None,
|
||||
resolve_nuget: false,
|
||||
registry_licenses: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Look up npm and Maven licenses on their public registries.
|
||||
pub(crate) fn with_registry_licenses(mut self, registries: Option<RegistryLicenses>) -> Self {
|
||||
self.registry_licenses = registries;
|
||||
self
|
||||
}
|
||||
|
||||
/// Resolve the transitive packages of unlocked `<PackageReference>`
|
||||
/// projects from nuget.org (#461); see [`nuget_resolve::enabled`].
|
||||
pub(crate) fn with_nuget_resolution(mut self, enabled: bool) -> Self {
|
||||
@@ -168,6 +179,13 @@ impl SbomScanner {
|
||||
// Their licenses: 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).
|
||||
registry_license::enrich_registry_licenses(
|
||||
repo_path,
|
||||
&mut entries,
|
||||
self.registry_licenses.as_ref(),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Enrich Cargo entries with license info from cargo metadata
|
||||
enrich_cargo_licenses(repo_path, &mut entries, self.exec).await;
|
||||
|
||||
@@ -39,7 +39,7 @@ use crate::pipeline::dotnet::{parse_xml, read_text, relative, walk_sources};
|
||||
const NUGET: &str = "nuget";
|
||||
|
||||
/// The license of a package that ships its license text as a file.
|
||||
const LICENSE_FILE: &str = "LicenseRef-file";
|
||||
pub(super) const LICENSE_FILE: &str = "LicenseRef-file";
|
||||
|
||||
/// The registration leaves (gzip-compressed, SemVer 2.0 packages included).
|
||||
const REGISTRATION_BASE: &str = "https://api.nuget.org/v3/registration5-gz-semver2";
|
||||
@@ -144,7 +144,7 @@ impl NugetRegistry {
|
||||
}
|
||||
|
||||
/// Whether the `NUGET_LICENSE_LOOKUP` value turns the lookup on (the default).
|
||||
fn lookup_enabled(value: Option<&str>) -> bool {
|
||||
pub(super) fn lookup_enabled(value: Option<&str>) -> bool {
|
||||
!value.is_some_and(|v| {
|
||||
let v = v.trim();
|
||||
v == "0" || v.eq_ignore_ascii_case("false") || v.eq_ignore_ascii_case("off")
|
||||
@@ -363,7 +363,7 @@ fn nuspec_license(text: &str) -> Option<(PackageKey, String)> {
|
||||
/// page, [`LICENSE_FILE`] for nuget.org's pointer to a packaged file, the
|
||||
/// URL itself otherwise. `None` for nuget.org's placeholder that says only
|
||||
/// "see the license element".
|
||||
fn license_from_url(url: &str) -> Option<String> {
|
||||
pub(super) fn license_from_url(url: &str) -> Option<String> {
|
||||
let url = url.trim();
|
||||
let lower = url.to_ascii_lowercase();
|
||||
let bare = lower
|
||||
@@ -791,13 +791,13 @@ fn catalog_license(entry: &serde_json::Value) -> Option<String> {
|
||||
/// the net guard, redirects re-checked, a per-request timeout.
|
||||
///
|
||||
/// [`guarded_client_builder`]: compliance_core::guarded_net::guarded_client_builder
|
||||
struct HttpFetch {
|
||||
pub(super) struct HttpFetch {
|
||||
http: reqwest::Client,
|
||||
guard: NetGuard,
|
||||
}
|
||||
|
||||
impl HttpFetch {
|
||||
fn new(guard: NetGuard) -> Result<Self, String> {
|
||||
pub(super) fn new(guard: NetGuard) -> Result<Self, String> {
|
||||
let http = compliance_core::guarded_net::guarded_client_builder(guard)
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
@@ -835,7 +835,7 @@ impl Fetch for HttpFetch {
|
||||
/// A response body, gunzipped if it is gzip: the registration leaves are
|
||||
/// stored compressed and served with `Content-Encoding: gzip` whatever the
|
||||
/// request accepts.
|
||||
fn decode_body(body: Vec<u8>) -> Result<Vec<u8>, String> {
|
||||
pub(super) fn decode_body(body: Vec<u8>) -> Result<Vec<u8>, String> {
|
||||
if !body.starts_with(&[0x1f, 0x8b]) {
|
||||
return Ok(body);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,771 @@
|
||||
//! Licenses of npm and Maven components (#467 follow-up), from their public
|
||||
//! registries, on the pattern of [`super::nuget_license`].
|
||||
//!
|
||||
//! - **npm**: the version document of `registry.npmjs.org/<name>/<version>`
|
||||
//! carries `license` (an SPDX expression, or the older `{type}` object or
|
||||
//! `licenses` list). The lockfiles and manifests in a repository do not.
|
||||
//! - **Maven** (Gradle builds included): the POM of the version on Maven
|
||||
//! Central (`repo1.maven.org`), or on Google's Maven repository
|
||||
//! (`dl.google.com`) for the Android groups, lists `<licenses>`; a POM
|
||||
//! without them inherits its parent's, which is followed a few levels.
|
||||
//!
|
||||
//! Only package names and versions leave the agent, through the guarded
|
||||
//! client, and never one a private registry may serve: an `.npmrc` (or
|
||||
//! `.yarnrc.yml`) that points the default registry elsewhere stops every npm
|
||||
//! lookup, a scope routed elsewhere stops that scope's; a Maven or Gradle
|
||||
//! build that declares any repository besides the public ones stops every
|
||||
//! Maven lookup, since nothing tells which groups the private one serves.
|
||||
//! Answers are cached across tenants with the NuGet licenses (keys
|
||||
//! `npm:<name>` and `maven:<group>:<artifact>`). Lookups are bounded like
|
||||
//! NuGet's; `REGISTRY_LICENSE_LOOKUP=false` turns them off. A package the
|
||||
//! lookup could not answer keeps an empty license; nothing here fails the
|
||||
//! SBOM stage.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use compliance_core::models::SbomEntry;
|
||||
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,
|
||||
};
|
||||
use crate::pipeline::dotnet::{parse_xml, read_text};
|
||||
|
||||
/// The npm registry.
|
||||
const NPM_REGISTRY: &str = "https://registry.npmjs.org";
|
||||
|
||||
/// Maven Central.
|
||||
const MAVEN_CENTRAL: &str = "https://repo1.maven.org/maven2";
|
||||
|
||||
/// Google's Maven repository (AndroidX, Play services, the Android tools).
|
||||
const GOOGLE_MAVEN: &str = "https://dl.google.com/android/maven2";
|
||||
|
||||
/// Groups only Google's repository serves.
|
||||
const GOOGLE_GROUPS: &[&str] = &["androidx.", "com.google.android.", "com.android."];
|
||||
|
||||
/// How many parent POMs are followed for `<licenses>`.
|
||||
const MAX_PARENTS: usize = 3;
|
||||
|
||||
/// Repository hosts a Gradle or Maven build may name without making the
|
||||
/// Maven lookup unsafe: public repositories with public packages only.
|
||||
const PUBLIC_MAVEN_HOSTS: &[&str] = &[
|
||||
"repo1.maven.org",
|
||||
"repo.maven.apache.org",
|
||||
"repo.maven.org",
|
||||
"dl.google.com",
|
||||
"maven.google.com",
|
||||
"plugins.gradle.org",
|
||||
"jcenter.bintray.com",
|
||||
];
|
||||
|
||||
/// Which ecosystem a lookup key belongs to.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Ecosystem {
|
||||
Npm,
|
||||
Maven,
|
||||
}
|
||||
|
||||
/// The npm and Maven registries: how to fetch, what is cached, how far to go.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct RegistryLicenses {
|
||||
fetch: Arc<dyn Fetch>,
|
||||
cache: Option<Arc<dyn LicenseCache>>,
|
||||
limits: Limits,
|
||||
}
|
||||
|
||||
impl RegistryLicenses {
|
||||
pub(crate) fn new(
|
||||
fetch: Arc<dyn Fetch>,
|
||||
cache: Option<Arc<dyn LicenseCache>>,
|
||||
limits: Limits,
|
||||
) -> Self {
|
||||
Self {
|
||||
fetch,
|
||||
cache,
|
||||
limits,
|
||||
}
|
||||
}
|
||||
|
||||
/// The registries over a guarded client, or `None` when the deployment
|
||||
/// turned the lookup off (`REGISTRY_LICENSE_LOOKUP=false`) or the client
|
||||
/// cannot be built.
|
||||
pub(crate) fn from_env(guard: NetGuard, cache: Option<Arc<dyn LicenseCache>>) -> Option<Self> {
|
||||
if !lookup_enabled(std::env::var("REGISTRY_LICENSE_LOOKUP").ok().as_deref()) {
|
||||
tracing::info!(
|
||||
"REGISTRY_LICENSE_LOOKUP is off: npm and Maven licenses are not looked up"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
match HttpFetch::new(guard) {
|
||||
Ok(fetch) => Some(Self::new(Arc::new(fetch), cache, Limits::default())),
|
||||
Err(e) => {
|
||||
tracing::warn!("npm and Maven license lookup disabled: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lookup key of an entry: `npm:<name>` or `maven:<group>:<artifact>`
|
||||
/// and its version, from its purl.
|
||||
fn lookup_key(entry: &SbomEntry) -> Option<(Ecosystem, PackageKey)> {
|
||||
let purl = entry.purl.as_deref()?;
|
||||
let (path, version) = purl.split_once('@')?;
|
||||
let version = version.split(['?', '#']).next()?.to_string();
|
||||
if version.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if let Some(name) = path.strip_prefix("pkg:npm/") {
|
||||
let name = name
|
||||
.replace("%40", "@")
|
||||
.replace("%2F", "/")
|
||||
.replace("%2f", "/");
|
||||
return Some((Ecosystem::Npm, (format!("npm:{name}"), version)));
|
||||
}
|
||||
if let Some(coordinate) = path.strip_prefix("pkg:maven/") {
|
||||
let (group, artifact) = coordinate.split_once('/')?;
|
||||
return Some((
|
||||
Ecosystem::Maven,
|
||||
(format!("maven:{group}:{artifact}"), version),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Which npm names may be sent to the public registry.
|
||||
#[derive(Debug, Default)]
|
||||
struct NpmPolicy {
|
||||
/// The default registry is not npmjs: nothing is sent.
|
||||
skip_all: bool,
|
||||
/// Scopes (`@corp`) routed to another registry.
|
||||
private_scopes: Vec<String>,
|
||||
}
|
||||
|
||||
impl NpmPolicy {
|
||||
fn allows(&self, name: &str) -> bool {
|
||||
if self.skip_all {
|
||||
return false;
|
||||
}
|
||||
let scope = name
|
||||
.split_once('/')
|
||||
.map(|(s, _)| s)
|
||||
.filter(|s| s.starts_with('@'));
|
||||
!scope.is_some_and(|s| self.private_scopes.iter().any(|p| p == s))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a registry URL is the public npm registry.
|
||||
fn is_npmjs(url: &str) -> bool {
|
||||
let host = url
|
||||
.trim()
|
||||
.trim_matches(['"', '\''])
|
||||
.trim_start_matches("https://")
|
||||
.trim_start_matches("http://");
|
||||
host.starts_with("registry.npmjs.org") || host.starts_with("registry.yarnpkg.com")
|
||||
}
|
||||
|
||||
/// The npm policy of the tree's `.npmrc` and `.yarnrc.yml`.
|
||||
fn npm_policy(root: &Path) -> NpmPolicy {
|
||||
let mut policy = NpmPolicy::default();
|
||||
if let Some(text) = read_text(&root.join(".npmrc")) {
|
||||
for line in text.lines().map(str::trim) {
|
||||
let Some((key, value)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let key = key.trim();
|
||||
if key == "registry" && !is_npmjs(value) {
|
||||
policy.skip_all = true;
|
||||
} else if let Some(scope) = key.strip_suffix(":registry") {
|
||||
if !is_npmjs(value) {
|
||||
policy.private_scopes.push(scope.trim().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(text) = read_text(&root.join(".yarnrc.yml")) {
|
||||
let mut in_scopes = false;
|
||||
let mut scope = None;
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some(value) = trimmed.strip_prefix("npmRegistryServer:") {
|
||||
if line.starts_with("npmRegistryServer") && !is_npmjs(value) {
|
||||
policy.skip_all = true;
|
||||
} else if let (true, Some(s)) = (in_scopes, &scope) {
|
||||
if !is_npmjs(value) {
|
||||
policy.private_scopes.push(format!("@{s}"));
|
||||
}
|
||||
}
|
||||
} else if line.starts_with("npmScopes:") {
|
||||
in_scopes = true;
|
||||
} else if in_scopes && line.starts_with(" ") && !line.starts_with(" ") {
|
||||
scope = trimmed.strip_suffix(':').map(str::to_string);
|
||||
} else if !line.starts_with(' ') && !trimmed.is_empty() {
|
||||
in_scopes = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
policy
|
||||
}
|
||||
|
||||
/// Whether the Maven and Gradle builds of the tree name only public
|
||||
/// repositories. A repository URL behind a variable counts as private.
|
||||
fn maven_public_only(root: &Path) -> bool {
|
||||
let files = walkdir::WalkDir::new(root)
|
||||
.max_depth(6)
|
||||
.into_iter()
|
||||
.filter_entry(|e| {
|
||||
!matches!(
|
||||
e.file_name().to_string_lossy().as_ref(),
|
||||
".git" | "node_modules" | "build" | ".gradle" | "target"
|
||||
)
|
||||
})
|
||||
.filter_map(Result::ok)
|
||||
.filter(|e| {
|
||||
matches!(
|
||||
e.file_name().to_string_lossy().as_ref(),
|
||||
"pom.xml"
|
||||
| "build.gradle"
|
||||
| "build.gradle.kts"
|
||||
| "settings.gradle"
|
||||
| "settings.gradle.kts"
|
||||
)
|
||||
});
|
||||
for file in files {
|
||||
let Some(text) = read_text(file.path()) else {
|
||||
continue;
|
||||
};
|
||||
if file.file_name() == "pom.xml" {
|
||||
if let Some(doc) = parse_xml(&text) {
|
||||
let private = doc
|
||||
.descendants()
|
||||
.filter(|n| n.has_tag_name("repository") || n.has_tag_name("pluginRepository"))
|
||||
.filter_map(|n| n.children().find(|c| c.has_tag_name("url")))
|
||||
.filter_map(|u| u.text())
|
||||
.any(|url| !public_maven_url(url));
|
||||
if private {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else if gradle_repositories(&text)
|
||||
.iter()
|
||||
.any(|url| !public_maven_url(url))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The repository URLs a Gradle build declares (`maven { url = uri("…") }`,
|
||||
/// `maven("…")`, `maven { url '…' }`).
|
||||
fn gradle_repositories(text: &str) -> Vec<String> {
|
||||
let mut urls = Vec::new();
|
||||
let mut in_maven = false;
|
||||
for line in text.lines().map(str::trim) {
|
||||
if let Some(rest) = line.strip_prefix("maven(") {
|
||||
urls.push(quoted(rest).unwrap_or_else(|| rest.to_string()));
|
||||
continue;
|
||||
}
|
||||
if line.starts_with("maven {") || line == "maven{" || line.starts_with("maven{") {
|
||||
in_maven = true;
|
||||
}
|
||||
if in_maven {
|
||||
if let Some(rest) = line.split_once("url").map(|(_, r)| r) {
|
||||
urls.push(quoted(rest).unwrap_or_else(|| rest.to_string()));
|
||||
in_maven = false;
|
||||
} else if line.contains('}') && !line.starts_with("maven") {
|
||||
in_maven = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
urls
|
||||
}
|
||||
|
||||
/// The first quoted string in `text`.
|
||||
fn quoted(text: &str) -> Option<String> {
|
||||
let start = text.find(['"', '\''])?;
|
||||
let quote = text[start..].chars().next()?;
|
||||
let rest = &text[start + 1..];
|
||||
let end = rest.find(quote)?;
|
||||
Some(rest[..end].to_string())
|
||||
}
|
||||
|
||||
/// Whether a Maven repository URL is one of [`PUBLIC_MAVEN_HOSTS`].
|
||||
fn public_maven_url(url: &str) -> bool {
|
||||
let host = url
|
||||
.trim()
|
||||
.trim_start_matches("https://")
|
||||
.trim_start_matches("http://");
|
||||
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.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub(crate) async fn enrich_registry_licenses(
|
||||
root: &Path,
|
||||
entries: &mut [SbomEntry],
|
||||
registry: Option<&RegistryLicenses>,
|
||||
) {
|
||||
let Some(registry) = registry else {
|
||||
return;
|
||||
};
|
||||
let wanted: Vec<(usize, Ecosystem, PackageKey)> = entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, e)| e.license.is_none())
|
||||
.filter_map(|(i, e)| lookup_key(e).map(|(eco, key)| (i, eco, key)))
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
return;
|
||||
}
|
||||
let npm = npm_policy(root);
|
||||
let maven = maven_public_only(root);
|
||||
if !maven && wanted.iter().any(|(_, eco, _)| *eco == Ecosystem::Maven) {
|
||||
tracing::info!(
|
||||
"Maven licenses not looked up: the build names a repository besides the public ones"
|
||||
);
|
||||
}
|
||||
let mut keys: Vec<(Ecosystem, PackageKey)> = Vec::new();
|
||||
for (_, eco, key) in &wanted {
|
||||
let allowed = match eco {
|
||||
Ecosystem::Npm => npm.allows(key.0.trim_start_matches("npm:")),
|
||||
Ecosystem::Maven => maven,
|
||||
};
|
||||
if allowed && !keys.iter().any(|(_, k)| k == key) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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>> {
|
||||
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 {
|
||||
Ok(hits) => out.extend(hits),
|
||||
Err(e) => tracing::warn!("registry license cache not read: {e}"),
|
||||
}
|
||||
}
|
||||
let uncached: Vec<(Ecosystem, PackageKey)> = keys
|
||||
.into_iter()
|
||||
.filter(|(_, k)| !out.contains_key(k))
|
||||
.collect();
|
||||
let deferred = uncached.len().saturating_sub(self.limits.max_lookups);
|
||||
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>)> =
|
||||
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,
|
||||
};
|
||||
(key, license)
|
||||
})
|
||||
.buffer_unordered(self.limits.concurrency.max(1))
|
||||
.take_until(tokio::time::sleep(self.limits.budget))
|
||||
.collect()
|
||||
.await;
|
||||
let unanswered = count - answers.len();
|
||||
let mut fresh = Vec::new();
|
||||
let mut failed = 0usize;
|
||||
let mut first_error = None;
|
||||
for (key, answer) in answers {
|
||||
match answer {
|
||||
Ok(license) => fresh.push((key, license)),
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
first_error.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if failed > 0 || unanswered > 0 || deferred > 0 {
|
||||
tracing::warn!(
|
||||
failed,
|
||||
unanswered,
|
||||
deferred,
|
||||
"npm/Maven license lookup incomplete (left empty){}",
|
||||
first_error
|
||||
.map(|e| format!("; first error: {e}"))
|
||||
.unwrap_or_default()
|
||||
);
|
||||
}
|
||||
if let Some(cache) = &self.cache {
|
||||
if !fresh.is_empty() {
|
||||
if let Err(e) = cache.put(&fresh).await {
|
||||
tracing::warn!("registry license cache not written: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
out.extend(fresh);
|
||||
out
|
||||
}
|
||||
|
||||
/// GET `url`: the body, or `None` for a 404.
|
||||
async fn get(&self, url: &str) -> Result<Option<Vec<u8>>, String> {
|
||||
self.fetch
|
||||
.get(url)
|
||||
.await
|
||||
.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> {
|
||||
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));
|
||||
let Some(body) = self
|
||||
.get(&url)
|
||||
.await
|
||||
.map_err(|e| format!("{name} {version}: {e}"))?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let doc: serde_json::Value =
|
||||
serde_json::from_slice(&body).map_err(|e| format!("{name} {version}: {e}"))?;
|
||||
Ok(npm_document_license(&doc))
|
||||
}
|
||||
|
||||
/// The license a Maven POM (or one of its parents) declares.
|
||||
async fn maven_license(&self, (key, version): &PackageKey) -> Result<Option<String>, String> {
|
||||
let mut coordinate = key.trim_start_matches("maven:").to_string();
|
||||
let mut version = version.clone();
|
||||
for _ in 0..=MAX_PARENTS {
|
||||
let (group, artifact) = coordinate
|
||||
.split_once(':')
|
||||
.map(|(g, a)| (g.to_string(), a.to_string()))
|
||||
.ok_or_else(|| format!("{coordinate}: not group:artifact"))?;
|
||||
let base = if GOOGLE_GROUPS.iter().any(|g| group.starts_with(g)) {
|
||||
GOOGLE_MAVEN
|
||||
} else {
|
||||
MAVEN_CENTRAL
|
||||
};
|
||||
let url = format!(
|
||||
"{base}/{}/{artifact}/{version}/{artifact}-{version}.pom",
|
||||
group.replace('.', "/")
|
||||
);
|
||||
let Some(body) = self
|
||||
.get(&url)
|
||||
.await
|
||||
.map_err(|e| format!("{coordinate} {version}: {e}"))?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let text = String::from_utf8_lossy(&body);
|
||||
match pom_license(&text) {
|
||||
PomLicense::Found(license) => return Ok(Some(license)),
|
||||
PomLicense::Parent(parent, parent_version) => {
|
||||
coordinate = parent;
|
||||
version = parent_version;
|
||||
}
|
||||
PomLicense::None => return Ok(None),
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// The license of an npm version document: `license` as a string (an SPDX
|
||||
/// expression) or `{type}`, or the older `licenses` list (joined with OR).
|
||||
fn npm_document_license(doc: &serde_json::Value) -> Option<String> {
|
||||
let one = |v: &serde_json::Value| -> Option<String> {
|
||||
let text = v
|
||||
.as_str()
|
||||
.or_else(|| v.get("type").and_then(|t| t.as_str()))?
|
||||
.trim()
|
||||
.to_string();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if text.to_ascii_uppercase().starts_with("SEE LICENSE IN") {
|
||||
return Some(LICENSE_FILE.to_string());
|
||||
}
|
||||
Some(text)
|
||||
};
|
||||
if let Some(license) = doc.get("license").and_then(one) {
|
||||
return Some(license);
|
||||
}
|
||||
let list: Vec<String> = doc
|
||||
.get("licenses")
|
||||
.and_then(|l| l.as_array())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(one)
|
||||
.collect();
|
||||
match list.len() {
|
||||
0 => None,
|
||||
1 => list.into_iter().next(),
|
||||
_ => Some(format!("({})", list.join(" OR "))),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a POM says about its license.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum PomLicense {
|
||||
Found(String),
|
||||
/// None here; the parent (`group:artifact` and version) may have one.
|
||||
Parent(String, String),
|
||||
None,
|
||||
}
|
||||
|
||||
/// The license of a POM: its first `<license>`'s name as an SPDX id where
|
||||
/// known, else what its URL stands for, else the name as written.
|
||||
fn pom_license(text: &str) -> PomLicense {
|
||||
let Some(doc) = parse_xml(text) else {
|
||||
return PomLicense::None;
|
||||
};
|
||||
let root = doc.root_element();
|
||||
let child = |node: roxmltree::Node<'_, '_>, name: &str| {
|
||||
node.children()
|
||||
.find(|c| c.is_element() && c.tag_name().name() == name)
|
||||
.and_then(|c| c.text())
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
.map(str::to_string)
|
||||
};
|
||||
let licenses: Vec<String> = root
|
||||
.children()
|
||||
.filter(|c| c.tag_name().name() == "licenses")
|
||||
.flat_map(|l| l.children().filter(|c| c.tag_name().name() == "license"))
|
||||
.filter_map(|license| {
|
||||
let name = child(license, "name");
|
||||
let url = child(license, "url");
|
||||
name.as_deref()
|
||||
.and_then(spdx_of_name)
|
||||
.or_else(|| {
|
||||
url.as_deref()
|
||||
.and_then(license_from_url)
|
||||
.filter(|l| Some(l) != url.as_ref())
|
||||
})
|
||||
.or(name)
|
||||
.or(url)
|
||||
})
|
||||
.collect();
|
||||
match licenses.len() {
|
||||
0 => {
|
||||
let parent = root.children().find(|c| c.tag_name().name() == "parent");
|
||||
match parent.and_then(|p| {
|
||||
Some((
|
||||
format!("{}:{}", child(p, "groupId")?, child(p, "artifactId")?),
|
||||
child(p, "version")?,
|
||||
))
|
||||
}) {
|
||||
Some((coordinate, version)) => PomLicense::Parent(coordinate, version),
|
||||
None => PomLicense::None,
|
||||
}
|
||||
}
|
||||
1 => PomLicense::Found(licenses.into_iter().next().unwrap_or_default()),
|
||||
_ => PomLicense::Found(format!("({})", licenses.join(" OR "))),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
use super::*;
|
||||
use futures_util::future::BoxFuture;
|
||||
|
||||
use super::super::nuget_license::FetchResult;
|
||||
|
||||
/// The registries answering from a table of URL → body.
|
||||
struct Fake(HashMap<String, String>, std::sync::Mutex<Vec<String>>);
|
||||
|
||||
impl Fetch for Fake {
|
||||
fn get<'a>(&'a self, url: &'a str) -> BoxFuture<'a, FetchResult> {
|
||||
Box::pin(async move {
|
||||
self.1.lock().unwrap().push(url.to_string());
|
||||
Ok(self.0.get(url).map(|b| b.as_bytes().to_vec()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn entry(purl: &str) -> SbomEntry {
|
||||
let mut e = SbomEntry::new("t".into(), "x".into(), "1".into(), "npm".into());
|
||||
e.purl = Some(purl.to_string());
|
||||
e
|
||||
}
|
||||
|
||||
fn tree(files: &[(&str, &str)]) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("cs-reglic-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (path, content) in files {
|
||||
let full = dir.join(path);
|
||||
std::fs::create_dir_all(full.parent().unwrap()).unwrap();
|
||||
std::fs::write(full, content).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
const POM_WITH_PARENT: &str = r#"<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<parent><groupId>com.squareup.okhttp3</groupId><artifactId>parent</artifactId><version>3.12.0</version></parent>
|
||||
<artifactId>okhttp</artifactId>
|
||||
</project>"#;
|
||||
|
||||
const PARENT_POM: &str = r#"<project><licenses><license>
|
||||
<name>The Apache Software License, Version 2.0</name>
|
||||
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
|
||||
</license></licenses></project>"#;
|
||||
|
||||
#[tokio::test]
|
||||
async fn npm_and_maven_licenses_come_from_their_registries() {
|
||||
let table: HashMap<String, String> = [
|
||||
(
|
||||
"https://registry.npmjs.org/lodash/4.17.20".to_string(),
|
||||
r#"{"name":"lodash","license":"MIT"}"#.to_string(),
|
||||
),
|
||||
(
|
||||
"https://registry.npmjs.org/@babel%2fcore/7.0.0".to_string(),
|
||||
r#"{"license":{"type":"MIT"}}"#.to_string(),
|
||||
),
|
||||
(
|
||||
"https://repo1.maven.org/maven2/com/squareup/okhttp3/okhttp/3.12.0/okhttp-3.12.0.pom"
|
||||
.to_string(),
|
||||
POM_WITH_PARENT.to_string(),
|
||||
),
|
||||
(
|
||||
"https://repo1.maven.org/maven2/com/squareup/okhttp3/parent/3.12.0/parent-3.12.0.pom"
|
||||
.to_string(),
|
||||
PARENT_POM.to_string(),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
let registry = RegistryLicenses::new(
|
||||
Arc::new(Fake(table, std::sync::Mutex::default())),
|
||||
None,
|
||||
Limits::default(),
|
||||
);
|
||||
let dir = tree(&[]);
|
||||
let mut entries = vec![
|
||||
entry("pkg:npm/lodash@4.17.20"),
|
||||
entry("pkg:npm/%40babel/core@7.0.0"),
|
||||
entry("pkg:maven/com.squareup.okhttp3/okhttp@3.12.0"),
|
||||
entry("pkg:npm/left-pad@1.0.0"),
|
||||
];
|
||||
enrich_registry_licenses(&dir, &mut entries, Some(®istry)).await;
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let licenses: Vec<Option<&str>> = entries.iter().map(|e| e.license.as_deref()).collect();
|
||||
assert_eq!(
|
||||
licenses,
|
||||
[Some("MIT"), Some("MIT"), Some("Apache-2.0"), None]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn private_registries_keep_names_inside() {
|
||||
let fake = Arc::new(Fake(HashMap::new(), std::sync::Mutex::default()));
|
||||
let registry = RegistryLicenses::new(fake.clone(), None, Limits::default());
|
||||
let dir = tree(&[
|
||||
(".npmrc", "@corp:registry=https://npm.corp.example.com/\n"),
|
||||
(
|
||||
"build.gradle",
|
||||
"repositories {\n mavenCentral()\n maven { url 'https://nexus.corp.example.com/repo' }\n}\n",
|
||||
),
|
||||
]);
|
||||
let mut entries = vec![
|
||||
entry("pkg:npm/%40corp/pump-ui@1.0.0"),
|
||||
entry("pkg:npm/react@18.2.0"),
|
||||
entry("pkg:maven/com.corp/pump@1.0.0"),
|
||||
];
|
||||
enrich_registry_licenses(&dir, &mut entries, Some(®istry)).await;
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let asked = fake.1.lock().unwrap().clone();
|
||||
assert_eq!(asked, ["https://registry.npmjs.org/react/18.2.0"]);
|
||||
}
|
||||
|
||||
/// Against the real registries (network): `cargo test -- --ignored`.
|
||||
#[tokio::test]
|
||||
#[ignore = "reaches registry.npmjs.org, repo1.maven.org and dl.google.com"]
|
||||
async fn real_registries_answer() {
|
||||
let registry =
|
||||
RegistryLicenses::from_env(compliance_core::NetGuard::public_only(), None).unwrap();
|
||||
let dir = tree(&[]);
|
||||
let mut entries = vec![
|
||||
entry("pkg:npm/lodash@4.17.20"),
|
||||
entry("pkg:npm/%40babel/core@7.24.0"),
|
||||
entry("pkg:maven/com.squareup.okhttp3/okhttp@3.12.0"),
|
||||
entry("pkg:maven/androidx.core/core@1.12.0"),
|
||||
entry("pkg:maven/com.google.code.gson/gson@2.8.8"),
|
||||
];
|
||||
enrich_registry_licenses(&dir, &mut entries, Some(®istry)).await;
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let licenses: Vec<Option<&str>> = entries.iter().map(|e| e.license.as_deref()).collect();
|
||||
eprintln!("{licenses:?}");
|
||||
assert!(licenses.iter().all(Option::is_some), "{licenses:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn license_shapes_are_read() {
|
||||
assert_eq!(
|
||||
npm_document_license(
|
||||
&serde_json::json!({"licenses":[{"type":"MIT"},{"type":"Apache-2.0"}]})
|
||||
),
|
||||
Some("(MIT OR Apache-2.0)".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
npm_document_license(&serde_json::json!({"license":"SEE LICENSE IN LICENSE.md"})),
|
||||
Some(LICENSE_FILE.to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
pom_license("<project><licenses><license><name>Eclipse Public License - v 2.0</name></license></licenses></project>"),
|
||||
PomLicense::Found("EPL-2.0".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
pom_license("<project><licenses><license><name>Custom Pump License</name></license></licenses></project>"),
|
||||
PomLicense::Found("Custom Pump License".to_string())
|
||||
);
|
||||
assert_eq!(pom_license("<project/>"), PomLicense::None);
|
||||
assert!(public_maven_url("https://dl.google.com/dl/android/maven2/"));
|
||||
assert!(!public_maven_url("https://nexus.corp.example.com/repo"));
|
||||
assert_eq!(
|
||||
gradle_repositories("maven(\"https://jitpack.io\")\nmaven {\n url = uri(\"https://x.example.com/m2\")\n}\n"),
|
||||
["https://jitpack.io", "https://x.example.com/m2"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,17 @@ database, the severity where known, and **Hinweis ansehen →** (View advisory).
|
||||
|
||||
The **Lizenzen** tab summarises the licenses.
|
||||
|
||||
Lockfiles name versions, not licenses. Where the tree does not carry them,
|
||||
they are looked up on the public registry of the package: nuget.org for
|
||||
NuGet, `registry.npmjs.org` for npm, and Maven Central (or Google's Maven
|
||||
repository for AndroidX and Play services) for Maven and Gradle, where a
|
||||
POM without a license inherits its parent's. Only package names and versions
|
||||
are sent, and none a private registry may serve: an `.npmrc` or `.yarnrc.yml`
|
||||
that points elsewhere (for all packages or a scope), a `nuget.config` routing,
|
||||
or a Maven or Gradle build that names a repository besides the public ones
|
||||
stops those lookups. A component whose license could not be found stays
|
||||
without one.
|
||||
|
||||
### Copyleft Warnings
|
||||
|
||||
If any component uses a copyleft license (GPL, AGPL, LGPL, MPL and their
|
||||
|
||||
@@ -138,6 +138,10 @@ Only package URLs (purl), CVE ids and CPE product prefixes are sent. Both source
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
## ClamAV -- Malware
|
||||
|
||||
[ClamAV](https://www.clamav.net/) (GPL-2.0, the official image unchanged) runs
|
||||
@@ -245,6 +249,8 @@ Every connection the agent opens, in one place. **Guarded** means: the HTTP clie
|
||||
| `api.osv.dev` (`/v1/querybatch`, `/v1/vulns/{id}`) | purls of SBOM components, advisory ids | `pipeline/cve.rs` | guarded | 10 s per request, 5 s connect, body ≤ 16 MiB, 8 advisory reads at once | none (CVE stage) |
|
||||
| `services.nvd.nist.gov` (`/rest/json/cves/2.0`) | CVE ids (CVSS score), CPE product prefixes (CODESYS, embedded libraries) | `pipeline/cve.rs`, `pipeline/nvd_cpe.rs` | guarded | 30 s per request, 5 s connect, body ≤ 16 MiB, 3 retries after 6/12/24 s, answers cached 6 h | `NVD_API_KEY` (optional, raises NVD's rate limit) |
|
||||
| `api.nuget.org` (registration, catalog) | NuGet package ids and versions, not for ids a `nuget.config` routes to another feed | `pipeline/sbom/nuget_license.rs` | guarded | 10 s per request, 5 s connect, body ≤ 2 MiB, 8 at once, 60 s and 300 uncached packages per scan | `NUGET_LICENSE_LOOKUP=false` |
|
||||
| `registry.npmjs.org` | npm package names and versions, not for a registry or scope `.npmrc`/`.yarnrc.yml` routes elsewhere | `pipeline/sbom/registry_license.rs` | guarded | as nuget.org (bounds per scan; answers cached for all tenants) | `REGISTRY_LICENSE_LOOKUP=false` |
|
||||
| `repo1.maven.org`, `dl.google.com` (POMs) | Maven group, artifact and version (and parent POMs), not when the build names a non-public repository | `pipeline/sbom/registry_license.rs` | guarded | as nuget.org | `REGISTRY_LICENSE_LOOKUP=false` |
|
||||
| Package registries (Go proxy, npm, PyPI, Maven Central) | package names and versions | Syft (`pipeline/sbom/syft.rs`, remote license lookups) and lockfile generation (`npm`, `cargo`, `pip-compile` in `pipeline/sbom/mod.rs`) | not guarded: subprocesses with their own HTTP | Syft 10 min per scan | lockfile generation follows the execution policy |
|
||||
|
||||
### Tenant-chosen addresses
|
||||
|
||||
@@ -17,6 +17,7 @@ together on stage in one pass before the next prod promotion.
|
||||
| #486 | The clone cache heals itself after an interrupted clone or fetch |
|
||||
| #465 | Malware stage (ClamAV), committed binaries, unchanged scheduled rescans skipped |
|
||||
| #461 | Transitive NuGet packages of `<PackageReference>` projects resolved from nuget.org |
|
||||
| #467 (follow-up) | npm and Maven licenses from their public registries |
|
||||
|
||||
**Customer-visible on the next prod rescan** is marked **[visible]**: these
|
||||
change what a customer sees on their existing targets, without them doing
|
||||
@@ -288,6 +289,22 @@ Unchanged rescans:
|
||||
transitive packages (and their CVEs) in the SBOM, and the "Nicht
|
||||
ausgeführt" list shrinks to one entry. On stage now.
|
||||
|
||||
### 17. #467 follow-up: npm and Maven licenses
|
||||
|
||||
- **Do:** scan `fixtures/nightly/js-npm-lock-v3` and
|
||||
`fixtures/nightly/mobile/android-gradle-lock` (or any npm and Gradle
|
||||
target); then add an `.npmrc` with `@corp:registry=https://npm.corp.example.com/`
|
||||
and a `maven { url 'https://nexus.corp.example.com/repo' }` repository to a
|
||||
copy and scan that.
|
||||
- **Expect:** **Lizenzen** shows MIT, Apache-2.0 … for the npm and Maven
|
||||
components (okhttp's comes from its parent POM, AndroidX from Google's
|
||||
repository). In the copy, `@corp/*` and every Maven component stay without
|
||||
a license; nothing about them leaves the agent.
|
||||
- **Log:** only when something is missing: `npm/Maven license lookup
|
||||
incomplete`; with the private Maven repository: `Maven licenses not looked up`.
|
||||
- **[visible]** npm and Maven components gain licenses in the SBOM and the
|
||||
**Lizenzen** tab (and copyleft warnings where they apply).
|
||||
|
||||
## After the pass
|
||||
|
||||
- The nightly job on `main` is green with the new mobile targets.
|
||||
|
||||
Reference in new issue
Block a user