This commit was merged in pull request #511.
This commit is contained in:
1 parent
8538b31682
commit
cd943b8d67
11 files changed
+462
-13
No files matched your search
@@ -0,0 +1,319 @@
|
||||
//! The files components are distributed as (#508): their hashes and where
|
||||
//! they are downloaded from, as the lockfiles record them. BSI TR-03183-2
|
||||
//! asks for the SHA-512 of each deployable component and its URI.
|
||||
//!
|
||||
//! Syft keeps what it read from each lockfile entry in its own JSON format
|
||||
//! (not in its CycloneDX output):
|
||||
//!
|
||||
//! | Lockfile | Hash | URL |
|
||||
//! |---|---|---|
|
||||
//! | `package-lock.json`, `yarn.lock` | `integrity` (SRI, mostly SHA-512) | `resolved` |
|
||||
//! | `pnpm-lock.yaml` | `resolution.integrity` | `resolution.tarball`, else npmjs |
|
||||
//! | `packages.lock.json` | `contentHash` (SHA-512 of the `.nupkg`) | nuget.org |
|
||||
//! | `Cargo.lock` | `checksum` (SHA-256 of the `.crate`) | crates.io |
|
||||
//!
|
||||
//! A URL the lockfile does not name is the public registry's, and only when
|
||||
//! the project takes the package from there: the npm and NuGet registry
|
||||
//! policies that keep private package names inside decide (see
|
||||
//! [`super::registry_license`], [`super::nuget_license`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use base64::Engine;
|
||||
use compliance_core::models::ComponentHash;
|
||||
|
||||
use super::nuget_license::{registry_policy, RegistryPolicy};
|
||||
use super::registry_license::{npm_policy, NpmPolicy};
|
||||
|
||||
/// The crates.io index, as `Cargo.lock` names it.
|
||||
const CRATES_IO: &str = "registry+https://github.com/rust-lang/crates.io-index";
|
||||
|
||||
/// A component's distributed file.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub(super) struct Distribution {
|
||||
pub hashes: Vec<ComponentHash>,
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
/// Where the project takes its packages from.
|
||||
pub(super) struct Origins {
|
||||
npm: NpmPolicy,
|
||||
nuget: RegistryPolicy,
|
||||
}
|
||||
|
||||
impl Origins {
|
||||
/// The registry configuration of the tree at `root`.
|
||||
pub(super) fn of(root: &Path) -> Self {
|
||||
Self {
|
||||
npm: npm_policy(root),
|
||||
nuget: registry_policy(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One package of Syft's JSON output, as far as it is read here.
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Artifact {
|
||||
#[serde(default)]
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
version: String,
|
||||
#[serde(default)]
|
||||
purl: Option<String>,
|
||||
#[serde(default, rename = "metadataType")]
|
||||
metadata_type: String,
|
||||
#[serde(default)]
|
||||
metadata: serde_json::Value,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct SyftJson {
|
||||
#[serde(default)]
|
||||
artifacts: Vec<Artifact>,
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let Ok(doc) = serde_json::from_slice::<SyftJson>(json) else {
|
||||
return HashMap::new();
|
||||
};
|
||||
doc.artifacts
|
||||
.into_iter()
|
||||
.filter_map(|a| {
|
||||
let purl = super::syft::canonical_purl(a.purl.clone()?);
|
||||
Some((purl, distribution(&a, origins)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The text at `path` in `value`, if it is a non-empty string.
|
||||
fn text<'a>(value: &'a serde_json::Value, path: &[&str]) -> Option<&'a str> {
|
||||
path.iter()
|
||||
.try_fold(value, |v, key| v.get(key))?
|
||||
.as_str()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// The distributed file of one lockfile entry.
|
||||
fn distribution(a: &Artifact, origins: &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));
|
||||
(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));
|
||||
(hashes, url)
|
||||
}
|
||||
"dotnet-packages-lock-entry" => {
|
||||
let digest = decode_base64(text(&a.metadata, &["contentHash"])?)?;
|
||||
let url = origins
|
||||
.nuget
|
||||
.allows(&a.name)
|
||||
.then(|| nuget_url(&a.name, &a.version));
|
||||
(vec![hash("SHA-512", &digest)], url)
|
||||
}
|
||||
"rust-cargo-lock-entry" => {
|
||||
let checksum = text(&a.metadata, &["checksum"])?;
|
||||
if checksum.len() != 64 || !checksum.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let url = (text(&a.metadata, &["source"]) == Some(CRATES_IO)).then(|| {
|
||||
format!(
|
||||
"https://static.crates.io/crates/{0}/{0}-{1}.crate",
|
||||
a.name, a.version
|
||||
)
|
||||
});
|
||||
let hash = ComponentHash {
|
||||
alg: "SHA-256".into(),
|
||||
content: checksum.to_ascii_lowercase(),
|
||||
};
|
||||
(vec![hash], url)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
(!hashes.is_empty()).then_some(Distribution { hashes, url })
|
||||
}
|
||||
|
||||
/// A lockfile's download URL, without the fragment yarn appends (`#<sha1>`).
|
||||
fn lockfile_url(url: &str) -> Option<String> {
|
||||
let url = url.split('#').next().unwrap_or(url);
|
||||
(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) {
|
||||
return None;
|
||||
}
|
||||
let file = name.rsplit('/').next().unwrap_or(name);
|
||||
Some(format!(
|
||||
"https://registry.npmjs.org/{name}/-/{file}-{version}.tgz"
|
||||
))
|
||||
}
|
||||
|
||||
/// nuget.org's download URL of a package (lowercase, as its flat container
|
||||
/// serves it).
|
||||
fn nuget_url(id: &str, version: &str) -> String {
|
||||
let (id, version) = (id.to_lowercase(), version.to_lowercase());
|
||||
format!("https://api.nuget.org/v3-flatcontainer/{id}/{version}/{id}.{version}.nupkg")
|
||||
}
|
||||
|
||||
/// The hashes of a Subresource Integrity value (`sha512-<base64>`, several
|
||||
/// separated by spaces). Algorithms CycloneDX does not name are skipped.
|
||||
fn sri_hashes(integrity: &str) -> Vec<ComponentHash> {
|
||||
integrity
|
||||
.split_whitespace()
|
||||
.filter_map(|part| {
|
||||
let (alg, digest) = part.split_once('-')?;
|
||||
let alg = match alg {
|
||||
"sha512" => "SHA-512",
|
||||
"sha384" => "SHA-384",
|
||||
"sha256" => "SHA-256",
|
||||
"sha1" => "SHA-1",
|
||||
_ => return None,
|
||||
};
|
||||
Some(hash(alg, &decode_base64(digest)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn decode_base64(text: &str) -> Option<Vec<u8>> {
|
||||
base64::engine::general_purpose::STANDARD.decode(text).ok()
|
||||
}
|
||||
|
||||
fn hash(alg: &str, digest: &[u8]) -> ComponentHash {
|
||||
ComponentHash {
|
||||
alg: alg.into(),
|
||||
content: hex::encode(digest),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// lodash 4.17.21's tarball, as npm records it.
|
||||
const LODASH: &str = "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==";
|
||||
|
||||
fn origins() -> Origins {
|
||||
Origins {
|
||||
npm: NpmPolicy::default(),
|
||||
nuget: RegistryPolicy::All,
|
||||
}
|
||||
}
|
||||
|
||||
fn syft(artifacts: serde_json::Value) -> Vec<u8> {
|
||||
serde_json::to_vec(&serde_json::json!({ "artifacts": artifacts })).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lockfile_hashes_and_urls_are_read() {
|
||||
let json = syft(serde_json::json!([
|
||||
{
|
||||
"name": "lodash", "version": "4.17.21", "purl": "pkg:npm/lodash@4.17.21",
|
||||
"metadataType": "javascript-yarn-lock-entry",
|
||||
"metadata": {
|
||||
"integrity": LODASH,
|
||||
"resolved": "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c5",
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "@angular/core", "version": "16.2.0",
|
||||
"purl": "pkg:npm/%40angular/core@16.2.0",
|
||||
"metadataType": "javascript-pnpm-lock-entry",
|
||||
"metadata": { "resolution": { "integrity": LODASH } },
|
||||
},
|
||||
{
|
||||
"name": "Newtonsoft.Json", "version": "13.0.3",
|
||||
"purl": "pkg:nuget/Newtonsoft.Json@13.0.3",
|
||||
"metadataType": "dotnet-packages-lock-entry",
|
||||
"metadata": { "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" },
|
||||
},
|
||||
{
|
||||
"name": "serde", "version": "1.0.200", "purl": "pkg:cargo/serde@1.0.200",
|
||||
"metadataType": "rust-cargo-lock-entry",
|
||||
"metadata": {
|
||||
"source": CRATES_IO,
|
||||
"checksum": "ddc6f9cc94d67c0e21aaf7eda3a010fd3af78ebf6e096aa6e2e13c79749cce4f",
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "jinja2", "version": "2.10", "purl": "pkg:pypi/jinja2@2.10",
|
||||
"metadataType": "python-poetry-lock-entry", "metadata": {},
|
||||
},
|
||||
]));
|
||||
let found = read(&json, &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"));
|
||||
assert_eq!(
|
||||
lodash.url.as_deref(),
|
||||
Some("https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz")
|
||||
);
|
||||
assert_eq!(
|
||||
found["pkg:npm/%40angular/core@16.2.0"].url.as_deref(),
|
||||
Some("https://registry.npmjs.org/@angular/core/-/core-16.2.0.tgz")
|
||||
);
|
||||
let nuget = &found["pkg:nuget/Newtonsoft.Json@13.0.3"];
|
||||
assert_eq!(nuget.hashes[0].alg, "SHA-512");
|
||||
assert_eq!(nuget.hashes[0].content.len(), 128);
|
||||
assert_eq!(
|
||||
nuget.url.as_deref(),
|
||||
Some("https://api.nuget.org/v3-flatcontainer/newtonsoft.json/13.0.3/newtonsoft.json.13.0.3.nupkg")
|
||||
);
|
||||
let serde = &found["pkg:cargo/serde@1.0.200"];
|
||||
assert_eq!(serde.hashes[0].alg, "SHA-256");
|
||||
assert_eq!(
|
||||
serde.url.as_deref(),
|
||||
Some("https://static.crates.io/crates/serde/serde-1.0.200.crate")
|
||||
);
|
||||
assert!(!found.contains_key("pkg:pypi/jinja2@2.10"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_private_registry_gets_no_public_url() {
|
||||
let json = syft(serde_json::json!([
|
||||
{
|
||||
"name": "@corp/ui", "version": "1.0.0", "purl": "pkg:npm/%40corp/ui@1.0.0",
|
||||
"metadataType": "javascript-pnpm-lock-entry",
|
||||
"metadata": { "resolution": { "integrity": LODASH } },
|
||||
},
|
||||
{
|
||||
"name": "Corp.Core", "version": "2.0.0", "purl": "pkg:nuget/Corp.Core@2.0.0",
|
||||
"metadataType": "dotnet-packages-lock-entry",
|
||||
"metadata": { "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" },
|
||||
},
|
||||
]));
|
||||
let private = Origins {
|
||||
npm: NpmPolicy {
|
||||
skip_all: false,
|
||||
private_scopes: vec!["@corp".into()],
|
||||
},
|
||||
nuget: RegistryPolicy::Skip("https://nuget.corp.example".into()),
|
||||
};
|
||||
let found = read(&json, &private);
|
||||
// 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);
|
||||
assert_eq!(found["pkg:nuget/Corp.Core@2.0.0"].url, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integrity_values_are_decoded() {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
mod cargo_audit;
|
||||
pub(crate) mod carthage;
|
||||
mod distribution;
|
||||
mod gradle;
|
||||
mod mobile;
|
||||
mod nuget;
|
||||
|
||||
@@ -138,15 +138,16 @@ fn lookup_key(entry: &SbomEntry) -> Option<(Ecosystem, PackageKey)> {
|
||||
|
||||
/// Which npm names may be sent to the public registry.
|
||||
#[derive(Debug, Default)]
|
||||
struct NpmPolicy {
|
||||
pub(super) struct NpmPolicy {
|
||||
/// The default registry is not npmjs: nothing is sent.
|
||||
skip_all: bool,
|
||||
pub(super) skip_all: bool,
|
||||
/// Scopes (`@corp`) routed to another registry.
|
||||
private_scopes: Vec<String>,
|
||||
pub(super) private_scopes: Vec<String>,
|
||||
}
|
||||
|
||||
impl NpmPolicy {
|
||||
fn allows(&self, name: &str) -> bool {
|
||||
/// Whether `name` comes from the public npm registry.
|
||||
pub(super) fn allows(&self, name: &str) -> bool {
|
||||
if self.skip_all {
|
||||
return false;
|
||||
}
|
||||
@@ -169,7 +170,7 @@ fn is_npmjs(url: &str) -> bool {
|
||||
}
|
||||
|
||||
/// The npm policy of the tree's `.npmrc` and `.yarnrc.yml`.
|
||||
fn npm_policy(root: &Path) -> NpmPolicy {
|
||||
pub(super) fn npm_policy(root: &Path) -> NpmPolicy {
|
||||
let mut policy = NpmPolicy::default();
|
||||
if let Some(text) = read_text(&root.join(".npmrc")) {
|
||||
for line in text.lines().map(str::trim) {
|
||||
|
||||
@@ -23,11 +23,16 @@ pub(super) async fn run_syft(
|
||||
repo_path: &Path,
|
||||
repo_id: &str,
|
||||
) -> Result<Vec<SyftPackage>, CoreError> {
|
||||
// Syft's own JSON keeps the lockfiles' hashes and download URLs, which
|
||||
// its CycloneDX output drops (#508); one run writes both.
|
||||
let syft_json = std::env::temp_dir().join(format!("syft-{}.json", uuid::Uuid::new_v4()));
|
||||
let output = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(600),
|
||||
crate::pipeline::tool_cmd::tool("syft", &["SYFT_CACHE_DIR"])
|
||||
.arg(repo_path)
|
||||
.args(["-o", "cyclonedx-json"])
|
||||
.arg("-o")
|
||||
.arg(format!("syft-json={}", syft_json.display()))
|
||||
.env("SYFT_GOLANG_SEARCH_REMOTE_LICENSES", "true")
|
||||
.env("SYFT_JAVASCRIPT_SEARCH_REMOTE_LICENSES", "true")
|
||||
.env("SYFT_PYTHON_SEARCH_REMOTE_LICENSES", "true")
|
||||
@@ -44,6 +49,11 @@ pub(super) async fn run_syft(
|
||||
source: Box::new(e),
|
||||
})?;
|
||||
|
||||
let distributions = std::fs::read(&syft_json)
|
||||
.map(|json| super::distribution::read(&json, &super::distribution::Origins::of(repo_path)))
|
||||
.unwrap_or_default();
|
||||
let _ = std::fs::remove_file(&syft_json);
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(CoreError::Scanner {
|
||||
@@ -52,7 +62,19 @@ pub(super) async fn run_syft(
|
||||
});
|
||||
}
|
||||
|
||||
Ok(parse_cyclonedx(&output.stdout, repo_id)?)
|
||||
let mut packages = parse_cyclonedx(&output.stdout, repo_id)?;
|
||||
for package in &mut packages {
|
||||
let found = package
|
||||
.entry
|
||||
.purl
|
||||
.as_ref()
|
||||
.and_then(|p| distributions.get(p));
|
||||
if let Some(found) = found {
|
||||
package.entry.hashes = found.hashes.clone();
|
||||
package.entry.download_url = found.url.clone();
|
||||
}
|
||||
}
|
||||
Ok(packages)
|
||||
}
|
||||
|
||||
/// The components of Syft's CycloneDX JSON output.
|
||||
@@ -192,7 +214,7 @@ fn extract_license(entries: &[CdxLicenseWrapper]) -> Option<String> {
|
||||
/// expects `pkg:swift/github.com/apple/swift-nio@2.40.0`: in Syft's form every
|
||||
/// Swift package matched no advisory at all. Every other purl, and a Swift one
|
||||
/// already in that form, is returned unchanged.
|
||||
fn canonical_purl(purl: String) -> String {
|
||||
pub(super) fn canonical_purl(purl: String) -> String {
|
||||
let Some(rest) = purl.strip_prefix("pkg:swift/") else {
|
||||
return purl;
|
||||
};
|
||||
|
||||
@@ -59,7 +59,9 @@ pub use pentest::{
|
||||
};
|
||||
pub use project::{Project, ProjectKind};
|
||||
pub use repository::ScanTrigger;
|
||||
pub use sbom::{SbomEntry, SbomQuality, SbomQualityCheck, SbomQualityProfile, VulnRef};
|
||||
pub use sbom::{
|
||||
ComponentHash, SbomEntry, SbomQuality, SbomQualityCheck, SbomQualityProfile, VulnRef,
|
||||
};
|
||||
pub use scan::{
|
||||
RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode, SkippedStage,
|
||||
};
|
||||
|
||||
@@ -34,12 +34,29 @@ pub struct SbomEntry {
|
||||
/// duplicates of one package are merged.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub evidence: Vec<String>,
|
||||
/// Hashes of the file the component is distributed as, from its lockfile
|
||||
/// (npm's `integrity`, NuGet's `contentHash`, Cargo's `checksum`; #508).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub hashes: Vec<ComponentHash>,
|
||||
/// Where that file is downloaded from: the lockfile's URL, or the public
|
||||
/// registry's when the project uses no other.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub download_url: Option<String>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
pub created_at: DateTime<Utc>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// A hash of a component's distributed file, as CycloneDX writes it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ComponentHash {
|
||||
/// CycloneDX's algorithm name: `SHA-512`, `SHA-384`, `SHA-256`, `SHA-1`.
|
||||
pub alg: String,
|
||||
/// The digest, lowercase hex.
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
impl SbomEntry {
|
||||
pub fn new(repo_id: String, name: String, version: String, package_manager: String) -> Self {
|
||||
let now = Utc::now();
|
||||
@@ -54,6 +71,8 @@ impl SbomEntry {
|
||||
purl: None,
|
||||
known_vulnerabilities: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
hashes: Vec::new(),
|
||||
download_url: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//! packages, a dependency graph whose completeness is stated, and licences as
|
||||
//! the suppliers declare them.
|
||||
|
||||
use crate::models::SbomEntry;
|
||||
use crate::models::{ComponentHash, SbomEntry};
|
||||
use crate::purl::Purl;
|
||||
|
||||
/// The `bom-ref` of a component, which a VEX statement refers to: its purl,
|
||||
@@ -124,6 +124,14 @@ pub fn cdx_severity(severity: &str) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hashes as CycloneDX writes them.
|
||||
fn cdx_hashes(hashes: &[ComponentHash]) -> serde_json::Value {
|
||||
hashes
|
||||
.iter()
|
||||
.map(|h| serde_json::json!({ "alg": h.alg, "content": h.content }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The components of a CycloneDX document, each with its `bom-ref`.
|
||||
pub fn cdx_components(entries: &[SbomEntry]) -> Vec<serde_json::Value> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
@@ -153,6 +161,19 @@ pub fn cdx_components(entries: &[SbomEntry]) -> Vec<serde_json::Value> {
|
||||
if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) {
|
||||
comp["licenses"] = license_choice(license);
|
||||
}
|
||||
if !e.hashes.is_empty() {
|
||||
let hashes = cdx_hashes(&e.hashes);
|
||||
// The file and where it is downloaded from: the TR's hash of
|
||||
// the deployable component and its URI (#508).
|
||||
if let Some(url) = &e.download_url {
|
||||
comp["externalReferences"] = serde_json::json!([{
|
||||
"type": "distribution",
|
||||
"url": url,
|
||||
"hashes": hashes,
|
||||
}]);
|
||||
}
|
||||
comp["hashes"] = hashes;
|
||||
}
|
||||
comp
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use compliance_core::models::SbomEntry;
|
||||
use compliance_core::models::{ComponentHash, SbomEntry};
|
||||
use compliance_core::sbom_docs;
|
||||
|
||||
/// One registry package per ecosystem whose file its purl names.
|
||||
@@ -47,6 +47,18 @@ fn entries() -> Vec<SbomEntry> {
|
||||
let mut e = SbomEntry::new("t".into(), name.into(), version.into(), manager.into());
|
||||
e.purl = Some(purl.into());
|
||||
e.license = Some(license.into());
|
||||
// What the lockfiles give (#508): npm and NuGet a SHA-512, Cargo a
|
||||
// SHA-256, Maven nothing.
|
||||
let (alg, len) = match manager {
|
||||
"npm" | "nuget" => ("SHA-512", 128),
|
||||
"cargo" => ("SHA-256", 64),
|
||||
_ => return e,
|
||||
};
|
||||
e.hashes = vec![ComponentHash {
|
||||
alg: alg.into(),
|
||||
content: "ab".repeat(len / 2),
|
||||
}];
|
||||
e.download_url = Some(format!("https://registry.example/{name}-{version}"));
|
||||
e
|
||||
})
|
||||
.collect()
|
||||
@@ -117,4 +129,8 @@ fn the_document_shape_meets_the_bsi_checks_it_can() {
|
||||
] {
|
||||
assert_eq!(scores.get(key).copied(), Some(8.0), "{key}");
|
||||
}
|
||||
// The deployable hash counts only as SHA-512 on a download: npm and
|
||||
// NuGet (2 of 5); the URL counts for Cargo too (3 of 5).
|
||||
assert_eq!(scores.get("comp_deployable_hash").copied(), Some(4.0));
|
||||
assert_eq!(scores.get("comp_download_url").copied(), Some(6.0));
|
||||
}
|
||||
@@ -82,6 +82,11 @@ fn sbom() -> Vec<SbomEntry> {
|
||||
let mut lodash = SbomEntry::new("t".into(), "lodash".into(), "4.17.20".into(), "npm".into());
|
||||
lodash.purl = Some("pkg:npm/lodash@4.17.20".into());
|
||||
lodash.license = Some("MIT OR Apache-2.0".into());
|
||||
lodash.hashes = vec![compliance_core::models::ComponentHash {
|
||||
alg: "SHA-512".into(),
|
||||
content: "bf690311ee7b95e713ba568322e3533f2dd1cb880b189e99d4edef13592b81764daec43e2c54c61d5c558dc5cfb35ecb85b65519e74026ff17675b6f8f916f4a".into(),
|
||||
}];
|
||||
lodash.download_url = Some("https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz".into());
|
||||
let mut fw = SbomEntry::new(
|
||||
"t".into(),
|
||||
"PumpSDK".into(),
|
||||
@@ -192,6 +197,17 @@ fn the_cyclonedx_sbom_is_valid_and_its_vulnerabilities_point_at_components() {
|
||||
Some("non-executable")
|
||||
);
|
||||
assert_eq!(property(2, "bsi:component:filename"), None);
|
||||
// The lockfile's hash, on the component and on its download.
|
||||
assert_eq!(doc["components"][1]["hashes"][0]["alg"], "SHA-512");
|
||||
assert_eq!(
|
||||
doc["components"][1]["externalReferences"][0]["type"],
|
||||
"distribution"
|
||||
);
|
||||
assert_eq!(
|
||||
doc["components"][1]["externalReferences"][0]["hashes"][0]["alg"],
|
||||
"SHA-512"
|
||||
);
|
||||
assert!(doc["components"][0].get("hashes").is_none());
|
||||
assert_eq!(doc["components"][0]["group"], "org.apache.logging.log4j");
|
||||
assert!(doc["components"][2].get("group").is_none());
|
||||
assert_eq!(
|
||||
|
||||
+13
-3
@@ -217,6 +217,12 @@ Prüfwerk has the data, BSI TR-03183-2 v2.1:
|
||||
- The dependency graph has the product depending on every component, and
|
||||
each component as its own entry. The SBOM is flat (which component depends
|
||||
on which is not known), so `compositions` states it `incomplete`.
|
||||
- Packages whose lockfile records the file they are distributed as carry
|
||||
its hash (`hashes`) and an `externalReferences` entry of type
|
||||
`distribution` with the download URL and the hash: the lockfile's URL
|
||||
(npm, yarn, pnpm), or the public registry's (npmjs, nuget.org, crates.io)
|
||||
when the project takes the package from there and the lockfile names
|
||||
none.
|
||||
- Licenses are an SPDX id, an SPDX expression or a named license, marked
|
||||
`acknowledgement: declared`: they are what the package declares, not a
|
||||
licence Prüfwerk concluded.
|
||||
@@ -300,9 +306,13 @@ open, and why:
|
||||
|
||||
- **Component creator**: the email or URL of each package's maintainer.
|
||||
Prüfwerk does not record it yet.
|
||||
- **Hash of the deployable component** (SHA-512) and its download URL: not
|
||||
recorded yet; lockfiles hold them for npm and NuGet. Cargo, Python and
|
||||
Maven lockfiles only have SHA-256 hashes, which the TR does not accept.
|
||||
- **Hash of the deployable component** (SHA-512) and its download URL: met
|
||||
for npm, yarn and pnpm packages (the lockfile's `integrity`) and NuGet
|
||||
packages with a `packages.lock.json` (its `contentHash`). Cargo's lockfile
|
||||
has a SHA-256, which the export lists but the TR does not accept; Python
|
||||
and Maven lockfiles give Prüfwerk no hash yet. Packages from a private
|
||||
registry keep their hash but get no download URL, since the export only
|
||||
names the public registry's.
|
||||
- **Distribution licence**: the licence the product is distributed under
|
||||
(`acknowledgement: concluded`) is the manufacturer's decision; the export
|
||||
states the declared licences only.
|
||||
|
||||
@@ -28,6 +28,7 @@ together on stage in one pass before the next prod promotion.
|
||||
| #498 (2/4) | VEX editor and downloads on the target page |
|
||||
| #508 (A) | CycloneDX 1.6 SBOM with BSI TR-03183-2 properties |
|
||||
| #498 (3/4) | CSAF 2.0 VEX advisory draft |
|
||||
| #508 (B1) | Lockfile hashes and download URLs in the SBOM |
|
||||
|
||||
**Customer-visible on the next prod rescan** is marked **[visible]**: these
|
||||
change what a customer sees on their existing targets, without them doing
|
||||
@@ -500,6 +501,7 @@ alerts (e.g. the log4j/gson target of check 19).
|
||||
- **[visible]** SBOM-Qualität card on the SBOM page, the score on cra-ai-23,
|
||||
`sbom-quality.json` in the evidence pack. Expect a low BSI grade until the
|
||||
export carries CycloneDX 1.6 and the TR's fields.
|
||||
|
||||
### 25. #494 DevSkim for .NET
|
||||
|
||||
- **Do:** upload `fixtures/dotnet/legacy-sample` and `fixtures/dotnet/framework48`
|
||||
@@ -607,6 +609,26 @@ Use the target of check 26, with statements of every status.
|
||||
- **[visible]** a new download and web-address field in the VEX card; the
|
||||
evidence pack gains `csaf-vex.json`.
|
||||
|
||||
### 29. #508 part B1: hashes and download URLs from lockfiles
|
||||
|
||||
Use a target with a `package-lock.json` (or `yarn.lock`/`pnpm-lock.yaml`)
|
||||
with `integrity` fields, one .NET target with `packages.lock.json`, and one
|
||||
Rust target.
|
||||
|
||||
- **Do:** rescan each; export **CycloneDX 1.6**. **Expect:** npm/yarn/pnpm
|
||||
components have `hashes` with a `SHA-512` and an `externalReferences`
|
||||
entry `distribution` with the tarball URL and the same hash; NuGet
|
||||
components a `SHA-512` and the nuget.org flat-container URL; Cargo
|
||||
components a `SHA-256` and the static.crates.io URL. Python and Maven
|
||||
components have none.
|
||||
- **Do:** a JS project whose `.npmrc` routes `@corp` to another registry.
|
||||
**Expect:** `@corp/*` packages keep their hash, but get a distribution
|
||||
URL only when the lockfile names one.
|
||||
- **Expect:** SBOM-Qualität: "Deployable Hash" is met for the npm/NuGet
|
||||
share of the components.
|
||||
- **[visible]** SBOM exports and evidence packs carry the hashes and URLs
|
||||
after the next rescan.
|
||||
|
||||
## After the pass
|
||||
|
||||
- The nightly job on `main` is green with the new mobile targets.
|
||||
|
||||
Reference in new issue
Block a user