diff --git a/.env.example b/.env.example index b91325b..cbefa3f 100644 --- a/.env.example +++ b/.env.example @@ -45,6 +45,10 @@ CVE_MONITOR_SCHEDULE=0 0 0 * * * # GIT_SOURCE_SYNC_MINUTES=30 # WEBHOOK_PUBLIC_URL=https://pruefwerk-hooks.example.com GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos +# NuGet licenses (#467): look up licenses the tree's .nuspec files do not give +# on api.nuget.org (package id and version only; never for ids a nuget.config +# routes to another feed). Set to false to keep the lookup offline. +NUGET_LICENSE_LOOKUP=true # Dynamic PLC testing — ephemeral soft-PLC provisioning (#183). Off unless # enabled; requires the agent container to have Docker access (socket mount). diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index 13476f3..25c1973 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -44,6 +44,9 @@ pub struct ComplianceAgent { pub secrets: SecretBox, /// Managed git sources (#439): allowed hosts, sync interval, webhook origin. pub git_source: Arc, + /// NuGet licenses looked up on nuget.org, for every tenant (#467): public + /// metadata keyed by package and version, in the admin database. + pub(crate) nuget_license_cache: Arc, } impl ComplianceAgent { @@ -69,6 +72,9 @@ impl ComplianceAgent { tracing::error!("{e}; using the default git source settings"); crate::git_source::Settings::default() })); + let nuget_license_cache = Arc::new(crate::pipeline::sbom::MongoLicenseCache::new( + &db_pool.admin_db(), + )); Self { config, db_pool, @@ -82,6 +88,7 @@ impl ComplianceAgent { scan_gate, secrets, git_source, + nuget_license_cache, } } @@ -197,7 +204,8 @@ impl ComplianceAgent { db.clone(), self.llm.clone(), self.http.clone(), - ); + ) + .with_nuget_license_cache(self.nuget_license_cache.clone()); let started = chrono::Utc::now(); orchestrator.run_target(target_id, trigger.clone()).await?; // Support's scans are ours, not the customer's usage. diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 98bc14e..2e4a27e 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -19,7 +19,7 @@ use crate::pipeline::mobsfscan::MobsfscanScanner; use crate::pipeline::patterns::{GdprPatternScanner, OAuthPatternScanner}; use crate::pipeline::plan::build_scan_plan; use crate::pipeline::repo_view::RepoView; -use crate::pipeline::sbom::SbomScanner; +use crate::pipeline::sbom::{LicenseCache, NugetRegistry, SbomScanner}; use crate::pipeline::semgrep::SemgrepScanner; use crate::secrets::SecretBox; @@ -46,6 +46,8 @@ pub struct PipelineOrchestrator { pub(super) secrets: SecretBox, /// Where clones and tracker calls may connect (#256, #294). pub(super) net_guard: NetGuard, + /// The cross-tenant cache of NuGet licenses (#467). + pub(super) nuget_license_cache: Option>, } impl PipelineOrchestrator { @@ -66,9 +68,16 @@ impl PipelineOrchestrator { http, secrets, net_guard, + nuget_license_cache: None, } } + /// Cache the NuGet licenses looked up on nuget.org in `cache` (#467). + pub(crate) fn with_nuget_license_cache(mut self, cache: Arc) -> Self { + self.nuget_license_cache = Some(cache); + self + } + #[tracing::instrument(skip_all, fields(repo_id = repo.name.as_str()))] async fn run_pipeline( &self, @@ -287,7 +296,11 @@ impl PipelineOrchestrator { .await; let (mut sbom_entries, syft_failure) = async { let sbom_scanner = - SbomScanner::new(compliance_core::ExecPolicy::from_env(self.config.app_env)); + SbomScanner::new(compliance_core::ExecPolicy::from_env(self.config.app_env)) + .with_nuget_registry(NugetRegistry::from_env( + self.net_guard, + self.nuget_license_cache.clone(), + )); sbom_scanner.generate(&repo_path, &repo_id).await } .instrument(tracing::info_span!("stage_sbom_generation")) diff --git a/compliance-agent/src/pipeline/sbom/mod.rs b/compliance-agent/src/pipeline/sbom/mod.rs index 1880c13..5f6103b 100644 --- a/compliance-agent/src/pipeline/sbom/mod.rs +++ b/compliance-agent/src/pipeline/sbom/mod.rs @@ -2,10 +2,12 @@ mod cargo_audit; mod gradle; mod mobile; mod nuget; +mod nuget_license; pub(crate) use nuget::is_restored_package; #[cfg(test)] pub(crate) use nuget::nuget_components; +pub(crate) use nuget_license::{LicenseCache, MongoLicenseCache, NugetRegistry}; mod syft; pub(crate) mod unity; @@ -19,11 +21,23 @@ use crate::pipeline::tool_cmd::{run_bounded, tool_in, CARGO_ENV, NPM_ENV}; pub struct SbomScanner { exec: ExecPolicy, + /// Where NuGet licenses missing from the tree are looked up (#467); + /// `None` reads only the tree's `.nuspec` files. + nuget_registry: Option, } impl SbomScanner { pub fn new(exec: ExecPolicy) -> Self { - Self { exec } + Self { + exec, + nuget_registry: None, + } + } + + /// Look up the NuGet licenses the tree does not carry on nuget.org. + pub(crate) fn with_nuget_registry(mut self, registry: Option) -> Self { + self.nuget_registry = registry; + self } } @@ -98,6 +112,9 @@ impl SbomScanner { // NuGet packages from packages.config, project files and restored // package folders, which Syft does not read (#445). nuget::merge_nuget(&mut entries, nuget::nuget_components(repo_path, repo_id)); + // 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; // Enrich Cargo entries with license info from cargo metadata enrich_cargo_licenses(repo_path, &mut entries, self.exec).await; diff --git a/compliance-agent/src/pipeline/sbom/nuget.rs b/compliance-agent/src/pipeline/sbom/nuget.rs index 79c6427..f1d68e8 100644 --- a/compliance-agent/src/pipeline/sbom/nuget.rs +++ b/compliance-agent/src/pipeline/sbom/nuget.rs @@ -136,7 +136,7 @@ pub(crate) fn unresolved_projects(root: &Path) -> Vec { /// A version NuGet would restore exactly: `1.2.3`, `[1.2.3]`, `1.2.3-beta`. /// `None` for a floating version or a range (`1.*`, `[1.0,2.0)`). -fn exact_version(raw: &str) -> Option { +pub(super) fn exact_version(raw: &str) -> Option { let v = raw.trim(); let v = v .strip_prefix('[') diff --git a/compliance-agent/src/pipeline/sbom/nuget_license.rs b/compliance-agent/src/pipeline/sbom/nuget_license.rs new file mode 100644 index 0000000..16ebd13 --- /dev/null +++ b/compliance-agent/src/pipeline/sbom/nuget_license.rs @@ -0,0 +1,1504 @@ +//! Licenses of the NuGet components (#467). +//! +//! None of the files the NuGet components come from (`packages.config`, +//! ``, lockfiles, `project.assets.json`) names a license, so +//! they are filled in here, in two steps: +//! +//! 1. **Local**: the `.nuspec` of a restored package (`packages/./`) +//! carries ``, `` or the +//! older ``. No network. +//! 2. **nuget.org**: the registration leaf of the package version +//! (`api.nuget.org/v3/registration5-gz-semver2//.json`) points +//! at its catalog entry, which holds `licenseExpression`, `licenseFile` and +//! `licenseUrl`. Answers are cached across tenants (the data is public). +//! +//! Only package *ids* and versions leave the agent, and only for packages the +//! tree's `nuget.config` does not route to another feed (see +//! [`RegistryPolicy`]): the name of a private package is the customer's. +//! `NUGET_LICENSE_LOOKUP=false` turns the nuget.org step off. +//! +//! The lookup is bounded (concurrency, per-request timeout, uncached lookups +//! and total time per scan). A package it could not answer for keeps an empty +//! license; nothing here fails the SBOM stage. + +use std::collections::{HashMap, HashSet}; +use std::io::Read; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +use compliance_core::models::SbomEntry; +use compliance_core::NetGuard; +use futures_util::future::BoxFuture; +use futures_util::StreamExt; + +use super::nuget::exact_version; +use crate::pipeline::dotnet::{parse_xml, read_text, relative, walk_sources}; + +/// The package manager name of the NuGet SBOM entries. +const NUGET: &str = "nuget"; + +/// The license of a package that ships its license text as a file. +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"; + +/// The only host a catalog entry is fetched from. +const CATALOG_PREFIX: &str = "https://api.nuget.org/"; + +/// Largest response body read (a registration leaf or catalog entry is a few +/// kilobytes). +const MAX_BODY_BYTES: usize = 2 * 1024 * 1024; + +/// A package version as nuget.org keys it: the lowercase id and the +/// normalised lowercase version. +pub(crate) type PackageKey = (String, String); + +/// Bounds of one scan's nuget.org lookup. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Limits { + /// Requests in flight at once. + pub concurrency: usize, + /// Packages looked up per scan that were not in the cache. The rest stay + /// empty this time and are filled on a later scan, through the cache. + pub max_lookups: usize, + /// Time the whole lookup may take; what answered by then is kept. + pub budget: Duration, +} + +impl Default for Limits { + fn default() -> Self { + Self { + concurrency: 8, + max_lookups: 300, + budget: Duration::from_secs(60), + } + } +} + +/// Per-request timeout of the nuget.org client. +const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); + +/// What a GET answered: the body as served (gzip or not), or `None` for a 404. +pub(crate) type FetchResult = Result>, String>; + +/// HTTP GET, behind a trait so tests answer without the network. +pub(crate) trait Fetch: Send + Sync { + fn get<'a>(&'a self, url: &'a str) -> BoxFuture<'a, FetchResult>; +} + +/// The licenses already known per package version, shared by all tenants. +/// `Some(None)` is a known answer without a license (a package nuget.org does +/// not have, or one that declares none). +pub(crate) trait LicenseCache: Send + Sync { + fn get_many<'a>( + &'a self, + keys: &'a [PackageKey], + ) -> BoxFuture<'a, Result>, String>>; + fn put<'a>( + &'a self, + answers: &'a [(PackageKey, Option)], + ) -> BoxFuture<'a, Result<(), String>>; +} + +/// The nuget.org step: where to fetch, what is cached, how far to go. +#[derive(Clone)] +pub(crate) struct NugetRegistry { + fetch: Arc, + cache: Option>, + limits: Limits, +} + +impl NugetRegistry { + pub(crate) fn new( + fetch: Arc, + cache: Option>, + limits: Limits, + ) -> Self { + Self { + fetch, + cache, + limits, + } + } + + /// The registry over a guarded client, or `None` when the deployment + /// turned the lookup off (`NUGET_LICENSE_LOOKUP=false`) or the client + /// cannot be built. + pub(crate) fn from_env(guard: NetGuard, cache: Option>) -> Option { + if !lookup_enabled(std::env::var("NUGET_LICENSE_LOOKUP").ok().as_deref()) { + tracing::info!( + "NUGET_LICENSE_LOOKUP is off: NuGet licenses come from .nuspec files only" + ); + return None; + } + match HttpFetch::new(guard) { + Ok(fetch) => Some(Self::new(Arc::new(fetch), cache, Limits::default())), + Err(e) => { + tracing::warn!("nuget.org license lookup disabled: {e}"); + None + } + } + } +} + +/// Whether the `NUGET_LICENSE_LOOKUP` value turns the lookup on (the default). +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") + }) +} + +/// Fill the license of every NuGet entry that has none: from the tree's +/// `.nuspec` files, then (with a `registry`) from nuget.org. +#[tracing::instrument(skip_all)] +pub(crate) async fn enrich_nuget_licenses( + root: &Path, + entries: &mut [SbomEntry], + registry: Option<&NugetRegistry>, +) { + let wanted: Vec<(usize, PackageKey)> = entries + .iter() + .enumerate() + .filter(|(_, e)| e.license.is_none()) + .filter_map(|(i, e)| lookup_key(e).map(|k| (i, k))) + .collect(); + if wanted.is_empty() { + return; + } + + let local = local_licenses(root); + let mut found: HashMap> = HashMap::new(); + for (_, key) in &wanted { + if let Some(license) = local.get(key) { + found.insert(key.clone(), Some(license.clone())); + } + } + + if let Some(registry) = registry { + let missing: Vec = unique( + wanted + .iter() + .map(|(_, k)| k) + .filter(|k| !found.contains_key(*k)), + ); + match registry_policy(root) { + RegistryPolicy::Skip(why) => { + tracing::info!("NuGet licenses not looked up on nuget.org: {why}"); + } + policy => { + let allowed: Vec = missing + .into_iter() + .filter(|(id, _)| policy.allows(id)) + .collect(); + found.extend(registry.licenses(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()); + } + } +} + +/// The distinct keys of `keys`, in their first order. +fn unique<'a>(keys: impl Iterator) -> Vec { + let mut seen = HashSet::new(); + keys.filter(|k| seen.insert((*k).clone())) + .cloned() + .collect() +} + +/// The nuget.org key of a NuGet entry: a real package id (no DLL-metadata +/// name, #460) at an exact version (no range). +fn lookup_key(entry: &SbomEntry) -> Option { + if !entry.package_manager.eq_ignore_ascii_case(NUGET) + || entry.version_requirement.is_some() + || !entry + .purl + .as_deref() + .is_some_and(|p| p.starts_with("pkg:nuget/")) + || !is_package_id(&entry.name) + { + return None; + } + let version = normalise_version(&exact_version(&entry.version)?)?; + Some((entry.name.to_ascii_lowercase(), version)) +} + +/// Whether `id` is a valid NuGet package id: letters, digits, `.`, `_`, `-`. +fn is_package_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= 100 + && id + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) +} + +/// A version as nuget.org files it: build metadata dropped, leading zeros +/// dropped, at least three parts, and a fourth part only when it is not `0` +/// (`2.0` → `2.0.0`, `6.2.0.0` → `6.2.0`, `1.0.0-Beta` → `1.0.0-beta`). +/// `None` for something that is not a version. +fn normalise_version(raw: &str) -> Option { + let raw = raw.split('+').next().unwrap_or(raw).trim(); + let (numeric, pre) = match raw.split_once('-') { + Some((n, p)) => (n, Some(p)), + None => (raw, None), + }; + let mut parts: Vec = numeric + .split('.') + .map(|p| p.parse::().ok()) + .collect::>()?; + if parts.is_empty() || parts.len() > 4 { + return None; + } + while parts.len() < 3 { + parts.push(0); + } + if parts.len() == 4 && parts[3] == 0 { + parts.pop(); + } + let mut out = parts + .iter() + .map(u64::to_string) + .collect::>() + .join("."); + if let Some(pre) = pre.filter(|p| !p.is_empty()) { + out.push('-'); + out.push_str(pre); + } + Some(out.to_ascii_lowercase()) +} + +// --------------------------------------------------------------------------- +// Local .nuspec files +// --------------------------------------------------------------------------- + +/// The license of every package whose `.nuspec` is in the tree (restored +/// package folders, committed or not stripped), by its own id and version. +fn local_licenses(root: &Path) -> HashMap { + let mut out = HashMap::new(); + // `packages/` is where the restored packages are, so the source walk + // (which skips it) is not used. + let walker = walkdir::WalkDir::new(root) + .min_depth(1) + .max_depth(16) + .into_iter() + .filter_entry(|e| { + let name = e.file_name().to_string_lossy(); + !(e.file_type().is_dir() + && [".git", "node_modules", "bin", "obj", ".vs"] + .iter() + .any(|d| name.eq_ignore_ascii_case(d))) + }) + .filter_map(Result::ok) + .filter(|e| e.file_type().is_file()) + .filter(|e| { + e.file_name() + .to_string_lossy() + .to_ascii_lowercase() + .ends_with(".nuspec") + }); + for entry in walker { + let Some(text) = read_text(entry.path()) else { + continue; + }; + if let Some((key, license)) = nuspec_license(&text) { + out.entry(key).or_insert(license); + } + } + out +} + +/// The id, version and license a `.nuspec` declares. `None` for a nuspec +/// without a license, or a template (`$id$`) a project packs itself from. +fn nuspec_license(text: &str) -> Option<(PackageKey, String)> { + let doc = parse_xml(text)?; + let metadata = doc + .descendants() + .find(|n| n.is_element() && n.tag_name().name() == "metadata")?; + let child = |name: &str| { + metadata + .children() + .find(|c| c.is_element() && c.tag_name().name() == name) + }; + let text_of = |name: &str| { + child(name) + .and_then(|n| n.text()) + .map(str::trim) + .filter(|t| !t.is_empty()) + }; + let id = text_of("id")?; + let version = text_of("version")?; + if id.contains('$') || version.contains('$') || !is_package_id(id) { + return None; + } + let license = match child("license") { + Some(node) + if node + .attribute("type") + .is_some_and(|t| t.eq_ignore_ascii_case("file")) => + { + Some(LICENSE_FILE.to_string()) + } + Some(node) => node + .text() + .map(str::trim) + .filter(|t| !t.is_empty()) + .map(str::to_string), + None => None, + } + .or_else(|| text_of("licenseUrl").and_then(license_from_url))?; + Some(( + (id.to_ascii_lowercase(), normalise_version(version)?), + license, + )) +} + +/// The license a `licenseUrl` stands for: the SPDX id of a well-known license +/// 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 { + let url = url.trim(); + let lower = url.to_ascii_lowercase(); + let bare = lower + .trim_start_matches("https://") + .trim_start_matches("http://") + .trim_start_matches("www.") + .trim_end_matches('/'); + // Written by NuGet beside a element: the license is elsewhere. + if bare == "aka.ms/deprecatelicenseurl" { + return None; + } + // nuget.org's link to the license file inside the package. + if bare.starts_with("nuget.org/packages/") && bare.ends_with("/license") { + return Some(LICENSE_FILE.to_string()); + } + // nuget.org's page of an expression: the path is the expression. + if let Some(expression) = url + .split_once("licenses.nuget.org/") + .map(|(_, e)| percent_decode(e.trim_end_matches('/'))) + .filter(|e| !e.is_empty()) + { + 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())) +} + +/// 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(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + let escaped = (bytes[i] == b'%') + .then(|| s.get(i + 1..i + 3)) + .flatten() + .and_then(|h| u8::from_str_radix(h, 16).ok()); + match escaped { + Some(b) => { + out.push(b); + i += 3; + } + None => { + out.push(bytes[i]); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +// --------------------------------------------------------------------------- +// nuget.config: which ids may be sent to nuget.org +// --------------------------------------------------------------------------- + +/// Which package ids the tree lets the agent name to nuget.org. +#[derive(Debug)] +pub(crate) enum RegistryPolicy { + /// No `nuget.config` names another feed: every package comes from nuget.org. + All, + /// `` says which feed each id comes from: only ids + /// whose most specific pattern belongs to nuget.org are sent. + Mapped(Vec), + /// A feed other than nuget.org, with no mapping to tell its packages + /// apart: no id is sent (it may be a private package's). + Skip(String), +} + +/// One `` of a ``. +#[derive(Debug, Clone)] +pub(crate) struct SourcePattern { + /// The pattern, lowercase: an id, a prefix ending in `*`, or `*`. + pattern: String, + /// Whether the source it maps to is nuget.org. + nuget_org: bool, +} + +impl RegistryPolicy { + /// Whether `id` may be looked up on nuget.org. + fn allows(&self, id: &str) -> bool { + match self { + RegistryPolicy::All => true, + RegistryPolicy::Skip(_) => false, + RegistryPolicy::Mapped(patterns) => { + let id = id.to_ascii_lowercase(); + let matched: Vec<(usize, bool)> = patterns + .iter() + .filter_map(|p| specificity(&p.pattern, &id).map(|s| (s, p.nuget_org))) + .collect(); + let Some(best) = matched.iter().map(|(s, _)| *s).max() else { + return false; + }; + // NuGet takes the most specific pattern; where it maps the id + // to another feed too, the package may be that feed's. + matched + .iter() + .filter(|(s, _)| *s == best) + .all(|(_, nuget_org)| *nuget_org) + } + } + } +} + +/// How specifically `pattern` matches `id` (both lowercase): an exact id +/// beats any prefix, a longer prefix a shorter one. `None` if it does not. +fn specificity(pattern: &str, id: &str) -> Option { + match pattern.strip_suffix('*') { + Some(prefix) => id.starts_with(prefix).then_some(prefix.len()), + None => (pattern == id).then_some(usize::MAX), + } +} + +/// Whether a package source URL is nuget.org's. +fn is_nuget_org(source: &str) -> bool { + reqwest::Url::parse(source.trim()).is_ok_and(|u| { + u.host_str().is_some_and(|h| { + let h = h.to_ascii_lowercase(); + h == "api.nuget.org" || h == "www.nuget.org" || h == "nuget.org" + }) + }) +} + +/// What the tree's `nuget.config` files allow (any depth, any case). +fn registry_policy(root: &Path) -> RegistryPolicy { + let mut patterns = Vec::new(); + for entry in walk_sources(root) { + if !entry + .file_name() + .to_string_lossy() + .eq_ignore_ascii_case("nuget.config") + { + continue; + } + let Some(text) = read_text(entry.path()) else { + continue; + }; + let Some(doc) = parse_xml(&text) else { + continue; + }; + let element = |name: &str| { + doc.descendants() + .find(|n| n.is_element() && n.tag_name().name() == name) + }; + // key -> whether it is nuget.org. + let mut sources: HashMap = HashMap::new(); + if let Some(list) = element("packageSources") { + for add in list + .children() + .filter(|n| n.is_element() && n.tag_name().name() == "add") + { + if let (Some(key), Some(value)) = (add.attribute("key"), add.attribute("value")) { + sources.insert(key.to_ascii_lowercase(), is_nuget_org(value)); + } + } + } + let mapping = element("packageSourceMapping"); + match mapping { + Some(mapping) => { + for source in mapping + .children() + .filter(|n| n.is_element() && n.tag_name().name() == "packageSource") + { + let key = source + .attribute("key") + .unwrap_or_default() + .to_ascii_lowercase(); + // A key this file does not define is nuget.org only by + // NuGet's default name for it. + let nuget_org = sources.get(&key).copied().unwrap_or(key == "nuget.org"); + patterns.extend( + source + .children() + .filter(|n| n.is_element() && n.tag_name().name() == "package") + .filter_map(|n| n.attribute("pattern")) + .map(|p| SourcePattern { + pattern: p.trim().to_ascii_lowercase(), + nuget_org, + }), + ); + } + } + None => { + if let Some((key, _)) = sources.iter().find(|(_, nuget_org)| !**nuget_org) { + return RegistryPolicy::Skip(format!( + "{} lists the package source '{key}' besides nuget.org and no \ + , so a package id may be a private one", + relative(root, entry.path()) + )); + } + } + } + } + if patterns.is_empty() { + RegistryPolicy::All + } else { + RegistryPolicy::Mapped(patterns) + } +} + +// --------------------------------------------------------------------------- +// nuget.org +// --------------------------------------------------------------------------- + +/// How one package's lookup ended. +enum Outcome { + /// nuget.org answered: the license, or none. + Answer(Option), + /// 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) -> HashMap> { + if keys.is_empty() { + return HashMap::new(); + } + let mut out = HashMap::new(); + if let Some(cache) = &self.cache { + match cache.get_many(&keys).await { + Ok(hits) => out.extend(hits), + Err(e) => tracing::warn!("NuGet license cache not read: {e}"), + } + } + let uncached: Vec = keys.into_iter().filter(|k| !out.contains_key(k)).collect(); + let deferred = uncached.len().saturating_sub(self.limits.max_lookups); + let asked: Vec = uncached.into_iter().take(self.limits.max_lookups).collect(); + let count = asked.len(); + + let answers: Vec<(PackageKey, Outcome)> = futures_util::stream::iter(asked) + .map(|key| async move { + let outcome = self.lookup(&key).await; + (key, outcome) + }) + .buffer_unordered(self.limits.concurrency.max(1)) + .take_until(tokio::time::sleep(self.limits.budget)) + .collect() + .await; + + let unanswered = count - answers.len(); + let mut failed = 0usize; + let mut first_error = None; + let mut fresh = Vec::new(); + for (key, outcome) in answers { + match outcome { + Outcome::Answer(license) => fresh.push((key, license)), + Outcome::Failed(e) => { + failed += 1; + first_error.get_or_insert(e); + } + } + } + // One line per scan, whatever went wrong how often. + if failed > 0 || unanswered > 0 || deferred > 0 { + tracing::warn!( + failed, + unanswered, + deferred, + "nuget.org license lookup incomplete: {failed} failed, {unanswered} not answered \ + within {}s, {deferred} over the limit of {} per scan (left empty){}", + self.limits.budget.as_secs(), + self.limits.max_lookups, + 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!("NuGet license cache not written: {e}"); + } + } + } + out.extend(fresh); + out + } + + /// The license nuget.org holds for one package version. + async fn lookup(&self, (id, version): &PackageKey) -> Outcome { + let url = format!("{REGISTRATION_BASE}/{id}/{version}.json"); + let leaf = match self + .fetch + .get(&url) + .await + .and_then(|b| b.map(decode_body).transpose()) + { + Ok(Some(body)) => body, + // Not on nuget.org (another feed's package, or unlisted for good). + Ok(None) => return Outcome::Answer(None), + Err(e) => return Outcome::Failed(format!("{id} {version}: {e}")), + }; + let catalog = match catalog_entry(&leaf) { + Ok(CatalogEntry::Inline(entry)) => entry, + Ok(CatalogEntry::Link(link)) => match self + .fetch + .get(&link) + .await + .and_then(|b| b.map(decode_body).transpose()) + { + Ok(Some(body)) => match serde_json::from_slice(&body) { + Ok(entry) => entry, + Err(e) => { + return Outcome::Failed(format!("{id} {version}: catalog entry: {e}")) + } + }, + Ok(None) => return Outcome::Answer(None), + Err(e) => return Outcome::Failed(format!("{id} {version}: catalog entry: {e}")), + }, + Err(e) => return Outcome::Failed(format!("{id} {version}: {e}")), + }; + Outcome::Answer(catalog_license(&catalog)) + } +} + +/// A registration leaf's `catalogEntry`: the entry itself (as in a +/// registration page) or the URL of it (as in a leaf). +#[derive(Debug)] +enum CatalogEntry { + Inline(serde_json::Value), + Link(String), +} + +/// The `catalogEntry` of a registration leaf. A link is followed only to +/// nuget.org's own API host. +fn catalog_entry(leaf: &[u8]) -> Result { + let leaf: serde_json::Value = + serde_json::from_slice(leaf).map_err(|e| format!("registration leaf: {e}"))?; + match leaf.get("catalogEntry") { + Some(serde_json::Value::String(link)) if link.starts_with(CATALOG_PREFIX) => { + Ok(CatalogEntry::Link(link.clone())) + } + Some(serde_json::Value::String(link)) => { + Err(format!("catalog entry outside {CATALOG_PREFIX}: {link}")) + } + Some(entry @ serde_json::Value::Object(_)) => Ok(CatalogEntry::Inline(entry.clone())), + _ => Err("registration leaf without a catalogEntry".to_string()), + } +} + +/// The license a catalog entry declares: its expression, [`LICENSE_FILE`] for +/// a packaged license file, or what its `licenseUrl` stands for. +fn catalog_license(entry: &serde_json::Value) -> Option { + let field = |name: &str| { + entry + .get(name) + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()) + }; + if let Some(expression) = field("licenseExpression") { + return Some(expression.to_string()); + } + if field("licenseFile").is_some() { + return Some(LICENSE_FILE.to_string()); + } + field("licenseUrl").and_then(license_from_url) +} + +/// GET over a [`guarded_client_builder`] client: every address checked by +/// the net guard, redirects re-checked, a per-request timeout. +/// +/// [`guarded_client_builder`]: compliance_core::guarded_net::guarded_client_builder +struct HttpFetch { + http: reqwest::Client, + guard: NetGuard, +} + +impl HttpFetch { + fn new(guard: NetGuard) -> Result { + let http = compliance_core::guarded_net::guarded_client_builder(guard) + .timeout(REQUEST_TIMEOUT) + .connect_timeout(Duration::from_secs(5)) + .build() + .map_err(|e| format!("HTTP client: {e}"))?; + Ok(Self { http, guard }) + } + + async fn get_body(&self, url: &str) -> FetchResult { + self.guard.check_url(url).map_err(|e| e.to_string())?; + let mut resp = self.http.get(url).send().await.map_err(|e| e.to_string())?; + if resp.status() == reqwest::StatusCode::NOT_FOUND { + return Ok(None); + } + if !resp.status().is_success() { + return Err(format!("HTTP {}", resp.status())); + } + let mut body = Vec::new(); + while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? { + if body.len() + chunk.len() > MAX_BODY_BYTES { + return Err(format!("response larger than {MAX_BODY_BYTES} bytes")); + } + body.extend_from_slice(&chunk); + } + Ok(Some(body)) + } +} + +impl Fetch for HttpFetch { + fn get<'a>(&'a self, url: &'a str) -> BoxFuture<'a, FetchResult> { + Box::pin(self.get_body(url)) + } +} + +/// 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) -> Result, String> { + if !body.starts_with(&[0x1f, 0x8b]) { + return Ok(body); + } + let mut out = Vec::new(); + flate2::read::GzDecoder::new(body.as_slice()) + .take(MAX_BODY_BYTES as u64 + 1) + .read_to_end(&mut out) + .map_err(|e| format!("gzip: {e}"))?; + if out.len() > MAX_BODY_BYTES { + return Err(format!("response larger than {MAX_BODY_BYTES} bytes")); + } + Ok(out) +} + +// --------------------------------------------------------------------------- +// Cache +// --------------------------------------------------------------------------- + +/// How long a license is cached: a published version's license does not change. +const CACHE_TTL_FOUND: Duration = Duration::from_secs(365 * 24 * 3600); +/// How long "no license known" is cached: the package may be published later. +const CACHE_TTL_NONE: Duration = Duration::from_secs(7 * 24 * 3600); + +/// The cache in the cluster-wide admin database (`__admin`), shared +/// by every tenant: what it holds is nuget.org's public metadata, keyed by +/// package id and version, with nothing of the tenant that asked. +pub(crate) struct MongoLicenseCache { + collection: mongodb::Collection, + indexed: tokio::sync::OnceCell<()>, +} + +/// One cached answer. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +struct CachedLicense { + /// `@`, both lowercase. + #[serde(rename = "_id")] + key: String, + license: Option, + /// Removed by Mongo's TTL monitor after this. + expires_at: mongodb::bson::DateTime, +} + +impl MongoLicenseCache { + /// The collection name in the admin database. + pub(crate) const COLLECTION: &'static str = "nuget_licenses"; + + pub(crate) fn new(admin_db: &mongodb::Database) -> Self { + Self { + collection: admin_db.collection(Self::COLLECTION), + indexed: tokio::sync::OnceCell::new(), + } + } + + /// The TTL index, once per process. + async fn ensure_index(&self) -> Result<(), String> { + self.indexed + .get_or_try_init(|| async { + let index = mongodb::IndexModel::builder() + .keys(mongodb::bson::doc! { "expires_at": 1 }) + .options( + mongodb::options::IndexOptions::builder() + .expire_after(Duration::ZERO) + .build(), + ) + .build(); + self.collection + .create_index(index) + .await + .map(drop) + .map_err(|e| e.to_string()) + }) + .await + .map(drop) + } + + fn id((id, version): &PackageKey) -> String { + format!("{id}@{version}") + } + + async fn read( + &self, + keys: &[PackageKey], + ) -> Result>, String> { + let by_id: HashMap = keys.iter().map(|k| (Self::id(k), k)).collect(); + let ids: Vec<&String> = by_id.keys().collect(); + let mut cursor = self + .collection + .find(mongodb::bson::doc! { + "_id": { "$in": ids }, + // The TTL monitor runs once a minute; an expired row is gone. + "expires_at": { "$gt": mongodb::bson::DateTime::now() }, + }) + .await + .map_err(|e| e.to_string())?; + let mut out = HashMap::new(); + while let Some(row) = cursor.next().await { + let row = row.map_err(|e| e.to_string())?; + if let Some(key) = by_id.get(&row.key) { + out.insert((*key).clone(), row.license); + } + } + Ok(out) + } + + async fn write(&self, answers: &[(PackageKey, Option)]) -> Result<(), String> { + self.ensure_index().await?; + let now = std::time::SystemTime::now(); + for (key, license) in answers { + let ttl = if license.is_some() { + CACHE_TTL_FOUND + } else { + CACHE_TTL_NONE + }; + let row = CachedLicense { + key: Self::id(key), + license: license.clone(), + expires_at: mongodb::bson::DateTime::from_system_time(now + ttl), + }; + self.collection + .replace_one(mongodb::bson::doc! { "_id": &row.key }, &row) + .upsert(true) + .await + .map_err(|e| e.to_string())?; + } + Ok(()) + } +} + +impl LicenseCache for MongoLicenseCache { + fn get_many<'a>( + &'a self, + keys: &'a [PackageKey], + ) -> BoxFuture<'a, Result>, String>> { + Box::pin(self.read(keys)) + } + + fn put<'a>( + &'a self, + answers: &'a [(PackageKey, Option)], + ) -> BoxFuture<'a, Result<(), String>> { + Box::pin(self.write(answers)) + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + use std::io::Write; + use std::path::PathBuf; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + + struct Tree(PathBuf); + impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + fn tree(files: &[(&str, &str)]) -> Tree { + let dir = std::env::temp_dir().join(format!("cs-nuget-lic-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).expect("mkdir"); + for (path, content) in files { + let full = dir.join(path); + std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir"); + std::fs::write(full, content).expect("write"); + } + Tree(dir) + } + + fn entry(name: &str, version: &str) -> SbomEntry { + let mut e = SbomEntry::new("r".into(), name.into(), version.into(), "nuget".into()); + e.purl = Some(format!("pkg:nuget/{name}@{version}")); + e + } + + fn gzip(text: &str) -> Vec { + let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + enc.write_all(text.as_bytes()).expect("gzip"); + enc.finish().expect("gzip") + } + + fn nuspec(metadata: &str) -> String { + format!( + r#" + + {metadata} +"# + ) + } + + /// Answers from a table of URLs; counts the requests. + #[derive(Default)] + struct FakeFetch { + answers: HashMap, + calls: AtomicUsize, + } + impl FakeFetch { + fn with(mut self, url: &str, answer: FetchResult) -> Self { + self.answers.insert(url.to_string(), answer); + self + } + } + impl Fetch for FakeFetch { + fn get<'a>(&'a self, url: &'a str) -> BoxFuture<'a, FetchResult> { + self.calls.fetch_add(1, Ordering::SeqCst); + let answer = self + .answers + .get(url) + .cloned() + .unwrap_or_else(|| Err(format!("no route to {url}"))); + Box::pin(async move { answer }) + } + } + + /// Never answers. + struct Hang; + impl Fetch for Hang { + fn get<'a>(&'a self, _: &'a str) -> BoxFuture<'a, FetchResult> { + Box::pin(std::future::pending()) + } + } + + #[derive(Default)] + struct MemoryCache(Mutex>>); + impl LicenseCache for MemoryCache { + fn get_many<'a>( + &'a self, + keys: &'a [PackageKey], + ) -> BoxFuture<'a, Result>, String>> { + let map = self.0.lock().unwrap(); + let hits = keys + .iter() + .filter_map(|k| map.get(k).map(|v| (k.clone(), v.clone()))) + .collect(); + Box::pin(async move { Ok(hits) }) + } + fn put<'a>( + &'a self, + answers: &'a [(PackageKey, Option)], + ) -> BoxFuture<'a, Result<(), String>> { + self.0.lock().unwrap().extend(answers.iter().cloned()); + Box::pin(async { Ok(()) }) + } + } + + fn registry(fetch: Arc, cache: Option>) -> NugetRegistry { + NugetRegistry::new(fetch, cache, Limits::default()) + } + + const NEWTONSOFT_LEAF: &str = + "https://api.nuget.org/v3/registration5-gz-semver2/newtonsoft.json/13.0.1.json"; + const NEWTONSOFT_CATALOG: &str = + "https://api.nuget.org/v3/catalog0/data/2022.12.08.16.43.03/newtonsoft.json.13.0.1.json"; + const DOTNETZIP_LEAF: &str = + "https://api.nuget.org/v3/registration5-gz-semver2/dotnetzip/1.16.0.json"; + + /// A registration leaf as nuget.org serves it (gzip, catalogEntry a link). + fn linked_leaf() -> Vec { + gzip(&format!( + r#"{{"@id":"{NEWTONSOFT_LEAF}","@type":["Package","http://schema.nuget.org/catalog#Permalink"], + "catalogEntry":"{NEWTONSOFT_CATALOG}","listed":true, + "packageContent":"https://api.nuget.org/v3-flatcontainer/newtonsoft.json/13.0.1/newtonsoft.json.13.0.1.nupkg", + "registration":"https://api.nuget.org/v3/registration5-gz-semver2/newtonsoft.json/index.json"}}"# + )) + } + + /// A leaf whose catalogEntry is inline, as in a registration page. + fn inline_leaf() -> Vec { + br#"{"@id":"x","catalogEntry":{"id":"DotNetZip","version":"1.16.0", + "licenseExpression":"", + "licenseUrl":"https://raw.githubusercontent.com/haf/DotNetZip.Semverd/master/LICENSE"}}"# + .to_vec() + } + + #[test] + fn nuspec_license_expression() { + let text = nuspec( + r#"Newtonsoft.Json13.0.1 + MIT + https://aka.ms/deprecateLicenseUrl"#, + ); + assert_eq!( + nuspec_license(&text), + Some((("newtonsoft.json".into(), "13.0.1".into()), "MIT".into())) + ); + } + + #[test] + fn nuspec_license_file() { + let text = nuspec( + r#"DotNetZip1.16.0 + LICENSE.txt"#, + ); + assert_eq!(nuspec_license(&text).unwrap().1, "LicenseRef-file"); + } + + #[test] + fn nuspec_license_url_known_and_unknown() { + let known = nuspec( + r#"log4net2.0.8 + http://www.apache.org/licenses/LICENSE-2.0"#, + ); + assert_eq!(nuspec_license(&known).unwrap().1, "Apache-2.0"); + let unknown = nuspec( + r#"EntityFramework6.2.0 + http://go.microsoft.com/fwlink/?LinkID=262998"#, + ); + assert_eq!( + nuspec_license(&unknown).unwrap().1, + "http://go.microsoft.com/fwlink/?LinkID=262998" + ); + // A template a project packs itself from names no real package. + let template = nuspec( + r#"$id$$version$MIT"#, + ); + assert_eq!(nuspec_license(&template), None); + } + + #[test] + fn license_urls_map_to_spdx() { + let map = |u: &str| license_from_url(u); + assert_eq!( + map("https://opensource.org/licenses/MIT").as_deref(), + Some("MIT") + ); + assert_eq!( + map("http://opensource.org/licenses/mit-license.php").as_deref(), + Some("MIT") + ); + assert_eq!( + map("https://opensource.org/licenses/MS-PL").as_deref(), + Some("MS-PL") + ); + assert_eq!( + map("https://opensource.org/licenses/BSD-3-Clause").as_deref(), + Some("BSD-3-Clause") + ); + assert_eq!( + map("https://www.gnu.org/licenses/lgpl-2.1.html").as_deref(), + Some("LGPL-2.1-only") + ); + assert_eq!( + map("https://www.gnu.org/licenses/agpl.html").as_deref(), + Some("AGPL-3.0-or-later") + ); + assert_eq!( + map("https://licenses.nuget.org/MIT%20OR%20Apache-2.0").as_deref(), + Some("MIT OR Apache-2.0") + ); + assert_eq!( + map("https://www.nuget.org/packages/DotNetZip/1.16.0/license").as_deref(), + Some("LicenseRef-file") + ); + assert_eq!(map("https://aka.ms/deprecateLicenseUrl"), None); + } + + #[test] + fn versions_are_normalised_as_nuget_org_files_them() { + let n = |v: &str| normalise_version(v); + assert_eq!(n("6.2.0.0").as_deref(), Some("6.2.0")); + assert_eq!(n("4.0.30319.1").as_deref(), Some("4.0.30319.1")); + assert_eq!(n("2.0").as_deref(), Some("2.0.0")); + assert_eq!(n("13.0.01").as_deref(), Some("13.0.1")); + assert_eq!(n("1.0.0-Beta2+sha.abc").as_deref(), Some("1.0.0-beta2")); + assert_eq!(n("1.*"), None); + } + + #[test] + fn only_real_ids_at_exact_versions_are_looked_up() { + assert_eq!( + lookup_key(&entry("Newtonsoft.Json", "13.0.1.0")), + Some(("newtonsoft.json".into(), "13.0.1".into())) + ); + // A DLL-metadata name (#460). + assert_eq!(lookup_key(&entry("Some Vendor Library", "1.0.0")), None); + // A range. + let mut ranged = SbomEntry::new("r".into(), "Polly".into(), String::new(), "nuget".into()); + ranged.version_requirement = Some("7.*".into()); + assert_eq!(lookup_key(&ranged), None); + // No purl. + let mut bare = entry("Dapper", "2.0.4"); + bare.purl = None; + assert_eq!(lookup_key(&bare), None); + // Another ecosystem. + let mut npm = entry("left-pad", "1.3.0"); + npm.package_manager = "npm".into(); + assert_eq!(lookup_key(&npm), None); + } + + #[test] + fn registration_leaf_with_a_linked_catalog_entry() { + let body = decode_body(linked_leaf()).unwrap(); + match catalog_entry(&body).unwrap() { + CatalogEntry::Link(link) => assert_eq!(link, NEWTONSOFT_CATALOG), + other => panic!("expected a link, got {other:?}"), + } + // A link off nuget.org's API host is not followed. + let off_host = br#"{"catalogEntry":"https://example.com/x.json"}"#; + assert!(catalog_entry(off_host).is_err()); + } + + #[test] + fn registration_leaf_with_an_inline_catalog_entry() { + let CatalogEntry::Inline(entry) = catalog_entry(&inline_leaf()).unwrap() else { + panic!("expected inline"); + }; + assert_eq!( + catalog_license(&entry).as_deref(), + Some("https://raw.githubusercontent.com/haf/DotNetZip.Semverd/master/LICENSE") + ); + let file = serde_json::json!({ + "licenseUrl": "https://aka.ms/deprecateLicenseUrl", "licenseFile": "LICENSE.txt" + }); + assert_eq!(catalog_license(&file).as_deref(), Some("LicenseRef-file")); + } + + #[tokio::test] + async fn local_nuspec_comes_first() { + let t = tree(&[( + "packages/Newtonsoft.Json.13.0.1/Newtonsoft.Json.nuspec", + &nuspec( + r#"Newtonsoft.Json13.0.1 + MIT"#, + ), + )]); + let fetch = Arc::new(FakeFetch::default()); + 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")); + assert_eq!(fetch.calls.load(Ordering::SeqCst), 0, "nuget.org was asked"); + } + + #[tokio::test] + async fn nuget_org_fills_the_rest_and_the_cache() { + let t = tree(&[]); + let fetch = Arc::new( + FakeFetch::default() + .with(NEWTONSOFT_LEAF, Ok(Some(linked_leaf()))) + .with( + NEWTONSOFT_CATALOG, + Ok(Some( + br#"{"id":"Newtonsoft.Json","licenseExpression":"MIT","licenseUrl":"https://licenses.nuget.org/MIT"}"# + .to_vec(), + )), + ) + .with(DOTNETZIP_LEAF, Ok(Some(inline_leaf()))), + ); + let cache = Arc::new(MemoryCache::default()); + let mut entries = vec![ + entry("Newtonsoft.Json", "13.0.1"), + entry("DotNetZip", "1.16.0"), + ]; + 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!(entries[1].license.as_deref().unwrap().contains("DotNetZip")); + assert_eq!(cache.0.lock().unwrap().len(), 2); + } + + #[tokio::test] + async fn a_cache_hit_asks_nobody() { + let t = tree(&[]); + let fetch = Arc::new(FakeFetch::default()); + let cache = Arc::new(MemoryCache::default()); + cache.0.lock().unwrap().insert( + ("newtonsoft.json".into(), "13.0.1".into()), + Some("MIT".into()), + ); + let mut entries = vec![entry("Newtonsoft.Json", "13.0.1.0")]; + enrich_nuget_licenses( + &t.0, + &mut entries, + Some(®istry(fetch.clone(), Some(cache))), + ) + .await; + assert_eq!(entries[0].license.as_deref(), Some("MIT")); + assert_eq!(fetch.calls.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn a_network_failure_leaves_the_license_empty_and_uncached() { + let t = tree(&[]); + let fetch = Arc::new(FakeFetch::default().with( + NEWTONSOFT_LEAF, + Err("error sending request: connection refused".into()), + )); + let cache = Arc::new(MemoryCache::default()); + let mut entries = vec![entry("Newtonsoft.Json", "13.0.1")]; + enrich_nuget_licenses( + &t.0, + &mut entries, + Some(®istry(fetch, Some(cache.clone()))), + ) + .await; + assert_eq!(entries[0].license, None); + assert!(cache.0.lock().unwrap().is_empty(), "a failure was cached"); + } + + #[tokio::test] + async fn a_package_nuget_org_does_not_have_is_cached_as_none() { + let t = tree(&[]); + let fetch = Arc::new(FakeFetch::default().with(NEWTONSOFT_LEAF, Ok(None))); + let cache = Arc::new(MemoryCache::default()); + let mut entries = vec![entry("Newtonsoft.Json", "13.0.1")]; + enrich_nuget_licenses( + &t.0, + &mut entries, + Some(®istry(fetch, Some(cache.clone()))), + ) + .await; + assert_eq!(entries[0].license, None); + assert_eq!( + cache + .0 + .lock() + .unwrap() + .get(&("newtonsoft.json".into(), "13.0.1".into())), + Some(&None) + ); + } + + #[tokio::test] + async fn the_lookup_is_bounded() { + let t = tree(&[]); + // Over the per-scan cap: only the first package is asked about. + let fetch = Arc::new(FakeFetch::default()); + let capped = NugetRegistry::new( + fetch.clone(), + None, + Limits { + max_lookups: 1, + ..Limits::default() + }, + ); + let mut entries = vec![ + entry("Newtonsoft.Json", "13.0.1"), + entry("DotNetZip", "1.16.0"), + ]; + enrich_nuget_licenses(&t.0, &mut entries, Some(&capped)).await; + assert_eq!(fetch.calls.load(Ordering::SeqCst), 1); + + // A registry that never answers is given up on at the budget. + let slow = NugetRegistry::new( + Arc::new(Hang), + None, + Limits { + budget: Duration::from_millis(50), + ..Limits::default() + }, + ); + let started = std::time::Instant::now(); + enrich_nuget_licenses(&t.0, &mut entries, Some(&slow)).await; + assert!(started.elapsed() < Duration::from_secs(5)); + assert!(entries.iter().all(|e| e.license.is_none())); + } + + #[test] + fn nuget_config_decides_which_ids_leave() { + // No nuget.config: everything comes from nuget.org. + assert!(registry_policy(&tree(&[]).0).allows("Newtonsoft.Json")); + + // Another feed and no mapping: nothing is sent. + let private = tree(&[( + ".nuget/NuGet.Config", + r#" + + + "#, + )]); + let policy = registry_policy(&private.0); + assert!(matches!(policy, RegistryPolicy::Skip(_)), "{policy:?}"); + assert!(!policy.allows("Newtonsoft.Json")); + + // Only nuget.org listed: everything. + let public = tree(&[( + "nuget.config", + r#" + + "#, + )]); + assert!(registry_policy(&public.0).allows("DotNetZip")); + + // A mapping: only ids whose most specific pattern is nuget.org's. + let mapped = tree(&[( + "nuget.config", + r#" + + + + + + + + + + + + "#, + )]); + let policy = registry_policy(&mapped.0); + assert!(policy.allows("Newtonsoft.Json")); + assert!(policy.allows("DotNetZip")); + assert!(!policy.allows("acme.plant.core")); + assert!(!policy.allows("Newtonsoft.Json.Internal")); + } + + #[tokio::test] + async fn a_private_feed_keeps_ids_local() { + let t = tree(&[( + "nuget.config", + r#" + + "#, + )]); + let fetch = Arc::new(FakeFetch::default()); + 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!(fetch.calls.load(Ordering::SeqCst), 0); + } + + #[test] + fn the_switch_defaults_to_on() { + assert!(lookup_enabled(None)); + assert!(lookup_enabled(Some("true"))); + assert!(!lookup_enabled(Some("false"))); + assert!(!lookup_enabled(Some("0"))); + } + + #[tokio::test] + #[ignore = "needs network"] + async fn nuget_org_answers_through_the_guarded_client() { + let reg = NugetRegistry::new( + Arc::new(HttpFetch::new(NetGuard::public_only()).unwrap()), + None, + Limits::default(), + ); + let mut entries = vec![ + entry("Newtonsoft.Json", "13.0.1"), + entry("DotNetZip", "1.16.0"), + entry("EntityFramework", "6.2.0.0"), + ]; + enrich_nuget_licenses(&tree(&[]).0, &mut entries, Some(®)).await; + let licenses: Vec<_> = entries.iter().map(|e| e.license.clone()).collect(); + assert_eq!(licenses[0].as_deref(), Some("MIT"), "{licenses:?}"); + assert!(licenses.iter().all(Option::is_some), "{licenses:?}"); + } + + #[tokio::test] + #[ignore = "needs MongoDB (TEST_MONGODB_URI)"] + async fn the_mongo_cache_round_trips() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let client = mongodb::Client::with_uri_str(&uri).await.unwrap(); + let db = client.database(&format!("cs_nuget_lic_{}", uuid::Uuid::new_v4().simple())); + let cache = MongoLicenseCache::new(&db); + let found: PackageKey = ("newtonsoft.json".into(), "13.0.1".into()); + let none: PackageKey = ("dotnetzip".into(), "1.16.0".into()); + let other: PackageKey = ("log4net".into(), "2.0.8".into()); + cache + .put(&[(found.clone(), Some("MIT".into())), (none.clone(), None)]) + .await + .unwrap(); + // A second write of the same key replaces it. + cache + .put(&[(found.clone(), Some("MIT".into()))]) + .await + .unwrap(); + let hits = cache + .get_many(&[found.clone(), none.clone(), other.clone()]) + .await + .unwrap(); + db.drop().await.unwrap(); + assert_eq!(hits.get(&found), Some(&Some("MIT".to_string()))); + assert_eq!(hits.get(&none), Some(&None)); + assert!(!hits.contains_key(&other)); + } + + #[test] + fn gzip_bodies_are_decoded_and_plain_ones_kept() { + assert_eq!(decode_body(gzip("{}")).unwrap(), b"{}"); + assert_eq!(decode_body(b"{}".to_vec()).unwrap(), b"{}"); + } +} diff --git a/docs/guide/dotnet-en.md b/docs/guide/dotnet-en.md index 0e8e812..a026c56 100644 --- a/docs/guide/dotnet-en.md +++ b/docs/guide/dotnet-en.md @@ -32,6 +32,19 @@ Every package with an exact version gets the purl `pkg:nuget/@` and is matched against OSV (ecosystem NuGet). A version range (`7.*`, `[1.0,2.0)`) is listed without a purl, with the range as its requirement. +**Licenses of NuGet packages.** First from the `.nuspec` of a restored package +(`packages/./`): `` as an SPDX +expression, `` as `LicenseRef-file`, an older +`` as an SPDX id when it points at a well-known license (MIT, +Apache-2.0, BSD, MS-PL, LGPL, …), otherwise as the URL. What is still missing +is looked up on nuget.org (the registration API on `api.nuget.org`, package id +and version only, no packages). Packages a `nuget.config` maps to another +source with `` are never looked up; when a `nuget.config` +lists another source without a mapping, nothing of that tree is looked up, as +a package id may be an internal one. Answers are cached for all tenants +(public data). `NUGET_LICENSE_LOOKUP=false` turns the lookup off for a +deployment. + **Dependencies not fully resolved.** A project with `` items and neither `packages.lock.json` nor `obj/project.assets.json` names only its direct packages. The scan lists it under **Nicht ausgeführt** diff --git a/docs/guide/dotnet.md b/docs/guide/dotnet.md index ddbe1e9..94c9ce3 100644 --- a/docs/guide/dotnet.md +++ b/docs/guide/dotnet.md @@ -33,6 +33,20 @@ wird gegen OSV (Ökosystem NuGet) abgeglichen. Ein Versionsbereich (`7.*`, `[1.0,2.0)`) steht ohne purl in der Stückliste, mit dem Bereich als Anforderung. +**Lizenzen der NuGet-Pakete.** Zuerst aus der `.nuspec` eines +wiederhergestellten Pakets (`packages/./`): `` als SPDX-Ausdruck, `` als +`LicenseRef-file`, eine ältere `` als SPDX-Kennung, wenn sie auf +eine bekannte Lizenz zeigt (MIT, Apache-2.0, BSD, MS-PL, LGPL, …), sonst als +URL. Was dort fehlt, wird bei nuget.org nachgeschlagen (Registration-API auf +`api.nuget.org`, nur Paket-Id und Version, keine Pakete). Nicht gefragt wird +nach Paketen, die eine `nuget.config` per `` einer +anderen Quelle zuordnet; nennt eine `nuget.config` eine andere Quelle ohne +Zuordnung, wird für diesen Baum gar nicht nachgeschlagen, denn eine Paket-Id +kann die eines internen Pakets sein. Die Antworten werden für alle Mandanten +zwischengespeichert (öffentliche Daten). `NUGET_LICENSE_LOOKUP=false` schaltet +die Abfrage für eine Installation ab. + **Unvollständig aufgelöste Abhängigkeiten.** Ein Projekt mit `` ohne `packages.lock.json` und ohne `obj/project.assets.json` nennt nur seine direkten Pakete. Die Prüfung führt diff --git a/docs/reference/tools.md b/docs/reference/tools.md index f352be3..d9817ea 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -109,6 +109,10 @@ Prüfwerk matches every SBOM component directly against two public vulnerability Matches are stored as CVE alerts with CVSS scores and re-checked hourly, so newly published CVEs against an unchanged dependency still raise a notification. +## 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. + ## Custom OAuth Scanner A purpose-built scanner that detects OAuth and OIDC misconfigurations in your code, including: