feat(sbom): explain an empty or incomplete SBOM with findings (#979) #985

Merged
sharang merged 1 commits from feat/979-empty-sbom-finding into main 2026-11-12 09:21:59 +00:00
20 changed files with 931 additions and 6 deletions

No files matched your search

+4
View File
@@ -65,6 +65,10 @@ pub struct FindingsFilter {
pub status: Option<String>,
#[serde(default)]
pub q: Option<String>,
/// Only the findings of one scanner (`Finding::scanner`, e.g.
/// `sbom-coverage`).
#[serde(default)]
pub scanner: Option<String>,
/// Only the findings in one app variant (`Tablet App`): its own, and the
/// groups listing a place in it.
#[serde(default)]
@@ -28,6 +28,9 @@ pub async fn list_findings(
if let Some(scan_type) = &filter.scan_type {
query.insert("scan_type", scan_type);
}
if let Some(scanner) = &filter.scanner {
query.insert("scanner", scanner);
}
if let Some(status) = &filter.status {
query.insert("status", status_filter(status));
}
+27 -1
View File
@@ -72,11 +72,12 @@ pub enum SbomCoverage {
}
/// The tools that check a target's components rather than its code.
const COMPONENT_TOOLS: [&str; 5] = [
const COMPONENT_TOOLS: [&str; 6] = [
"syft",
"osv",
"dotnet-lifecycle",
"build-lifecycle",
compliance_core::models::SBOM_COVERAGE_SCANNER,
"yocto-release",
];
@@ -513,6 +514,31 @@ mod tests {
);
}
#[test]
fn an_sbom_coverage_finding_is_evidence_against_the_sbom_requirement() {
let map = ControlMap::cra().expect("map");
let mut f = finding(SBOM_CONTROL, FindingStatus::Open);
f.scanner = compliance_core::models::SBOM_COVERAGE_SCANNER.into();
f.rule_id = Some("sbom-dependencies-unresolved".into());
let unresolved = SbomCoverage::Unresolved(vec!["Cargo.toml".into()]);
let statuses = control_statuses(&map, &[f], Some(&python()), &[], &unresolved);
let sbom = status_of(&statuses, SBOM_CONTROL);
assert_eq!(sbom.state, ControlState::NotSatisfied);
assert_eq!(sbom.findings.len(), 1);
// The CVE controls still say why their components were not checked.
for control in ["cra-ai-22", "cra-ai-33"] {
assert_eq!(
status_of(&statuses, control).reason,
Some(NotAssessedReason::DependenciesUnresolved {
manifests: vec!["Cargo.toml".into()]
}),
"{control}"
);
}
}
#[test]
fn a_failed_cve_lookup_claims_nothing_about_component_cves() {
let map = ControlMap::cra().expect("map");
@@ -27,6 +27,7 @@ fn language_of(extension: &str) -> Option<&'static str> {
"cs" => "csharp",
"vb" => "vb",
"swift" => "swift",
"dart" => "dart",
// Objective-C; `.m` is also MATLAB's extension, which only means
// mobsfscan looks at a tree it finds nothing in.
"m" | "mm" => "objc",
+46 -2
View File
@@ -538,7 +538,8 @@ 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, &resolved_nuget) {
let unlocked = crate::pipeline::sbom::unlocked_ecosystems(&repo_path, &resolved_nuget);
for eco in &unlocked {
self.skip_stage(
scan_run_id,
SkippedStage::new(
@@ -549,7 +550,7 @@ impl PipelineOrchestrator {
eco.manifest, eco.problem, eco.remedy
),
)
.about(eco.manifest),
.about(eco.manifest.clone()),
)
.await;
}
@@ -642,6 +643,49 @@ impl PipelineOrchestrator {
}
}
// Why the SBOM is empty or incomplete (#979): code with no manifest
// at all, and manifests whose dependencies were not resolved. Every
// code scan completes this check, so a finding closes at the next
// scan that finds the manifest or lockfile. A firmware SBOM, which
// the firmware step stored before this, counts as an SBOM.
let firmware_sbom = self
.db
.sbom_entries()
.count_documents(doc! {
"repo_id": &repo_id,
"package_manager": {
"$in": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
},
})
.limit(1)
.await?
> 0;
let (coverage, entries) = {
let (root, vendor, languages) = (repo_path.clone(), vendor.clone(), languages.clone());
let (target, yocto_layers) = (repo_id.clone(), repo.yocto_layers);
tokio::task::spawn_blocking(move || {
use crate::pipeline::sbom::coverage::{coverage_findings, ScannedTree};
let tree = ScannedTree {
repo_id: &target,
root: &root,
vendor: &vendor,
languages: &languages,
yocto_layers,
firmware_sbom,
};
(
coverage_findings(&tree, &sbom_entries, &unlocked),
sbom_entries,
)
})
.await
.map_err(|e| AgentError::Other(format!("SBOM coverage check: {e}")))?
};
sbom_entries = entries;
run_findings.completed(crate::pipeline::sbom::coverage::SCANNER);
all_findings.extend(coverage);
run_findings.save_new(&self.db, &mut all_findings).await?;
// Stage 3: CVE Scanning
tracing::info!("[{repo_id}] Stage 3: CVE Scanning");
self.update_phase(scan_run_id, ScanPhase::CveScanning).await;
@@ -0,0 +1,623 @@
//! Why an SBOM is empty or incomplete, as findings (#979).
//!
//! The SBOM is built from the manifests and lockfiles in the code. Without
//! them it is empty, which reads as "no libraries" to someone who is not a
//! developer. Two findings say what is missing instead:
//!
//! - [`NO_MANIFEST_RULE`] (Medium): the tree holds code in a language with a
//! package manager, but no manifest or lockfile for it at all;
//! - [`UNRESOLVED_RULE`] (Low): a manifest whose dependencies were not
//! resolved (no lockfile, or one no tool reads), as
//! [`super::unlocked_ecosystems`] reports it.
//!
//! C and C++ have no standard manifest, and a firmware tree's components come
//! from its sources (library headers, the firmware build, a CODESYS archive, a
//! Yocto layer tree): such a tree never gets the first finding. Nothing is
//! guessed and no code is run to resolve dependencies. Both findings belong
//! to [`SCANNER`], which completes on every code scan, so a finding closes at
//! the next scan that no longer reports it.
use std::path::Path;
use compliance_core::models::{Finding, SbomEntry, ScanType, Severity, YOCTO_RECIPE_MANAGER};
use super::UnlockedEcosystem;
use crate::pipeline::dedup::compute_fingerprint;
use crate::pipeline::embedded_versions::EMBEDDED_MANAGER;
use crate::pipeline::vendor::walk_outside;
/// The scanner name of these findings.
pub(crate) const SCANNER: &str = compliance_core::models::SBOM_COVERAGE_SCANNER;
/// Code in a language with a package manager, and no manifest for it.
pub(crate) const NO_MANIFEST_RULE: &str = "sbom-no-manifest";
/// A manifest whose dependencies were not resolved.
pub(crate) const UNRESOLVED_RULE: &str = "sbom-dependencies-unresolved";
/// The weakness both findings stand for: components nobody tracks.
const CWE: &str = "CWE-1104";
/// The CRA requirement both findings are evidence against: the SBOM.
const SBOM_CONTROL: &str = crate::evidence::compliance::SBOM_CONTROL;
/// Languages whose code never asks for a manifest: C and C++ have no
/// standard one, and a Yocto layer tree's recipes are its inventory.
const NO_MANIFEST_LANGUAGES: [&str; 3] = ["c", "cpp", "bitbake"];
/// The `package_manager` values of components read from the sources rather
/// than a manifest: library headers, CODESYS archives, Yocto recipes.
const SOURCE_MANAGERS: [&str; 3] = [EMBEDDED_MANAGER, "codesys", YOCTO_RECIPE_MANAGER];
/// A package ecosystem: the languages that use it, the files that declare
/// or pin its dependencies, and how to add them.
struct Ecosystem {
/// What the finding calls the code (`Python`, `JavaScript/TypeScript`).
name: &'static str,
/// The language codes of [`crate::pipeline::languages`] it covers.
languages: &'static [&'static str],
/// The purl types of its SBOM entries: entries of one mean the SBOM
/// already lists some of its libraries (from committed jars, DLLs or
/// installed packages), so a manifest is not all there is.
purl_types: &'static [&'static str],
/// Whether a file name (lowercased) is one of its manifests or lockfiles.
declares: fn(&str) -> bool,
/// Its manifests, as the finding names them.
manifests: &'static str,
/// A concrete way to add a manifest or lockfile.
example: &'static str,
}
/// The ecosystems the finding covers, in the order the findings list them.
static ECOSYSTEMS: [Ecosystem; 9] = [
Ecosystem {
name: "Python",
languages: &["python"],
purl_types: &["pypi"],
declares: |f| {
(f.starts_with("requirements") && f.ends_with(".txt"))
|| matches!(
f,
"pyproject.toml"
| "setup.py"
| "setup.cfg"
| "pipfile"
| "pipfile.lock"
| "poetry.lock"
| "uv.lock"
| "pdm.lock"
| "environment.yml"
| "environment.yaml"
)
},
manifests: "requirements.txt or pyproject.toml",
example: "run pip freeze > requirements.txt in the project's environment, or declare \
the dependencies in pyproject.toml and run uv lock or poetry lock",
},
Ecosystem {
name: "JavaScript/TypeScript",
languages: &["javascript", "typescript"],
purl_types: &["npm"],
declares: |f| {
matches!(
f,
"package.json"
| "package-lock.json"
| "npm-shrinkwrap.json"
| "yarn.lock"
| "pnpm-lock.yaml"
| "bun.lock"
| "bun.lockb"
| "deno.json"
| "deno.jsonc"
| "deno.lock"
)
},
manifests: "package.json",
example: "declare the dependencies in package.json and run npm install, which writes \
package-lock.json",
},
Ecosystem {
name: "Rust",
languages: &["rust"],
purl_types: &["cargo"],
declares: |f| matches!(f, "cargo.toml" | "cargo.lock"),
manifests: "Cargo.toml",
example: "commit Cargo.toml and Cargo.lock (cargo generate-lockfile writes it)",
},
Ecosystem {
name: "Go",
languages: &["go"],
purl_types: &["golang"],
declares: |f| matches!(f, "go.mod" | "go.sum" | "gopkg.toml" | "gopkg.lock"),
manifests: "go.mod",
example: "run go mod init and go mod tidy, which write go.mod and go.sum, and commit both",
},
Ecosystem {
name: "Java/Kotlin",
languages: &["java", "kotlin"],
purl_types: &["maven"],
declares: |f| {
matches!(
f,
"pom.xml"
| "build.gradle"
| "build.gradle.kts"
| "settings.gradle"
| "settings.gradle.kts"
| "gradle.lockfile"
| "ivy.xml"
)
},
manifests: "pom.xml or build.gradle",
example: "declare the dependencies in a Maven pom.xml or a Gradle build file; with \
Gradle, also commit gradle.lockfile (./gradlew dependencies --write-locks)",
},
Ecosystem {
name: "C#",
languages: &["csharp"],
purl_types: &["nuget"],
// A Unity project (`ProjectVersion.txt`) is the build lifecycle
// check's: without its package manifest it is a legacy build system.
declares: |f| {
[".csproj", ".fsproj", ".vbproj", ".nuspec"]
.iter()
.any(|suffix| f.ends_with(suffix))
|| matches!(
f,
"packages.config"
| "packages.lock.json"
| "directory.packages.props"
| "project.json"
| "projectversion.txt"
)
},
manifests: "a .csproj project file",
example: "reference the NuGet packages in the .csproj project file, set \
RestorePackagesWithLockFile to true and commit the packages.lock.json that \
dotnet restore writes",
},
Ecosystem {
name: "PHP",
languages: &["php"],
purl_types: &["composer"],
declares: |f| matches!(f, "composer.json" | "composer.lock"),
manifests: "composer.json",
example: "declare the dependencies in composer.json and run composer install, which \
writes composer.lock; commit both",
},
Ecosystem {
name: "Ruby",
languages: &["ruby"],
purl_types: &["gem"],
declares: |f| {
f.ends_with(".gemspec") || matches!(f, "gemfile" | "gemfile.lock" | "gems.rb")
},
manifests: "a Gemfile",
example: "declare the gems in a Gemfile and run bundle install, which writes \
Gemfile.lock; commit both",
},
Ecosystem {
name: "Dart",
languages: &["dart"],
purl_types: &["pub"],
declares: |f| matches!(f, "pubspec.yaml" | "pubspec.lock"),
manifests: "pubspec.yaml",
example: "declare the dependencies in pubspec.yaml and run dart pub get (or flutter pub \
get), which writes pubspec.lock; commit both",
},
];
/// What one scan knows about its tree when it asks for these findings.
pub(crate) struct ScannedTree<'a> {
/// The target (`Finding::repo_id`).
pub repo_id: &'a str,
/// The working copy, after the left-out paths were pruned.
pub root: &'a Path,
/// Its vendor directories, which are not the customer's code.
pub vendor: &'a [String],
/// Its source languages ([`crate::pipeline::languages::source_languages`]).
pub languages: &'a [String],
/// Whether the tree is read as Yocto layers.
pub yocto_layers: bool,
/// Whether the target has a firmware SBOM from its sources, which the
/// firmware step stored before this scan of the tree.
pub firmware_sbom: bool,
}
/// The coverage findings of one scan: a [`NO_MANIFEST_RULE`] finding per
/// ecosystem the tree's code needs a manifest for and has none, and an
/// [`UNRESOLVED_RULE`] finding per entry of `unlocked` (other than a legacy
/// build system, which is a finding of the build lifecycle check already).
///
/// # Arguments
///
/// * `tree` - the scanned tree and what the scan detected in it
/// * `sbom` - the components this scan listed, from every source
/// * `unlocked` - the manifests whose dependencies were not resolved
///
/// # Returns
///
/// The findings, with `control_refs` set to the SBOM requirement; empty when
/// the SBOM speaks for the whole tree.
pub(crate) fn coverage_findings(
tree: &ScannedTree<'_>,
sbom: &[SbomEntry],
unlocked: &[UnlockedEcosystem],
) -> Vec<Finding> {
let mut findings: Vec<Finding> = missing_manifests(tree, sbom)
.into_iter()
.map(|eco| no_manifest_finding(tree.repo_id, eco))
.collect();
findings.extend(
unlocked
.iter()
.filter(|eco| !eco.legacy_build)
.map(|eco| unresolved_finding(tree.repo_id, eco)),
);
findings
}
/// The ecosystems whose code the tree holds outside vendor directories, with
/// no manifest or lockfile of theirs anywhere outside them and no component
/// of theirs in `sbom`. Empty for a tree with C, C++ or Yocto layers, and for
/// one whose components come from its sources ([`SOURCE_MANAGERS`], or the
/// firmware SBOM).
fn missing_manifests(tree: &ScannedTree<'_>, sbom: &[SbomEntry]) -> Vec<&'static Ecosystem> {
let has_language = |l: &str| tree.languages.iter().any(|x| x == l);
let from_sources = tree.firmware_sbom
|| sbom
.iter()
.any(|e| SOURCE_MANAGERS.contains(&e.package_manager.as_str()));
if tree.yocto_layers || from_sources || NO_MANIFEST_LANGUAGES.iter().any(|l| has_language(l)) {
return Vec::new();
}
// `pkg:pypi/requests@2` has the purl type `pypi`.
let listed = |eco: &Ecosystem| {
sbom.iter().any(|e| {
e.purl
.as_deref()
.and_then(|p| p.strip_prefix("pkg:"))
.and_then(|p| p.split('/').next())
.is_some_and(|t| eco.purl_types.contains(&t))
})
};
let mut candidates: Vec<&'static Ecosystem> = ECOSYSTEMS
.iter()
.filter(|eco| eco.languages.iter().any(|l| has_language(l)))
.filter(|eco| !listed(eco))
.collect();
if candidates.is_empty() {
return candidates;
}
// One walk for all of them; it stops once each has shown a manifest.
for entry in walk_outside(tree.root, tree.vendor) {
if !entry.file_type().is_file() {
continue;
}
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
candidates.retain(|eco| !(eco.declares)(&name));
if candidates.is_empty() {
break;
}
}
candidates
}
/// The [`NO_MANIFEST_RULE`] finding for `eco` on target `repo_id`.
fn no_manifest_finding(repo_id: &str, eco: &Ecosystem) -> Finding {
let mut finding = Finding::new(
repo_id.to_string(),
compute_fingerprint(&[repo_id, NO_MANIFEST_RULE, eco.name]),
SCANNER.to_string(),
ScanType::Sbom,
format!(
"No package manifest: the SBOM lists no libraries of the {} code",
eco.name
),
format!(
"The code contains {name} files, but no manifest or lockfile (such as {manifests}) \
that lists the libraries they use. The SBOM is built from these files, so it shows \
none of the {name} libraries, and their known vulnerabilities (CVEs) are not \
checked. An empty SBOM here does not mean that the code uses no libraries.",
name = eco.name,
manifests = eco.manifests,
),
Severity::Medium,
);
finding.remediation = Some(format!(
"Add a manifest or lockfile and commit it. For {}: {}. The finding closes at the next \
scan that finds it.",
eco.name, eco.example
));
stamp(&mut finding, NO_MANIFEST_RULE);
finding
}
/// The [`UNRESOLVED_RULE`] finding for `eco` on target `repo_id`.
fn unresolved_finding(repo_id: &str, eco: &UnlockedEcosystem) -> Finding {
let mut finding = Finding::new(
repo_id.to_string(),
compute_fingerprint(&[repo_id, UNRESOLVED_RULE, &eco.manifest]),
SCANNER.to_string(),
ScanType::Sbom,
format!(
"Dependencies not resolved: the SBOM is incomplete ({})",
eco.manifest
),
format!(
"{} {}. So the versions of these libraries, and of the libraries they pull in, are \
not known: the SBOM does not list them completely, and their known \
vulnerabilities (CVEs) are not checked. Prüfwerk does not run the project's code \
to resolve them.",
eco.manifest, eco.problem
),
Severity::Low,
);
finding.remediation = Some(format!(
"{}. The finding closes at the next scan that finds the lockfile.",
capitalised(eco.remedy)
));
finding.file_path = Some(eco.manifest.clone());
stamp(&mut finding, UNRESOLVED_RULE);
finding
}
/// Give `finding` its rule, weakness and CRA requirement. The control triage
/// judges a finding on its code, which these have none of, so the mapping is
/// set here, as `cra-ai-23` in the control map binds it.
fn stamp(finding: &mut Finding, rule: &str) {
finding.rule_id = Some(rule.to_string());
finding.cwe = Some(CWE.to_string());
finding.control_refs = vec![SBOM_CONTROL.to_string()];
}
/// `text` with its first letter upper-case.
fn capitalised(text: &str) -> String {
let mut chars = text.chars();
chars
.next()
.map(|first| first.to_uppercase().chain(chars).collect())
.unwrap_or_default()
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
/// A temporary tree holding `files`, removed on drop.
struct Tree(std::path::PathBuf);
impl Tree {
fn with(files: &[&str]) -> Self {
let root = std::env::temp_dir().join(format!("cs-coverage-{}", uuid::Uuid::new_v4()));
for path in files {
let file = root.join(path);
std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
std::fs::write(file, "x").expect("write");
}
std::fs::create_dir_all(&root).expect("root");
Self(root)
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn langs(codes: &[&str]) -> Vec<String> {
codes.iter().map(|c| c.to_string()).collect()
}
fn findings_for(
files: &[&str],
languages: &[&str],
sbom: &[SbomEntry],
unlocked: &[UnlockedEcosystem],
) -> Vec<Finding> {
let tree = Tree::with(files);
let languages = langs(languages);
let vendor = vec!["vendor".to_string()];
coverage_findings(
&ScannedTree {
repo_id: "t1",
root: &tree.0,
vendor: &vendor,
languages: &languages,
yocto_layers: false,
firmware_sbom: false,
},
sbom,
unlocked,
)
}
fn entry(package_manager: &str, purl: Option<&str>) -> SbomEntry {
let mut e = SbomEntry::new(
"t1".into(),
"lib".into(),
"1.0".into(),
package_manager.into(),
);
e.purl = purl.map(str::to_string);
e
}
fn unlocked(manifest: &str, legacy_build: bool) -> UnlockedEcosystem {
UnlockedEcosystem {
manifest: manifest.into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit Cargo.lock",
legacy_build,
}
}
#[test]
fn code_without_any_manifest_is_a_medium_finding_per_ecosystem() {
let found = findings_for(
&["app/main.py", "web/app.ts", "web/util.js"],
&["javascript", "python", "typescript"],
&[],
&[],
);
let titles: Vec<&str> = found.iter().map(|f| f.title.as_str()).collect();
assert_eq!(
titles,
[
"No package manifest: the SBOM lists no libraries of the Python code",
"No package manifest: the SBOM lists no libraries of the JavaScript/TypeScript \
code",
]
);
let python = &found[0];
assert_eq!(python.severity, Severity::Medium);
assert_eq!(python.rule_id.as_deref(), Some(NO_MANIFEST_RULE));
assert_eq!(python.scanner, SCANNER);
assert_eq!(python.control_refs, [SBOM_CONTROL]);
assert_eq!(python.file_path, None);
assert!(python
.remediation
.as_deref()
.is_some_and(|r| r.contains("pip freeze > requirements.txt")));
// Stable across scans, one per ecosystem.
assert_ne!(found[0].fingerprint, found[1].fingerprint);
let again = findings_for(&["main.py"], &["python"], &[], &[]);
assert_eq!(again[0].fingerprint, python.fingerprint);
}
#[test]
fn a_manifest_or_lockfile_anywhere_outside_vendor_code_counts() {
for (manifest, language) in [
("backend/requirements-dev.txt", "python"),
("pyproject.toml", "python"),
("frontend/package.json", "javascript"),
("Cargo.lock", "rust"),
("svc/go.mod", "go"),
("app/build.gradle.kts", "kotlin"),
("pom.xml", "java"),
("src/App/App.csproj", "csharp"),
("composer.json", "php"),
("tool.gemspec", "ruby"),
("app/pubspec.yaml", "dart"),
] {
let found = findings_for(&[manifest], &[language], &[], &[]);
assert!(found.is_empty(), "{manifest} declares {language}");
}
// A vendored library's manifest is not the customer code's.
let found = findings_for(&["vendor/lib/package.json"], &["javascript"], &[], &[]);
assert_eq!(found.len(), 1);
}
#[test]
fn c_cpp_firmware_sources_and_yocto_never_ask_for_a_manifest() {
// An embedded C tree with a flashing script.
assert!(findings_for(&["tools/flash.py"], &["c", "python"], &[], &[]).is_empty());
assert!(findings_for(&["tools/flash.py"], &["cpp", "python"], &[], &[]).is_empty());
assert!(findings_for(&["lib/oe/x.py"], &["bitbake", "python"], &[], &[]).is_empty());
// Components read from the sources are an SBOM.
for manager in ["embedded", "codesys", "yocto-recipe"] {
let sbom = [entry(manager, None)];
assert!(
findings_for(&["main.py"], &["python"], &sbom, &[]).is_empty(),
"{manager}"
);
}
// So are the firmware SBOM and a Yocto layer tree.
let tree = Tree::with(&["main.py"]);
let languages = langs(&["python"]);
for (yocto_layers, firmware_sbom) in [(true, false), (false, true)] {
let found = coverage_findings(
&ScannedTree {
repo_id: "t1",
root: &tree.0,
vendor: &[],
languages: &languages,
yocto_layers,
firmware_sbom,
},
&[],
&[],
);
assert!(
found.is_empty(),
"yocto {yocto_layers}, firmware {firmware_sbom}"
);
}
}
#[test]
fn components_of_the_ecosystem_already_listed_need_no_manifest() {
// Committed jars give Maven components without a pom.xml.
let sbom = [entry("maven", Some("pkg:maven/org.slf4j/slf4j-api@2.0.9"))];
assert!(findings_for(&["Main.java"], &["java"], &sbom, &[]).is_empty());
// Components of another ecosystem do not.
let found = findings_for(&["Main.java", "main.py"], &["java", "python"], &sbom, &[]);
assert_eq!(found.len(), 1);
assert!(found[0].title.contains("Python"));
}
#[test]
fn dart_is_covered() {
let found = findings_for(&["lib/main.dart"], &["dart"], &[], &[]);
assert_eq!(found.len(), 1);
assert!(found[0]
.remediation
.as_deref()
.is_some_and(|r| r.contains("pubspec.lock")));
}
#[test]
fn an_unresolved_manifest_is_a_low_finding_and_legacy_builds_are_not_repeated() {
let found = findings_for(
&["Cargo.toml", "src/main.rs"],
&["rust"],
&[],
&[
unlocked("Cargo.toml", false),
unlocked("app/project.properties", true),
],
);
assert_eq!(found.len(), 1);
let f = &found[0];
assert_eq!(f.severity, Severity::Low);
assert_eq!(f.rule_id.as_deref(), Some(UNRESOLVED_RULE));
assert_eq!(f.file_path.as_deref(), Some("Cargo.toml"));
assert_eq!(f.line_number, None);
assert_eq!(f.control_refs, [SBOM_CONTROL]);
assert_eq!(
f.title,
"Dependencies not resolved: the SBOM is incomplete (Cargo.toml)"
);
assert!(f
.description
.starts_with("Cargo.toml declares dependencies but no lockfile pins them."));
assert_eq!(
f.remediation.as_deref(),
Some("Commit Cargo.lock. The finding closes at the next scan that finds the lockfile.")
);
}
#[test]
fn the_stamped_requirement_is_the_one_the_control_map_binds() {
let map = control_map::ControlMap::cra().expect("map");
for rule in [NO_MANIFEST_RULE, UNRESOLVED_RULE] {
let controls: Vec<&str> = map
.bindings_for_finding(SCANNER, Some(CWE), Some(rule))
.into_iter()
.map(|(entry, _)| entry.control.as_str())
.collect();
assert_eq!(controls, [SBOM_CONTROL], "{rule}");
}
}
#[test]
fn a_tree_without_package_manager_code_has_no_findings() {
assert!(findings_for(&["README.md"], &[], &[], &[]).is_empty());
assert!(findings_for(&["App.swift"], &["swift"], &[], &[]).is_empty());
}
}
@@ -147,6 +147,7 @@ pub(crate) fn unlocked_mobile_ecosystems(root: &Path) -> Vec<UnlockedEcosystem>
manifest,
problem: eco.problem,
remedy: eco.remedy,
legacy_build: false,
})
})
.collect()
@@ -1,5 +1,6 @@
mod cargo_audit;
pub(crate) mod carthage;
pub(crate) mod coverage;
mod distribution;
mod gradle;
mod mobile;
@@ -224,6 +225,9 @@ pub(crate) struct UnlockedEcosystem {
pub problem: &'static str,
/// What to commit so they are.
pub remedy: &'static str,
/// A legacy build system ([`crate::pipeline::build_lifecycle`]), which
/// is a finding of its own already.
pub legacy_build: bool,
}
/// Lockfiles that pin an npm-registry project. Bun's count: npm must never
@@ -266,12 +270,14 @@ pub(crate) fn unlocked_ecosystems(
manifest: "package.json".into(),
problem: "is locked only by bun.lockb, Bun's binary lockfile, which is not read",
remedy: "commit the text bun.lock (`bun install --save-text-lockfile`)",
legacy_build: false,
});
} else if !readable {
out.push(UnlockedEcosystem {
manifest: "package.json".into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit package-lock.json, yarn.lock, pnpm-lock.yaml or bun.lock",
legacy_build: false,
});
}
}
@@ -284,6 +290,7 @@ pub(crate) fn unlocked_ecosystems(
manifest: manifest.into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit requirements.txt, poetry.lock, Pipfile.lock or uv.lock",
legacy_build: false,
});
}
}
@@ -292,6 +299,7 @@ pub(crate) fn unlocked_ecosystems(
manifest: "Cargo.toml".into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit Cargo.lock",
legacy_build: false,
});
}
out.extend(mobile::unlocked_mobile_ecosystems(repo_path));
@@ -307,6 +315,7 @@ pub(crate) fn unlocked_ecosystems(
Packages/manifest.json) whose dependencies cannot be read",
remedy: "migrate the build (Gradle with the Android Gradle Plugin, or a \
current Unity LTS with the Package Manager)",
legacy_build: true,
}),
);
out.extend(nuget::unresolved_projects(repo_path, resolved_nuget));
@@ -250,6 +250,7 @@ pub(crate) fn unresolved_projects(root: &Path, resolved: &[String]) -> Vec<Unloc
remedy: "set <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> (in the \
project or a Directory.Build.props), restore once and commit \
packages.lock.json",
legacy_build: false,
}]
}
+1 -1
View File
@@ -85,7 +85,7 @@ pub use project::{Project, ProjectKind};
pub use repository::ScanTrigger;
pub use sbom::{
ComponentHash, InImage, InImageBasis, SbomEntry, SbomQuality, SbomQualityCheck,
SbomQualityProfile, VulnRef, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
SbomQualityProfile, VulnRef, SBOM_COVERAGE_SCANNER, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
};
pub use scan::{
RunErrorCode, RunNote, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode,
+5
View File
@@ -27,6 +27,11 @@ impl VulnRef {
/// in a layer tree, without a build.
pub const YOCTO_RECIPE_MANAGER: &str = "yocto-recipe";
/// The scanner (`Finding::scanner`) of the findings that say why a target's
/// SBOM is empty or incomplete: code without a manifest, and manifests whose
/// dependencies were not resolved (#979).
pub const SBOM_COVERAGE_SCANNER: &str = "sbom-coverage";
/// Where a [`YOCTO_RECIPE_MANAGER`] component comes from, as the SBOM view,
/// the exports and the evidence say it. Layer overrides, PACKAGECONFIG and
/// what the image installs are not resolved, so the inventory lists more than
+27
View File
@@ -2725,6 +2725,33 @@ tbody tr:last-child td {
margin-bottom: 16px;
}
/* The empty component table (#979): why, and what to add. */
.sbom-empty p {
margin: 0 0 10px;
font-size: 14px;
line-height: 1.5;
}
.sbom-empty-findings {
margin: 0;
padding: 0;
list-style: none;
display: grid;
gap: 12px;
}
.sbom-empty-findings li {
padding: 10px 12px;
border-left: 3px solid var(--accent);
background: var(--accent-muted);
border-radius: 4px;
}
.sbom-empty-findings li p {
margin: 4px 0 6px;
color: var(--text-secondary);
}
.sbom-quality-head {
margin: 0 0 4px;
font-size: 15px;
+40
View File
@@ -2481,6 +2481,10 @@ pub mod findings {
de: "Build-System und Plattform",
en: "Build system and platform",
},
compliance_core::models::SBOM_COVERAGE_SCANNER => Text {
de: "Vollständigkeit der Stückliste",
en: "SBOM completeness",
},
"clamav" => Text {
de: "Schadsoftware (ClamAV)",
en: "Malware (ClamAV)",
@@ -2858,6 +2862,41 @@ pub mod sbom {
de: "Die Komponenten Ihrer Software, ihre Lizenzen und bekannte Schwachstellen (CVE)",
en: "Software bill of materials: dependencies, licenses and known vulnerabilities",
};
/// The empty state of the component table (#979).
pub const EMPTY_TITLE: Text = Text {
de: "Keine Komponenten gefunden",
en: "No components found",
};
/// Why the component table is empty.
pub const EMPTY_WHY: Text = Text {
de: "Die Stückliste entsteht aus den Paketmanifesten und Lockfiles im Code (etwa \
requirements.txt, package-lock.json oder Cargo.lock), aus den Firmware-Quellen \
oder aus einem SPS-Projektarchiv. Die letzte Prüfung hat dort keine Komponenten \
gefunden. Das heißt nicht, dass die Software keine Bibliotheken verwendet.",
en: "The SBOM is built from the package manifests and lockfiles in the code (such as \
requirements.txt, package-lock.json or Cargo.lock), from the firmware sources or \
from a PLC project archive. The last scan found no components there. That does \
not mean the software uses no libraries.",
};
/// How to fill the component table, by example.
pub const EMPTY_EXAMPLE: Text = Text {
de: "Zum Beispiel: Für Python schreibt pip freeze > requirements.txt die Bibliotheken \
in eine requirements.txt, für JavaScript schreibt npm install die \
package-lock.json, für Rust gehört die Cargo.lock ins Repository. Nach der \
nächsten Prüfung stehen die Komponenten hier.",
en: "For example: for Python, pip freeze > requirements.txt writes the libraries to a \
requirements.txt; for JavaScript, npm install writes package-lock.json; for Rust, \
commit Cargo.lock. After the next scan the components are listed here.",
};
/// Above the open findings that say what is missing.
pub const EMPTY_FINDINGS: Text = Text {
de: "Was in diesem Prüfobjekt fehlt und wie Sie es ergänzen:",
en: "What this target is missing, and how to add it:",
};
pub const OPEN_FINDING: Text = Text {
de: "Zum Befund",
en: "Open the finding",
};
pub const PACKAGES_TAB: Text = Text {
de: "Pakete",
en: "Packages",
@@ -3856,6 +3895,7 @@ pub mod compliance {
"csharp" => "C#",
"vb" => "Visual Basic",
"swift" => "Swift",
"dart" => "Dart",
"structured_text" => "Structured Text",
"plcopen" => "PLCopen XML",
other => other,
@@ -18,6 +18,8 @@ pub struct FindingsQuery {
pub status: String,
pub repo_id: String,
pub q: String,
/// One scanner (`Finding::scanner`), or empty for all.
pub scanner: String,
/// One app variant (`Tablet App`), or empty for all.
pub variant: String,
/// One folder of the folder chart (`src/`, `src/*`, `/`), or empty.
@@ -104,6 +106,9 @@ pub async fn fetch_findings(query: FindingsQuery) -> Result<FindingsListResponse
if !query.status.is_empty() {
path.push_str(&format!("&status={}", query.status));
}
if !query.scanner.is_empty() {
path.push_str(&format!("&scanner={}", query.scanner));
}
if !query.repo_id.is_empty() {
path.push_str(&format!("&repo_id={}", query.repo_id));
}
@@ -99,6 +99,7 @@ pub fn FindingsPage(
path: path_filter(),
sort_by: sort_by(),
sort_order: sort_order(),
..Default::default()
};
async move {
if grouped_view {
+71 -1
View File
@@ -1,4 +1,5 @@
use compliance_core::models::{LicenseConclusion, YOCTO_RECIPE_MANAGER};
use compliance_core::finding_breakdown::OPEN_STATUS_FILTER;
use compliance_core::models::{LicenseConclusion, SBOM_COVERAGE_SCANNER, YOCTO_RECIPE_MANAGER};
use dioxus::prelude::*;
use crate::app::Route;
@@ -13,6 +14,7 @@ use crate::components::pagination::Pagination;
use crate::components::toast::{ToastType, Toasts};
use crate::i18n::texts::{common, license_edit as lx, license_review as rx, sbom as tx};
use crate::i18n::{use_lang, Lang};
use crate::infrastructure::findings::{fetch_findings, FindingsQuery};
use crate::infrastructure::sbom::*;
use compliance_core::models::ReviewDecision;
@@ -109,6 +111,16 @@ pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element
}
});
// Only the target narrows the table: an empty one then means the SBOM
// is empty, not that nothing matched a filter.
let unfiltered = move || {
pm_filter().is_empty()
&& search_q().is_empty()
&& vuln_toggle().is_none()
&& license_filter().is_empty()
&& in_image_filter().is_none()
};
// ── SBOM quality of the selected target (#496) ──
let sbom_quality = use_resource(move || {
let repo = repo_filter();
@@ -336,6 +348,9 @@ pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element
// ── SBOM table ──
match &*sbom.read() {
Some(Some(resp)) if resp.data.is_empty() && unfiltered() => rsx! {
SbomEmpty { target_id: repo_filter() }
},
Some(Some(resp)) => {
let total_pages = resp.total.unwrap_or(0).div_ceil(50).max(1);
rsx! {
@@ -1039,6 +1054,61 @@ fn epss_label(epss: &EpssData) -> String {
)
}
/// The component table's empty state (#979): why the SBOM is empty, and the
/// target's open findings that say what it is missing and how to add it, or
/// an example where there are none (all targets, or code such as C that has
/// no standard manifest).
#[component]
fn SbomEmpty(target_id: ReadSignal<String>) -> Element {
let lang = use_lang()();
let findings = use_resource(move || async move {
let repo_id = target_id();
if repo_id.is_empty() {
return Vec::new();
}
fetch_findings(FindingsQuery {
page: 1,
repo_id,
scanner: SBOM_COVERAGE_SCANNER.to_string(),
status: OPEN_STATUS_FILTER.to_string(),
..Default::default()
})
.await
.map(|resp| resp.data)
.unwrap_or_default()
});
let findings = findings.read().clone().unwrap_or_default();
rsx! {
section { class: "card sbom-empty",
h3 { class: "sbom-quality-head", {tx::EMPTY_TITLE.get(lang)} }
p { {tx::EMPTY_WHY.get(lang)} }
if findings.is_empty() {
p { {tx::EMPTY_EXAMPLE.get(lang)} }
} else {
p { {tx::EMPTY_FINDINGS.get(lang)} }
ul { class: "sbom-empty-findings",
for finding in findings {
{
let id = finding.id.map(|id| id.to_hex()).unwrap_or_default();
rsx! {
li { key: "{id}",
strong { "{finding.title}" }
if let Some(remediation) = &finding.remediation {
p { "{remediation}" }
}
Link { to: Route::FindingDetailPage { id: id.clone() },
{tx::OPEN_FINDING.get(lang)}
}
}
}
}
}
}
}
}
}
}
/// The selected target's SBOM quality score: one line per profile, the checks
/// it does not meet folded under it.
fn sbom_quality_card(resp: SbomQualityResponse, lang: Lang) -> Element {
+23
View File
@@ -1254,6 +1254,29 @@
"legacy-build-system-no-sbom"
],
"check": "The product's components must be declared in a machine-readable form an SBOM can be built from; a build system that declares none (Eclipse/ADT, Unity without its package manifest) violates it."
},
{
"tool": "sbom-coverage",
"scan_type": "sbom",
"languages": [
"python",
"javascript",
"typescript",
"rust",
"go",
"java",
"kotlin",
"csharp",
"php",
"ruby",
"dart"
],
"cwe": [],
"rules": [
"sbom-no-manifest",
"sbom-dependencies-unresolved"
],
"check": "The product's components must be declared in a manifest or lockfile an SBOM can be built from; code in a language with a package manager and no manifest, or a manifest whose dependencies are not resolved, violates it."
}
],
"note": null,
+1
View File
@@ -116,6 +116,7 @@ The most common types in a scan of source code:
| **OAuth** | Prüfwerk's own pattern rules |
| **Code-Qualität** (Lint) | Linters, where the deployment runs them |
| **SPS-Steuerungslogik** (PLC control logic) | Prüfwerk's PLC analyser, see [SPS / PLC (CODESYS)](/guide/plc) |
| **Vollständigkeit der Stückliste** (SBOM completeness) | Code without a manifest or lockfile, and manifests whose dependencies were not resolved, see [SBOM](/guide/sbom#when-the-sbom-is-empty-or-incomplete) |
| **Penetrationstest**, **Dynamische Prüfung (DAST)** | Entered or imported by hand, see [Befunde aus manuellen Tests](/guide/manual-findings) |
## Statuses
+41
View File
@@ -86,6 +86,41 @@ and is not judged.
Firmware images, container images and app packages are not unpacked yet; their
components come from the source code.
### When the SBOM is empty or incomplete
An SBOM without components does not mean the software uses no libraries:
the code may simply not declare them. Two findings of the type
**Vollständigkeit der Stückliste** (SBOM completeness) say so, both mapped to
the CRA requirement *Software Bill of Materials (SBOM)*:
| Rule | Severity | When |
|------|----------|------|
| `sbom-no-manifest` | Medium | The code is in a language with a package manager (Python, JavaScript/TypeScript, Rust, Go, Java/Kotlin, C#, PHP, Ruby, Dart), but the tree holds no manifest or lockfile for it anywhere outside vendor directories, and the SBOM lists no component of that ecosystem. One finding per ecosystem. |
| `sbom-dependencies-unresolved` | Low | A manifest exists, but its dependencies were not resolved: no lockfile, or one no tool reads (`bun.lockb`, Gradle without dependency locking, `<PackageReference>` without `packages.lock.json`). One finding per manifest, the same gap that is listed under **Nicht ausgeführt**. A legacy build system is reported by its own finding instead (see above). |
Each finding says why the SBOM is empty or incomplete and how to add the
missing file, for example:
- **Python** -- `pip freeze > requirements.txt` in the project's environment,
or the dependencies in `pyproject.toml` and `uv lock` or `poetry lock`;
- **JavaScript/TypeScript** -- the dependencies in `package.json`;
`npm install` writes `package-lock.json`;
- **Rust** -- commit `Cargo.toml` and `Cargo.lock`;
- **Go** -- `go mod init` and `go mod tidy` write `go.mod` and `go.sum`;
- **Java/Kotlin** -- a Maven `pom.xml` or a Gradle build file, with Gradle
also `gradle.lockfile`;
- **C#** -- the NuGet packages in the `.csproj` file and the
`packages.lock.json` that `dotnet restore` writes;
- **PHP**, **Ruby**, **Dart** -- `composer.json`/`composer.lock`,
`Gemfile`/`Gemfile.lock`, `pubspec.yaml`/`pubspec.lock`.
C and C++ have no standard manifest, so their code never raises
`sbom-no-manifest`; neither does a tree whose components come from its
sources (library headers, the firmware build, a CODESYS archive, Yocto
layers) or a PLC target. Prüfwerk does not guess the components or run the
project's code to resolve them. A finding closes at the next scan that
finds the manifest or lockfile.
## Known vulnerabilities
Package dependencies are matched against [OSV.dev](https://osv.dev/). Libraries
@@ -123,6 +158,12 @@ complete scan.
Open **Stückliste** in the sidebar. The **Pakete** (Packages) tab lists the
components of all targets, 50 per page.
When a target has no components at all, the tab says why instead of showing
an empty table: where the SBOM comes from, and the target's open
[SBOM completeness findings](#when-the-sbom-is-empty-or-incomplete), each with
its example and a link to the finding. Without such a finding (all targets,
or C/C++ code) it gives a general example.
### Charts for one target
With one target picked, two bar charts open the tab ("Diagramm"; "Tabelle"
+1 -1
View File
@@ -175,7 +175,7 @@ as a clean result: the CRA requirements it checks show as **Nicht geprüft**.
| **Testdaten (fixtures, testdata)** | Testdaten, von der ganzen Prüfung ausgenommen (Codeanalyse, Stückliste, CVEs): *(directories)* | Nothing; for information. Findings an earlier scan reported there are closed as test data. |
| **Ausgenommene Pfade** | In den Einstellungen des Prüfobjekts ausgenommen, von der ganzen Prüfung ausgenommen (Codeanalyse, Stückliste, CVEs): *(paths)* | Nothing; for information. Change the list under **Bearbeiten**. |
| e.g. **Statische Codeanalyse (Semgrep)**, **C/C++-Analyse (cppcheck)** | *(tool)* wurde nicht fertig; was es prüft, gilt als nicht bewertet. | Start the scan again; if it recurs, contact support. |
| **Abhängigkeiten (SBOM)** | *(manifest)* ohne Lockfile: Die Versionen der Abhängigkeiten und ihre CVEs sind nicht bekannt. | Commit the lockfile (see below). |
| **Abhängigkeiten (SBOM)** | *(manifest)* ohne Lockfile: Die Versionen der Abhängigkeiten und ihre CVEs sind nicht bekannt. | Commit the lockfile (see below). The same gap is a Low finding, `sbom-dependencies-unresolved`, which closes once the lockfile is there; see [SBOM](/guide/sbom#when-the-sbom-is-empty-or-incomplete). |
| e.g. **Firmware-Binäranalyse**, **Container-Analyse**, **Mobile-App-Analyse** | e.g. Firmware-Images werden noch nicht entpackt … | Nothing analyses these files yet; scan the source code instead. |
| **SPS-Bibliotheken (SBOM)** | *(file)* ist kein lesbares CODESYS-Projektarchiv. | Export the archive again with *File → Project Archive*, with the referenced libraries ticked. |
| **SPS-Projekt (natives Format)** | CODESYS-Projekt im nativen Format, Steuerungslogik nicht geprüft: *(files)* … | Export the POUs as PLCopen XML (*Project → Export PLCopenXML*) and add the export to the target; see [PLC / SPS](/guide/plc), which also has a script that exports it automatically. |