From c5b4a18bda434dbc4213e10c5fcb8eef7395b63b Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 9 Oct 2026 19:22:46 +0200 Subject: [PATCH] feat(yocto): recipes an image recipe installs are marked as in the image (declared) The recipe helper now also reads the image recipes (inherit core-image/image, or *-image*.bb / an image bbappend that declares installs), local.conf.sample and distro configurations: IMAGE_INSTALL and CORE_IMAGE_EXTRA_INSTALL with =, ?=, +=, :append, the old _append and :remove, and IMAGE_FEATURES / EXTRA_IMAGE_FEATURES. Package groups in the tree are read with their RDEPENDS/RRECOMMENDS per package, and each recipe with the packages its PACKAGES names. Still oelint-parser, nothing executed; the recipe inventory itself is unchanged (checked against Poky's meta: 834 identical recipes). The agent maps the declared names to recipes (recipe name, PACKAGES, default -dev/-dbg/... packages), expands package groups one level and maps IMAGE_FEATURES to OE-Core's FEATURE_PACKAGES groups only where they are in the tree. Components get SbomEntry.in_image {basis: declared, images}, an evidence line, a CycloneDX property pruefwerk:component:in_image and the SPDX package comment. Names not in the tree are listed on the run (image_install, SkipCode::NotInTree); no component is invented. The SBOM list sorts in-image components first and filters by in_image; the dashboard shows an "Im Image (deklariert)" badge and filter whose tooltip says it is read from the recipes, not resolved by bitbake. The nightly fixture's image installs a package group (packagegroup-pump -> pump-web-ui of pump-web); pump-fw stays in no image. Baseline updated; the nine recipe-lint findings are unchanged. Drops the .pyc committed by #551. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- .gitignore | 3 + compliance-agent/src/api/handlers/dto.rs | 4 + compliance-agent/src/api/handlers/sbom.rs | 11 +- compliance-agent/src/pipeline/orchestrator.rs | 41 +- .../src/pipeline/yocto_inventory.rs | 691 +++++++++++++++++- compliance-agent/tests/integration/api/mod.rs | 1 + .../tests/integration/api/sbom.rs | 85 +++ compliance-agent/tests/nightly.rs | 12 +- compliance-core/src/models/mod.rs | 4 +- compliance-core/src/models/sbom.rs | 48 ++ compliance-core/src/models/scan.rs | 4 + compliance-core/src/sbom_docs.rs | 87 ++- compliance-dashboard/src/i18n/texts.rs | 41 +- .../src/infrastructure/sbom.rs | 7 + compliance-dashboard/src/pages/sbom.rs | 26 + .../pruefwerk_yocto_recipes.cpython-314.pyc | Bin 21331 -> 0 bytes docker/pruefwerk_yocto_recipes.py | 333 ++++++++- docs/guide/yocto.md | 64 +- .../nightly/baselines/fw-yocto-layer.json | 9 +- fixtures/nightly/firmware/README.md | 2 +- .../recipes-app/pump-web/pump-web_2.1.bb | 5 + .../recipes-core/images/pump-image.bb | 4 + .../packagegroups/packagegroup-pump.bb | 9 + fixtures/nightly/targets.json | 2 +- 24 files changed, 1416 insertions(+), 77 deletions(-) create mode 100644 compliance-agent/tests/integration/api/sbom.rs delete mode 100644 docker/__pycache__/pruefwerk_yocto_recipes.cpython-314.pyc create mode 100644 fixtures/nightly/firmware/yocto-layer/recipes-core/packagegroups/packagegroup-pump.bb diff --git a/.gitignore b/.gitignore index 12c7009..5d8dead 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ .playwright-mcp/ report-preview-full.png compliance-dashboard/attack-chain-final.html + +# Python bytecode (the agent image helpers) +__pycache__/ diff --git a/compliance-agent/src/api/handlers/dto.rs b/compliance-agent/src/api/handlers/dto.rs index aa8ed80..d75e72b 100644 --- a/compliance-agent/src/api/handlers/dto.rs +++ b/compliance-agent/src/api/handlers/dto.rs @@ -226,6 +226,10 @@ pub struct SbomFilter { pub has_vulns: Option, #[serde(default)] pub license: Option, + /// Only components an image is known to contain (`true`), or only the + /// others (`false`); see [`compliance_core::models::InImage`]. + #[serde(default)] + pub in_image: Option, #[serde(default = "default_page", deserialize_with = "de_page")] pub page: u64, #[serde(default = "default_limit", deserialize_with = "de_limit")] diff --git a/compliance-agent/src/api/handlers/sbom.rs b/compliance-agent/src/api/handlers/sbom.rs index 8747f49..b72d04b 100644 --- a/compliance-agent/src/api/handlers/sbom.rs +++ b/compliance-agent/src/api/handlers/sbom.rs @@ -84,6 +84,9 @@ pub async fn list_sbom( if let Some(license) = &filter.license { query.insert("license", license); } + if let Some(in_image) = filter.in_image { + query.insert("in_image", doc! { "$exists": in_image }); + } let skip = filter.skip(); let total = db @@ -95,7 +98,7 @@ pub async fn list_sbom( let entries = match db .sbom_entries() .find(query) - .sort(doc! { "name": 1 }) + .sort(list_order()) .skip(skip) .limit(filter.limit) .await @@ -114,6 +117,12 @@ pub async fn list_sbom( })) } +/// The order of the SBOM list: the components an image contains first (a +/// missing `in_image` sorts as null, below any value), then by name. +fn list_order() -> mongodb::bson::Document { + doc! { "in_image.basis": -1, "name": 1 } +} + #[tracing::instrument(skip_all)] pub async fn export_sbom( Extension(agent): AgentExt, diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index c629ecc..a6b5239 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -24,7 +24,7 @@ use crate::pipeline::plan::build_scan_plan; use crate::pipeline::repo_view::RepoView; use crate::pipeline::sbom::{LicenseCache, NugetRegistry, SbomScanner}; use crate::pipeline::semgrep::SemgrepScanner; -use crate::pipeline::yocto_inventory::{self, Recipe}; +use crate::pipeline::yocto_inventory::{self, Inventory}; use crate::secrets::SecretBox; /// Context from graph analysis passed to LLM triage for enhanced filtering @@ -500,12 +500,32 @@ impl PipelineOrchestrator { .unwrap_or_default(); // A Yocto layer tree: its recipes, read without a build and labelled // as the recipe inventory (not the image SBOM). - let yocto_recipes = if repo.yocto_layers { + let yocto = if repo.yocto_layers { self.yocto_recipes(&repo_path, scan_run_id).await } else { - Vec::new() + Inventory::default() }; - let yocto_entries = yocto_inventory::entries(&yocto_recipes, &repo_id); + // The recipes the image recipes name are marked as in the image + // (declared); what an image names that is not in the tree is listed. + let declarations = yocto_inventory::declared_in_images(&yocto); + if !declarations.unresolved.is_empty() { + let names: Vec = declarations.unresolved.iter().cloned().collect(); + self.skip_stage( + scan_run_id, + SkippedStage::new( + yocto_inventory::IMAGE_STAGE, + SkipCode::NotInTree, + format!( + "named by an image but not a recipe or package group in the tree: {}", + component_list(&names) + ), + ) + .about(component_list(&names)), + ) + .await; + } + let yocto_entries = yocto_inventory::entries(&yocto.recipes, &declarations, &repo_id); + let yocto_recipes = yocto.recipes; for entry in embedded.into_iter().chain(codesys).chain(yocto_entries) { let known = sbom_entries .iter() @@ -2368,9 +2388,10 @@ impl PipelineOrchestrator { .await; } - /// The recipes of a Yocto layer tree. A parser that failed, a tree with - /// no layer, or recipes the parser could not read are recorded on the run. - async fn yocto_recipes(&self, tree: &std::path::Path, scan_run_id: &str) -> Vec { + /// The recipes, images and package groups of a Yocto layer tree. A parser + /// that failed, a tree with no layer, or recipes the parser could not read + /// are recorded on the run. + async fn yocto_recipes(&self, tree: &std::path::Path, scan_run_id: &str) -> Inventory { match yocto_inventory::read(tree).await { Ok(inventory) if inventory.recipes.is_empty() && inventory.errors.is_empty() => { self.skip_stage( @@ -2383,7 +2404,7 @@ impl PipelineOrchestrator { ), ) .await; - Vec::new() + Inventory::default() } Ok(inventory) => { if !inventory.errors.is_empty() { @@ -2404,11 +2425,11 @@ impl PipelineOrchestrator { ) .await; } - inventory.recipes + inventory } Err(skipped) => { self.skip_stage(scan_run_id, skipped).await; - Vec::new() + Inventory::default() } } } diff --git a/compliance-agent/src/pipeline/yocto_inventory.rs b/compliance-agent/src/pipeline/yocto_inventory.rs index 30647b7..20e8fbe 100644 --- a/compliance-agent/src/pipeline/yocto_inventory.rs +++ b/compliance-agent/src/pipeline/yocto_inventory.rs @@ -8,27 +8,37 @@ //! SRCREV), its LICENSE, and the CPE NVD knows it by (CVE_PRODUCT, CVE_VERSION). //! //! It is labelled [`YOCTO_RECIPE_SOURCE`] everywhere it shows: layer -//! overrides, PACKAGECONFIG, the distro and machine configuration and what an -//! image installs are not resolved, so the inventory lists every recipe in the -//! tree, more than an image contains. +//! overrides, PACKAGECONFIG, the distro and machine configuration are not +//! resolved, so the inventory lists every recipe in the tree, more than an +//! image contains. +//! +//! The recipes an image recipe names (IMAGE_INSTALL, a package group it +//! installs, one level deep, the package groups of its IMAGE_FEATURES) are +//! marked as in the image, declared ([`declared_in_images`]): read from the +//! recipes as written, not resolved by BitBake. //! //! What a recipe says about its CVEs becomes the alert's VEX statement //! ([`vex_statements`]): a CVE_STATUS (or CVE_STATUS_GROUPS, or the older //! CVE_CHECK_IGNORE) and a patch in SRC_URI with a `CVE:` tag, as Yocto's own //! cve-check reads them. +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::path::Path; use std::time::Duration; use compliance_core::models::{ - CveAlert, SbomEntry, SkipCode, SkippedStage, StatusChange, VexAssessment, VexJustification, - VexStatus, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE, + CveAlert, InImage, InImageBasis, SbomEntry, SkipCode, SkippedStage, StatusChange, + VexAssessment, VexJustification, VexStatus, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE, }; use compliance_core::purl::encode; /// The scan run's stage id for the recipe inventory. pub const STAGE: &str = "recipe_inventory"; +/// The scan run's stage id for the names an image declares that are not +/// recipes in the tree. +pub const IMAGE_STAGE: &str = "image_install"; + /// The helper the agent image installs (see `Dockerfile.agent`). const HELPER: &str = "/opt/pruefwerk/pruefwerk_yocto_recipes.py"; @@ -57,6 +67,10 @@ pub struct Recipe { pub pn: String, /// The base recipe name (BPN): PN without a `-native` or multilib part. pub bpn: String, + /// The packages PACKAGES names besides the defaults (`pump-web-ui`), as + /// far as they are written without a variable. + #[serde(default)] + pub packages: Vec, /// PV as assigned, expanded as far as the tree allows, or from the file /// name; `None` when neither gives one. #[serde(default)] @@ -105,10 +119,63 @@ pub struct Patch { pub cves: Vec, } +/// An image recipe (or a bbappend of an image not in the tree) and what it +/// declares the image installs. +#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)] +pub struct ImageRecipe { + /// The `.bb` (or `.bbappend`) file, relative to the tree. + pub file: String, + /// The image's name (`pump-image`). + pub pn: String, + /// IMAGE_INSTALL and CORE_IMAGE_EXTRA_INSTALL, every operation and + /// override counted (`:append`, `_append`, `+=`). + #[serde(default)] + pub install: Vec, + /// IMAGE_FEATURES and EXTRA_IMAGE_FEATURES. + #[serde(default)] + pub features: Vec, +} + +/// A local.conf.sample or distro configuration, which declares installs for +/// every image. +#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)] +pub struct ImageConfig { + /// The file, relative to the tree. + pub file: String, + #[serde(default)] + pub install: Vec, + #[serde(default)] + pub features: Vec, +} + +/// A package group recipe: what each of its packages pulls in. +#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)] +pub struct PackageGroup { + /// The `.bb` file, relative to the tree. + pub file: String, + /// The recipe name (`packagegroup-pump`). + pub pn: String, + /// Its packages (`packagegroup-pump`, `packagegroup-pump-web`). + #[serde(default)] + pub packages: Vec, + /// RDEPENDS and RRECOMMENDS per package, `${PN}` expanded. + #[serde(default)] + pub rdepends: BTreeMap>, +} + /// What the helper read from a tree. #[derive(Debug, Default, PartialEq, serde::Deserialize)] pub struct Inventory { pub recipes: Vec, + /// Image recipes. + #[serde(default)] + pub images: Vec, + /// Package group recipes. + #[serde(default)] + pub packagegroups: Vec, + /// Configurations declaring installs for every image. + #[serde(default)] + pub configs: Vec, /// Recipes the parser could not read. #[serde(default)] pub errors: Vec, @@ -162,13 +229,54 @@ fn failed(reason: String) -> SkippedStage { fn parse(json: &[u8]) -> Result { let mut inventory: Inventory = serde_json::from_slice(json)?; inventory.recipes.retain(plausible); + inventory + .images + .retain(|i| short(&i.file) && short(&i.pn) && !i.pn.is_empty()); + inventory.configs.retain(|c| short(&c.file)); + inventory + .packagegroups + .retain(|g| short(&g.file) && short(&g.pn) && !g.pn.is_empty()); + for image in &mut inventory.images { + image.install.retain(|w| is_package_name(w)); + image.features.retain(|w| is_package_name(w)); + } + for config in &mut inventory.configs { + config.install.retain(|w| is_package_name(w)); + config.features.retain(|w| is_package_name(w)); + } + for group in &mut inventory.packagegroups { + group.packages.retain(|w| is_package_name(w)); + group.rdepends.retain(|package, _| is_package_name(package)); + for words in group.rdepends.values_mut() { + words.retain(|w| is_package_name(w)); + } + } + for recipe in &mut inventory.recipes { + recipe.packages.retain(|w| is_package_name(w)); + } Ok(inventory) } +/// Whether `text` is short and on one line, with no control characters. +fn short(text: &str) -> bool { + text.len() <= MAX_VALUE && !text.chars().any(char::is_control) +} + +/// Whether `word` reads as a package, recipe or feature name +/// (`packagegroup-core-boot`, `libstdc++`, `python3.12-dev`): not a variable +/// left unexpanded, nor a piece of inline Python or a version constraint. +fn is_package_name(word: &str) -> bool { + word.len() <= MAX_VALUE + && word.starts_with(|c: char| c.is_ascii_alphanumeric()) + && word + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '+' | '.' | '_')) +} + /// Whether every value of `recipe` reads as a value: short, one line, no /// control characters. Anything else is dropped rather than stored. fn plausible(recipe: &Recipe) -> bool { - let ok = |text: &str| text.len() <= MAX_VALUE && !text.chars().any(char::is_control); + let ok = short; let optional = |text: &Option| text.as_deref().is_none_or(ok); ok(&recipe.file) && ok(&recipe.pn) @@ -416,8 +524,209 @@ fn spdx_license(license: &str) -> String { .join(" ") } -/// The SBOM components of `recipes`, one per base recipe name and version. -pub fn entries(recipes: &[Recipe], repo_id: &str) -> Vec { +/// The package groups an image feature installs (`FEATURE_PACKAGES_*` in +/// OpenEmbedded-Core's image.bbclass). Features whose packages a variable +/// sets (`hwcodecs`, `package-management`, `splash`) are in +/// [`VARIABLE_FEATURES`]; any other feature (`debug-tweaks`) installs nothing. +const FEATURE_PACKAGES: &[(&str, &[&str])] = &[ + ("weston", &["packagegroup-core-weston"]), + ("x11", &["packagegroup-core-x11"]), + ("x11-base", &["packagegroup-core-x11-base"]), + ("x11-sato", &["packagegroup-core-x11-sato"]), + ("tools-debug", &["packagegroup-core-tools-debug"]), + ("eclipse-debug", &["packagegroup-core-eclipse-debug"]), + ("tools-profile", &["packagegroup-core-tools-profile"]), + ("tools-testapps", &["packagegroup-core-tools-testapps"]), + ( + "tools-sdk", + &[ + "packagegroup-core-sdk", + "packagegroup-core-standalone-sdk-target", + ], + ), + ("nfs-server", &["packagegroup-core-nfs-server"]), + ("nfs-client", &["packagegroup-core-nfs-client"]), + ("ssh-server-dropbear", &["packagegroup-core-ssh-dropbear"]), + ("ssh-server-openssh", &["packagegroup-core-ssh-openssh"]), +]; + +/// The image features whose packages a variable of the build sets. +const VARIABLE_FEATURES: &[&str] = &["hwcodecs", "package-management", "splash"]; + +/// The packages BitBake makes of every recipe by default (`PACKAGES` in +/// bitbake.conf), by their suffix: `busybox-dev` comes from `busybox`. +const DEFAULT_PACKAGE_SUFFIXES: &[&str] = &[ + "-src", + "-dbg", + "-staticdev", + "-dev", + "-doc", + "-locale", + "-ptest", +]; + +/// What the image recipes declare, by recipe. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Declarations { + /// Per recipe (BPN), the images that declare it. + pub images: BTreeMap>, + /// What an image names that is not a recipe or package group in the tree + /// (`packagegroup-core-boot`, `ssh-server-dropbear (IMAGE_FEATURES)`). + pub unresolved: BTreeSet, +} + +/// Maps the package names of the tree to their recipes and package groups. +struct PackageIndex<'a> { + /// Package (and recipe) name to BPN. + recipes: HashMap<&'a str, &'a str>, + /// Package of a package group to what it pulls in. + groups: HashMap<&'a str, &'a [String]>, + /// Every package and name of the package groups. + group_names: BTreeSet<&'a str>, +} + +impl<'a> PackageIndex<'a> { + fn new(inventory: &'a Inventory) -> Self { + let mut recipes = HashMap::new(); + // A package PACKAGES names, unless a recipe of that name exists. + for recipe in &inventory.recipes { + for package in &recipe.packages { + recipes + .entry(package.as_str()) + .or_insert(recipe.bpn.as_str()); + } + } + for recipe in &inventory.recipes { + recipes.insert(recipe.pn.as_str(), recipe.bpn.as_str()); + recipes.insert(recipe.bpn.as_str(), recipe.bpn.as_str()); + } + let mut groups = HashMap::new(); + let mut group_names = BTreeSet::new(); + for group in &inventory.packagegroups { + group_names.insert(group.pn.as_str()); + group_names.extend(group.packages.iter().map(String::as_str)); + for (package, pulled) in &group.rdepends { + group_names.insert(package.as_str()); + groups.insert(package.as_str(), pulled.as_slice()); + } + } + Self { + recipes, + groups, + group_names, + } + } + + /// The recipe (BPN) that makes `package`: a recipe of that name, a + /// package its PACKAGES names, or a default package (`-dev`, `-dbg`). + fn recipe_of(&self, package: &str) -> Option<&'a str> { + self.recipes.get(package).copied().or_else(|| { + DEFAULT_PACKAGE_SUFFIXES.iter().find_map(|suffix| { + package + .strip_suffix(suffix) + .and_then(|base| self.recipes.get(base).copied()) + }) + }) + } + + /// The recipes `name` installs: itself, or, for a package group, the + /// recipes it pulls in (one level: a group in a group is not expanded). + /// What is not in the tree goes to `unresolved`. + fn install( + &self, + name: &str, + found: &mut BTreeSet<&'a str>, + unresolved: &mut BTreeSet, + ) { + if let Some(pulled) = self.groups.get(name) { + for package in pulled.iter() { + match self.recipe_of(package) { + Some(bpn) => { + found.insert(bpn); + } + None if self.group_names.contains(package.as_str()) => { + unresolved.insert(format!("{package} (a package group in {name})")); + } + None => { + unresolved.insert(format!("{package} (in {name})")); + } + } + } + } else if let Some(bpn) = self.recipe_of(name) { + found.insert(bpn); + } else if !self.group_names.contains(name) { + unresolved.insert(name.to_string()); + } + } + + /// The recipes the image `feature` installs through its package groups, + /// where they are in the tree. + fn feature( + &self, + feature: &str, + found: &mut BTreeSet<&'a str>, + unresolved: &mut BTreeSet, + ) { + if VARIABLE_FEATURES.contains(&feature) { + unresolved.insert(format!("{feature} (IMAGE_FEATURES)")); + return; + } + let Some((_, groups)) = FEATURE_PACKAGES.iter().find(|(f, _)| *f == feature) else { + return; + }; + for group in groups.iter() { + if self.group_names.contains(group) { + self.install(group, found, unresolved); + } else { + unresolved.insert(format!("{feature} (IMAGE_FEATURES)")); + } + } + } +} + +/// Which recipes of `inventory` the images declare: what IMAGE_INSTALL (and +/// CORE_IMAGE_EXTRA_INSTALL) names, the package groups among them expanded +/// one level, and the package groups of IMAGE_FEATURES where they are in the +/// tree. A local.conf.sample or distro configuration declares for every +/// image; with no image recipe in the tree, under its own file name. +pub fn declared_in_images(inventory: &Inventory) -> Declarations { + let index = PackageIndex::new(inventory); + let all_images: Vec<&str> = inventory.images.iter().map(|i| i.pn.as_str()).collect(); + let declarers = inventory + .images + .iter() + .map(|i| (vec![i.pn.as_str()], &i.install, &i.features)) + .chain(inventory.configs.iter().map(|c| { + let images = if all_images.is_empty() { + vec![c.file.as_str()] + } else { + all_images.clone() + }; + (images, &c.install, &c.features) + })); + let mut declarations = Declarations::default(); + for (images, install, features) in declarers { + let mut found = BTreeSet::new(); + for name in install { + index.install(name, &mut found, &mut declarations.unresolved); + } + for feature in features { + index.feature(feature, &mut found, &mut declarations.unresolved); + } + for bpn in found { + declarations + .images + .entry(bpn.to_string()) + .or_default() + .extend(images.iter().map(|i| i.to_string())); + } + } + declarations +} + +/// The SBOM components of `recipes`, one per base recipe name and version, +/// marked with the images that declare them. +pub fn entries(recipes: &[Recipe], declarations: &Declarations, repo_id: &str) -> Vec { let mut seen = std::collections::HashSet::new(); let mut out = Vec::with_capacity(recipes.len()); for recipe in recipes { @@ -451,6 +760,13 @@ pub fn entries(recipes: &[Recipe], repo_id: &str) -> Vec { evidence.push_str(&format!(" (+ {})", recipe.appends.join(", "))); } entry.evidence.push(evidence); + entry.in_image = declarations.images.get(&recipe.bpn).map(|images| InImage { + basis: InImageBasis::Declared, + images: images.iter().cloned().collect(), + }); + if let Some(in_image) = &entry.in_image { + entry.evidence.push(in_image.describe()); + } out.push(entry); } out @@ -692,7 +1008,11 @@ mod tests { let mut busybox = recipe("busybox", Some("1.35.0")); busybox.cve_version = Some("1.35".into()); - let entry = &entries(std::slice::from_ref(&busybox), "t")[0]; + let entry = &entries( + std::slice::from_ref(&busybox), + &Declarations::default(), + "t", + )[0]; assert_eq!( entry.cpe.as_deref(), Some("cpe:2.3:a:*:busybox:1.35:*:*:*:*:*:*:*") @@ -705,7 +1025,7 @@ mod tests { let mut r = recipe("busybox", Some("1.35.0")); r.license = Some("GPL-2.0-only & bzip2-1.0.4".into()); r.appends = vec!["recipes-core/busybox/busybox_%.bbappend".into()]; - let entries = entries(&[r.clone(), r], "t"); + let entries = entries(&[r.clone(), r], &Declarations::default(), "t"); assert_eq!(entries.len(), 1, "one component per name and version"); let entry = &entries[0]; assert_eq!(entry.package_manager, YOCTO_RECIPE_MANAGER); @@ -860,10 +1180,222 @@ mod tests { assert_eq!(inventory.errors.len(), 1); } - /// The helper on the nightly fixture, where Python and oelint-parser are - /// installed (the agent image); skipped elsewhere. + fn image(pn: &str, install: &[&str], features: &[&str]) -> ImageRecipe { + ImageRecipe { + file: format!("recipes-core/images/{pn}.bb"), + pn: pn.into(), + install: install.iter().map(|w| w.to_string()).collect(), + features: features.iter().map(|w| w.to_string()).collect(), + } + } + + fn group(pn: &str, rdepends: &[(&str, &[&str])]) -> PackageGroup { + PackageGroup { + file: format!("recipes-core/packagegroups/{pn}.bb"), + pn: pn.into(), + packages: rdepends.iter().map(|(p, _)| p.to_string()).collect(), + rdepends: rdepends + .iter() + .map(|(p, words)| (p.to_string(), words.iter().map(|w| w.to_string()).collect())) + .collect(), + } + } + + fn declared(declarations: &Declarations) -> Vec<(&str, Vec<&str>)> { + declarations + .images + .iter() + .map(|(bpn, images)| (bpn.as_str(), images.iter().map(String::as_str).collect())) + .collect() + } + #[test] - fn the_helper_reads_the_fixture() { + fn a_package_maps_to_the_recipe_that_makes_it() { + let mut web = recipe("pump-web", Some("2.1")); + web.packages = vec!["pump-web-ui".into(), "libpumpweb".into()]; + let inventory = Inventory { + recipes: vec![ + web, + recipe("busybox", Some("1.35.0")), + recipe("libpumpweb", None), + ], + ..Inventory::default() + }; + let index = PackageIndex::new(&inventory); + assert_eq!(index.recipe_of("pump-web"), Some("pump-web")); + assert_eq!(index.recipe_of("pump-web-ui"), Some("pump-web"), "PACKAGES"); + assert_eq!( + index.recipe_of("busybox-dev"), + Some("busybox"), + "a default package" + ); + assert_eq!(index.recipe_of("busybox-ptest"), Some("busybox")); + assert_eq!( + index.recipe_of("libpumpweb"), + Some("libpumpweb"), + "a recipe of that name wins over another recipe's PACKAGES" + ); + assert_eq!(index.recipe_of("busybox-extra"), None); + assert_eq!(index.recipe_of("openssh"), None); + } + + #[test] + fn a_package_group_is_expanded_one_level() { + let mut ctl = recipe("pump-ctl", Some("1.0")); + ctl.packages = vec!["pump-ctl-tools".into()]; + let inventory = Inventory { + recipes: vec![ + ctl, + recipe("pump-web", Some("2.1")), + recipe("libmodbus", Some("3.1.6")), + recipe("pump-fw", Some("1.0")), + ], + images: vec![image("pump-image", &["packagegroup-pump", "busybox"], &[])], + packagegroups: vec![ + group( + "packagegroup-pump", + &[ + ( + "packagegroup-pump", + &["pump-ctl-tools", "packagegroup-base", "zlib"], + ), + ("packagegroup-pump-web", &["pump-web"]), + ], + ), + group( + "packagegroup-base", + &[("packagegroup-base", &["libmodbus"])], + ), + ], + ..Inventory::default() + }; + let declarations = declared_in_images(&inventory); + assert_eq!( + declared(&declarations), + [("pump-ctl", vec!["pump-image"])], + "only the package the image names (not -web), and not the group inside the group" + ); + assert_eq!( + declarations.unresolved.iter().collect::>(), + [ + "busybox", + "packagegroup-base (a package group in packagegroup-pump)", + "zlib (in packagegroup-pump)" + ] + ); + } + + #[test] + fn image_features_install_their_package_groups_only_when_in_the_tree() { + let inventory = Inventory { + recipes: vec![recipe("dropbear", Some("2022.83"))], + images: vec![image( + "pump-image", + &[], + &[ + "ssh-server-dropbear", + "tools-debug", + "splash", + "debug-tweaks", + ], + )], + packagegroups: vec![group( + "packagegroup-core-ssh-dropbear", + &[("packagegroup-core-ssh-dropbear", &["dropbear"])], + )], + ..Inventory::default() + }; + let declarations = declared_in_images(&inventory); + assert_eq!(declared(&declarations), [("dropbear", vec!["pump-image"])]); + assert_eq!( + declarations.unresolved.iter().collect::>(), + ["splash (IMAGE_FEATURES)", "tools-debug (IMAGE_FEATURES)"], + "debug-tweaks installs nothing" + ); + } + + #[test] + fn a_configuration_declares_for_every_image_or_under_its_own_name() { + let config = ImageConfig { + file: "conf/local.conf.sample".into(), + install: vec!["busybox".into()], + features: Vec::new(), + }; + let mut inventory = Inventory { + recipes: vec![recipe("busybox", Some("1.35.0")), recipe("pump-ctl", None)], + images: vec![ + image("pump-image", &["pump-ctl"], &[]), + image("rescue-image", &[], &[]), + ], + configs: vec![config], + ..Inventory::default() + }; + assert_eq!( + declared(&declared_in_images(&inventory)), + [ + ("busybox", vec!["pump-image", "rescue-image"]), + ("pump-ctl", vec!["pump-image"]), + ] + ); + inventory.images.clear(); + assert_eq!( + declared(&declared_in_images(&inventory)), + [("busybox", vec!["conf/local.conf.sample"])] + ); + } + + #[test] + fn only_names_are_kept_from_what_an_image_declares() { + let json = br#"{"recipes": [{"file": "a.bb", "pn": "a", "bpn": "a", + "packages": ["a-tools", "^a-plugin-.*"]}], + "images": [{"file": "i.bb", "pn": "i", + "install": ["a", "${CORE_IMAGE_BASE_INSTALL}", "'", "d)}", "libstdc++", "python3.12"], + "features": ["debug-tweaks"]}], + "packagegroups": [{"file": "p.bb", "pn": "p", "packages": ["p"], + "rdepends": {"p": ["a (>= 1.0)", "a"]}}]}"#; + let inventory = parse(json).expect("the helper's shape"); + assert_eq!(inventory.recipes[0].packages, ["a-tools"]); + assert_eq!( + inventory.images[0].install, + ["a", "libstdc++", "python3.12"] + ); + assert_eq!(inventory.packagegroups[0].rdepends["p"], ["a"]); + } + + #[test] + fn a_declared_recipe_is_marked_with_its_images_and_says_so() { + let mut declarations = Declarations::default(); + declarations.images.insert( + "busybox".into(), + ["pump-image".to_string(), "rescue-image".to_string()].into(), + ); + let entries = entries( + &[ + recipe("busybox", Some("1.35.0")), + recipe("pump-fw", Some("1.0")), + ], + &declarations, + "t", + ); + assert_eq!( + entries[0].in_image, + Some(InImage { + basis: InImageBasis::Declared, + images: vec!["pump-image".into(), "rescue-image".into()], + }) + ); + assert_eq!( + entries[0].evidence[1], + "In the image (declared in the recipes, not resolved by bitbake): pump-image, \ + rescue-image" + ); + assert_eq!(entries[1].in_image, None); + assert_eq!(entries[1].evidence.len(), 1); + } + + /// The helper's reading of `tree`, where Python and oelint-parser are + /// installed (the agent image); `None` elsewhere, and the test passes. + fn run_helper(tree: &Path) -> Option { let helper = Path::new(env!("CARGO_MANIFEST_DIR")).join("../docker/pruefwerk_yocto_recipes.py"); let available = std::process::Command::new("python3") @@ -872,12 +1404,12 @@ mod tests { .is_ok_and(|o| o.status.success()); if !available { eprintln!("skipped: python3 with oelint-parser is not installed"); - return; + return None; } let output = std::process::Command::new("python3") - .arg("-I") + .args(["-I", "-B"]) .arg(&helper) - .arg(fixture()) + .arg(tree) .output() .expect("the helper runs"); assert!( @@ -885,7 +1417,98 @@ mod tests { "{}", String::from_utf8_lossy(&output.stderr) ); - let inventory = parse(&output.stdout).expect("the helper's shape"); + Some(parse(&output.stdout).expect("the helper's shape")) + } + + /// Every way an install is written: `=`, `+=`, `:append`, the old + /// `_append` (which oelint-parser splits only in a file without `:` + /// overrides), an override's append, `:remove`, inline Python and a + /// variable; old-syntax RDEPENDS of a package group; and a configuration. + #[test] + fn the_helper_reads_what_images_declare_in_every_syntax() { + let t = crate::pipeline::recipe_lint::tests::tree(&[ + ("conf/layer.conf", "BBFILE_COLLECTIONS += \"t\"\n"), + ( + "conf/local.conf.sample", + "CORE_IMAGE_EXTRA_INSTALL += \"conf-tool\"\nIMAGE_INSTALL_append = \" old-conf\"\n", + ), + ( + "recipes-core/images/new-image.bb", + "inherit core-image\n\ + IMAGE_INSTALL = \"a b gone\"\n\ + IMAGE_INSTALL += \"c\"\n\ + IMAGE_INSTALL:append = \" d ${@bb.utils.contains('DISTRO_FEATURES', 'x11', 'xterm', '', d)}\"\n\ + IMAGE_INSTALL_append = \" e\"\n\ + IMAGE_INSTALL:append:qemux86 = \" f\"\n\ + IMAGE_INSTALL:remove = \"gone\"\n\ + IMAGE_INSTALL += \"${UNSET_VARIABLE}\"\n\ + IMAGE_FEATURES += \"ssh-server-openssh\"\n\ + IMAGE_FEATURES_REPLACES_ssh-server-openssh = \"ssh-server-dropbear\"\n", + ), + ( + "recipes-core/images/old-image.bb", + "inherit image\nIMAGE_INSTALL = \"a\"\nIMAGE_INSTALL_append = \" g\"\n", + ), + ( + "recipes-core/packagegroups/packagegroup-old.bb", + "inherit packagegroup\n\ + PACKAGES = \"${PN} ${PN}-extra\"\n\ + RDEPENDS_${PN} = \"a (>= 1.0)\"\n\ + RDEPENDS_${PN}-extra = \"b\"\n\ + RDEPENDS_${PN}-extra_append = \" c\"\n\ + RRECOMMENDS_${PN} += \"d\"\n", + ), + ( + "recipes-core/a/a_1.0.bb", + "PACKAGES =+ \"${PN}-tools\"\nPACKAGES_DYNAMIC = \"a-plugin-x\"\n", + ), + ]); + let Some(inventory) = run_helper(&t.0) else { + return; + }; + assert!(inventory.errors.is_empty(), "{:?}", inventory.errors); + let installs: Vec<(&str, Vec<&str>)> = inventory + .images + .iter() + .map(|i| { + ( + i.pn.as_str(), + i.install.iter().map(String::as_str).collect(), + ) + }) + .collect(); + assert_eq!( + installs, + [ + ("new-image", vec!["a", "b", "c", "d", "e", "f"]), + ("old-image", vec!["a", "g"]), + ], + "the inline Python and the unset variable are left out" + ); + assert_eq!(inventory.images[0].features, ["ssh-server-openssh"]); + assert_eq!(inventory.configs.len(), 1); + assert_eq!(inventory.configs[0].install, ["old-conf", "conf-tool"]); + let group = &inventory.packagegroups[0]; + assert_eq!( + group.packages, + ["packagegroup-old", "packagegroup-old-extra"] + ); + assert_eq!(group.rdepends["packagegroup-old"], ["a", "d"]); + assert_eq!(group.rdepends["packagegroup-old-extra"], ["b", "c"]); + assert_eq!( + inventory.recipes[0].packages, + ["a-tools"], + "PACKAGES_DYNAMIC is not PACKAGES" + ); + } + + /// The helper on the nightly fixture, where Python and oelint-parser are + /// installed (the agent image); skipped elsewhere. + #[test] + fn the_helper_reads_the_fixture() { + let Some(inventory) = run_helper(&fixture()) else { + return; + }; assert!(inventory.errors.is_empty(), "{:?}", inventory.errors); let names: Vec<&str> = inventory.recipes.iter().map(|r| r.bpn.as_str()).collect(); @@ -917,7 +1540,39 @@ mod tests { ); assert_eq!(busybox.patches[0].cves, ["CVE-2022-30065"]); - let entries = entries(&inventory.recipes, "t"); + assert_eq!(inventory.images.len(), 1); + assert_eq!(inventory.images[0].pn, "pump-image"); + assert_eq!( + inventory.images[0].install, + [ + "packagegroup-core-boot", + "busybox", + "libmodbus", + "pump-ctl", + "packagegroup-pump" + ], + "IMAGE_INSTALL and its :append" + ); + assert_eq!(inventory.packagegroups[0].pn, "packagegroup-pump"); + assert_eq!(inventory.recipes[2].packages, ["pump-web-ui"]); + let declarations = declared_in_images(&inventory); + let declared: Vec<&str> = declarations.images.keys().map(String::as_str).collect(); + assert_eq!( + declared, + ["busybox", "libmodbus", "pump-ctl", "pump-web"], + "pump-fw is in no image" + ); + assert_eq!( + declarations.unresolved.iter().collect::>(), + [ + "packagegroup-core-boot", + "ssh-server-dropbear (IMAGE_FEATURES)" + ] + ); + + let entries = entries(&inventory.recipes, &declarations, "t"); + let in_image: Vec = entries.iter().map(|e| e.in_image.is_some()).collect(); + assert_eq!(in_image, [true, false, true, true, true]); let purls: Vec<&str> = entries.iter().filter_map(|e| e.purl.as_deref()).collect(); assert_eq!( purls, diff --git a/compliance-agent/tests/integration/api/mod.rs b/compliance-agent/tests/integration/api/mod.rs index 23f1594..d13c726 100644 --- a/compliance-agent/tests/integration/api/mod.rs +++ b/compliance-agent/tests/integration/api/mod.rs @@ -3,4 +3,5 @@ mod dast; mod findings; mod health; mod onboarding; +mod sbom; mod stats; diff --git a/compliance-agent/tests/integration/api/sbom.rs b/compliance-agent/tests/integration/api/sbom.rs new file mode 100644 index 0000000..5f50623 --- /dev/null +++ b/compliance-agent/tests/integration/api/sbom.rs @@ -0,0 +1,85 @@ +use crate::common::TestServer; +use compliance_core::models::{InImage, InImageBasis, SbomEntry, YOCTO_RECIPE_MANAGER}; + +/// A Yocto recipe component, in `pump-image` when `in_image`. +fn recipe(name: &str, in_image: bool) -> SbomEntry { + let mut entry = SbomEntry::new( + "yocto-target".into(), + name.into(), + "1.0".into(), + YOCTO_RECIPE_MANAGER.into(), + ); + entry.purl = Some(format!("pkg:generic/{name}@1.0")); + entry.in_image = in_image.then(|| InImage { + basis: InImageBasis::Declared, + images: vec!["pump-image".into()], + }); + entry +} + +/// The names of the components a list request returns, in its order. +async fn names(server: &TestServer, query: &str) -> Vec { + let resp = server + .get(&format!("/api/v1/sbom?repo_id=yocto-target{query}")) + .await; + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await.unwrap(); + body["data"] + .as_array() + .unwrap() + .iter() + .map(|e| e["name"].as_str().unwrap().to_string()) + .collect() +} + +#[tokio::test] +async fn the_sbom_lists_components_in_the_image_first_and_filters_by_it() { + let server = TestServer::start().await; + let mongodb_uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); + // The dev tenant's database, which the API reads. + let db = client.database(&format!("{}_dev", server.db_name())); + let entries = [ + recipe("aaa-tools", false), + recipe("busybox", true), + recipe("pump-fw", false), + recipe("zlib", true), + ]; + db.collection::("sbom_entries") + .insert_many(&entries) + .await + .unwrap(); + + assert_eq!( + names(&server, "").await, + ["busybox", "zlib", "aaa-tools", "pump-fw"], + "nothing is dropped; the image's components come first" + ); + assert_eq!(names(&server, "&in_image=true").await, ["busybox", "zlib"]); + assert_eq!( + names(&server, "&in_image=false").await, + ["aaa-tools", "pump-fw"] + ); + + let resp = server + .get("/api/v1/sbom/export?repo_id=yocto-target&format=cyclonedx") + .await; + assert_eq!(resp.status(), 200); + let cdx: serde_json::Value = resp.json().await.unwrap(); + let busybox = cdx["components"] + .as_array() + .unwrap() + .iter() + .find(|c| c["name"] == "busybox") + .expect("busybox"); + assert!(busybox["properties"] + .as_array() + .unwrap() + .iter() + .any( + |p| p["name"] == "pruefwerk:component:in_image" && p["value"] == "declared: pump-image" + )); + + server.cleanup().await; +} diff --git a/compliance-agent/tests/nightly.rs b/compliance-agent/tests/nightly.rs index cc76619..91a54d5 100644 --- a/compliance-agent/tests/nightly.rs +++ b/compliance-agent/tests/nightly.rs @@ -331,7 +331,8 @@ struct Snapshot { #[serde(default, skip_serializing_if = "String::is_empty")] error: String, skipped_stages: BTreeSet, - /// `package_manager:name@version`, compared exactly. + /// `package_manager:name@version`, with ` [in image: ]` for a + /// component an image declares, compared exactly. sbom: BTreeSet, /// Deterministic findings as `scanner:rule file:line`, compared exactly. findings: BTreeSet, @@ -477,8 +478,15 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected { } } for e in &sbom { + let in_image = e["in_image"]["images"] + .as_array() + .map(|images| { + let names: Vec<&str> = images.iter().filter_map(Value::as_str).collect(); + format!(" [in image: {}]", names.join(", ")) + }) + .unwrap_or_default(); snapshot.sbom.insert(format!( - "{}:{}@{}", + "{}:{}@{}{in_image}", text(e, "package_manager"), text(e, "name"), text(e, "version") diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 974082e..acba099 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -64,8 +64,8 @@ pub use pentest::{ pub use project::{Project, ProjectKind}; pub use repository::ScanTrigger; pub use sbom::{ - ComponentHash, SbomEntry, SbomQuality, SbomQualityCheck, SbomQualityProfile, VulnRef, - YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE, + ComponentHash, InImage, InImageBasis, SbomEntry, SbomQuality, SbomQualityCheck, + SbomQualityProfile, VulnRef, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE, }; pub use scan::{ RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode, SkippedStage, diff --git a/compliance-core/src/models/sbom.rs b/compliance-core/src/models/sbom.rs index 5a1b868..28ef6f2 100644 --- a/compliance-core/src/models/sbom.rs +++ b/compliance-core/src/models/sbom.rs @@ -33,6 +33,48 @@ pub const YOCTO_RECIPE_MANAGER: &str = "yocto-recipe"; /// an image contains. pub const YOCTO_RECIPE_SOURCE: &str = "Yocto recipe inventory (not the image SBOM)"; +/// How a component is known to be in the product's image. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum InImageBasis { + /// An image recipe names it (IMAGE_INSTALL, a package group it installs), + /// read from the recipes without BitBake: what the image declares, not + /// what a build resolved. + Declared, +} + +impl InImageBasis { + /// Its stored name (`declared`). + pub fn as_str(self) -> &'static str { + match self { + Self::Declared => "declared", + } + } + + /// How the exports and the evidence say it. + pub fn describe(self) -> &'static str { + match self { + Self::Declared => "In the image (declared in the recipes, not resolved by bitbake)", + } + } +} + +/// The images a component is in, and how that is known. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct InImage { + pub basis: InImageBasis, + /// The image recipes (`pump-image`) that install it, or the + /// configuration file that does for every image (`conf/local.conf.sample`). + pub images: Vec, +} + +impl InImage { + /// `In the image (declared …): pump-image, rescue-image`. + pub fn describe(&self) -> String { + format!("{}: {}", self.basis.describe(), self.images.join(", ")) + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SbomEntry { #[serde(rename = "_id", skip_serializing_if = "Option::is_none")] @@ -72,6 +114,11 @@ pub struct SbomEntry { /// advisory database could look up (a Yocto recipe's CVE_PRODUCT). #[serde(default, skip_serializing_if = "Option::is_none")] pub cpe: Option, + /// The images the component is in, where that is known (a Yocto recipe + /// an image recipe installs); `None` when it is not, and on components + /// stored before it was recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub in_image: Option, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, #[serde(with = "super::serde_helpers::bson_datetime")] @@ -105,6 +152,7 @@ impl SbomEntry { download_url: None, manufacturer_url: None, cpe: None, + in_image: None, created_at: now, updated_at: now, } diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index 5e05297..1445ff5 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -241,6 +241,10 @@ pub enum SkipCode { /// (`# nooelint` in a Yocto recipe), so they are not shown; `subject` is /// how many. SuppressedInSource, + /// Names an image recipe declares it installs that are not recipes or + /// package groups in the scanned tree (they come from layers that are not + /// in it, such as Poky's); `subject` lists them. + NotInTree, } /// Why a scan run failed, stable for the dashboard to word. diff --git a/compliance-core/src/sbom_docs.rs b/compliance-core/src/sbom_docs.rs index d13fadc..4070c65 100644 --- a/compliance-core/src/sbom_docs.rs +++ b/compliance-core/src/sbom_docs.rs @@ -90,11 +90,41 @@ fn bsi_properties(purl: &Purl) -> Option { /// necessarily in the image. const SOURCE_PROPERTY: &str = "pruefwerk:component:source"; +/// The property naming the images a component is in and how that is known +/// (`declared: pump-image`). +const IN_IMAGE_PROPERTY: &str = "pruefwerk:component:in_image"; + /// Where `entry` comes from, when the reader must know it to weigh it. fn source_note(entry: &SbomEntry) -> Option<&'static str> { (entry.package_manager == YOCTO_RECIPE_MANAGER).then_some(YOCTO_RECIPE_SOURCE) } +/// The CycloneDX properties saying where `entry` comes from and which images +/// it is in. +fn provenance_properties(entry: &SbomEntry) -> Vec { + let source = source_note(entry) + .map(|source| serde_json::json!({ "name": SOURCE_PROPERTY, "value": source })); + let in_image = entry.in_image.as_ref().map(|in_image| { + let value = format!( + "{}: {}", + in_image.basis.as_str(), + in_image.images.join(", ") + ); + serde_json::json!({ "name": IN_IMAGE_PROPERTY, "value": value }) + }); + source.into_iter().chain(in_image).collect() +} + +/// The SPDX package comment saying the same: the source, and the images. +fn provenance_comment(entry: &SbomEntry) -> Option { + let notes: Vec = source_note(entry) + .map(str::to_string) + .into_iter() + .chain(entry.in_image.as_ref().map(|in_image| in_image.describe())) + .collect(); + (!notes.is_empty()).then(|| notes.join(". ")) +} + /// A CycloneDX severity from an advisory's (`HIGH`, `MODERATE`, `critical`). pub fn cdx_severity(severity: &str) -> &'static str { match severity.trim().to_ascii_lowercase().as_str() { @@ -145,11 +175,11 @@ pub fn cdx_components(entries: &[SbomEntry]) -> Vec { if let Some(cpe) = &e.cpe { comp["cpe"] = serde_json::Value::String(cpe.clone()); } - if let Some(source) = source_note(e) { - let property = serde_json::json!({ "name": SOURCE_PROPERTY, "value": source }); + let provenance = provenance_properties(e); + if !provenance.is_empty() { match comp["properties"].as_array_mut() { - Some(properties) => properties.push(property), - None => comp["properties"] = serde_json::json!([property]), + Some(properties) => properties.extend(provenance), + None => comp["properties"] = serde_json::Value::Array(provenance), } } if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) { @@ -377,8 +407,8 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { "referenceLocator": cpe, })); } - if let Some(source) = source_note(e) { - package["comment"] = serde_json::Value::String(source.to_string()); + if let Some(comment) = provenance_comment(e) { + package["comment"] = serde_json::Value::String(comment); } package }) @@ -397,6 +427,7 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { #[cfg(test)] mod tests { use super::*; + use crate::models::{InImage, InImageBasis}; #[test] fn both_formats_list_every_component() { @@ -483,4 +514,48 @@ mod tests { assert_eq!(package["externalRefs"][1]["referenceType"], "cpe23Type"); assert!(spdx["packages"][1].get("comment").is_none()); } + + #[test] + fn a_recipe_an_image_installs_says_so_in_both_formats() { + let mut recipe = SbomEntry::new( + "t".into(), + "busybox".into(), + "1.35.0".into(), + YOCTO_RECIPE_MANAGER.into(), + ); + recipe.in_image = Some(InImage { + basis: InImageBasis::Declared, + images: vec!["pump-image".into(), "rescue-image".into()], + }); + let inventory_only = SbomEntry::new( + "t".into(), + "pump-fw".into(), + "1.0".into(), + YOCTO_RECIPE_MANAGER.into(), + ); + let entries = [recipe, inventory_only]; + + let cdx = cyclonedx(&entries, "t"); + assert_eq!( + cdx["components"][0]["properties"], + serde_json::json!([ + { "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE }, + { "name": IN_IMAGE_PROPERTY, "value": "declared: pump-image, rescue-image" }, + ]) + ); + assert_eq!( + cdx["components"][1]["properties"], + serde_json::json!([{ "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE }]) + ); + + let spdx = spdx(&entries, "t"); + assert_eq!( + spdx["packages"][0]["comment"], + format!( + "{YOCTO_RECIPE_SOURCE}. In the image (declared in the recipes, not resolved \ + by bitbake): pump-image, rescue-image" + ) + ); + assert_eq!(spdx["packages"][1]["comment"], YOCTO_RECIPE_SOURCE); + } } diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index ff80892..0a51808 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -505,6 +505,10 @@ pub mod scans { de: "Rezept-Prüfung: unterdrückte Befunde", en: "Recipe lint: suppressed findings", }, + "image_install" => Text { + de: "Im Image (deklariert)", + en: "In the image (declared)", + }, "recipe_lint_upstream" => Text { de: "Upstream-Layer (Poky, OpenEmbedded, BSP)", en: "Upstream layers (Poky, OpenEmbedded, BSP)", @@ -673,6 +677,16 @@ pub mod scans { "{subject} findings are suppressed by comments in the recipes (# nooelint) and \ are not shown." ), + (SkipCode::NotInTree, Lang::De) => format!( + "Von einem Image-Rezept genannt, aber kein Rezept und keine Paketgruppe im \ + Layer-Baum (aus Layern, die nicht im Baum liegen, etwa Poky), daher nicht \ + als Komponente markiert: {subject}" + ), + (SkipCode::NotInTree, Lang::En) => format!( + "Named by an image recipe but not a recipe or package group in the layer tree \ + (from layers that are not in it, such as Poky), so not marked as a component: \ + {subject}" + ), (SkipCode::PlatformProjectGenerated, Lang::De) => format!( "Für {subject} erzeugt Unity das App-Projekt erst beim Build; es liegt nicht \ im Repository. Info.plist bzw. Manifest, Berechtigungen und nativer Code sind \ @@ -2082,8 +2096,23 @@ pub mod sbom { en: "Yocto recipe", }; pub const YOCTO_RECIPE_HINT: Text = Text { - de: "Yocto-Rezeptinventar (nicht die SBOM des Images): aus den Rezepten im Layer-Baum gelesen, ohne Build. Layer-Overrides, PACKAGECONFIG und was das Image installiert sind nicht aufgelöst; es listet daher mehr, als das Image enthält.", - en: "Yocto recipe inventory (not the image SBOM): read from the recipes in the layer tree, without a build. Layer overrides, PACKAGECONFIG and what the image installs are not resolved, so it lists more than the image contains.", + de: "Yocto-Rezeptinventar (nicht die SBOM des Images): aus den Rezepten im Layer-Baum gelesen, ohne Build. Layer-Overrides und PACKAGECONFIG sind nicht aufgelöst; es listet daher mehr, als das Image enthält. Was ein Image-Rezept installiert, ist mit „Im Image (deklariert)“ markiert.", + en: "Yocto recipe inventory (not the image SBOM): read from the recipes in the layer tree, without a build. Layer overrides and PACKAGECONFIG are not resolved, so it lists more than the image contains. What an image recipe installs is marked \"In the image (declared)\".", + }; + /// A component an image recipe installs (its badge and filter). + pub const IN_IMAGE: Text = Text { + de: "Im Image (deklariert)", + en: "In the image (declared)", + }; + /// The badge's and the filter's tooltip; the badge adds the images. + pub const IN_IMAGE_HINT: Text = Text { + de: "Aus den Rezepten gelesen (IMAGE_INSTALL, Paketgruppen eine Ebene tief, IMAGE_FEATURES), nicht von BitBake aufgelöst: Overrides, PACKAGECONFIG und von DISTRO_FEATURES abhängige Pakete sind nicht berücksichtigt.", + en: "Read from the recipes (IMAGE_INSTALL, package groups one level deep, IMAGE_FEATURES), not resolved by bitbake: overrides, PACKAGECONFIG and packages that depend on DISTRO_FEATURES are not taken into account.", + }; + /// The in-image filter's other choice. + pub const ALL_COMPONENTS: Text = Text { + de: "Alle Komponenten", + en: "All components", }; pub const LICENSE: Text = Text { de: "Lizenz", @@ -3520,6 +3549,14 @@ mod skipped_reason_tests { .starts_with("Für Pump Game – iOS (Xcode) erzeugt Unity das App-Projekt erst")); assert!(skipped_reason(&unity, Lang::En) .starts_with("For Pump Game – iOS (Xcode), Unity generates the app project")); + let not_in_tree = SkippedStage::new( + "image_install", + SkipCode::NotInTree, + "named by an image but not a recipe or package group in the tree", + ) + .about("packagegroup-core-boot"); + assert!(skipped_reason(¬_in_tree, Lang::De).ends_with(": packagegroup-core-boot")); + assert!(skipped_reason(¬_in_tree, Lang::En).starts_with("Named by an image recipe")); let suppressed = SkippedStage::new( "recipe_lint_suppressed", SkipCode::SuppressedInSource, diff --git a/compliance-dashboard/src/infrastructure/sbom.rs b/compliance-dashboard/src/infrastructure/sbom.rs index 1084414..2a8d903 100644 --- a/compliance-dashboard/src/infrastructure/sbom.rs +++ b/compliance-dashboard/src/infrastructure/sbom.rs @@ -61,6 +61,9 @@ pub struct SbomEntryData { pub purl: Option, #[serde(default)] pub known_vulnerabilities: Vec, + /// The images an image recipe declares it in (a Yocto recipe). + #[serde(default)] + pub in_image: Option, #[serde(default)] pub created_at: Option, #[serde(default)] @@ -146,6 +149,7 @@ pub async fn fetch_sbom_filtered( q: Option, has_vulns: Option, license: Option, + in_image: Option, page: u64, ) -> Result { let mut params = vec![format!("page={page}"), "limit=50".to_string()]; @@ -172,6 +176,9 @@ pub async fn fetch_sbom_filtered( params.push(format!("license={}", l.replace(' ', "%20"))); } } + if let Some(in_image) = in_image { + params.push(format!("in_image={in_image}")); + } let path = format!("/api/v1/sbom?{}", params.join("&")); let resp = super::agent_client::agent_get(&path) diff --git a/compliance-dashboard/src/pages/sbom.rs b/compliance-dashboard/src/pages/sbom.rs index 2c39ce6..bfaebd2 100644 --- a/compliance-dashboard/src/pages/sbom.rs +++ b/compliance-dashboard/src/pages/sbom.rs @@ -20,6 +20,8 @@ pub fn SbomPage(target: String) -> Element { let mut search_q = use_signal(String::new); let mut vuln_toggle = use_signal(|| Option::::None); let mut license_filter = use_signal(String::new); + // Only the components an image declares (`Some(true)`), or all. + let mut in_image_filter = use_signal(|| Option::::None); // ── Active tab: "packages" | "licenses" | "diff" ── let mut active_tab = use_signal(|| "packages".to_string()); @@ -53,6 +55,7 @@ pub fn SbomPage(target: String) -> Element { let q = search_q(); let hv = vuln_toggle(); let lic = license_filter(); + let in_image = in_image_filter(); async move { fetch_sbom_filtered( if repo.is_empty() { None } else { Some(repo) }, @@ -60,6 +63,7 @@ pub fn SbomPage(target: String) -> Element { if q.is_empty() { None } else { Some(q) }, hv, if lic.is_empty() { None } else { Some(lic) }, + in_image, p, ) .await @@ -188,6 +192,16 @@ pub fn SbomPage(target: String) -> Element { option { value: "true", {tx::WITH_VULNS.get(lang)} } option { value: "false", {tx::NO_VULNS.get(lang)} } } + select { + class: "sbom-filter-select", + title: tx::IN_IMAGE_HINT.get(lang), + onchange: move |e| { + in_image_filter.set((e.value() == "true").then_some(true)); + page.set(1); + }, + option { value: "", {tx::ALL_COMPONENTS.get(lang)} } + option { value: "true", {tx::IN_IMAGE.get(lang)} } + } select { class: "sbom-filter-select", onchange: move |e| { license_filter.set(e.value()); page.set(1); }, @@ -294,11 +308,23 @@ pub fn SbomPage(target: String) -> Element { let has_vulns = !entry.known_vulnerabilities.is_empty(); let license_class = license_css_class(entry.license.as_deref()); let row_key_click = row_key.clone(); + // Which images declare it, on the badge's tooltip. + let in_image_title = entry.in_image.as_ref().map(|i| { + format!("{} (Images: {})", tx::IN_IMAGE_HINT.get(lang), i.images.join(", ")) + }); rsx! { tr { td { style: "font-weight: 500;", "{entry.name}" + if let Some(title) = in_image_title { + " " + span { + class: "badge badge-success", + title: "{title}", + {tx::IN_IMAGE.get(lang)} + } + } } td { style: "font-family: var(--font-mono, monospace); font-size: 13px;", diff --git a/docker/__pycache__/pruefwerk_yocto_recipes.cpython-314.pyc b/docker/__pycache__/pruefwerk_yocto_recipes.cpython-314.pyc deleted file mode 100644 index 06bb56d3ec230db48b4074cb3a57802c39d51704..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 21331 zcmb_^dvqJudFKEaya9smH${k~BvK+lS)yLFC|Tk|q$!aMNI|hf83YNCf&~Kb44?;H zHH?!zrX07D5@khswGrK@HQm@JN{_Pk?s^+L&YpO;=@v8?fgUSspKbo>AKfFBR&A$e zd-nI;!2loyQEA$dc;{m7WA5X-zwdFsJ6m$BC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2Pj}p}$C2s#rF4Muz6nR-?w8|q&;0=vTw3p&;O%(7lKiCZTga8=ekJx@ z@0Vj=;(jSiZ}%Iae%|j^ff3!U<9N%=)S{;BBfV*6`-R=-cYpKTtZGqTwq!70Fr7Cg z45bT((pXvVqTw(-GQ4ECnD?@IiPyi_{X+Nop^LRw>MzyLKK8vWaqGI None: setattr(cls_stash, "__oe_utils_read_file_regex__", regex.compile(r"(?!)")) -def walk(tree: str) -> tuple[list[str], list[str], list[str]]: - """The layer roots (directories with conf/layer.conf), recipes and appends.""" +def is_config(root: str, name: str) -> bool: + """Whether `name` in directory `root` is a configuration that can declare + what images install: a local.conf.sample or a distro configuration.""" + if name == "local.conf.sample": + return True + return name.endswith(".conf") and os.path.basename(root) == "distro" and ( + os.path.basename(os.path.dirname(root)) == "conf" + ) + + +def walk(tree: str) -> tuple[list[str], list[str], list[str], list[str]]: + """The layer roots (directories with conf/layer.conf), recipes, appends + and the configurations that can declare what images install.""" layers: list[str] = [] recipes: list[str] = [] appends: list[str] = [] + configs: list[str] = [] for root, dirs, files in os.walk(tree): dirs[:] = sorted(d for d in dirs if d not in SKIPPED_DIRS) if os.path.basename(root) == "conf" and "layer.conf" in files: @@ -76,7 +103,9 @@ def walk(tree: str) -> tuple[list[str], list[str], list[str]]: recipes.append(path) elif name.endswith(".bbappend"): appends.append(path) - return sorted(layers), sorted(recipes), sorted(appends) + elif is_config(root, name): + configs.append(path) + return sorted(layers), sorted(recipes), sorted(appends), sorted(configs) def appends_for(recipe: str, appends: list[str]) -> list[str]: @@ -91,6 +120,22 @@ def appends_for(recipe: str, appends: list[str]) -> list[str]: return matching +def file_stem(path: str) -> str: + """The recipe name part of a .bb or .bbappend file name: before the + version (`busybox_1.35.0.bb`), without an append's `%` wildcard.""" + name = os.path.basename(path) + for suffix in (".bbappend", ".bb"): + if name.endswith(suffix): + name = name[: -len(suffix)] + break + return name.split("_", 1)[0].replace("%", "") + + +def is_image_name(path: str) -> bool: + """Whether the file is named like an image recipe (`*-image*.bb`).""" + return "-image" in file_stem(path) + + def is_build_host_recipe(name: str) -> bool: """Whether the recipe only builds a tool for the build host or SDK.""" return name.endswith(("-native", "-cross", "-crosssdk")) or name.startswith("nativesdk-") @@ -176,6 +221,134 @@ def flags(stash: Stash, recipe: str, name: str) -> dict[str, str]: return found +def assignment_parts( + item: Variable, name: str, scoped: bool +) -> tuple[list[str], str | None, list[str]] | None: + """What an assignment to `name` is: the words before its operation (a + package such as `${PN}-utils`, or an override such as `qemux86`), the + operation (`append`, `prepend`, `remove` or None) and the overrides after + it. None for an assignment of another variable. + + oelint-parser splits `IMAGE_INSTALL_append` (the syntax before Kirkstone) + into the variable and `append` only in a file without any `:` override; + otherwise it keeps the whole name, which is split here. Another variable + with a longer name (`IMAGE_FEATURES_REPLACES_…`) is not an assignment of + `name`: in the old syntax only an operation may follow the name directly, + or, for a per-package variable (RDEPENDS), the package.""" + if item.VarName == name: + subs = list(item.SubItems) + elif item.VarName.startswith(name + "_"): + subs = item.VarName[len(name) + 1 :].split("_") + list(item.SubItems) + if not scoped and subs[0] not in OPERATIONS: + return None + else: + return None + operation = next((s for s in subs if s in OPERATIONS), None) + if operation is None: + return subs, None, [] + at = subs.index(operation) + return subs[:at], operation, subs[at + 1 :] + + +def without_inline_python(text: str) -> str: + """`text` without its inline Python (`${@bb.utils.contains(...)}`): what + it would add depends on the configuration, which is not resolved.""" + kept = [] + at = 0 + while (start := text.find("${@", at)) != -1: + kept.append(text[at:start]) + depth = 0 + end = start + 1 + while end < len(text): + if text[end] == "{": + depth += 1 + elif text[end] == "}": + depth -= 1 + if depth == 0: + break + end += 1 + at = end + 1 + kept.append(text[at:]) + return " ".join(kept) + + +def fold(stash: Stash, path: str, items: list[Variable], name: str, scoped: bool) -> list[str]: + """The words `items` (assignments of `name`) give together: `=`, `?=`, + `+=` in order, then every `:append`/`:prepend` and every override's + assignment added, then `:remove` taken away. With `scoped`, the first word + before the operation is the package and the rest are overrides.""" + base: list[str] | None = None + added: list[str] = [] + removed: set[str] = set() + for item in sorted(items, key=lambda i: i.Line): + parts = assignment_parts(item, name, scoped) + if parts is None: + continue + before, operation, after = parts + overrides = before[1:] if scoped else before + text = without_inline_python(stash.ExpandTerm(path, raw(stash, item))) + # A version constraint (`foo (>= 1.2)`) is not a package. + found = Item.safe_linesplit(VERSION_CONSTRAINT.sub(" ", text)) + if operation == "remove" and not overrides and not after: + removed.update(found) + elif operation is not None or overrides: + # An override (a machine, a distro) is not resolved: it counts. + if operation != "remove": + added.extend(found) + else: + op = item.VarOp.strip() + if op in ("=", ":="): + base = found + elif op in ("?=", "??="): + base = found if base is None else base + else: + base = (base or []) + found + words_found = [w for w in (base or []) + added if w not in removed] + return list(dict.fromkeys(words_found)) + + +def variables(stash: Stash, path: str) -> list[Variable]: + """Every variable assignment in `path`, its includes and appends.""" + return stash.GetItemsFor(filename=path, classifier=Variable.CLASSIFIER) + + +def declared(stash: Stash, path: str, names: tuple[str, ...]) -> list[str]: + """The words the variables `names` declare in `path`, in order, once.""" + items = variables(stash, path) + found = [w for name in names for w in fold(stash, path, items, name, scoped=False)] + return list(dict.fromkeys(found)) + + +def per_package(stash: Stash, path: str, names: tuple[str, ...]) -> dict[str, list[str]]: + """The words the per-package variables `names` (RDEPENDS:${PN}-x) give + each package of `path`, keyed by the package name as expanded.""" + items = variables(stash, path) + keyed: dict[str, list[Variable]] = {} + for name in names: + for item in items: + parts = assignment_parts(item, name, scoped=True) + if parts is None or not parts[0]: + continue + package = stash.ExpandTerm(path, parts[0][0]).strip() + keyed.setdefault(package, []) + if item not in keyed[package]: + keyed[package].append(item) + found: dict[str, list[str]] = {} + for package, group in sorted(keyed.items()): + words_found = [w for name in names for w in fold(stash, path, group, name, scoped=True)] + if words_found: + found[package] = list(dict.fromkeys(words_found)) + return found + + +def image_declarations(stash: Stash, path: str) -> dict[str, list[str]]: + """What `path` declares an image installs, and its features.""" + return { + "install": declared(stash, path, INSTALL_VARIABLES), + "features": declared(stash, path, FEATURE_VARIABLES), + } + + def status_entry(cve: str, value: str) -> dict[str, str]: """A CVE_STATUS value `reason: detail` as its parts.""" reason, _, detail = value.partition(":") @@ -243,26 +416,94 @@ def sources(origins: list[str], tree: str, src_uri: list[str]) -> tuple[str | No return upstream, patches -def read_recipe(recipe: str, appends: list[str], layers: list[str], tree: str) -> dict | None: - """One recipe as JSON, or None for an image, a package group or a - build-host tool, which are not components of the product.""" - stash = Stash(quiet=True, layer_paths=layers) - for path in [recipe, *appends]: +def parsed(paths: list[str], layers: list[str], negative: bool = False) -> Stash: + """A stash of `paths` (a recipe and its appends, or a configuration). + oelint-parser emulates `bb.utils.contains` by taking its true branch, or + with `negative` its false one; it never runs the Python.""" + stash = Stash(quiet=True, layer_paths=layers, negative_inline=negative) + for path in paths: stash.AddFile(path) stash.Finalize() - if stash.IsImage(recipe) or stash.IsPackageGroup(recipe): - return None + return stash + + +def static_words(found: list[str]) -> list[str]: + """The words that are names as written, not a variable left unexpanded.""" + return [w for w in found if "${" not in w and "@" not in w] + + +def common(positive, negative): + """What two readings agree on: the words of a list in both (in the first + one's order), a dictionary key by key, any other value as first read.""" + if isinstance(positive, list): + kept = set(negative) if isinstance(negative, list) else set() + return [w for w in positive if w in kept] + if isinstance(positive, dict): + other = negative if isinstance(negative, dict) else {} + return {key: common(value, other.get(key)) for key, value in positive.items()} + return positive + + +def unconditional(paths: list[str], layers: list[str], read) -> dict: + """`read(stash)` of `paths` with what both branches of every inline + condition give: an install only when `DISTRO_FEATURES` contains `x11` + is not declared for the image as such.""" + return common(read(parsed(paths, layers)), read(parsed(paths, layers, negative=True))) + + +def read_image(stash: Stash, recipe: str, appends: list[str], tree: str) -> dict: + """An image recipe (or a bbappend of one not in the tree): its name and + what it declares it installs.""" + return { + "file": os.path.relpath(recipe, tree), + "appends": [os.path.relpath(a, tree) for a in appends], + "pn": file_stem(recipe), + **image_declarations(stash, recipe), + } + + +def read_packagegroup(stash: Stash, recipe: str, tree: str) -> dict: + """A package group: the packages it makes and what each one pulls in + (RDEPENDS, and RRECOMMENDS, which are installed unless excluded).""" + pn = stash.GuessRecipeName(recipe) + return { + "file": os.path.relpath(recipe, tree), + "pn": pn, + "packages": static_words(declared(stash, recipe, ("PACKAGES",))) or [pn], + "rdepends": per_package(stash, recipe, ("RDEPENDS", "RRECOMMENDS")), + } + + +def read_recipe( + recipe: str, appends: list[str], layers: list[str], tree: str +) -> tuple[str, dict] | None: + """One recipe as JSON with its kind: `recipe` for a component of the + product, `image` or `packagegroup`; None for a build-host tool.""" + paths = [recipe, *appends] + stash = parsed(paths, layers) + if stash.IsPackageGroup(recipe): + return "packagegroup", unconditional( + paths, layers, lambda s: read_packagegroup(s, recipe, tree) + ) + if stash.IsImage(recipe) or is_image_name(recipe): + image = unconditional(paths, layers, lambda s: read_image(s, recipe, appends, tree)) + # Named like an image (`*-image*.bb`) without inheriting an image + # class: an image only if it declares what to install + # (`xcb-util-image` is a library). + if stash.IsImage(recipe) or image["install"] or image["features"]: + return "image", image pn = stash.GuessRecipeName(recipe) if is_build_host_recipe(pn): return None pv = value(stash, recipe, "PV") or stash.GuessRecipeVersion(recipe) origins = [recipe, *appends] upstream, patches = sources(origins, tree, words(stash, recipe, "SRC_URI")) - return { + return "recipe", { "file": os.path.relpath(recipe, tree), "appends": [os.path.relpath(a, tree) for a in appends], "pn": pn, "bpn": stash.GuessBaseRecipeName(recipe), + "packages": static_words(declared(stash, recipe, ("PACKAGES",))), "pv": pv, "srcrev": value(stash, recipe, "SRCREV") or None, "src_uri": upstream, @@ -274,21 +515,63 @@ def read_recipe(recipe: str, appends: list[str], layers: list[str], tree: str) - } +def orphan_image_appends(recipe_files: list[str], appends: list[str]) -> list[str]: + """The bbappends of images whose recipe is not in the tree + (`core-image-minimal.bbappend` extending Poky's image).""" + return [ + append + for append in appends + if is_image_name(append) + and not any(append in appends_for(recipe, [append]) for recipe in recipe_files) + ] + + +def declaring_image(append: str, layers: list[str], tree: str) -> tuple[str, dict] | None: + """The bbappend of an image not in the tree, if it declares anything.""" + image = unconditional([append], layers, lambda s: read_image(s, append, [], tree)) + return ("image", image) if image["install"] or image["features"] else None + + +def read_config(config: str, layers: list[str], tree: str) -> tuple[str, dict] | None: + """What a local.conf.sample or distro configuration declares every image + installs; None when it declares nothing.""" + declarations = unconditional([config], layers, lambda s: image_declarations(s, config)) + if not declarations["install"] and not declarations["features"]: + return None + return "config", {"file": os.path.relpath(config, tree), **declarations} + + def main(tree: str) -> int: tree = os.path.realpath(tree) confine(tree) - layers, recipe_files, appends = walk(tree) - recipes = [] + layers, recipe_files, appends, configs = walk(tree) + layers = layers or [tree] + read: dict[str, list[dict]] = {"recipe": [], "image": [], "packagegroup": [], "config": []} errors = [] - for recipe in recipe_files: + + def attempt(path: str, reader) -> None: try: - read = read_recipe(recipe, appends_for(recipe, appends), layers or [tree], tree) - except Exception as error: # noqa: BLE001 - one unreadable recipe must not stop the rest - errors.append({"file": os.path.relpath(recipe, tree), "error": type(error).__name__}) - continue - if read is not None: - recipes.append(read) - json.dump({"recipes": recipes, "errors": errors}, sys.stdout, sort_keys=True) + result = reader() + except Exception as error: # noqa: BLE001 - one unreadable file must not stop the rest + errors.append({"file": os.path.relpath(path, tree), "error": type(error).__name__}) + return + if result is not None: + read[result[0]].append(result[1]) + + for recipe in recipe_files: + attempt(recipe, lambda: read_recipe(recipe, appends_for(recipe, appends), layers, tree)) + for append in orphan_image_appends(recipe_files, appends): + attempt(append, lambda: declaring_image(append, layers, tree)) + for config in configs: + attempt(config, lambda: read_config(config, layers, tree)) + output = { + "recipes": read["recipe"], + "images": sorted(read["image"], key=lambda i: i["file"]), + "packagegroups": read["packagegroup"], + "configs": read["config"], + "errors": errors, + } + json.dump(output, sys.stdout, sort_keys=True) return 0 diff --git a/docs/guide/yocto.md b/docs/guide/yocto.md index 2d16c3f..53feccf 100644 --- a/docs/guide/yocto.md +++ b/docs/guide/yocto.md @@ -38,6 +38,7 @@ searched. | Firmware SBOM (Firmwerk) | not run: listed under **Nicht ausgeführt** as "Yocto build analysis is planned (tier 2)" | | Recipe lint (oelint-adv and our own rules) | runs over your layers, see below | | Recipe inventory | runs: SBOM components and NVD CVEs from the recipes, `CVE_STATUS` and `CVE:` patches as VEX; see [Recipe inventory](#recipe-inventory) | +| In the image (declared) | runs: the recipes your image recipes install are marked; see [Im Image (deklariert)](#im-image-deklariert) | | Image SBOM / CVE | needs build artefacts (SPDX / manifest), planned (tier 2) | | DAST | opt-in, with an http(s) address of the running device | | Penetration test | not offered until an image can be booted in an emulation sandbox | @@ -122,10 +123,10 @@ Image recipes, package groups and tools built only for the build host checked on a target's components (SBOM, known vulnerabilities) are **Teilweise bewertet** (*partly assessed*, "recipe inventory only, not the image SBOM") until an image SBOM can be imported (tier 2). Layer overrides between layers, -`PACKAGECONFIG`, the distro and machine configuration and what an image -actually installs are not resolved, so the inventory lists every recipe in the -tree: more than an image contains, and nothing from layers that are not in the -tree. The components say so wherever they appear: the **Yocto-Rezept** badge in +`PACKAGECONFIG` and the distro and machine configuration are not resolved, so +the inventory lists every recipe in the tree: more than an image contains, and +nothing from layers that are not in the tree. The recipes an image recipe names +are marked, see [Im Image (deklariert)](#im-image-deklariert). The components say so wherever they appear: the **Yocto-Rezept** badge in the SBOM view, the component property `pruefwerk:component:source` in the CycloneDX export and the package `comment` in the SPDX export (both read "Yocto recipe inventory (not the image SBOM)"), and the component's evidence @@ -162,10 +163,63 @@ analysis `detail`. `CVE_STATUS_GROUPS` count like single `CVE_STATUS` flags. The again on every scan and withdraws one the recipe no longer makes; a statement a person made is never replaced. +## Im Image (deklariert) + +The inventory keeps every recipe, but marks those your image recipes say they +install: **Im Image (deklariert)** (*In the image (declared)*). It is read from +the recipes as they are written, with the same parser and without a build; it +is what the image recipes declare, not what BitBake would resolve. + +**What is read.** Image recipes are the `.bb` files that inherit `core-image`, +`image` (or another image class) or set `IMAGE_INSTALL` / `IMAGE_FEATURES`, +files named `*-image*.bb` that declare what to install, and a `*-image*.bbappend` +of an image that is not in the tree (`core-image-minimal.bbappend`). From them, +and from every `conf/local.conf.sample` and `conf/distro/*.conf`: + +- `IMAGE_INSTALL` and `CORE_IMAGE_EXTRA_INSTALL` with every operation: `=`, + `?=`, `+=`, `:append` and the older `_append`, `:remove`; +- `IMAGE_FEATURES` and `EXTRA_IMAGE_FEATURES`. + +A local.conf.sample or distro configuration counts for every image recipe in +the tree (with none, the component names the configuration file instead). + +**How a name becomes a recipe.** + +| The image names | Marked | +|---|---| +| a recipe (`busybox`) | that recipe | +| a package a recipe's `PACKAGES` names (`pump-web-ui`) | that recipe | +| a default package (`busybox-dev`, `-dbg`, `-doc`, `-locale`, `-src`, `-staticdev`, `-ptest`) | its recipe | +| a package group in the tree (`packagegroup-pump`) | what that package's `RDEPENDS` and `RRECOMMENDS` name, one level: a package group inside it is not expanded | +| an image feature (`ssh-server-dropbear`) | its package group from OpenEmbedded-Core's `FEATURE_PACKAGES_*` (`packagegroup-core-ssh-dropbear`), if that package group is in the tree | + +**Where it shows.** A badge **Im Image (deklariert)** next to the component in +the SBOM view, whose tooltip names the images and says it is read from the +recipes, not resolved by bitbake; a filter of the same name; and the SBOM list +puts these components first. The component's evidence line names the images, +the CycloneDX export carries the property `pruefwerk:component:in_image` +(`declared: pump-image`), and the SPDX export adds it to the package `comment`. +What an image names that is neither a recipe nor a package group in the tree +(`packagegroup-core-boot` from Poky, a feature whose package group is not in +the tree, a feature such as `splash` whose packages a variable chooses) is +listed on the run under **Im Image (deklariert)**; no component is invented for +it. + +**What is not resolved.** Overrides (`IMAGE_INSTALL:append:qemux86` counts as +if it applied to every machine), `PACKAGECONFIG`, installs that depend on +`DISTRO_FEATURES` or other inline Python (a package only one branch of +`${@bb.utils.contains(...)}` names is left out; the Python is never run), variables the tree does not set (`${CORE_IMAGE_BASE_INSTALL}`), package +groups more than one level deep, `RPROVIDES` and virtual packages, a +`FEATURE_PACKAGES_*` of your own, `BAD_RECOMMENDATIONS`, and which distro a +build selects (every distro configuration counts). Nothing is built, and no +recipe from a layer that is not in the tree is marked. The CRA state of the +SBOM requirement stays **Teilweise bewertet** until an image SBOM from a build +can be imported (tier 2). + ## What is planned | Tier | Input | Analysis | | --- | --- | --- | -| **1: layer tree** (in progress) | the layers in git, no build | **Recipe inventory**: every recipe's name, version, `SRC_URI`, `CVE_PRODUCT` and `CVE_STATUS`, matched against NVD; labelled as a recipe inventory, not the image's SBOM. **Recipe lint**: done, see above | +| **1: layer tree** (in progress) | the layers in git, no build | **Recipe inventory**: every recipe's name, version, `SRC_URI`, `CVE_PRODUCT` and `CVE_STATUS`, matched against NVD; labelled as a recipe inventory, not the image's SBOM; the recipes an image recipe installs marked as declared. **Recipe lint**: done, see above | | **2: build artefacts** | `tmp/deploy/spdx` (SPDX 3.0, or 2.2 up to Scarthgap), `*.vex.json`, the image `.manifest`, the kernel `.config` | **SPDX import** into the SBOM view and CycloneDX export; **sbom-cve-check** with the Yocto VEX annotations; kernel CVEs filtered by the configuration; a nightly re-check without a rebuild | | **3: image / rootfs** | `.wic`, tar, ext4, squashfs | unpacking, ELF hardening of every binary, secrets and default credentials in the root filesystem; DAST and pentest only for a qemu build in an isolated sandbox | diff --git a/fixtures/nightly/baselines/fw-yocto-layer.json b/fixtures/nightly/baselines/fw-yocto-layer.json index f8755ea..bc76036 100644 --- a/fixtures/nightly/baselines/fw-yocto-layer.json +++ b/fixtures/nightly/baselines/fw-yocto-layer.json @@ -2,14 +2,15 @@ "scan_status": "completed", "skipped_stages": [ "firmware_sbom", + "image_install", "malware" ], "sbom": [ - "yocto-recipe:busybox@1.35.0", - "yocto-recipe:libmodbus@3.1.6", - "yocto-recipe:pump-ctl@1.0", + "yocto-recipe:busybox@1.35.0 [in image: pump-image]", + "yocto-recipe:libmodbus@3.1.6 [in image: pump-image]", + "yocto-recipe:pump-ctl@1.0 [in image: pump-image]", "yocto-recipe:pump-fw@1.0", - "yocto-recipe:pump-web@2.1" + "yocto-recipe:pump-web@2.1 [in image: pump-image]" ], "findings": [ "oelint-adv:oelint.task.network pump-web_2.1.bb:8", diff --git a/fixtures/nightly/firmware/README.md b/fixtures/nightly/firmware/README.md index fd7c95b..dc963d5 100644 --- a/fixtures/nightly/firmware/README.md +++ b/fixtures/nightly/firmware/README.md @@ -19,7 +19,7 @@ SBOM reads as declared dependencies (#317): | `freertos-lostbuild` | `lostbuild` | source archaeology: no build system, FreeRTOS found from its headers | | `c-sensor-node` | (ours) | Make; C/C++ SAST (#334): planted flaws in `Core/`, a vendored HAL in `Drivers/` that must not be reported | | `embedded-libs` | (ours) | Make; FreeRTOS 10.3.1, lwIP 2.1.2 and Mbed TLS 2.16.2 vendored as source: versions read from their headers, CVEs matched in NVD by CPE. The headers hold only the version defines | -| `yocto-layer` | (ours) | none: detected as a BitBake layer tree (`build_system = bitbake`); the recipe lint reports the image's debug-tweaks and allow-empty-password, a password hash in `EXTRA_USERS_PARAMS`, an `http://` fetch without a checksum, a task with network access, `AUTOREV`, `PermitRootLogin yes` and a distro without `security_flags.inc`; the recipe inventory lists the recipes (BusyBox 1.35.0 and libmodbus 3.1.6 with NVD CVEs; BusyBox carries a `CVE_STATUS`, a `CVE_STATUS_GROUPS` entry in a `.bbappend` and a `CVE:` patch) yet | +| `yocto-layer` | (ours) | none: detected as a BitBake layer tree (`build_system = bitbake`); the recipe lint reports the image's debug-tweaks and allow-empty-password, a password hash in `EXTRA_USERS_PARAMS`, an `http://` fetch without a checksum, a task with network access, `AUTOREV`, `PermitRootLogin yes` and a distro without `security_flags.inc`; the recipe inventory lists the recipes (BusyBox 1.35.0 and libmodbus 3.1.6 with NVD CVEs; BusyBox carries a `CVE_STATUS`, a `CVE_STATUS_GROUPS` entry in a `.bbappend` and a `CVE:` patch) and marks four of them as in `pump-image` (declared: three in `IMAGE_INSTALL`, pump-web through `packagegroup-pump` by its package `pump-web-ui`), pump-fw in no image | `make` is also onboarded as a backend service (`fw-make-onboarded-as-service`): the firmware SBOM follows detection, not the type picked in the wizard. diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-app/pump-web/pump-web_2.1.bb b/fixtures/nightly/firmware/yocto-layer/recipes-app/pump-web/pump-web_2.1.bb index ca02210..eb82349 100644 --- a/fixtures/nightly/firmware/yocto-layer/recipes-app/pump-web/pump-web_2.1.bb +++ b/fixtures/nightly/firmware/yocto-layer/recipes-app/pump-web/pump-web_2.1.bb @@ -9,3 +9,8 @@ do_compile[network] = "1" do_compile() { oe_runmake } + +# The web UI's static files are their own package, which the product's +# package group installs. +PACKAGES =+ "${PN}-ui" +FILES:${PN}-ui = "${datadir}/pump-web" diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-core/images/pump-image.bb b/fixtures/nightly/firmware/yocto-layer/recipes-core/images/pump-image.bb index bc02003..abc7bb8 100644 --- a/fixtures/nightly/firmware/yocto-layer/recipes-core/images/pump-image.bb +++ b/fixtures/nightly/firmware/yocto-layer/recipes-core/images/pump-image.bb @@ -11,3 +11,7 @@ inherit core-image extrausers # A password hash baked into the image: the same root password on every device. EXTRA_USERS_PARAMS = "usermod -p '\$6\$pumpsalt\$Qm1sZWFzZWQtZml4dHVyZS1oYXNoLW5vdC1yZWFs' root;" + +# The application packages come through the product's package group; pump-fw +# (the firmware tools) is built but no image installs it. +IMAGE_INSTALL:append = " packagegroup-pump" diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-core/packagegroups/packagegroup-pump.bb b/fixtures/nightly/firmware/yocto-layer/recipes-core/packagegroups/packagegroup-pump.bb new file mode 100644 index 0000000..fcf628e --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-core/packagegroups/packagegroup-pump.bb @@ -0,0 +1,9 @@ +# Nightly fixture: the product's package group. It pulls in the web UI by its +# package name (pump-web-ui, made by the pump-web recipe); an image naming the +# group installs what it RDEPENDS on. +SUMMARY = "Pump controller application packages" +LICENSE = "MIT" + +inherit packagegroup + +RDEPENDS:${PN} = "pump-web-ui" diff --git a/fixtures/nightly/targets.json b/fixtures/nightly/targets.json index a8b98d6..e39c147 100644 --- a/fixtures/nightly/targets.json +++ b/fixtures/nightly/targets.json @@ -266,7 +266,7 @@ "key": "fw-yocto-layer", "name": "Firmware · Yocto layer", "target_type": "embedded_linux_yocto", - "description": "A Yocto layer with an insecure product image, recipes and distro. Detected as a BitBake layer tree; recipe lint (oelint-adv and our own rules) reports each insecure setting; the recipe inventory lists the recipes as SBOM components (BusyBox 1.35.0 and libmodbus 3.1.6 with NVD CVEs by CPE, one CVE_STATUS, a CVE_STATUS group and a CVE: patch as VEX). The firmware SBOM (a build) is recorded as skipped with its reason.", + "description": "A Yocto layer with an insecure product image, recipes and distro. Detected as a BitBake layer tree; recipe lint (oelint-adv and our own rules) reports each insecure setting; the recipe inventory lists the recipes as SBOM components (BusyBox 1.35.0 and libmodbus 3.1.6 with NVD CVEs by CPE, one CVE_STATUS, a CVE_STATUS group and a CVE: patch as VEX); the recipes pump-image installs (IMAGE_INSTALL, one package group) are marked as in the image (declared), pump-fw is not. The firmware SBOM (a build) is recorded as skipped with its reason.", "artifacts": [ { "kind": "source_archive",