fix(sbom): npm registry policy per project, from nested .npmrc/.yarnrc.yml
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 11m37s
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 11m37s
The npm private-registry policy read .npmrc and .yarnrc.yml only at the archive root, so a monorepo project in a subfolder with its own `@corp:registry=...` had its private-scope names looked up on registry.npmjs.org. The policy of an npm package now comes from the files next to the lockfile Syft read it from and every parent directory up to the root: the nearest file names a scope's registry, and a non-public default registry anywhere on the way stops every lookup for that project. A package found in several projects is looked up only if all of them take it from the public registry. The same policy gates the fallback tarball URL in the SBOM's distribution references. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
1 parent
e1bf9e861c
commit
595de73c4a
7 files changed
+321
-52
No files matched your search
@@ -24,7 +24,7 @@ use base64::Engine;
|
||||
use compliance_core::models::ComponentHash;
|
||||
|
||||
use super::nuget_license::{registry_policy, RegistryPolicy};
|
||||
use super::registry_license::{npm_policy, NpmPolicy};
|
||||
use super::registry_license::NpmPolicies;
|
||||
|
||||
/// The crates.io index, as `Cargo.lock` names it.
|
||||
const CRATES_IO: &str = "registry+https://github.com/rust-lang/crates.io-index";
|
||||
@@ -38,7 +38,7 @@ pub(super) struct Distribution {
|
||||
|
||||
/// Where the project takes its packages from.
|
||||
pub(super) struct Origins {
|
||||
npm: NpmPolicy,
|
||||
npm: NpmPolicies,
|
||||
nuget: RegistryPolicy,
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ impl Origins {
|
||||
/// The registry configuration of the tree at `root`.
|
||||
pub(super) fn of(root: &Path) -> Self {
|
||||
Self {
|
||||
npm: npm_policy(root),
|
||||
npm: NpmPolicies::of(root),
|
||||
nuget: registry_policy(root),
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,25 @@ struct Artifact {
|
||||
metadata_type: String,
|
||||
#[serde(default)]
|
||||
metadata: serde_json::Value,
|
||||
/// The files Syft read it from (`/web/package-lock.json`).
|
||||
#[serde(default)]
|
||||
locations: Vec<Location>,
|
||||
}
|
||||
|
||||
/// One file of [`Artifact::locations`].
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Location {
|
||||
#[serde(default)]
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl Artifact {
|
||||
/// Whether the project the package was found in takes it from the
|
||||
/// public npm registry.
|
||||
fn public_npm(&self, origins: &mut Origins) -> bool {
|
||||
let paths: Vec<String> = self.locations.iter().map(|l| l.path.clone()).collect();
|
||||
origins.npm.allows(&self.name, &paths)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
@@ -75,7 +94,7 @@ struct SyftJson {
|
||||
|
||||
/// The distributed files of the packages in Syft's JSON output `json`, by
|
||||
/// purl (as [`super::syft::canonical_purl`] writes it).
|
||||
pub(super) fn read(json: &[u8], origins: &Origins) -> HashMap<String, Distribution> {
|
||||
pub(super) fn read(json: &[u8], origins: &mut Origins) -> HashMap<String, Distribution> {
|
||||
let Ok(doc) = serde_json::from_slice::<SyftJson>(json) else {
|
||||
return HashMap::new();
|
||||
};
|
||||
@@ -98,20 +117,28 @@ fn text<'a>(value: &'a serde_json::Value, path: &[&str]) -> Option<&'a str> {
|
||||
}
|
||||
|
||||
/// The distributed file of one lockfile entry.
|
||||
fn distribution(a: &Artifact, origins: &Origins) -> Option<Distribution> {
|
||||
fn distribution(a: &Artifact, origins: &mut Origins) -> Option<Distribution> {
|
||||
let (hashes, url) = match a.metadata_type.as_str() {
|
||||
"javascript-npm-package-lock-entry" | "javascript-yarn-lock-entry" => {
|
||||
let hashes = sri_hashes(text(&a.metadata, &["integrity"])?);
|
||||
let url = text(&a.metadata, &["resolved"])
|
||||
.and_then(lockfile_url)
|
||||
.or_else(|| npm_url(&a.name, &a.version, &origins.npm));
|
||||
.or_else(|| {
|
||||
a.public_npm(origins)
|
||||
.then(|| npm_url(&a.name, &a.version))
|
||||
.flatten()
|
||||
});
|
||||
(hashes, url)
|
||||
}
|
||||
"javascript-pnpm-lock-entry" => {
|
||||
let hashes = sri_hashes(text(&a.metadata, &["resolution", "integrity"])?);
|
||||
let url = text(&a.metadata, &["resolution", "tarball"])
|
||||
.and_then(lockfile_url)
|
||||
.or_else(|| npm_url(&a.name, &a.version, &origins.npm));
|
||||
.or_else(|| {
|
||||
a.public_npm(origins)
|
||||
.then(|| npm_url(&a.name, &a.version))
|
||||
.flatten()
|
||||
});
|
||||
(hashes, url)
|
||||
}
|
||||
"dotnet-packages-lock-entry" => {
|
||||
@@ -150,10 +177,10 @@ fn lockfile_url(url: &str) -> Option<String> {
|
||||
(url.starts_with("https://") || url.starts_with("http://")).then(|| url.to_string())
|
||||
}
|
||||
|
||||
/// The npm registry's tarball URL of `name@version`, when the project takes
|
||||
/// the package from the public registry.
|
||||
fn npm_url(name: &str, version: &str, policy: &NpmPolicy) -> Option<String> {
|
||||
if name.is_empty() || version.is_empty() || !policy.allows(name) {
|
||||
/// The npm registry's tarball URL of `name@version`, for a package the
|
||||
/// project takes from the public registry.
|
||||
fn npm_url(name: &str, version: &str) -> Option<String> {
|
||||
if name.is_empty() || version.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let file = name.rsplit('/').next().unwrap_or(name);
|
||||
@@ -200,6 +227,7 @@ fn hash(alg: &str, digest: &[u8]) -> ComponentHash {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -208,7 +236,7 @@ mod tests {
|
||||
|
||||
fn origins() -> Origins {
|
||||
Origins {
|
||||
npm: NpmPolicy::default(),
|
||||
npm: NpmPolicies::of(Path::new("/nonexistent-tree")),
|
||||
nuget: RegistryPolicy::All,
|
||||
}
|
||||
}
|
||||
@@ -253,7 +281,7 @@ mod tests {
|
||||
"metadataType": "python-poetry-lock-entry", "metadata": {},
|
||||
},
|
||||
]));
|
||||
let found = read(&json, &origins());
|
||||
let found = read(&json, &mut origins());
|
||||
let lodash = &found["pkg:npm/lodash@4.17.21"];
|
||||
assert_eq!(lodash.hashes[0].alg, "SHA-512");
|
||||
assert!(lodash.hashes[0].content.starts_with("bf690311ee7b95e7"));
|
||||
@@ -288,6 +316,7 @@ mod tests {
|
||||
"name": "@corp/ui", "version": "1.0.0", "purl": "pkg:npm/%40corp/ui@1.0.0",
|
||||
"metadataType": "javascript-pnpm-lock-entry",
|
||||
"metadata": { "resolution": { "integrity": LODASH } },
|
||||
"locations": [{ "path": "/web/pnpm-lock.yaml" }],
|
||||
},
|
||||
{
|
||||
"name": "Corp.Core", "version": "2.0.0", "purl": "pkg:nuget/Corp.Core@2.0.0",
|
||||
@@ -295,14 +324,20 @@ mod tests {
|
||||
"metadata": { "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" },
|
||||
},
|
||||
]));
|
||||
let private = Origins {
|
||||
npm: NpmPolicy {
|
||||
skip_all: false,
|
||||
private_scopes: vec!["@corp".into()],
|
||||
},
|
||||
// The project in `web/` routes `@corp` to its own registry.
|
||||
let tree = std::env::temp_dir().join(format!("cs-dist-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(tree.join("web")).unwrap();
|
||||
std::fs::write(
|
||||
tree.join("web/.npmrc"),
|
||||
"@corp:registry=https://npm.corp.example.com/\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut private = Origins {
|
||||
npm: NpmPolicies::of(&tree),
|
||||
nuget: RegistryPolicy::Skip("https://nuget.corp.example".into()),
|
||||
};
|
||||
let found = read(&json, &private);
|
||||
let found = read(&json, &mut private);
|
||||
let _ = std::fs::remove_dir_all(&tree);
|
||||
// The hash is still the file's; where it comes from is not known.
|
||||
assert_eq!(found["pkg:npm/%40corp/ui@1.0.0"].url, None);
|
||||
assert_eq!(found["pkg:npm/%40corp/ui@1.0.0"].hashes.len(), 1);
|
||||
@@ -314,6 +349,6 @@ mod tests {
|
||||
assert_eq!(sri_hashes("sha1-AAAA md5-AAAA").len(), 1);
|
||||
assert!(sri_hashes("sha512-not base64!").is_empty());
|
||||
assert_eq!(lockfile_url("file:../local.tgz"), None);
|
||||
assert_eq!(read(b"not json", &origins()), HashMap::new());
|
||||
assert_eq!(read(b"not json", &mut origins()), HashMap::new());
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,7 @@ impl SbomScanner {
|
||||
// NuGet packages from packages.config, project files and restored
|
||||
// package folders, which Syft does not read (#445), and the .NET
|
||||
// assemblies Syft read from DLL metadata as NuGet packages (#460).
|
||||
let npm_locations = syft::npm_locations(&syft_packages);
|
||||
let mut nuget_manifest = nuget::nuget_components(repo_path, repo_id);
|
||||
let resolved =
|
||||
nuget_assembly::resolve_assemblies(repo_path, syft_packages, &mut nuget_manifest);
|
||||
@@ -188,6 +189,7 @@ impl SbomScanner {
|
||||
registry_license::enrich_registry_licenses(
|
||||
repo_path,
|
||||
&mut entries,
|
||||
&npm_locations,
|
||||
self.registry_licenses.as_ref(),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -121,6 +121,7 @@ pub(super) fn resolve_assemblies(
|
||||
for SyftPackage {
|
||||
mut entry,
|
||||
assembly_paths,
|
||||
..
|
||||
} in packages
|
||||
{
|
||||
let Some(paths) = assembly_paths else {
|
||||
|
||||
@@ -12,7 +12,9 @@
|
||||
//! Only package names and versions leave the agent, through the guarded
|
||||
//! client, and never one a private registry may serve: an `.npmrc` (or
|
||||
//! `.yarnrc.yml`) that points the default registry elsewhere stops every npm
|
||||
//! lookup, a scope routed elsewhere stops that scope's; a Maven or Gradle
|
||||
//! lookup, a scope routed elsewhere stops that scope's. Each project of a
|
||||
//! monorepo has its own: the files next to its lockfile and in every parent
|
||||
//! directory up to the root (see [`NpmPolicies`]). A Maven or Gradle
|
||||
//! build that declares any repository besides the public ones stops every
|
||||
//! Maven lookup, since nothing tells which groups the private one serves.
|
||||
//! Answers are cached across tenants with the NuGet licenses (keys
|
||||
@@ -21,8 +23,8 @@
|
||||
//! lookup could not answer keeps an empty license; nothing here fails the
|
||||
//! SBOM stage.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use compliance_core::models::SbomEntry;
|
||||
@@ -169,36 +171,32 @@ fn is_npmjs(url: &str) -> bool {
|
||||
host.starts_with("registry.npmjs.org") || host.starts_with("registry.yarnpkg.com")
|
||||
}
|
||||
|
||||
/// The npm policy of the tree's `.npmrc` and `.yarnrc.yml`.
|
||||
pub(super) fn npm_policy(root: &Path) -> NpmPolicy {
|
||||
let mut policy = NpmPolicy::default();
|
||||
if let Some(text) = read_text(&root.join(".npmrc")) {
|
||||
/// The registry settings of the `.npmrc` and `.yarnrc.yml` in `dir`, as
|
||||
/// npm names them: `registry` (the default registry) and `@scope:registry`,
|
||||
/// each with its URL.
|
||||
fn npm_settings(dir: &Path) -> Vec<(String, String)> {
|
||||
let mut settings = Vec::new();
|
||||
if let Some(text) = read_text(&dir.join(".npmrc")) {
|
||||
for line in text.lines().map(str::trim) {
|
||||
let Some((key, value)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let key = key.trim();
|
||||
if key == "registry" && !is_npmjs(value) {
|
||||
policy.skip_all = true;
|
||||
} else if let Some(scope) = key.strip_suffix(":registry") {
|
||||
if !is_npmjs(value) {
|
||||
policy.private_scopes.push(scope.trim().to_string());
|
||||
}
|
||||
if key == "registry" || key.ends_with(":registry") {
|
||||
settings.push((key.to_string(), value.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(text) = read_text(&root.join(".yarnrc.yml")) {
|
||||
if let Some(text) = read_text(&dir.join(".yarnrc.yml")) {
|
||||
let mut in_scopes = false;
|
||||
let mut scope = None;
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some(value) = trimmed.strip_prefix("npmRegistryServer:") {
|
||||
if line.starts_with("npmRegistryServer") && !is_npmjs(value) {
|
||||
policy.skip_all = true;
|
||||
if line.starts_with("npmRegistryServer") {
|
||||
settings.push(("registry".to_string(), value.to_string()));
|
||||
} else if let (true, Some(s)) = (in_scopes, &scope) {
|
||||
if !is_npmjs(value) {
|
||||
policy.private_scopes.push(format!("@{s}"));
|
||||
}
|
||||
settings.push((format!("@{s}:registry"), value.to_string()));
|
||||
}
|
||||
} else if line.starts_with("npmScopes:") {
|
||||
in_scopes = true;
|
||||
@@ -209,7 +207,96 @@ pub(super) fn npm_policy(root: &Path) -> NpmPolicy {
|
||||
}
|
||||
}
|
||||
}
|
||||
policy
|
||||
settings
|
||||
}
|
||||
|
||||
/// The npm policies of the projects in a tree. A project's policy comes
|
||||
/// from the `.npmrc` and `.yarnrc.yml` in its directory and in every parent
|
||||
/// up to the root: the nearest file names a scope's registry, as npm reads
|
||||
/// them, and a default registry other than npmjs anywhere on the way stops
|
||||
/// every lookup for the project. Each directory's files are read once.
|
||||
pub(super) struct NpmPolicies {
|
||||
root: PathBuf,
|
||||
/// The settings of each directory read so far (relative to `root`).
|
||||
settings: HashMap<PathBuf, Vec<(String, String)>>,
|
||||
/// The policy of each project directory asked about so far.
|
||||
policies: HashMap<PathBuf, NpmPolicy>,
|
||||
}
|
||||
|
||||
impl NpmPolicies {
|
||||
/// The policies of the tree at `root`.
|
||||
pub(super) fn of(root: &Path) -> Self {
|
||||
Self {
|
||||
root: root.to_path_buf(),
|
||||
settings: HashMap::new(),
|
||||
policies: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The policy of the project directory of the file at `location` (a path
|
||||
/// in the tree as Syft gives it, `/web/package-lock.json`); the root's
|
||||
/// for a path that leaves the tree.
|
||||
pub(super) fn at(&mut self, location: &str) -> &NpmPolicy {
|
||||
// Only plain names: `..` or an absolute prefix must not leave the tree.
|
||||
let parts: Vec<&std::ffi::OsStr> = Path::new(location.trim_start_matches('/'))
|
||||
.components()
|
||||
.map(|c| match c {
|
||||
std::path::Component::Normal(name) => Some(name),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.unwrap_or_default();
|
||||
let dir: PathBuf = parts[..parts.len().saturating_sub(1)].iter().collect();
|
||||
if !self.policies.contains_key(&dir) {
|
||||
let policy = self.policy_of(&dir);
|
||||
self.policies.insert(dir.clone(), policy);
|
||||
}
|
||||
&self.policies[&dir]
|
||||
}
|
||||
|
||||
/// Whether `name` may be looked up for a package found in the files at
|
||||
/// `locations`: only if every project it was found in takes it from the
|
||||
/// public registry. Without a location, the root's policy decides.
|
||||
pub(super) fn allows(&mut self, name: &str, locations: &[String]) -> bool {
|
||||
if locations.is_empty() {
|
||||
return self.at("").allows(name);
|
||||
}
|
||||
locations.iter().all(|l| self.at(l).allows(name))
|
||||
}
|
||||
|
||||
/// The policy of `dir` (relative to the root), from the root down.
|
||||
fn policy_of(&mut self, dir: &Path) -> NpmPolicy {
|
||||
let mut skip_all = false;
|
||||
// Scope -> registry URL; a nearer directory's setting replaces a
|
||||
// farther one's.
|
||||
let mut scopes: HashMap<String, String> = HashMap::new();
|
||||
for depth in 0..=dir.components().count() {
|
||||
let level: PathBuf = dir.components().take(depth).collect();
|
||||
let root = &self.root;
|
||||
let settings = self
|
||||
.settings
|
||||
.entry(level)
|
||||
.or_insert_with_key(|level| npm_settings(&root.join(level)));
|
||||
for (key, value) in settings.iter() {
|
||||
match key.strip_suffix(":registry") {
|
||||
Some(scope) => {
|
||||
scopes.insert(scope.trim().to_string(), value.clone());
|
||||
}
|
||||
None => skip_all |= !is_npmjs(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut private_scopes: Vec<String> = scopes
|
||||
.into_iter()
|
||||
.filter(|(_, url)| !is_npmjs(url))
|
||||
.map(|(scope, _)| scope)
|
||||
.collect();
|
||||
private_scopes.sort();
|
||||
NpmPolicy {
|
||||
skip_all,
|
||||
private_scopes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the Maven and Gradle builds of the tree name only public
|
||||
@@ -306,10 +393,19 @@ fn public_maven_url(url: &str) -> bool {
|
||||
|
||||
/// Fill the license and project URL of every npm and Maven entry that lacks
|
||||
/// one, from their public registries.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `root` - The scanned tree
|
||||
/// * `entries` - The SBOM entries, filled in place
|
||||
/// * `npm_locations` - By purl, the files an npm package was found in
|
||||
/// (its lockfiles); they choose the `.npmrc` that applies to it
|
||||
/// * `registry` - The registries; `None` when lookups are off
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub(crate) async fn enrich_registry_licenses(
|
||||
root: &Path,
|
||||
entries: &mut [SbomEntry],
|
||||
npm_locations: &HashMap<String, Vec<String>>,
|
||||
registry: Option<&RegistryLicenses>,
|
||||
) {
|
||||
let Some(registry) = registry else {
|
||||
@@ -324,20 +420,35 @@ pub(crate) async fn enrich_registry_licenses(
|
||||
if wanted.is_empty() {
|
||||
return;
|
||||
}
|
||||
let npm = npm_policy(root);
|
||||
let mut npm = NpmPolicies::of(root);
|
||||
let maven = maven_public_only(root);
|
||||
if !maven && wanted.iter().any(|(_, eco, _)| *eco == Ecosystem::Maven) {
|
||||
tracing::info!(
|
||||
"Maven licenses not looked up: the build names a repository besides the public ones"
|
||||
);
|
||||
}
|
||||
let mut keys: Vec<(Ecosystem, PackageKey)> = Vec::new();
|
||||
for (_, eco, key) in &wanted {
|
||||
// A key is asked only if every entry wanting it may be looked up: the
|
||||
// same name can be public in one project and private in another.
|
||||
let mut denied: HashSet<&PackageKey> = HashSet::new();
|
||||
for (i, eco, key) in &wanted {
|
||||
let allowed = match eco {
|
||||
Ecosystem::Npm => npm.allows(key.0.trim_start_matches("npm:")),
|
||||
Ecosystem::Npm => {
|
||||
let locations = entries[*i]
|
||||
.purl
|
||||
.as_ref()
|
||||
.and_then(|p| npm_locations.get(p))
|
||||
.map_or(&[][..], Vec::as_slice);
|
||||
npm.allows(key.0.trim_start_matches("npm:"), locations)
|
||||
}
|
||||
Ecosystem::Maven => maven,
|
||||
};
|
||||
if allowed && !keys.iter().any(|(_, k)| k == key) {
|
||||
if !allowed {
|
||||
denied.insert(key);
|
||||
}
|
||||
}
|
||||
let mut keys: Vec<(Ecosystem, PackageKey)> = Vec::new();
|
||||
for (_, eco, key) in &wanted {
|
||||
if !denied.contains(key) && !keys.iter().any(|(_, k)| k == key) {
|
||||
keys.push((*eco, key.clone()));
|
||||
}
|
||||
}
|
||||
@@ -787,7 +898,7 @@ mod tests {
|
||||
entry("pkg:maven/com.squareup.okhttp3/okhttp@3.12.0"),
|
||||
entry("pkg:npm/left-pad@1.0.0"),
|
||||
];
|
||||
enrich_registry_licenses(&dir, &mut entries, Some(®istry)).await;
|
||||
enrich_registry_licenses(&dir, &mut entries, &HashMap::new(), Some(®istry)).await;
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let licenses: Vec<Option<&str>> = entries.iter().map(|e| e.license.as_deref()).collect();
|
||||
assert_eq!(
|
||||
@@ -816,12 +927,79 @@ mod tests {
|
||||
entry("pkg:npm/react@18.2.0"),
|
||||
entry("pkg:maven/com.corp/pump@1.0.0"),
|
||||
];
|
||||
enrich_registry_licenses(&dir, &mut entries, Some(®istry)).await;
|
||||
enrich_registry_licenses(&dir, &mut entries, &HashMap::new(), Some(®istry)).await;
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let asked = fake.1.lock().unwrap().clone();
|
||||
assert_eq!(asked, ["https://registry.npmjs.org/react/18.2.0"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_nested_npmrc_keeps_its_projects_names_inside() {
|
||||
let fake = Arc::new(Fake(HashMap::new(), std::sync::Mutex::default()));
|
||||
let registry = RegistryLicenses::new(fake.clone(), None, Limits::default());
|
||||
let dir = tree(&[(
|
||||
"web/.npmrc",
|
||||
"@corp:registry=https://npm.corp.example.com/\n",
|
||||
)]);
|
||||
let mut entries = vec![
|
||||
entry("pkg:npm/%40corp/pump-ui@1.0.0"),
|
||||
entry("pkg:npm/%40corp/shared@1.0.0"),
|
||||
entry("pkg:npm/react@18.2.0"),
|
||||
];
|
||||
// `@corp/shared` is the root project's (public there); the web
|
||||
// project's `@corp` packages come from its own registry.
|
||||
let locations: HashMap<String, Vec<String>> = [
|
||||
("pkg:npm/%40corp/pump-ui@1.0.0", "/web/package-lock.json"),
|
||||
("pkg:npm/%40corp/shared@1.0.0", "/package-lock.json"),
|
||||
("pkg:npm/react@18.2.0", "/web/package-lock.json"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(purl, path)| (purl.to_string(), vec![path.to_string()]))
|
||||
.collect();
|
||||
enrich_registry_licenses(&dir, &mut entries, &locations, Some(®istry)).await;
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut asked = fake.1.lock().unwrap().clone();
|
||||
asked.sort();
|
||||
assert_eq!(
|
||||
asked,
|
||||
[
|
||||
"https://registry.npmjs.org/@corp%2fshared/1.0.0",
|
||||
"https://registry.npmjs.org/react/18.2.0",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nearest_npmrc_names_a_scopes_registry() {
|
||||
let dir = tree(&[
|
||||
(".npmrc", "@corp:registry=https://npm.corp.example.com/\n"),
|
||||
(
|
||||
"public/.npmrc",
|
||||
"@corp:registry=https://registry.npmjs.org/\n",
|
||||
),
|
||||
(
|
||||
"app/.yarnrc.yml",
|
||||
"npmRegistryServer: \"https://npm.corp.example.com\"\n",
|
||||
),
|
||||
]);
|
||||
let mut policies = NpmPolicies::of(&dir);
|
||||
assert!(!policies.allows("@corp/ui", &["/package-lock.json".into()]));
|
||||
assert!(policies.allows("@corp/ui", &["/public/package-lock.json".into()]));
|
||||
assert!(!policies.allows("@corp/ui", &[]));
|
||||
// A private default registry stops everything below it.
|
||||
assert!(!policies.allows("react", &["/app/web/yarn.lock".into()]));
|
||||
assert!(policies.allows("react", &["/public/package-lock.json".into()]));
|
||||
// Found in two projects: public only if public in both.
|
||||
let both = [
|
||||
"/public/package-lock.json".into(),
|
||||
"/package-lock.json".into(),
|
||||
];
|
||||
assert!(!policies.allows("@corp/ui", &both));
|
||||
// A path that leaves the tree is the root's.
|
||||
assert!(!policies.allows("@corp/ui", &["/../public/package-lock.json".into()]));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Against the real registries (network): `cargo test -- --ignored`.
|
||||
#[tokio::test]
|
||||
#[ignore = "reaches registry.npmjs.org, repo1.maven.org and dl.google.com"]
|
||||
@@ -836,7 +1014,7 @@ mod tests {
|
||||
entry("pkg:maven/androidx.core/core@1.12.0"),
|
||||
entry("pkg:maven/com.google.code.gson/gson@2.8.8"),
|
||||
];
|
||||
enrich_registry_licenses(&dir, &mut entries, Some(®istry)).await;
|
||||
enrich_registry_licenses(&dir, &mut entries, &HashMap::new(), Some(®istry)).await;
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let licenses: Vec<Option<&str>> = entries.iter().map(|e| e.license.as_deref()).collect();
|
||||
eprintln!("{licenses:?}");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::models::SbomEntry;
|
||||
@@ -16,6 +17,26 @@ pub(super) struct SyftPackage {
|
||||
/// version are the DLL's product name and file version, not yet a NuGet
|
||||
/// id and package version (see `nuget_assembly`).
|
||||
pub assembly_paths: Option<Vec<String>>,
|
||||
/// For an npm package: the files Syft read it from (its lockfiles),
|
||||
/// which tell the project whose `.npmrc` applies.
|
||||
pub npm_locations: Vec<String>,
|
||||
}
|
||||
|
||||
/// By purl, the files Syft read each npm package from.
|
||||
pub(super) fn npm_locations(packages: &[SyftPackage]) -> HashMap<String, Vec<String>> {
|
||||
let mut out: HashMap<String, Vec<String>> = HashMap::new();
|
||||
for package in packages.iter().filter(|p| !p.npm_locations.is_empty()) {
|
||||
let Some(purl) = &package.entry.purl else {
|
||||
continue;
|
||||
};
|
||||
let locations = out.entry(purl.clone()).or_default();
|
||||
for location in &package.npm_locations {
|
||||
if !locations.contains(location) {
|
||||
locations.push(location.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
@@ -50,7 +71,9 @@ pub(super) async fn run_syft(
|
||||
})?;
|
||||
|
||||
let distributions = std::fs::read(&syft_json)
|
||||
.map(|json| super::distribution::read(&json, &super::distribution::Origins::of(repo_path)))
|
||||
.map(|json| {
|
||||
super::distribution::read(&json, &mut super::distribution::Origins::of(repo_path))
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let _ = std::fs::remove_file(&syft_json);
|
||||
|
||||
@@ -93,6 +116,11 @@ pub(super) fn parse_cyclonedx(
|
||||
.filter(|c| c.component_type.as_deref() != Some("file"))
|
||||
.map(|c| {
|
||||
let assembly_paths = c.is_dotnet_assembly().then(|| c.locations());
|
||||
let npm_locations = if c.purl.as_deref().is_some_and(|p| p.starts_with("pkg:npm/")) {
|
||||
c.locations()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let package_manager = c
|
||||
.purl
|
||||
.as_deref()
|
||||
@@ -109,6 +137,7 @@ pub(super) fn parse_cyclonedx(
|
||||
SyftPackage {
|
||||
entry,
|
||||
assembly_paths,
|
||||
npm_locations,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -253,6 +282,27 @@ fn extract_ecosystem_from_purl(purl: &str) -> Option<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn npm_packages_keep_the_lockfiles_they_were_read_from() {
|
||||
let location =
|
||||
|path: &str| serde_json::json!({ "name": "syft:location:0:path", "value": path });
|
||||
let json = serde_json::json!({ "components": [
|
||||
{ "name": "react", "version": "18.2.0", "type": "library",
|
||||
"purl": "pkg:npm/react@18.2.0", "properties": [location("/web/package-lock.json")] },
|
||||
{ "name": "react", "version": "18.2.0", "type": "library",
|
||||
"purl": "pkg:npm/react@18.2.0", "properties": [location("/package-lock.json")] },
|
||||
{ "name": "serde", "version": "1.0.0", "type": "library",
|
||||
"purl": "pkg:cargo/serde@1.0.0", "properties": [location("/Cargo.lock")] },
|
||||
]});
|
||||
let packages = parse_cyclonedx(json.to_string().as_bytes(), "r").unwrap_or_default();
|
||||
let found = npm_locations(&packages);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(
|
||||
found["pkg:npm/react@18.2.0"],
|
||||
["web/package-lock.json", "package-lock.json"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swift_purl_is_keyed_by_its_repository() {
|
||||
assert_eq!(
|
||||
|
||||
+5
-2
@@ -154,8 +154,11 @@ POM without a license inherits its parent's. Only package names and versions
|
||||
are sent, and none a private registry may serve: an `.npmrc` or `.yarnrc.yml`
|
||||
that points elsewhere (for all packages or a scope), a `nuget.config` routing,
|
||||
or a Maven or Gradle build that names a repository besides the public ones
|
||||
stops those lookups. A component whose license could not be found stays
|
||||
without one.
|
||||
stops those lookups. In a monorepo each npm project has its own: the
|
||||
`.npmrc`/`.yarnrc.yml` next to its lockfile and in every folder above it up
|
||||
to the archive root count (the nearest one names a scope's registry; a
|
||||
private default registry anywhere on the way stops every lookup for that
|
||||
project). A component whose license could not be found stays without one.
|
||||
|
||||
### Copyleft Warnings
|
||||
|
||||
|
||||
@@ -256,7 +256,7 @@ Licenses of NuGet packages that no `.nuspec` in the tree gives, and the project
|
||||
|
||||
## npm and Maven -- Licenses
|
||||
|
||||
Licenses of npm packages come from their version document on `registry.npmjs.org` (`license`, or the older `licenses` list), with the project URL (`homepage`, else `repository`); those of Maven and Gradle dependencies, with the project URL (`<url>`, else `<scm><url>`), from their POM on Maven Central or, for AndroidX and Google Play services, Google's Maven repository; a POM without `<licenses>` inherits its parent's (followed up to three levels). Only names and versions are sent, never for a scope or registry the tree's `.npmrc`/`.yarnrc.yml` routes elsewhere, and no Maven name at all when a build names a repository besides the public ones. Bounded and cached like the NuGet lookup; `REGISTRY_LICENSE_LOOKUP=false` turns it off.
|
||||
Licenses of npm packages come from their version document on `registry.npmjs.org` (`license`, or the older `licenses` list), with the project URL (`homepage`, else `repository`); those of Maven and Gradle dependencies, with the project URL (`<url>`, else `<scm><url>`), from their POM on Maven Central or, for AndroidX and Google Play services, Google's Maven repository; a POM without `<licenses>` inherits its parent's (followed up to three levels). Only names and versions are sent, never for a scope or registry the `.npmrc`/`.yarnrc.yml` of the package's project (next to its lockfile or in a folder above it) routes elsewhere, and no Maven name at all when a build names a repository besides the public ones. Bounded and cached like the NuGet lookup; `REGISTRY_LICENSE_LOOKUP=false` turns it off.
|
||||
|
||||
## ClamAV -- Malware
|
||||
|
||||
|
||||
Reference in new issue
Block a user