feat(sbom): transitive NuGet packages resolved from nuget.org metadata (#461) #489

Merged
sharang merged 1 commits from feat/461-transitive-nuget into main 2026-10-06 09:07:36 +00:00
9 changed files with 886 additions and 57 deletions

No files matched your search

@@ -57,7 +57,7 @@ fn nuget_components_and_the_unresolved_warning() {
);
// packages.config lists transitive packages too; the PackageReference
// project without a lockfile does not.
let unresolved: Vec<String> = crate::pipeline::sbom::unlocked_ecosystems(&fixture())
let unresolved: Vec<String> = crate::pipeline::sbom::unlocked_ecosystems(&fixture(), &[])
.into_iter()
.map(|u| u.manifest)
.collect();
@@ -309,6 +309,9 @@ impl PipelineOrchestrator {
.with_nuget_registry(NugetRegistry::from_env(
self.net_guard,
self.nuget_license_cache.clone(),
))
.with_nuget_resolution(crate::pipeline::sbom::nuget_resolution_enabled(
self.config.app_env,
));
sbom_scanner.generate(&repo_path, &repo_id).await
}
@@ -317,6 +320,7 @@ impl PipelineOrchestrator {
let mut sbom_entries = generated.entries;
let syft_failure = generated.syft_failure;
let unmapped_assemblies = generated.unmapped_assemblies;
let resolved_nuget = generated.resolved_nuget;
// Syft reads the lockfiles and archives: without it the SBOM is short
// of most components, and the SBOM requirements are not assessed.
if let Some(reason) = syft_failure {
@@ -336,7 +340,7 @@ impl PipelineOrchestrator {
// the project's own code, which this deployment may not. Syft reports
// nothing for it, so say so rather than leaving the gap in an SBOM that
// looks complete.
for eco in crate::pipeline::sbom::unlocked_ecosystems(&repo_path) {
for eco in crate::pipeline::sbom::unlocked_ecosystems(&repo_path, &resolved_nuget) {
self.skip_stage(
scan_run_id,
SkippedStage::new(
+34 -6
View File
@@ -5,11 +5,13 @@ mod mobile;
mod nuget;
mod nuget_assembly;
mod nuget_license;
mod nuget_resolve;
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;
mod syft;
pub(crate) mod unity;
@@ -26,6 +28,9 @@ pub struct SbomScanner {
/// Where NuGet licenses missing from the tree are looked up (#467);
/// `None` reads only the tree's `.nuspec` files.
nuget_registry: Option<NugetRegistry>,
/// Whether the transitive packages of unlocked `<PackageReference>`
/// projects are resolved on that registry (#461).
resolve_nuget: bool,
}
impl SbomScanner {
@@ -33,9 +38,17 @@ impl SbomScanner {
Self {
exec,
nuget_registry: None,
resolve_nuget: false,
}
}
/// 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 {
self.resolve_nuget = enabled;
self
}
/// Look up the NuGet licenses the tree does not carry on nuget.org.
pub(crate) fn with_nuget_registry(mut self, registry: Option<NugetRegistry>) -> Self {
self.nuget_registry = registry;
@@ -73,6 +86,9 @@ pub struct GeneratedSbom {
/// found for (`<product> <file version>`, #460): in the SBOM without a
/// purl, so not matched against advisories, which the caller records.
pub unmapped_assemblies: Vec<String>,
/// The `<PackageReference>` projects whose transitive packages nuget.org
/// gave in full (#461): not a gap any more.
pub resolved_nuget: Vec<String>,
}
impl SbomScanner {
@@ -142,6 +158,13 @@ impl SbomScanner {
);
nuget::merge_nuget(&mut entries, nuget_manifest);
// The transitive packages of projects no lockfile resolves (#461).
let mut resolved_nuget = Vec::new();
if let (true, Some(registry)) = (self.resolve_nuget, self.nuget_registry.as_ref()) {
let resolution = nuget_resolve::resolve(repo_path, repo_id, registry).await;
nuget::merge_nuget(&mut entries, resolution.entries);
resolved_nuget = resolution.resolved;
}
// 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;
@@ -159,6 +182,7 @@ impl SbomScanner {
entries,
syft_failure,
unmapped_assemblies: resolved.unmapped,
resolved_nuget,
}
}
}
@@ -196,9 +220,13 @@ const NPM_LOCKFILES: &[&str] = &[
///
/// npm, Python and Cargo are checked at the root, where their workspaces keep
/// the lockfile; the mobile package managers anywhere in the tree (see
/// [`mobile`]), and every .NET project with `<PackageReference>` items (see
/// [`nuget`]).
pub(crate) fn unlocked_ecosystems(repo_path: &Path) -> Vec<UnlockedEcosystem> {
/// [`mobile`]), and the .NET projects with `<PackageReference>` items (see
/// [`nuget`]) other than `resolved_nuget`, whose transitive packages
/// nuget.org gave (see [`nuget_resolve`]), as one entry.
pub(crate) fn unlocked_ecosystems(
repo_path: &Path,
resolved_nuget: &[String],
) -> Vec<UnlockedEcosystem> {
let has = |name: &str| repo_path.join(name).exists();
let mut out = Vec::new();
if has("package.json") {
@@ -256,7 +284,7 @@ pub(crate) fn unlocked_ecosystems(repo_path: &Path) -> Vec<UnlockedEcosystem> {
current Unity LTS with the Package Manager)",
}),
);
out.extend(nuget::unresolved_projects(repo_path));
out.extend(nuget::unresolved_projects(repo_path, resolved_nuget));
out
}
@@ -476,7 +504,7 @@ mod unlocked_tests {
}
fn names(tree: &Tree) -> Vec<String> {
unlocked_ecosystems(&tree.0)
unlocked_ecosystems(&tree.0, &[])
.into_iter()
.map(|e| e.manifest)
.collect()
@@ -513,7 +541,7 @@ mod unlocked_tests {
#[test]
fn a_binary_bun_lockfile_is_named_as_unread() {
let tree = Tree::new(&["package.json", "bun.lockb"]);
let found = unlocked_ecosystems(&tree.0);
let found = unlocked_ecosystems(&tree.0, &[]);
assert_eq!(found.len(), 1);
assert!(
found[0].problem.contains("bun.lockb"),
+123 -24
View File
@@ -147,32 +147,112 @@ pub(crate) fn merge_nuget(entries: &mut Vec<SbomEntry>, nuget: Vec<SbomEntry>) {
}
}
/// The projects whose transitive NuGet dependencies are unknown: they declare
/// `<PackageReference>` items and have no `packages.lock.json` and no
/// `obj/project.assets.json` beside them. A `packages.config` project is
/// never one: its file lists the transitive packages too.
pub(crate) fn unresolved_projects(root: &Path) -> Vec<UnlockedEcosystem> {
/// A project whose transitive NuGet dependencies no file lists: it declares
/// `<PackageReference>` items and has no `packages.lock.json` and no
/// `obj/project.assets.json` beside it. A `packages.config` project is never
/// one: its file lists the transitive packages too.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct UnlockedProject {
/// Relative to the tree's root.
pub path: String,
/// Its target frameworks as written (`net48`, `net8.0`); old-style
/// projects give `v4.7.2` from `<TargetFrameworkVersion>`.
pub frameworks: Vec<String>,
/// Its direct packages: id and exact version, `None` for a range.
pub references: Vec<(String, Option<String>)>,
}
/// The [`UnlockedProject`]s of the tree under `root`.
pub(crate) fn unlocked_projects(root: &Path) -> Vec<UnlockedProject> {
let central = central_versions(root);
walk_sources(root)
.filter(|e| is_project_file(&e.file_name().to_string_lossy()))
.filter(|e| {
read_text(e.path()).is_some_and(|text| text.contains("<PackageReference"))
&& e.path().parent().is_some_and(|dir| {
!dir.join("packages.lock.json").is_file()
&& !dir.join("obj/project.assets.json").is_file()
})
})
.map(|e| UnlockedEcosystem {
manifest: relative(root, e.path()),
problem: "declares NuGet packages with <PackageReference>, but neither a \
packages.lock.json nor an obj/project.assets.json lists the \
transitive ones",
remedy: "set <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> \
(in the project or a Directory.Build.props), restore once and commit \
packages.lock.json",
.filter_map(|e| {
let text = read_text(e.path())?;
let dir = e.path().parent()?;
let unlocked = text.contains("<PackageReference")
&& !dir.join("packages.lock.json").is_file()
&& !dir.join("obj/project.assets.json").is_file();
unlocked.then(|| UnlockedProject {
path: relative(root, e.path()),
frameworks: target_frameworks(&text),
references: read_package_references(e.path(), &central)
.into_iter()
.map(|p| (p.id, p.version))
.collect(),
})
})
.collect()
}
/// The target frameworks a project file names.
fn target_frameworks(text: &str) -> Vec<String> {
let Some(doc) = parse_xml(text) else {
return Vec::new();
};
let value = |name: &str| {
doc.descendants()
.find(|n| n.is_element() && n.tag_name().name() == name)
.and_then(|n| n.text())
.map(str::trim)
.filter(|t| !t.is_empty() && !t.contains("$("))
.map(str::to_string)
};
if let Some(many) = value("TargetFrameworks") {
return many
.split(';')
.map(str::trim)
.filter(|t| !t.is_empty())
.map(str::to_string)
.collect();
}
value("TargetFramework")
.or_else(|| value("TargetFrameworkVersion"))
.into_iter()
.collect()
}
/// How many projects one gap entry names before "and N more".
const LISTED_PROJECTS: usize = 10;
/// The projects whose transitive NuGet dependencies remain unknown (every
/// [`UnlockedProject`] not in `resolved`), as one gap for the whole run.
pub(crate) fn unresolved_projects(root: &Path, resolved: &[String]) -> Vec<UnlockedEcosystem> {
let open: Vec<String> = unlocked_projects(root)
.into_iter()
.map(|p| p.path)
.filter(|p| !resolved.contains(p))
.collect();
if open.is_empty() {
return Vec::new();
}
let mut manifest = open
.iter()
.take(LISTED_PROJECTS)
.cloned()
.collect::<Vec<_>>()
.join(", ");
if open.len() > LISTED_PROJECTS {
manifest.push_str(&format!(" and {} more", open.len() - LISTED_PROJECTS));
}
let problem = if open.len() == 1 {
"declares NuGet packages with <PackageReference>, but neither a packages.lock.json \
nor an obj/project.assets.json lists the transitive ones, and nuget.org did not give \
all of them"
} else {
"declare NuGet packages with <PackageReference>, but neither a packages.lock.json nor \
an obj/project.assets.json lists the transitive ones, and nuget.org did not give all \
of them"
};
vec![UnlockedEcosystem {
manifest,
problem,
remedy: "set <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> (in the \
project or a Directory.Build.props), restore once and commit \
packages.lock.json",
}]
}
/// 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)`).
pub(super) fn exact_version(raw: &str) -> Option<String> {
@@ -543,10 +623,29 @@ mod tests {
"pkg:nuget/Serilog@2.10.0",
]
);
// Direct references only: the project is reported as unresolved.
let unresolved = unresolved_projects(&t.0);
// Direct references only: the project is reported as unresolved,
// unless nuget.org gave its graph in full.
let unresolved = unresolved_projects(&t.0, &[]);
assert_eq!(unresolved.len(), 1);
assert_eq!(unresolved[0].manifest, "src/App/App.csproj");
assert!(unresolved[0].problem.starts_with("declares "));
assert!(unresolved_projects(&t.0, &["src/App/App.csproj".to_string()]).is_empty());
}
#[test]
fn unresolved_projects_are_one_gap_naming_them_all() {
let project = r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFrameworks>net48;net8.0</TargetFrameworks></PropertyGroup><ItemGroup><PackageReference Include="Dapper" Version="2.0.4" /></ItemGroup></Project>"#;
let t = tree(&[("A/A.csproj", project), ("B/B.csproj", project)]);
let unresolved = unresolved_projects(&t.0, &[]);
assert_eq!(unresolved.len(), 1);
assert_eq!(unresolved[0].manifest, "A/A.csproj, B/B.csproj");
assert!(unresolved[0].problem.starts_with("declare "));
let projects = unlocked_projects(&t.0);
assert_eq!(projects[0].frameworks, ["net48", "net8.0"]);
assert_eq!(
projects[0].references,
[("Dapper".to_string(), Some("2.0.4".to_string()))]
);
}
#[test]
@@ -580,7 +679,7 @@ mod tests {
"pkg:nuget/System.Memory@4.5.4",
]
);
assert!(unresolved_projects(&t.0).is_empty());
assert!(unresolved_projects(&t.0, &[]).is_empty());
}
#[test]
@@ -646,6 +745,6 @@ mod tests {
),
("Hmi/packages.config", "<packages />"),
]);
assert!(unresolved_projects(&t.0).is_empty());
assert!(unresolved_projects(&t.0, &[]).is_empty());
}
}
@@ -487,7 +487,7 @@ pub(crate) struct SourcePattern {
impl RegistryPolicy {
/// Whether `id` may be looked up on nuget.org.
fn allows(&self, id: &str) -> bool {
pub(super) fn allows(&self, id: &str) -> bool {
match self {
RegistryPolicy::All => true,
RegistryPolicy::Skip(_) => false,
@@ -531,7 +531,7 @@ fn is_nuget_org(source: &str) -> bool {
}
/// What the tree's `nuget.config` files allow (any depth, any case).
fn registry_policy(root: &Path) -> RegistryPolicy {
pub(super) fn registry_policy(root: &Path) -> RegistryPolicy {
let mut patterns = Vec::new();
for entry in walk_sources(root) {
if !entry
@@ -688,7 +688,26 @@ impl NugetRegistry {
}
/// The license nuget.org holds for one package version.
async fn lookup(&self, (id, version): &PackageKey) -> Outcome {
async fn lookup(&self, key: &PackageKey) -> Outcome {
match self.catalog(key).await {
Ok(Some(catalog)) => Outcome::Answer(catalog_license(&catalog)),
// Not on nuget.org (another feed's package, or unlisted for good).
Ok(None) => Outcome::Answer(None),
Err(e) => Outcome::Failed(e),
}
}
/// The catalog entry nuget.org holds for one package version (its
/// license, its dependency groups, …), or `None` when nuget.org does not
/// have it.
///
/// # Errors
///
/// The request failed or the answer is unreadable, as `<id> <version>: …`.
pub(crate) async fn catalog(
&self,
(id, version): &PackageKey,
) -> Result<Option<serde_json::Value>, String> {
let url = format!("{REGISTRATION_BASE}/{id}/{version}.json");
let leaf = match self
.fetch
@@ -697,30 +716,30 @@ impl NugetRegistry {
.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}")),
Ok(None) => return Ok(None),
Err(e) => return Err(format!("{id} {version}: {e}")),
};
let catalog = match catalog_entry(&leaf) {
Ok(CatalogEntry::Inline(entry)) => entry,
match catalog_entry(&leaf) {
Ok(CatalogEntry::Inline(entry)) => Ok(Some(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}")),
Ok(Some(body)) => serde_json::from_slice(&body)
.map(Some)
.map_err(|e| format!("{id} {version}: catalog entry: {e}")),
Ok(None) => Ok(None),
Err(e) => Err(format!("{id} {version}: catalog entry: {e}")),
},
Err(e) => return Outcome::Failed(format!("{id} {version}: {e}")),
};
Outcome::Answer(catalog_license(&catalog))
Err(e) => Err(format!("{id} {version}: {e}")),
}
}
/// The bounds of this registry's lookups.
pub(crate) fn limits(&self) -> Limits {
self.limits
}
}
@@ -0,0 +1,634 @@
//! Transitive NuGet packages of `<PackageReference>` projects without a
//! lockfile or assets file (#461), resolved from nuget.org's metadata.
//!
//! `dotnet restore` would write `obj/project.assets.json`, but it evaluates
//! the project's MSBuild files, which can run any code the repository brings
//! (targets hooked into restore): the agent does not run it. Instead the
//! dependency graph is read from nuget.org's catalog entries (each package
//! version's `dependencyGroups` per target framework) and resolved with
//! NuGet's own rules:
//!
//! - a direct reference fixes its version;
//! - a dependency resolves to the lowest version its range admits (the lower
//! bound), and among several ranges for the same package to the highest of
//! those bounds;
//! - the dependency group taken is the nearest one the project's target
//! framework is compatible with (.NET Framework, .NET and .NET Core, .NET
//! Standard, or the framework-independent group).
//!
//! Only package ids and versions leave the agent, through the same guarded
//! client, limits and `nuget.config` routing as the license lookup (#467): a
//! package the tree's configuration sends to another feed is never asked
//! about, and the project then stays unresolved. A project counts as resolved
//! only when every package of its graph was answered; anything less keeps it
//! listed as a gap (with what was found in the SBOM). `NUGET_TRANSITIVE_RESOLVE`
//! switches it: on by default, off where `APP_ENV=production` until it is
//! tested on staging.
use std::cmp::Ordering;
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use compliance_core::config::AppEnv;
use compliance_core::models::SbomEntry;
use futures_util::StreamExt;
use super::nuget::{add_evidence, unlocked_projects, UnlockedProject};
use super::nuget_license::{
normalise_version, registry_policy, NugetRegistry, PackageKey, RegistryPolicy,
};
/// The package manager name of the NuGet SBOM entries.
const NUGET: &str = "nuget";
/// Packages fetched per scan at most, over all projects.
const MAX_LOOKUPS: usize = 400;
/// How long the resolution of one scan may take.
const BUDGET: Duration = Duration::from_secs(90);
/// Whether the resolution runs: `NUGET_TRANSITIVE_RESOLVE` if set, else on
/// outside production.
pub(crate) fn enabled(app_env: AppEnv) -> bool {
match std::env::var("NUGET_TRANSITIVE_RESOLVE")
.ok()
.as_deref()
.map(str::trim)
{
Some(v) if v == "1" || v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("on") => {
true
}
Some(v) if v == "0" || v.eq_ignore_ascii_case("false") || v.eq_ignore_ascii_case("off") => {
false
}
_ => app_env != AppEnv::Production,
}
}
/// What the resolution found.
#[derive(Debug, Default)]
pub(crate) struct Resolution {
/// The transitive packages, as SBOM entries.
pub entries: Vec<SbomEntry>,
/// The projects (relative paths) whose whole graph was answered.
pub resolved: Vec<String>,
}
/// A target framework, as far as dependency groups are matched against it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Framework {
/// .NET Framework `major.minor.patch` (`net48` = 4.8.0).
Classic(u32, u32, u32),
/// .NET Core and .NET 5+ (`netcoreapp3.1`, `net8.0`).
Core(u32, u32),
/// .NET Standard (`netstandard2.0`).
Standard(u32, u32),
/// A group without a framework: applies to every project.
Any,
}
/// The digits of a short .NET Framework moniker (`48` → 4.8.0, `472` →
/// 4.7.2).
fn classic(digits: &str) -> Option<Framework> {
let d: Vec<u32> = digits
.chars()
.map(|c| c.to_digit(10))
.collect::<Option<_>>()?;
match d.as_slice() {
[major, minor] => Some(Framework::Classic(*major, *minor, 0)),
[major, minor, patch] => Some(Framework::Classic(*major, *minor, *patch)),
_ => None,
}
}
/// `major.minor` from `8.0`, `3.1`, `2.0`.
fn dotted(version: &str) -> Option<(u32, u32)> {
let mut parts = version.split('.');
let major = parts.next()?.trim().parse().ok()?;
let minor = parts.next().map_or(Some(0), |m| m.trim().parse().ok())?;
Some((major, minor))
}
/// A framework from a project (`net48`, `net8.0-windows`, `v4.7.2`) or a
/// catalog dependency group (`.NETFramework4.5`, `.NETStandard2.0`,
/// `net6.0`, empty).
fn framework(raw: &str) -> Option<Framework> {
let t = raw.trim().to_ascii_lowercase();
let t = t.split('-').next().unwrap_or(&t);
if t.is_empty() {
return Some(Framework::Any);
}
if let Some(v) = t
.strip_prefix(".netframework")
.or_else(|| t.strip_prefix('v'))
{
let (major, rest) = v.split_once('.')?;
let mut parts = rest.split('.');
let minor = parts.next()?.parse().ok()?;
let patch = parts.next().map_or(Some(0), |p| p.parse().ok())?;
return Some(Framework::Classic(major.parse().ok()?, minor, patch));
}
if let Some(v) = t
.strip_prefix(".netstandard")
.or_else(|| t.strip_prefix("netstandard"))
{
let (major, minor) = dotted(v)?;
return Some(Framework::Standard(major, minor));
}
if let Some(v) = t
.strip_prefix(".netcoreapp")
.or_else(|| t.strip_prefix("netcoreapp"))
{
let (major, minor) = dotted(v)?;
return Some(Framework::Core(major, minor));
}
let v = t.strip_prefix("net")?;
if v.contains('.') {
let (major, minor) = dotted(v)?;
return Some(Framework::Core(major, minor));
}
classic(v)
}
/// The highest .NET Standard a framework implements.
fn standard_of(project: Framework) -> Option<(u32, u32)> {
match project {
Framework::Classic(4, 5, 0) => Some((1, 1)),
Framework::Classic(4, 5, _) => Some((1, 2)),
Framework::Classic(4, 6, 0) => Some((1, 3)),
Framework::Classic(4, ..) => Some((2, 0)),
Framework::Core(major, _) if major >= 3 => Some((2, 1)),
Framework::Core(..) => Some((2, 0)),
Framework::Standard(major, minor) => Some((major, minor)),
Framework::Classic(..) | Framework::Any => None,
}
}
/// How well a dependency group's framework fits a project's: `None` when it
/// does not apply, else a rank where higher is nearer.
fn fit(project: Framework, group: Framework) -> Option<(u8, u32, u32, u32)> {
match (project, group) {
(_, Framework::Any) => Some((0, 0, 0, 0)),
(Framework::Classic(a, b, c), Framework::Classic(x, y, z)) if (x, y, z) <= (a, b, c) => {
Some((2, x, y, z))
}
(Framework::Core(a, b), Framework::Core(x, y)) if (x, y) <= (a, b) => Some((2, x, y, 0)),
(_, Framework::Standard(x, y)) => standard_of(project)
.filter(|s| (x, y) <= *s)
.map(|_| (1, x, y, 0)),
_ => None,
}
}
/// The dependencies (id and lower bound) of the group of `catalog` nearest
/// to `project`; `Err` names a dependency whose range has no inclusive lower
/// bound (it cannot be resolved without the version list).
fn dependencies(
catalog: &serde_json::Value,
project: Framework,
) -> Result<Vec<(String, String)>, String> {
let groups = catalog
.get("dependencyGroups")
.and_then(|g| g.as_array())
.cloned()
.unwrap_or_default();
let best = groups
.iter()
.filter_map(|g| {
let fw = framework(
g.get("targetFramework")
.and_then(|t| t.as_str())
.unwrap_or(""),
)?;
Some((fit(project, fw)?, g))
})
.max_by(|a, b| a.0.cmp(&b.0))
.map(|(_, g)| g);
let Some(group) = best else {
return Ok(Vec::new());
};
group
.get("dependencies")
.and_then(|d| d.as_array())
.into_iter()
.flatten()
.map(|dep| {
let id = dep.get("id").and_then(|i| i.as_str()).unwrap_or_default();
let range = dep.get("range").and_then(|r| r.as_str()).unwrap_or("");
lower_bound(range)
.map(|v| (id.to_string(), v))
.ok_or_else(|| format!("{id} {range}"))
})
.filter(|d| d.as_ref().map_or(true, |(id, _)| !id.is_empty()))
.collect()
}
/// The inclusive lower bound of a NuGet version range (`1.2.3`,
/// `[1.2.3, )`, `[1.2.3, 2.0.0)`, `[1.2.3]`).
fn lower_bound(range: &str) -> Option<String> {
let r = range.trim();
if r.starts_with('(') {
return None;
}
let inner = r.trim_start_matches('[').trim_end_matches([']', ')']);
let low = inner.split(',').next()?.trim();
normalise_version(low)
}
/// NuGet's version order: numeric parts, then a release above its
/// prereleases.
fn compare_versions(a: &str, b: &str) -> Ordering {
let split = |v: &str| {
let (release, pre) = v
.split_once('-')
.map_or((v, None), |(r, p)| (r, Some(p.to_string())));
let numbers: Vec<u64> = release.split('.').map(|n| n.parse().unwrap_or(0)).collect();
(numbers, pre)
};
let (an, ap) = split(a);
let (bn, bp) = split(b);
let len = an.len().max(bn.len());
for i in 0..len {
match an.get(i).unwrap_or(&0).cmp(bn.get(i).unwrap_or(&0)) {
Ordering::Equal => continue,
other => return other,
}
}
match (ap, bp) {
(None, None) => Ordering::Equal,
(None, Some(_)) => Ordering::Greater,
(Some(_), None) => Ordering::Less,
(Some(x), Some(y)) => x.to_ascii_lowercase().cmp(&y.to_ascii_lowercase()),
}
}
/// The catalog entries already fetched in this scan.
type Catalogs = HashMap<PackageKey, Result<Option<serde_json::Value>, String>>;
/// One project's resolution: the packages its graph adds (lowercase id →
/// id and version), and whether every one was answered.
struct Graph {
packages: HashMap<String, (String, String)>,
complete: bool,
}
/// Resolve the transitive packages of every [`UnlockedProject`] under `root`.
///
/// # Arguments
///
/// * `root` - the checked-out or unpacked tree
/// * `repo_id` - the target the entries belong to
/// * `registry` - nuget.org, through the guarded client and its limits
pub(crate) async fn resolve(root: &Path, repo_id: &str, registry: &NugetRegistry) -> Resolution {
let projects = unlocked_projects(root);
if projects.is_empty() {
return Resolution::default();
}
let policy = registry_policy(root);
if let RegistryPolicy::Skip(why) = &policy {
tracing::info!("transitive NuGet packages not resolved on nuget.org: {why}");
return Resolution::default();
}
let started = tokio::time::Instant::now();
let mut catalogs: Catalogs = HashMap::new();
let mut lookups = 0usize;
let mut out = Resolution::default();
let mut found: HashMap<(String, String), SbomEntry> = HashMap::new();
for project in &projects {
let mut complete = true;
let frameworks: Vec<Framework> = project
.frameworks
.iter()
.filter_map(|f| framework(f))
.collect();
if frameworks.is_empty() || project.references.iter().any(|(_, v)| v.is_none()) {
// No framework to pick dependency groups by, or a range nobody
// can resolve without a restore.
complete = false;
}
for fw in &frameworks {
let graph = resolve_project(
project,
*fw,
registry,
&policy,
&mut catalogs,
&mut lookups,
started,
)
.await;
complete &= graph.complete;
for (_, (id, version)) in graph.packages {
let entry = found
.entry((id.to_ascii_lowercase(), version.clone()))
.or_insert_with(|| {
let mut e = SbomEntry::new(
repo_id.to_string(),
id.clone(),
version.clone(),
NUGET.to_string(),
);
e.purl = Some(format!("pkg:nuget/{id}@{version}"));
e
});
add_evidence(entry, format!("{} (transitive, nuget.org)", project.path));
}
}
if complete {
out.resolved.push(project.path.clone());
}
}
let mut entries: Vec<SbomEntry> = found.into_values().collect();
entries.sort_by(|a, b| (&a.name, &a.version).cmp(&(&b.name, &b.version)));
tracing::info!(
projects = projects.len(),
resolved = out.resolved.len(),
packages = entries.len(),
lookups,
"transitive NuGet packages resolved from nuget.org"
);
out.entries = entries;
out
}
/// The transitive graph of one project for one framework.
async fn resolve_project(
project: &UnlockedProject,
fw: Framework,
registry: &NugetRegistry,
policy: &RegistryPolicy,
catalogs: &mut Catalogs,
lookups: &mut usize,
started: tokio::time::Instant,
) -> Graph {
// Direct references fix their versions; they are not part of the graph's
// output (the SBOM has them already).
let direct: HashMap<String, String> = project
.references
.iter()
.filter_map(|(id, v)| Some((id.to_ascii_lowercase(), normalise_version(v.as_deref()?)?)))
.collect();
let mut chosen: HashMap<String, (String, String)> = HashMap::new();
// A direct package another feed serves is never asked about, and its
// dependencies stay unknown.
let mut complete = direct.keys().all(|id| policy.allows(id));
let mut frontier: Vec<PackageKey> = direct
.iter()
.filter(|(id, _)| policy.allows(id))
.map(|(id, v)| (id.clone(), v.clone()))
.collect();
let mut expanded: std::collections::HashSet<PackageKey> = std::collections::HashSet::new();
while !frontier.is_empty() {
frontier.retain(|k| expanded.insert(k.clone()));
let wanted: Vec<PackageKey> = frontier
.iter()
.filter(|k| !catalogs.contains_key(*k))
.cloned()
.collect();
let room = MAX_LOOKUPS.saturating_sub(*lookups);
if wanted.len() > room || started.elapsed() > BUDGET {
complete = false;
}
let asked: Vec<PackageKey> = wanted.into_iter().take(room).collect();
*lookups += asked.len();
let concurrency = registry.limits().concurrency.max(1);
let fetched: Vec<(PackageKey, Result<Option<serde_json::Value>, String>)> =
futures_util::stream::iter(asked)
.map(|key| async move {
let catalog = registry.catalog(&key).await;
(key, catalog)
})
.buffer_unordered(concurrency)
.take_until(tokio::time::sleep(BUDGET.saturating_sub(started.elapsed())))
.collect()
.await;
catalogs.extend(fetched);
let mut next = Vec::new();
for key in std::mem::take(&mut frontier) {
let deps = match catalogs.get(&key) {
Some(Ok(Some(catalog))) => match dependencies(catalog, fw) {
Ok(deps) => deps,
Err(range) => {
tracing::debug!(%range, "NuGet range without a lower bound");
complete = false;
Vec::new()
}
},
// Not on nuget.org, failed, or not asked (over the limits).
_ => {
complete = false;
continue;
}
};
for (id, version) in deps {
let lower = id.to_ascii_lowercase();
if direct.contains_key(&lower) {
continue;
}
if !policy.allows(&lower) {
// Routed to another feed: its graph is not asked about.
complete = false;
continue;
}
let raise = chosen
.get(&lower)
.is_none_or(|(_, have)| compare_versions(&version, have) == Ordering::Greater);
if raise {
chosen.insert(lower.clone(), (id.clone(), version.clone()));
next.push((lower, version));
}
}
}
frontier = next;
}
Graph {
packages: chosen,
complete,
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use std::sync::Arc;
use futures_util::future::BoxFuture;
use super::super::nuget_license::{Fetch, FetchResult, Limits};
/// nuget.org answering from a table of `id/version` → dependency groups.
struct Fake(HashMap<String, serde_json::Value>);
impl Fetch for Fake {
fn get<'a>(&'a self, url: &'a str) -> BoxFuture<'a, FetchResult> {
Box::pin(async move {
let key = url
.trim_start_matches("https://api.nuget.org/v3/registration5-gz-semver2/")
.trim_end_matches(".json");
Ok(self.0.get(key).map(|groups| {
serde_json::to_vec(&serde_json::json!({
"catalogEntry": { "dependencyGroups": groups }
}))
.unwrap()
}))
})
}
}
fn registry(table: &[(&str, serde_json::Value)]) -> NugetRegistry {
let fake = Fake(
table
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect(),
);
NugetRegistry::new(Arc::new(fake), None, Limits::default())
}
fn tree(files: &[(&str, &str)]) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("cs-nugetres-{}", uuid::Uuid::new_v4()));
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 PROJECT: &str = r#"<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><TargetFramework>net48</TargetFramework></PropertyGroup>
<ItemGroup>
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>"#;
#[tokio::test]
async fn the_graph_follows_nugets_rules_for_the_projects_framework() {
let registry = registry(&[
(
"serilog.sinks.file/5.0.0",
serde_json::json!([
{ "targetFramework": ".NETFramework4.5",
"dependencies": [ { "id": "Serilog", "range": "[2.10.0, )" } ] },
{ "targetFramework": ".NETStandard2.1",
"dependencies": [ { "id": "Serilog", "range": "[2.99.0, )" } ] }
]),
),
(
"serilog/2.10.0",
serde_json::json!([
{ "targetFramework": ".NETStandard2.0",
"dependencies": [ { "id": "System.Memory", "range": "4.5.4" },
{ "id": "Newtonsoft.Json", "range": "[9.0.1, )" } ] }
]),
),
(
"system.memory/4.5.4",
serde_json::json!([
{ "targetFramework": ".NETFramework4.6.1",
"dependencies": [ { "id": "System.Buffers", "range": "[4.5.1, )" } ] }
]),
),
("system.buffers/4.5.1", serde_json::json!([])),
("newtonsoft.json/13.0.3", serde_json::json!([])),
]);
let dir = tree(&[("src/Plant.Hmi/Plant.Hmi.csproj", PROJECT)]);
let found = resolve(&dir, "t", &registry).await;
let _ = std::fs::remove_dir_all(&dir);
let packages: Vec<(String, String)> = found
.entries
.iter()
.map(|e| (e.name.clone(), e.version.clone()))
.collect();
// The .NET Framework group, not netstandard2.1 (which net48 does not
// implement); Newtonsoft.Json stays at its direct version.
assert_eq!(
packages,
[
("Serilog".into(), "2.10.0".into()),
("System.Buffers".into(), "4.5.1".into()),
("System.Memory".into(), "4.5.4".into()),
]
);
assert_eq!(found.resolved, ["src/Plant.Hmi/Plant.Hmi.csproj"]);
assert_eq!(
found.entries[0].purl.as_deref(),
Some("pkg:nuget/Serilog@2.10.0")
);
assert!(found.entries[0].evidence[0].contains("transitive, nuget.org"));
}
#[tokio::test]
async fn a_missing_package_or_a_private_feed_leaves_the_project_unresolved() {
let registry = registry(&[(
"serilog.sinks.file/5.0.0",
serde_json::json!([
{ "targetFramework": "", "dependencies": [ { "id": "Serilog", "range": "2.10.0" } ] }
]),
)]);
// Serilog 2.10.0 is not answered (as if nuget.org failed).
let dir = tree(&[("App/App.csproj", PROJECT)]);
let found = resolve(&dir, "t", &registry).await;
let _ = std::fs::remove_dir_all(&dir);
assert!(found.resolved.is_empty());
assert_eq!(found.entries.len(), 1, "what was found is still listed");
let private = tree(&[
("App/App.csproj", PROJECT),
(
"nuget.config",
r#"<configuration><packageSources><clear/>
<add key="corp" value="https://nuget.corp.example.com/v3/index.json"/>
</packageSources></configuration>"#,
),
]);
let none = resolve(&private, "t", &registry).await;
let _ = std::fs::remove_dir_all(&private);
assert!(none.entries.is_empty() && none.resolved.is_empty());
}
/// Against the real nuget.org (network): `cargo test -- --ignored`.
#[tokio::test]
#[ignore = "reaches nuget.org"]
async fn a_real_graph_resolves_from_nuget_org() {
let registry =
NugetRegistry::from_env(compliance_core::NetGuard::public_only(), None).unwrap();
let dir = tree(&[("App/App.csproj", PROJECT)]);
let found = resolve(&dir, "t", &registry).await;
let _ = std::fs::remove_dir_all(&dir);
let names: Vec<String> = found
.entries
.iter()
.map(|e| format!("{}@{}", e.name, e.version))
.collect();
eprintln!("{names:?}");
assert_eq!(found.resolved, ["App/App.csproj"]);
assert!(names.iter().any(|n| n.starts_with("Serilog@")), "{names:?}");
}
#[test]
fn frameworks_and_ranges_are_read_as_nuget_writes_them() {
assert_eq!(framework("net48"), Some(Framework::Classic(4, 8, 0)));
assert_eq!(framework("net472"), Some(Framework::Classic(4, 7, 2)));
assert_eq!(framework("v4.7.2"), Some(Framework::Classic(4, 7, 2)));
assert_eq!(framework("net8.0-windows"), Some(Framework::Core(8, 0)));
assert_eq!(framework(".NETCoreApp3.1"), Some(Framework::Core(3, 1)));
assert_eq!(
framework(".NETStandard2.0"),
Some(Framework::Standard(2, 0))
);
assert_eq!(framework(""), Some(Framework::Any));
assert!(fit(Framework::Classic(4, 8, 0), Framework::Standard(2, 0)).is_some());
assert!(fit(Framework::Classic(4, 8, 0), Framework::Standard(2, 1)).is_none());
assert!(fit(Framework::Core(8, 0), Framework::Classic(4, 5, 0)).is_none());
assert_eq!(lower_bound("[1.2.3, )").as_deref(), Some("1.2.3"));
assert_eq!(lower_bound("1.2.3").as_deref(), Some("1.2.3"));
assert_eq!(lower_bound("[1.2.3, 2.0.0)").as_deref(), Some("1.2.3"));
assert_eq!(lower_bound("(1.2.3, )"), None);
assert_eq!(compare_versions("4.5.10", "4.5.9"), Ordering::Greater);
assert_eq!(compare_versions("2.0.0-beta", "2.0.0"), Ordering::Less);
}
}
+14 -3
View File
@@ -61,9 +61,20 @@ deployment.
**Dependencies not fully resolved.** A project with `<PackageReference>` items
and neither `packages.lock.json` nor `obj/project.assets.json` names only its
direct packages. The scan lists it under **Nicht ausgeführt**
(`sbom_dependencies`), and the SBOM requirements of the CRA view stay **Nicht
bewertet** until a lockfile is committed.
direct packages. Prüfwerk then resolves the transitive ones from nuget.org's
package metadata, the way NuGet itself does (a direct reference fixes its
version; a dependency takes the lowest version its range admits; the
dependency group nearest the project's target framework applies). No
`dotnet restore` runs: it would evaluate the repository's MSBuild files,
which can run code. Only package ids and versions are sent, and none that
`nuget.config` routes to another feed. These packages appear in the SBOM with
the evidence "transitive, nuget.org". A project whose graph could not be
resolved completely (a package on another feed, a lookup that failed, a
version range without a lower bound) stays listed under **Nicht ausgeführt**
(`sbom_dependencies`), all such projects in one entry, and the SBOM
requirements of the CRA view stay **Nicht bewertet** until a lockfile is
committed. `NUGET_TRANSITIVE_RESOLVE` switches the resolution (on by default,
off in production until released there).
**Recommendation:** switch lockfiles on and commit them:
+16 -3
View File
@@ -63,9 +63,22 @@ die Abfrage für eine Installation ab.
**Unvollständig aufgelöste Abhängigkeiten.** Ein Projekt mit
`<PackageReference>` ohne `packages.lock.json` und ohne
`obj/project.assets.json` nennt nur seine direkten Pakete. Die Prüfung führt
es unter **Nicht ausgeführt** (`sbom_dependencies`), und die SBOM-Anforderungen
der CRA-Ansicht sind **Nicht bewertet**, bis eine Lockdatei vorliegt.
`obj/project.assets.json` nennt nur seine direkten Pakete. Prüfwerk löst die
transitiven dann aus den Paket-Metadaten von nuget.org auf, nach den Regeln
von NuGet selbst (eine direkte Referenz legt ihre Version fest, eine
Abhängigkeit nimmt die niedrigste Version, die ihr Bereich zulässt, und es gilt
die Abhängigkeitsgruppe, die zum Zielframework des Projekts am besten passt).
Es läuft kein `dotnet restore`: Es würde die MSBuild-Dateien des Repositorys
auswerten, die Code ausführen können. Gesendet werden nur Paket-IDs und
Versionen, keine, die `nuget.config` einem anderen Feed zuordnet. Diese Pakete
erscheinen in der SBOM mit dem Nachweis „transitive, nuget.org“. Ein Projekt,
dessen Abhängigkeiten nicht vollständig aufgelöst werden konnten (ein Paket
aus einem anderen Feed, eine fehlgeschlagene Abfrage, ein Versionsbereich ohne
Untergrenze), bleibt unter **Nicht ausgeführt** (`sbom_dependencies`) aufgeführt,
alle solchen Projekte in einem Eintrag, und die SBOM-Anforderungen der
CRA-Ansicht sind **Nicht bewertet**, bis eine Lockdatei vorliegt.
`NUGET_TRANSITIVE_RESOLVE` schaltet die Auflösung (standardmäßig an, in
Produktion bis zur Freigabe dort aus).
**Empfehlung:** Lockdateien einschalten und einchecken:
@@ -16,6 +16,7 @@ together on stage in one pass before the next prod promotion.
| #484 | Groups take over their places' decisions (#483) |
| #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 |
**Customer-visible on the next prod rescan** is marked **[visible]**: these
change what a customer sees on their existing targets, without them doing
@@ -267,6 +268,26 @@ Unchanged rescans:
- **[visible]** scheduled scans of unchanged targets no longer count as scans
(usage), and a new Prüfwerk release rescans every target once.
### 16. #461 Transitive NuGet packages
- **Do:** upload a tree with an SDK-style project, no `packages.lock.json` and
no `obj/`, e.g. `App/App.csproj` targeting `net48` with
`<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />`; and a
second project that references a package only a private feed has, with a
`nuget.config` mapping that id to the private feed.
- **Expect:** the SBOM lists `Serilog 2.10.0` (`pkg:nuget/Serilog@2.10.0`)
with the evidence `App/App.csproj (transitive, nuget.org)`, licence filled.
**Nicht ausgeführt** has **one** `sbom_dependencies` entry naming only the
second project (all unresolved projects in one entry, not one per project).
A project with a `packages.lock.json` is unaffected.
- **Log:** `transitive NuGet packages resolved from nuget.org` with
`projects`, `resolved`, `packages`, `lookups`.
- **Switch:** stage runs it by default (`APP_ENV=staging`); prod stays off
until `NUGET_TRANSITIVE_RESOLVE=true` is set there.
- **[visible]** after it is switched on in prod: .NET targets gain their
transitive packages (and their CVEs) in the SBOM, and the "Nicht
ausgeführt" list shrinks to one entry. On stage now.
## After the pass
- The nightly job on `main` is green with the new mobile targets.